branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>package lab05; public class BinarySearchSetTester { static<T>void out(T o) {System.out.println(o);} static<T>void err(T o) {System.err.println(o);} static<T>void slp() {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}} public static void main(String[] a) { //double[] te = new double[6]; //for (int i = 0; i < 6; i++) {te[i] = Math.random()*20; System.out.print(te[i] + ","); System.out.println();} //BinarySearchSet b = new BinarySearchSet(te); BinarySearchSet b = new BinarySearchSet(); String s = ""; if (!(b.isEmpty())) err("Not empty"); if (!(b.size()==0)) err("Not correct size"); b.grow(); s = "0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,12,0"; if (!(b.size()==0)) err("Not correct after grow"); if (!(b.toString().equals(s))) err("Not correct after initialization"); double arr1[] = new double[]{5.0,6.2,8.4,2.8,1.8,9.5,7.6}; //for (double d : arr1) if (!(b.sequential_add(d)) && !(b.contains(d))) err("Not returning true for arr1"); for (double d : arr1) if (!(b.binary_add(d)) || !(b.contains(d))) err("Not returning true for arr1"); for (double d : new double[]{3.3,6.4}) if (b.contains(d)) err("contains: Should not contain element " + d); if (!(b.containsAll(arr1))) err("containsAll: Should contain elements in arr1"); if (b.containsAll(new double[]{3.3,6.4,5.0})) err("containsAll: Should not contain elements (arr1 test)"); s = "1.8,2.8,5.0,6.2,7.6,8.4,9.5,0.0,0.0,0.0,0.0,0.0,12,7"; //if (!(b.toString().equals(s))) err("Not correct after adding arr1"); double arr2[] = new double[]{5.1,6.3,8.5,2.9,1.9,9.6,7.7,0.2,1.9}; //for (double d : arr2) if (!(b.sequential_add(d)) && !(b.contains(d)) && !(d == 1.9)) err("Not returning true for arr2"); for (double d : arr2) if (!(b.binary_add(d)) && !(b.contains(d)) && !(d == 1.9)) err("Not returning true for arr2"); for (double d : new double[]{3.3,6.4}) if (b.contains(d)) err("contains: Should not contain element " + d); if (!(b.containsAll(arr2))) err("containsAll: Should contain elements in arr2"); if (b.containsAll(new double[]{3.3,6.4,5.0})) err("containsAll: Should not contain elements (arr2 test)"); s = "0.2,1.8,1.9,2.8,2.9,5.0,5.1,6.2,6.3,7.6,7.7,8.4,8.5,9.5,9.6,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,24,15"; //if (!(b.toString().equals(s))) err("Not correct after adding arr2"); for (double d : arr2) {b.remove(d);} s = "1.8,2.8,5.0,6.2,7.6,8.4,9.5,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,24,7"; //if (!(b.toString().equals(s))) err("Not correct after removing arr2"); for (double d : arr1) {b.remove(d);} s = "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,24,0"; //if (!(b.toString().equals(s))) err("Not correct after removing arr1"); out("Testing done."); } }<file_sep>#Wed Oct 10 15:35:30 EDT 2018 org.eclipse.core.runtime=2 org.eclipse.platform=4.4.2.v20150204-1700 <file_sep>package lab01; public class SumExperiment { public static int check_sum(int[] array){ int a = 0; int b = array.length - 1; int sum = 0; for (int i = 0; i < array.length - 1; i++) { sum = array[a] + array[b]; if (sum > 20) { b--; } else if (sum < 20) { a++; } else { return a; } } return -1; } public static void main(String[] args) { int[] array1 = new int[]{5, 7, 8, 9, 10, 15, 16}; if (check_sum(array1) != 0) System.err.println("TEST1 FAILED"); int[] array2 = new int[]{3, 5, 8, 9, 10, 15, 16}; if (check_sum(array2) != 1) System.err.println("TEST2 FAILED"); int[] array3 = new int[]{3, 4, 6, 9, 10, 14, 15}; if (check_sum(array3) != 2) System.err.println("TEST3 FAILED"); int[] array4 = new int[]{6, 7, 8, 9, 10, 15, 16}; if (check_sum(array4) != -1) System.err.println("TEST4 FAILED"); System.out.println("Done!!!"); } } <file_sep>package lab01; public class CoinFlipExperiment1 { public static void main(String[] args) { System.out.println(coinFlipExperiment()); } public static int coinFlipExperiment() { int i = 1; return ++i; } }
b0f66b91e4e4cc7f9bb9fa569d8411b04d75f6f2
[ "Java", "INI" ]
4
Java
JBWalrider/lab_assignments
cc28a83b9241edb6b436fa7146c8eb608b1b54cd
169a00f42b5d31d9e207548acbf2e52506a9f42e
refs/heads/master
<repo_name>melissa8717/appli_frais<file_sep>/cAllJustificatif.php <?php /** * Script de contrôle et d'affichage du cas d'utilisation "Se connecter" * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); // est-on au 1er appel du programme ou non ? $etape=(count($_POST)!=0)?'validerConnexion' : 'demanderConnexion'; if ($etape=='validerConnexion') { // un client demande à s'authentifier // acquisition des données envoyées, ici login et mot de passe $login = lireDonneePost("txtLogin"); $mdp = lireDonneePost("txtMdp"); $lgUser = verifierInfosConnexion($idConnexion, $login, $mdp) ; // si l'id utilisateur a été trouvé, donc informations fournies sous forme de tableau if ( is_array($lgUser) ) { affecterInfosConnecte($lgUser["id"], $lgUser["login"]); } else { ajouterErreur($tabErreurs, "Pseudo et/ou mot de passe incorrects"); } } if ( $etape == "validerConnexion" && nbErreurs($tabErreurs) == 0 ) { header("Location:cAccueil.php"); } if(isset($_GET['delete'])){ $file_to_delete = $_GET['delete']; unlink($file_to_delete); $requete = modifiEtatJustificatif($idConnexion, $id); $id=$_GET['id']; header("Location:/appli_frais/cVoirfrais.php/?id=$id"); } $unIdFrais = $_GET["id"]; $unIdV =$_GET["id2"]; require($repInclude . "_entete.inc.html"); require($repInclude . "_sommaireComptable.inc.php"); ?> <!-- Division pour le contenu principal --> <div id="contenuUpload"> <div id="imgUpload"> <?php $mois = date('Ym'); if(isset($unIdV)){ if ( $etape == "validerConnexionCompta" ) { if ( nbErreurs($tabErreurs) > 0 ) { echo toStringErreurs($tabErreurs); } } $nbFichier = 0; $dir = 'C:/wamp64/www/appli_frais/upload/'.$unIdV."/".$mois."/".$unIdFrais."/"; if($dossier = opendir($dir)){ $path = $_SERVER['SERVER_NAME'] ; $path_file = str_replace($_SERVER['DOCUMENT_ROOT'],$path, $dir); while(false !== ($fichier = readdir($dossier))){ if($fichier !='.' && $fichier !='..' && $fichier != 'index.php'){ $nbFichier++; ?> <table> <tr> <?php echo '<td>'.'<img src="http://'.$path_file.'/'.$fichier.'"/>'.'</td>';?></tr> <tr><td><h2><a href="../cFormCompta.php?id=<?php echo $unIdV;?>&id2=<?php echo $unIdFrais;?>">Refuser</a> </h2><td></tr><br /></table>; <?php } } closedir($dossier); } else{ echo ' Pas de frais '; } } require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php"); <file_sep>/cVoirfrais.php <?php /** * Script de contrôle et d'affichage du cas d'utilisation "Se connecter" * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); // est-on au 1er appel du programme ou non ? $etape=(count($_POST)!=0)?'validerConnexionCompta' : 'demanderConnexionCompta'; if ($etape=='validerConnexionCompta') { // un client demande à s'authentifier // acquisition des données envoyées, ici login et mot de passe $login = lireDonneePost("txtLoginCompta"); $mdp = lireDonneePost("txtMdpCompta"); $lgUser = verifierInfosConnexionComptable($idConnexion, $login, $mdp) ; // si l'id utilisateur a été trouvé, donc informations fournies sous forme de tableau if ( is_array($lgUser) ) { affecterInfosConnecte($lgUser["id"], $lgUser["login"]); } else { ajouterErreur($tabErreurs, "Pseudo et/ou mot de passe incorrects"); } } if ( $etape == "validerConnexionCompta" && nbErreurs($tabErreurs) == 0 ) { header("Location:cValideFrais.php"); } $moisSaisi=lireDonneePost("lstMois", ""); $unId = $_GET["id"]; require($repInclude . "_entete.inc.html"); require($repInclude . "_sommaireComptable.inc.php"); ?> <?php if ( $etape == "validerConnexionCompta" ) { if ( nbErreurs($tabErreurs) > 0 ) { echo toStringErreurs($tabErreurs); } } $mois = date("Ym"); ?> <div id="contenu"> <?php $requeteVisiteur= infoVisiteur($idConnexion, $unId); foreach ($requeteVisiteur as $value) { $nom=$value[0]; $prenom=$value[1]; } ?> <?php echo '<h1>'.'Mois de '.$mois.' pour '.$nom.' '.$prenom.'</h1>'; ?> <h2>Frais forfaitisés</h2> <table> <tr> <td>Type</td><td>Quantité</td></tr> <?php $requete= fraisAll($idConnexion, $unId,$mois); foreach ($requete as $valeur) { ?> <tr> <?php $idFrais =$valeur[2]; $frais = $valeur[3]; $Id =$valeur[1]; ?> <td><?php echo $idFrais ; ?></td><td><?php echo $frais ; ?></td> </tr> <?php }?> </table> <br /> <h2>Frais hors forfait</h2> <table> <tr> <td>Type</td><td>Montant en €</td><td>Justificatifs</td></tr> <?php $requeteHF= fraisHF($idConnexion, $unId,$mois); foreach ($requeteHF as $valeur) { ?> <tr> <?php $fraisHF = $valeur[3]; $montantFHF = $valeur[4]; $unId =$valeur[1]; $nomU = $valeur[0]; $justificatif = $valeur[6]; $cause = $valeur [7]; ?> <td><?php echo $fraisHF ; ?></td><td><?php echo $montantFHF ; ?></td> <?php if($justificatif == 1){ echo '<td><a href="../cAllJustificatif.php/?id='.$nomU.'&id2='.$unId.'" target="_blank">Voir le justificatif</a></td>'; } else { echo '<td>Pas de frais</td>'; } if ($justificatif == 1 && $cause){ echo '<td>Frais refusé</td>'; } ?> </tr> <?php }?> </table> <br /> <?php echo"".'<a href="../cFicheFrais.php/?id='.$unId.'">Voir la fiche de frais</a>';?><?php require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php"); <file_sep>/cValideFrais.php <?php /** * Script de contrôle et d'affichage du cas d'utilisation "Se connecter" * @package default * @todo RAS */ // Afficher les erreurs à l'écran ini_set('display_errors', 1); // Enregistrer les erreurs dans un fichier de log ini_set('log_errors', 1); // Nom du fichier qui enregistre les logs (attention aux droits à l'écriture) ini_set('error_log', dirname(__file__) . '/log_error_php.txt'); // Afficher les erreurs et les avertissements error_reporting(E_ALL); $repInclude = './include/'; require($repInclude . "_init.inc.php"); // est-on au 1er appel du programme ou non ? $etape=(count($_POST)!=0)?'validerConnexionCompta' : 'demanderConnexionCompta'; if ($etape=='validerConnexionCompta') { // un client demande à s'authentifier // acquisition des données envoyées, ici login et mot de passe $login = lireDonneePost("txtLoginCompta"); $mdp = lireDonneePost("txtMdpCompta"); $lgUser = verifierInfosConnexionComptable($idConnexion, $login, $mdp) ; // si l'id utilisateur a été trouvé, donc informations fournies sous forme de tableau if ( is_array($lgUser) ) { affecterInfosConnecte($lgUser["id"], $lgUser["login"]); } else { ajouterErreur($tabErreurs, "Pseudo et/ou mot de passe incorrects"); } } if ( $etape == "validerConnexionCompta" && nbErreurs($tabErreurs) == 0 ) { header("Location:cValideFrais.php"); } require($repInclude . "_entete.inc.html"); require($repInclude . "sommaire_comptable.php"); //$unId = $_GET["id"]; ?> <!-- Division pour le contenu principal --> <div id="contenu"> <?php if ( $etape == "validerConnexionCompta" ) { if ( nbErreurs($tabErreurs) > 0 ) { echo toStringErreurs($tabErreurs); } } ?> <table class="listeLegere"> <tr class="corpsForm"> <td style="visibility: hidden;">id</td><td>Nom </td><td>Prénom</td><td>Téléphone</td><td>Justificatifs Frais</td><td>Carte grise</td><td>Fiche de frais</td></tr> <?php $req= listeVisiteur($idConnexion, $lgUser["id"]); $reqVH=obtenirInfoVH($idConnexion,$lgUser["id"] ); foreach ( $req as $value ) { ?> <tr> <?php $nom = $value[0]; $prenom = $value[1]; $unId = $value[2]; $tel=$value[3]; ?> <td style="visibility: hidden;"><?php echo $unId ; ?></td><td><?php echo $nom ; ?></td><td><?php echo $prenom ; ?></td><td><?php echo $tel;?></td><?php echo"".'<td><a href="cVoirfrais.php/?id='.$unId.'">Voir les frais</a></td>';?><?php echo"".'<td><a href="cJustificatifVehiculeComptable.php/?id='.$unId.'">Voir le justificatif</a></td>';?><?php echo"".'<td><a href="cConsultFiche.php/?id='.$unId.'">Voir les fiches de frais</a></td>';?> </tr> <?php }?> </table> <?php require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php"); <file_sep>/pdf.php class myFPDF extends FPDF { var $db; function myFPDF ($orientation='P',$unit='mm',$format='A4',$db){ parent::FPDF($orientation='P',$unit='mm',$format='A4'); $this->db = $db; } $pdf = new myFPDF; //création d'une instance de classe, P pour portrait, pt pour point en unité de mesure, A4 pour le format $pdf ->Open(); //indique que l'on crée un fichier PDF $pdf ->AddPage(); //permet d'ajouter une page $pdf ->SetFont('Helvetica','B',11); //choix de la police $pdf ->SetXY(330, 25); // indique des coordonnées pourplacer un élément $pdf ->Cell(190,50,"texte dans le cadre",0,0, "L"); //création d'une cellule $pdf ->Text(498,20, "texte"); //insertion d'une ligne de texte $pdf ->Output(); //génère le PDF et l'affiche <file_sep>/cGed.php <?php /** * Page d'accueil de l'application web AppliFrais * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); // page inaccessible si visiteur non connecté if ( ! estVisiteurConnecte() ) { header("Location: cSeConnecter.php"); } $idHF= $_GET['id']; require($repInclude . "_entete.inc.html"); require($repInclude . "_sommaire.inc.php"); ?> <!-- Division principale --> <div id="contenu"> <h1>GED</h1> <form action="../upload.php" method="post" enctype="multipart/form-data" > Transfèrer le fichier<br /><br /><br /> <input type="hidden" name="id" value="<?php echo $idHF;?>" /> <input type="file" name="userfile" value="userfile" /><br /><br /> <input type="submit" value="Valider" /> </form> </div> <?php require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php"); ?> <file_sep>/README.md # appli_frais Application in PHP for create expense for medical visitor and to edit and upload their remboursement <file_sep>/cSeConnecterComptable.php <?php /** * Script de contrôle et d'affichage du cas d'utilisation "Se connecter" * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); // est-on au 1er appel du programme ou non ? $etape=(count($_POST)!=0)?'validerConnexionCompta' : 'demanderConnexionCompta'; if ($etape=='validerConnexionCompta') { // un client demande à s'authentifier // acquisition des données envoyées, ici login et mot de passe $login = lireDonneePost("txtLoginCompta"); $mdp = lireDonneePost("txtMdpCompta"); $lgUser = verifierInfosConnexionComptable($idConnexion, $login, $mdp) ; // si l'id utilisateur a été trouvé, donc informations fournies sous forme de tableau if ( is_array($lgUser) ) { affecterInfosConnecte($lgUser["id"], $lgUser["login"]); } else { ajouterErreur($tabErreurs, "Pseudo et/ou mot de passe incorrects"); } } if ( $etape == "validerConnexionCompta" && nbErreurs($tabErreurs) == 0 ) { header("Location:cValideFrais.php"); } require($repInclude . "_entete.inc.html"); require($repInclude . "_sommaireComptable.inc.php"); ?> <!-- Division pour le contenu principal --> <div id="contenu"> <h2 id="frmConnexion">Identification comptable</h2> <?php if ( $etape == "validerConnexionCompta" ) { if ( nbErreurs($tabErreurs) > 0 ) { echo toStringErreurs($tabErreurs); } } ?> <form id="frmConnexion" action="" method="post"> <div class="corpsForm"> <input type="hidden" name="etape" id="etape" value="validerConnexionCompta" /> <p> <label for="txtLoginCompta" accesskey="n">* Login : </label> <input type="text" id="txtLogin" name="txtLoginCompta" maxlength="20" size="15" value="" title="Entrez votre login" /> </p> <p> <label for="txtMdpCompta" accesskey="m">* Mot de passe : </label> <input type="password" id="txtMdp" name="txtMdpCompta" maxlength="8" size="15" value="" title="Entrez votre mot de passe"/> </p> </div> <div class="piedForm"> <p> <input type="submit" id="ok" value="Valider" /> <input type="reset" id="annuler" value="Effacer" /> </p> </div> </form> </div> <?php require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php"); ?><file_sep>/uploadCG.php <?php /** * Page d'accueil de l'application web AppliFrais * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); // page inaccessible si visiteur non connecté if ( ! estVisiteurConnecte() ) { header("Location: cSeConnecter.php"); } require($repInclude . "_entete.inc.html"); require($repInclude . "_sommaire.inc.php"); $idUser = obtenirIdUserConnecte() ; $lgUser = obtenirDetailVisiteur($idConnexion, $idUser); $nom = $lgUser['nom']; $nomU= $lgUser['nom']."/".$prenom."/"; $prenom = $lgUser['prenom']; $idVehi= $_POST['idVehi']; $mois = date('Ym'); $date = date("d-m-Y "); $heure= date('H:i:s'); $login = lireDonneePost("txtLogin"); $dossier_visiteur = 'C:/wamp64/www/appli_frais/upload/Vehicule'.$idUser."/".$idVehi."/"; $fichier = $_FILES['userfile']['name'].$date.$heure; $taille_maxi = 1000000; $taille = $_FILES['userfile']['size']; $extensions = array('.png', '.gif', '.jpg', '.jpeg'); $extension = strrchr($_FILES['userfile']['name'], '.'); //si extension non autorisée if(!in_array($extension, $extensions)) { $erreur = 'Vous devez uploader un fichier de type png, gif, jpg, jpeg'; } if($taille>$taille_maxi) { $erreur = 'Le fichier est trop gros...'; } //remplacement des caracteres speciaux if(!isset($erreur)){ $fichier = strtr($fichier, 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy'); //tout autre caracteres que des lettres ou des chiffres sera remplaces par un tiret $fichier = preg_replace('/([^.a-z0-9]+)/i', '-', $fichier); //creation du dossier si inexistant if(is_dir($dossier_visiteur) == FALSE) { mkdir($dossier_visiteur, 0777, true); } //deplacement du fichier vers le bon dossier if(move_uploaded_file($_FILES['userfile']['tmp_name'], $dossier_visiteur.$fichier)) { $url = $dossier_visiteur.$fichier; AjoutCheminJustificatif($idConnexion, $url, $idHF); //TODO //Requete à créer : update sur la table fraisforfait ligne mettre en valeur $dossier_visiteur.$chemin AjoutCheminJustificatif() header('Location: cJustificatifVehicule.php?id='.$idVehi.''); } else { echo 'Echec de l\'upload !'; } } require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php"); ?> <file_sep>/cVehicule.php <?php /** * Page d'accueil de l'application web AppliFrais * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); $unId = $_GET["id"]; // page inaccessible si visiteur non connecté if ( ! estVisiteurConnecte() ) { header("Location: cSeConnecter.php"); } require($repInclude . "_entete.inc.html"); require($repInclude . "_sommaireComptable.inc.php"); if (isset($_POST['txtPuissance'])){ //Fonction de validation / enregistrement ajoutVehicule($idConnexion, obtenirIdUserConnecte(), $_POST['txtMarque'], $_POST['txtModele'], $_POST['txtPuissance'], $_POST['txtImmatriculation']); header("Location: ../cConsultVehicule.php/?id=$unId"); } if (isset($_POST['ok'])){ echo 'Véhicule ajouté correctement'; } ?> <!-- Division principale --> <div id="contenu"> <h1>Fiche Véhicule</h1> <form id="" action="" method="post"> <div class="corpsForm"> <input type="hidden" name="etape" id="etape" value="validerConnexion" /> <p> <label for="txtMarque" >* Marque :</label> <input type="text" id="txtMarque" name="txtMarque" /> </p> <p> <label for="txtModel" >* Modèle : </label> <input type="text" id="txtModele" name="txtModele"/> </p> <p> <label for="txtPuissance" >* Puissance fiscale : </label> <input type="text" id="txtPuissance" name="txtPuissance" /> </p> <p> <label for="txtImmatriculation" >* Immatriculation : </label> <input type="text" id="txtImmatriculation" name="txtImmatriculation" /> </p> </div> <div class="piedForm"> <p> <input type="submit" id="ok" value="Valider" name="ok" /> <input type="reset" id="annuler" value="Effacer" /> </p> </div> </form> </div> <?php require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php"); ?> <file_sep>/cFicheFrais.php <?php /** * Script de contrôle et d'affichage du cas d'utilisation "Se connecter" * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); if(isset($_POST['rembourser'])){ require('PHP.php'); echo '<p class="info">La fiche de remboursement a bien été créér</p>'; ; } // est-on au 1er appel du programme ou non ? $etape=(count($_POST)!=0)?'validerConnexionCompta' : 'demanderConnexionCompta'; if ($etape=='validerConnexionCompta') { // un client demande à s'authentifier // acquisition des données envoyées, ici login et mot de passe $login = lireDonneePost("txtLoginCompta"); $mdp = lireDonneePost("txtMdpCompta"); $lgUser = verifierInfosConnexionComptable($idConnexion, $login, $mdp) ; // si l'id utilisateur a été trouvé, donc informations fournies sous forme de tableau if ( is_array($lgUser) ) { affecterInfosConnecte($lgUser["id"], $lgUser["login"]); } else { ajouterErreur($tabErreurs, "Pseudo et/ou mot de passe incorrects"); } } if ( $etape == "validerConnexionCompta" && nbErreurs($tabErreurs) == 0 ) { header("Location:cValideFrais.php"); } $moisSaisi=lireDonneePost("lstMois", ""); $unId = $_GET["id"]; require($repInclude . "_entete.inc.html"); require($repInclude . "_sommaireComptable.inc.php"); ?> <?php if ( $etape == "validerConnexionCompta" ) { if ( nbErreurs($tabErreurs) > 0 ) { echo toStringErreurs($tabErreurs); } } $mois = date('Ym'); ?> <div id="contenu"> <?php $requeteVisiteur=infoVisiteur($idConnexion, $unId); foreach ($requeteVisiteur as $value) { $nom=$value[0]; $prenom=$value[1]; } ?> <?php echo '<h1>'.'Fiche de '.$nom.' '.$prenom.'</h1>';?> <h2>Frais forfaitisés</h2> <table> <tr> <td>Type</td><td>Quantité</td><td>Forfait</td><td>Total ligne</td> </tr> <?php $requeteForfait= fraisForfait($idConnexion, $unId,$mois); $calculFrais = 0; foreach ($requeteForfait as $valeur ) { ?> <tr> <?php $unIdForfait =$valeur[0]; $frais = $valeur[6]; $idLigne=$valeur[2]; $forfait=$valeur[2]; if($unIdForfait != 'KM'){ $tot_ligne = $forfait * $frais; $total_ligne = $tot_ligne .' €'; $forfait=$valeur[2]; } else { $bareme = calculKM($idConnexion, $unId); $tot_ligne = $bareme * $frais; $total_ligne = $tot_ligne.' €'; $forfait = $bareme; } ?> <td><?php echo $unIdForfait ; ?></td><td><?php echo $frais ; ?></td><td><?php echo $forfait;?></td><td><?php echo $total_ligne;?></td> </tr> <?php $calculFrais = $calculFrais + $tot_ligne; } ?> <tr> <td><h3>Total</h3></td><td colspan="3"><h3 style="text-align:center;"><?php echo $calculFrais;?></h3></td> </tr> </table> <br /> <h2>Frais hors forfait</h2> <table> <tr> <td>Type</td><td>Montant</td></tr> <?php $requeteHF= fraisHF($idConnexion, $unId,$mois); foreach ($requeteHF as $valeur) { ?> <tr> <?php $fraisHF = $valeur[3]; $montantFHF = $valeur[4]; $mois= $valeur[2]; ?> <td><?php echo $fraisHF ; ?></td><td><?php echo $montantFHF.' €' ; ?></td> </tr> <?php } $requeteCalcul = calculfraisHF($idConnexion, $unId,$mois); if (is_array($requeteCalcul) || is_object($requeteCalcul)) { foreach ($requeteCalcul as $cal) { $calcul=$cal[0]; $calulTotal = $calcul + $calculFrais; } } ?> <tr> <td><h3>Total</h3></td><td><h3><?php echo $calcul.' €';?></h3></td> </tr> </table> <br /> <table> <tr style="font-size: 25px;" > <td ><strong>Totaux</strong></td><td><?php echo $calulTotal.' €';?></td> </tr> </table> <form id="" method="post"> <div > <input type="hidden" name="etape" id="etape" value="validerConnexion" /> <br /> <?php if (isset($_POST['valider'])){ //Fonction de validation / enregistrement modifierEtatFicheFrais($idConnexion,$unId,$calulTotal ); } ?> <input type="submit" id="ok" value="Mise en paiement" name="valider"/> <?php if (isset($_POST['refus'])){ //Fonction de validation / enregistrement modifierEtatRefus($idConnexion,$unId, $calulTotal ); } ?> <input type="submit" id="refus" value="Refuser" name="refus"/> <?php if (isset($_POST['rembourser'])){ //Fonction de validation / enregistrement modifierEtatRB($idConnexion,$unId,$calulTotal ); echo 'Fiche de remboursement créée'; } ?> <input type="submit" id="rembourser" value="Rembourser" name="rembourser"/> <div> </form> <?php require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php"); <file_sep>/cModifierFrais.php <?php /** * Script de contrôle et d'affichage du cas d'utilisation "Se connecter" * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); if ( ! estVisiteurConnecte() ) { header("Location:cValideFrais.php"); } require($repInclude . "_entete.inc.html"); require($repInclude . "_sommaireComptable.inc.php"); $idFrais=$_GET["id"]; if ($_POST){ $requete = modifierFrais($idConnexion, $idFrais, $_POST['txtLibelle'], $_POST['txtMontant']); //header("Location: ../cConsultFrais.php"); } if (isset($_POST['ok'])){ echo 'Frais modifié correctement'; } ?> <div id="contenu"> <h2>Frais forfaitisés</h2> <form id="" action="" method="post"> <div class="corpsForm"> <input type="hidden" name="etape" id="etape" value="validerConnexion" /> <p> <label for="txtMarque" >* Libellé :</label> <input type="text" id="txtLibelle" name="txtLibelle" /> </p> <p> <label for="txtModel" >* Montant : </label> <input type="text" id="txtMontant" name="txtMontant"/> </p> </div> <div class="piedForm"> <p> <input type="submit" id="ok" value="Valider" name="ok" /> <input type="reset" id="annuler" value="Effacer" /> </p> </div> </form> </div> <?php require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php"); <file_sep>/cAccueil.php <?php /** * Page d'accueil de l'application web AppliFrais * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); // page inaccessible si visiteur non connecté if ( ! estVisiteurConnecte() ) { header("Location: cSeConnecter.php"); } require($repInclude . "_entete.inc.html"); require($repInclude . "_sommaire.inc.php"); ?> <!-- Division principale --> <div id="contenuAccueil"> <h1>Bienvenue sur l'intranet GSB</h1> <h3>Dans cet espace vous pouvez enrgistrer, consulter et modifier toutes vos fiches de frais, qu'elles soient en forfait ou en hors forfait.<br /> Utilisez simplement le menu situé à gauche. <div style="height:500px;"><img src="images/comm.jpg" /></div> </h3> </div> <?php require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php"); ?> <file_sep>/cFicheRemboursement.php <?php /** * Script de contrôle et d'affichage du cas d'utilisation "Consulter une fiche de frais" * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); // page inaccessible si visiteur non connecté if ( ! estVisiteurConnecte() ) { header("Location: cSeConnecter.php"); } require($repInclude . "_entete.inc.html"); require($repInclude . "_sommaire.inc.php"); // acquisition des données entrées, ici le numéro de mois et l'étape du traitement $moisSaisi=lireDonneePost("lstMois", ""); $etape=lireDonneePost("etape",""); if ($etape != "demanderConsult" && $etape != "validerConsult") { // si autre valeur, on considère que c'est le début du traitement $etape = "demanderConsult"; } if ($etape == "validerConsult") { // l'utilisateur valide ses nouvelles données // vérification de l'existence de la fiche de frais pour le mois demandé $existeFicheFrais = existeFicheFrais($idConnexion, $moisSaisi, obtenirIdUserConnecte()); // si elle n'existe pas, on la crée avec les élets frais forfaitisés à 0 if ( !$existeFicheFrais ) { ajouterErreur($tabErreurs, "Le mois demandé est invalide"); } else { // récupération des données sur la fiche de frais demandée $tabFicheFrais = obtenirDetailFicheFrais($idConnexion, $moisSaisi, obtenirIdUserConnecte()); } } $unId = $_SESSION["idUser"]; $requete = fraisMois($idConnexion, obtenirIdUserConnecte()); ?> <!-- Division principale --> <div id="contenu"> <h2>Mes fiches de remboursement</h2> <?php $nbFichier = 0; $mois = date('Ym'); ?> <table> <tr> <td>Mois</td> <td>Lien</td> </tr> <?php foreach($requete->fetch_all() as $result){ $dir = 'C:/wamp64/www/appli_frais/PDF_Fiche_Frais/'.$unId."/".$result[0]; ?> <tr> <td><?php echo $result[0];?></td> <?php if(is_dir($dir)){ $dossier = opendir($dir); $path = $_SERVER['SERVER_NAME'] ; $path_file = str_replace($_SERVER['DOCUMENT_ROOT'],$path, $dir); ?> <td> <?php while (false !== ($fichier = readdir($dossier))) { if ($fichier != "." && $fichier != "..") { echo '<a href="http://'.$path_file.'/'.$fichier.'">Télécharger le PDF</a>'; } }?> </td> <?php closedir($dossier); } else { echo '<td>Pas de fiche de remboursement</td>'; } ?> </tr> <?php } <file_sep>/PHP.php <?php require_once('_bdGestionDonnees.lib.php'); $db = connecterServeurBD(); require('fpdf/fpdf.php'); function fraisForfaitPdf($db, $unId, $mois){ $requeteForfait = "select * from FraisForfait inner join LigneFraisForfait on LigneFraisForfait.idFraisForfait = FraisForfait.idFrais where idVisiteur='". $unId . "' and mois='".$mois."'"; $result = $db->query($requeteForfait); if($result){ $ligne= mysqli_fetch_all($result); } return $ligne; } $unId = $_GET["id"]; $mois = date('Ym'); $requeteVisiteur=infoVisiteur($db, $unId); foreach ($requeteVisiteur as $value) { $nom=$value[0]; $prenom=$value[1];} class PDF extends FPDF { // En-tête function Header() { // Logo $this->Image('http://localhost/appli_frais/images/logo.jpg',10,6,30); // Police Arial gras 15 $this->SetFont('Arial','B',15); // Décalage à droite $this->Cell(80); // Titre // Saut de ligne $this->Ln(20); } // Pied de page function Footer() { // Positionnement à 1,5 cm du bas $this->SetY(-15); // Police Arial italique 8 $this->SetFont('Arial','I',8); // Numéro de page $txt_a_pdf = utf8_decode('Société GSB - Saint Denis'); $this->Cell(0,0,$txt_a_pdf, 2,0,'C'); $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C'); } function LoadData($db, $unId, $mois){ $requeteForfait= fraisForfait($db, $unId, $mois); $calculFrais = 0; $data_table = array(); $compteur_frais = 0; foreach ($requeteForfait as $valeur) { $data_table[$compteur_frais]['unIdForfait'] =$valeur[1]; $data_table[$compteur_frais]['frais'] = $valeur[6]; $data_table[$compteur_frais]['forfait']=$valeur[2]; $mois=$valeur[4]; if($data_table[$compteur_frais]['unIdForfait'] != 'KM'){ $data_table[$compteur_frais]['total_ligne'] = $data_table[$compteur_frais]['forfait'] * $data_table[$compteur_frais]['frais']; } else{ $bareme=calculKM($db, $unId); $data_table[$compteur_frais]['total_ligne'] = $bareme * $data_table[$compteur_frais]['frais']; $data_table[$compteur_frais]['forfait'] = $bareme; } $data_table[$compteur_frais]['calculFrais'] = $calculFrais + $data_table[$compteur_frais]['total_ligne']; $calculFrais = $data_table[$compteur_frais]['calculFrais']; $compteur_frais++; } return $data_table; } function LoadHF($db,$unId, $mois){ $requeteHF= fraisHF($db, $unId, $mois); $table=array(); $compteurHF=0; foreach ($requeteHF as $valeurHF) { $table[$compteurHF]['$fraisHF'] = $valeurHF[3]; $table[$compteurHF]['$montantFHF'] = $valeurHF[4]; $compteurHF++; } return $table; } function BasicTable($header, $valeur) { // En-tête foreach($header as $col) { $this->Cell(40,7,$col,1); } $this->Ln(); // Données foreach($valeur as $row) { unset($row['calculFrais']); foreach($row as $col){ $this->Cell(40,6,$col,1); } $this->Ln(); } } function BasicTable1($header1, $valeurHF) { // En-tête foreach($header1 as $col) { $this->Cell(40,7,$col,1); } $this->Ln(); // Données foreach($valeurHF as $row) { foreach($row as $col){ $this->Cell(40,6,$col,1); } $this->Ln(); } } } $requeteCalcul = calculfraisHF($db, $unId, $mois); foreach ($requeteCalcul as $cal) { $calcul=$cal[0]; //$calulTotal = $calcul + $calculFrais; } // Instanciation de la classe dérivée $pdf = new PDF(); $pdf->AliasNbPages(); $pdf->AddPage(); $pdf->SetFont('Times','',18); $pdf->Cell(0,10,'Fiche de frais du mois de '.$mois. ' de '.$nom.' '.$prenom,2,0,'C'); $pdf->Ln(20); $pdf->SetFont('Times','B',14); $pdf->Cell(0,10,utf8_decode('FRAIS FORFATISÉS'),2,0,'C'); $pdf->SetFont('Times','',12); $pdf->Ln(20); $valeur = $pdf->LoadData($db, $unId, $mois); $last_ligne = end($valeur); $header=array('Type',,utf8_decode('Quantité'),'Forfait','Total ligne'); $total = $last_ligne['calculFrais']; $pdf->BasicTable($header, $valeur); $pdf->Ln(20); $pdf->Cell(0,10,'Total : '. $total.' euros ',1); $pdf->SetFont('Times','B',14); $pdf->Ln(20); $pdf->Cell(0,10,'<NAME>',2,0,'C'); $pdf->Ln(20); $pdf->SetFont('Times','',12); $header1= array('Type', 'Montant en euros'); $valeurHF = $pdf->LoadHF($db, $unId, $mois); $pdf->BasicTable1($header1, $valeurHF); $pdf->Ln(20); $pdf->Cell(0,10,'Total : '. $calcul.' euros ',1); $pdf->Ln(20); $pdf->SetFont('Times','B',16); $totalAll = $total+$calcul; $pdf->Cell(0,10,'Total : '. $totalAll.' euros ',1); $dossierPDF= 'C:/wamp64/www/appli_frais/PDF_Fiche_Frais/'.$unId."/".$mois."/"; if(is_dir($dossierPDF) == FALSE) { mkdir($dossierPDF, 0777, true); } $dossier = 'C:/wamp64/www/appli_frais/PDF_Fiche_Frais/'.$unId."/".$mois."/"; $pdf->output($dossier.$nom.$prenom.' '.$mois.' Fiche de remboursement.pdf', 'F'); ?> <file_sep>/cConsultFrais.php <?php /** * Script de contrôle et d'affichage du cas d'utilisation "Se connecter" * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); // est-on au 1er appel du programme ou non ? $etape=(count($_POST)!=0)?'validerConnexionCompta' : 'demanderConnexionCompta'; if ($etape=='validerConnexionCompta') { // un client demande à s'authentifier // acquisition des données envoyées, ici login et mot de passe $login = lireDonneePost("txtLoginCompta"); $mdp = lireDonneePost("txtMdpCompta"); $lgUser = verifierInfosConnexionComptable($idConnexion, $login, $mdp) ; // si l'id utilisateur a été trouvé, donc informations fournies sous forme de tableau if ( is_array($lgUser) ) { affecterInfosConnecte($lgUser["id"], $lgUser["login"]); } else { ajouterErreur($tabErreurs, "Pseudo et/ou mot de passe incorrects"); } } if ( $etape == "validerConnexionCompta" && nbErreurs($tabErreurs) == 0 ) { header("Location:cValideFrais.php"); } $moisSaisi=lireDonneePost("lstMois", ""); require($repInclude . "_entete.inc.html"); require($repInclude . "_sommaireComptable.inc.php"); if ( $etape == "validerConnexionCompta" ) { if ( nbErreurs($tabErreurs) > 0 ) { echo toStringErreurs($tabErreurs); } } ?> <div id="contenu"> <h2>Frais forfaitisés</h2> <table> <tr> <td>Type</td><td>Libellé</td><td>Montant</td><td>Modifier</td> </tr> <?php $requeteForfait= listeFrais($idConnexion); foreach ($requeteForfait as $valeur ) { ?> <tr> <?php $unIdForfait =$valeur[0]; $libelle = $valeur[1]; $montant = $valeur[2]; ?> <td><?php echo $unIdForfait ; ?></td><td><?php echo $libelle ; ?></td><td><?php echo $montant;?></td><?php echo"".'<td><a href="cModifierFrais.php/?id='.$unIdForfait.'">Modifier ce frais</a></td>';?> </tr> <?php } ?> </table> <br /> </table> <br /> <form id="" action="" method="post"> <div > <input type="hidden" name="etape" id="etape" value="validerConnexion" /> <br /> <div> </form> <?php require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php"); <file_sep>/cJustificatif.php <?php /** * Script de contrôle et d'affichage du cas d'utilisation "Se connecter" * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); // est-on au 1er appel du programme ou non ? $etape=(count($_POST)!=0)?'validerConnexion' : 'demanderConnexion'; if ($etape=='validerConnexion') { // un client demande à s'authentifier // acquisition des données envoyées, ici login et mot de passe $login = lireDonneePost("txtLogin"); $mdp = lireDonneePost("txtMdp"); $lgUser = verifierInfosConnexion($idConnexion, $login, $mdp) ; // si l'id utilisateur a été trouvé, donc informations fournies sous forme de tableau if ( is_array($lgUser) ) { affecterInfosConnecte($lgUser["id"], $lgUser["login"]); } else { ajouterErreur($tabErreurs, "Pseudo et/ou mot de passe incorrects"); } } if ( $etape == "validerConnexion" && nbErreurs($tabErreurs) == 0 ) { header("Location:cAccueil.php"); } require($repInclude . "_entete.inc.html"); require($repInclude . "_sommaire.inc.php"); $idFrais = $_GET['id']; ?> <!-- Division pour le contenu principal --> <div id="contenuUpload"> <?php if ( $etape == "validerConnexionCompta" ) { if ( nbErreurs($tabErreurs) > 0 ) { echo toStringErreurs($tabErreurs); } } $path = $_SERVER['SERVER_NAME'] ; // Requete pour aller chercher le chemin en base de données a partir de l'ID que tu as dans $_GET['id'] $results_file = recupererCheminFichier($idConnexion, $idFrais); $url_file = $results_file->fetch_assoc(); $path_file = str_replace($_SERVER['DOCUMENT_ROOT'],$path, $url_file['url_justificatif']); ?> <?php if(isset($_GET['delete'])){ unlink($_SESSION['url']); echo '<h3>Fichier supprimé</h3>'; header('Refresh: 4; cGed.php'); } if(isset($_GET['valider'])){ $requete = valideFrais($idConnexion,$idFrais); echo '<h3>Fichier validé</h3>'; header('Refresh: 3; cAccueil'); }?> <table> <tr> <h1>Vérification du fichier</h1> <br /> <h2>Merci de valider ou non le fichier téléchargé</h2> <br /> </tr> <tr > <td ><img src="http://<?php echo $path_file;?>" style="padding-left:3 0%;height:75%;"/></td> </tr> <tr> <td><h2><a href="?delete=<?php echo $path_file;?>">Supprimer le fichier</a> </h2> <h2><a href="?valider&id=<?php echo $idFrais;?>">Valider</a></h2> </td> </tr> </table> <?php require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php"); <file_sep>/cConsultVehicule.php <?php /** * Script de contrôle et d'affichage du cas d'utilisation "Consulter une fiche de frais" * @package default * @todo RAS */ $repInclude = './include/'; require($repInclude . "_init.inc.php"); // page inaccessible si visiteur non connecté if ( ! estVisiteurConnecte() ) { header("Location: cSeConnecter.php"); } require($repInclude . "_entete.inc.html"); require($repInclude . "sommaire_up.inc.php"); $unId = $_GET["id"]; if($_POST && isset($_POST['ok'])){ if($_POST['txtIdVehicule']){ $requeteVehi = modifVH($idConnexion, $_POST['txtMarque'], $_POST['txtModele'], $_POST['txtPuissance'], $_POST['txtIdVehicule']); } else { $requeteVehi=ajoutVehicule($idConnexion, $unId, $_POST['txtMarque'], $_POST['txtModele'], $_POST['txtPuissance'], $_POST['txtImmatriculation']); } } ?> <div id="contenu" > <form action="" method="post"> <table class="listeLegere"> <tr class="corpsForm"> <td>Marque *</td><td>Modèle</td><td>Puissance fiscale</td><td>Immatriculation</td> </tr> <?php $requete=obtenirInfoVH($idConnexion, $unId); if($requete){ foreach ($requete as $vehi) {?> <tr> <?php $idVehi=$vehi[0]; $marque=$vehi[2]; $modele=$vehi[3]; $puissance=$vehi[4]; $immatriculation=$vehi[5]; ?> <td> <input type="hidden" id="<?php echo $idVehi;?>" name="txtIdVehicule" value="<?php echo $idVehi;?>" /> <input type="text" id="<?php echo $marque;?>" name="txtMarque" value="<?php echo $marque;?>" /></td> <td> <input type="text" id="<?php echo $modele;?>" name="txtModele" value="<?php echo $modele;?>" /></td> <td> <input style="width:30px;" type="text" id="<?php echo $puissance;?>" name="txtPuissance" value="<?php echo $puissance;?>" /></td> <td> <input type="text" id="<?php echo $immatriculation;?>" name="txtImmatriculation" value="<?php echo $immatriculation;?>" /></td> <td> <div class="piedForm"> <input type="submit" name="ok" value="Modifier" /> </div> </form> </td> </tr> <tr > <td colspan="4"> <form action="../uploadCG.php" method="post" enctype="multipart/form-data" > Transfèrer la carte grise<br /><br /><br /> <input type="hidden" name="idVehi" value="<?php echo $idVehi; ?>" /> <input type="file" name="userfile" value="userfile" /><br /><br /> <input type="submit" value="Valider" /> </form> </td> </tr> <?php } } else { ?> <tr> <td> <input type="text" name="txtMarque" value="" /></td> <td> <input type="text" name="txtModele" value="" /></td> <td> <input type="text" name="txtPuissance" value="" /></td> <td> <input type="text" name="txtImmatriculation" value="" /></td> <td> <div class="piedForm"> <input type="submit" name="ok" value="Modifier" /> </div> </form> </td> </tr> <?php } ?> </table> </div> <?php require($repInclude . "_pied.inc.html"); require($repInclude . "_fin.inc.php");
427df7c9ade1dc2d09cd85818b1cd1ab4b5157d0
[ "Markdown", "PHP" ]
17
PHP
melissa8717/appli_frais
f9fb6cf08d3125f72a1e8535adebea27c623c871
c4d6d802c499ff30e1b9987df04eccc241cebcae
refs/heads/master
<repo_name>skatkov/danger-rubyc<file_sep>/lib/danger_plugin.rb require "rubyc/plugin" <file_sep>/README.md # danger-rubyc Danger plugin to validate syntax for ruby files ## Installation $ gem install danger-rubyc ## Usage Add this to your Dangerfile: rubyc.lint ## Development 1. Clone this repo 2. Run `bundle install` to setup dependencies. 3. Run `bundle exec rake spec` to run the tests. 4. Use `bundle exec guard` to automatically have tests run as you make changes. 5. Make your changes. <file_sep>/lib/danger_rubyc.rb require "rubyc/gem_version" <file_sep>/lib/rubyc/plugin.rb module Danger # This is your plugin class. Any attributes or methods you expose here will # be available from within your Dangerfile. # # To be published on the Danger plugins site, you will need to have # the public interface documented. Danger uses [YARD](http://yardoc.org/) # for generating documentation from your plugin source, and you can verify # by running `danger plugins lint` or `bundle exec rake spec`. # # You should replace these comments with a public description of your library. # # @example Ensure people are well warned about merging on Mondays # # my_plugin.warn_on_mondays # # @see Stanislav/danger-rubyc # @tags monday, weekends, time, rattata # class DangerRubyc < Plugin def lint broken_files = [] changed_files.each do |file| next unless File.readable?(file) if file.end_with?('.rb') || file.eql?('Rakefile') broken_files << file unless system('ruby', '-c', file) end end if !broken_files.empty? fail("Ruby code is not valid (SyntaxError) in files: **#{broken_files.join('<br/>')}** ") end end private def changed_files (git.modified_files + git.added_files) end end end
a265586d5e1ebd16f729d1338566aa586ac8da14
[ "Markdown", "Ruby" ]
4
Ruby
skatkov/danger-rubyc
f0bf10c1ec9be6ae232243c73f23582343c09a32
b26be4639a1add060ba548cb4889c396cfc5cfda
refs/heads/master
<file_sep>/* This is a skeleton and a reference application for a simple Arrowhead-compliant consuming system. Read more about Arrowhead Framework: http://www.arrowhead.eu/ Here you can download the Arrowhead G3.2 Framework (Milestone 3): https://github.com/hegeduscs/arrowhead */ #include <WiFi.h> #include <HTTPClient.h> #include <ArduinoJson.h> #include <PubSubClient.h> /* These two variables are required to access Wifi. Obviously, the values need to be changed according to our own data. */ const char* ssid = "Arrowhead-RasPi-IoT"; const char* password = "<PASSWORD>"; /* Parameters for MQTT connection to ThingSpeak Read more: https://thingspeak.com/ */ /* The username could be whatever you want*/ char mqttUserName[] = "testUserName"; /* Change this to your MQTT API Key (Account -> MyProfile)*/ char mqttPass[] = "YourMQTTAPIKey"; /* Change to your channel Write API Key (Channels -> MyChannels -> APIKeys) */ char writeAPIKey[] = "YourWriteAPIKey"; /* Change it to your own ChannelID (Channels -> MyChannels) */ long channelID = 123456; // /* This is used for the random generation of the clientID */ static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; // For random generation of client ID. /* The initialization of the Wifi Client Library and the PubSubClient library. The PubSubClient library offers an Arduino client for MQTT. Finally, we define the ThingSpeak MQTT broker. Read more: https://www.arduino.cc/en/Reference/WiFiClient https://pubsubclient.knolleary.net/api.html#state */ WiFiClient client; PubSubClient mqttClient(client); const char* mqttServer = "mqtt.thingspeak.com"; /* Define other global variables to track the last connection time and to define the time interval to publish the data. In this example we will post data in every 60 seconds, but you can modify it according to your needs */ unsigned long lastConnectionTime = 0; const unsigned long postingInterval = 60L * 1000L; /* Creating orchRequest message. The backslash (\) escape character turns special characters into string characters; You could read more about the orchestration request in Arrowhead Orchestration M3 IDD-REST-JSON-TLS document: https://github.com/hegeduscs/arrowhead/tree/M3/documentation/Orchestrator */ String reqSys = String("\"requesterSystem\": {\"systemName\": \"client1\",\"address\": \"localhost\",\"port\": 0},"); String reqSrv = String("\"requestedService\": {\"serviceDefinition\": \"IndoorTemperature\",\"interfaces\": [\"json\"],\"serviceMetadata\": {\"unit\": \"celsius\"}},"); String orchFlags = String("\"orchestrationFlags\": {\"overrideStore\": true, \"metadataSearch\": true, \"enableInterCloud\": true}"); String orchRequest = String("{") + reqSys + reqSrv + orchFlags + String("}"); /* The orchestrated service endpoint */ String endpoint = String(""); /* We define a DHT sensor. You must modify this section according to your sensors! */ #define DHT_PIN 0 DHT dht(DHT_PIN, DHT11); /* ArduinoJson library uses a fixed memory allocation, allowing to work on devices with very little RAM. In this example we choose to store data in the stack. You have the opportunity to use heap instead of the stack. ArduinoJson is a header-only library, meaning that all the code is the headers. This greatly simplifies the compilation as you don’t have to worry about compiling and linking the library. Read more and see examples: https://arduinojson.org/ */ StaticJsonBuffer<1000> JSONBuffer; StaticJsonBuffer<500> JSONBuffer_srv; /* In this function we will request an orchestration from the Orchestrator System. The POST request will be sent with the help of the HTTPClient library Read more: https://github.com/hegeduscs/arrowhead/tree/M3/documentation/Orchestrator https://www.arduino.cc/en/Tutorial/HttpClient */ void sendOrchReq(String &endpoint , String request_name , String unit ) { Serial.println("Sending orchestration request with the following payload:"); Serial.println(orchRequest); HTTPClient http_orch; /*You can modify the IP address and the associated port according to your system's data, if needed. */ http_orch.begin("http://192.168.42.1:8440/orchestrator/orchestration"); /* Specifying the content-type header */ http_orch.addHeader("Content-Type", "application/json"); /* Sending the actual POST request with the payload what is specified above.The return value will be an HTTP code.*/ int httpResponseCode_orch = http_orch.POST(String(orchRequest)); /* Getting the response to the request and then printing it for verification purposes. The printing step may omitted.*/ String orch_response = http_orch.getString(); Serial.println("Orchestration Response:"); Serial.println(orch_response); http_orch.end(); /* Parsing the orchestration response with the help of the ArduinoJSON library. The response is an error message, if the orchestration process failed (e.g. there is no proper system that can serve our request). */ JsonObject& root = JSONBuffer.parseObject(orch_response); if (!root.containsKey("errorMessage")) { /* The address, port and uri variables belong to the provider system which provides the requested service for us. The endpoint is a concatenated URL which leading exactly to the requested service. */ const char* address = root["response"][0]["provider"]["address"]; const char* port = root["response"][0]["provider"]["port"]; const char* uri = root["response"][0]["serviceURI"]; endpoint = "http://" + String(address) + ":" + String(port) + "/" + String(uri); Serial.println("Received endpoint, connecting to: " + endpoint); } else { Serial.println("Orchestration failed!"); } } /* Generally the setup() function initializes and sets the initial values The setup() function will only run once, after each powerup or reset of the Arduino board. */ void setup() { /* Initialize serial and wait for port to open */ Serial.begin(115200); delay(1000); /* Building up a wifi connection and accessing the network. This section can be used without modification. Read more: https://www.arduino.cc/en/Reference/WiFiStatus */ WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } Serial.print("Connected, my IP is:"); Serial.println(WiFi.localIP()); /* Set the MQTT Broker details: host and port */ mqttClient.setServer(mqttServer, 1883); /* Send the orchestration request. */ sendOrchReq(endpointTemp, "Temperature", "celsius"); } /* This function implements the reconnection to MQTT Broker It contains a loop what continuously trying to connect until we succeed. */ void reconnect() { char clientID[10]; while (!mqttClient.connected()) { Serial.print("Attempting MQTT connection..."); /* Generate a random ClientID based on alphanum global variable.*/ for (int i = 0; i < 8; i++) { clientID[i] = alphanum[random(51)]; } /* This character is very important, beacuse clientID strings are terminated with a null character (ASCII code 0). */ clientID[8] = '\0'; /* Connect to the MQTT Broker */ if (mqttClient.connect(clientID, mqttUserName, mqttPass)) { Serial.println("connected"); } else { Serial.print("failed, rc="); /* Printing the cause of the failure. For the failure code explanation visit this site: http://pubsubclient.knolleary.net/api.html#state */ Serial.print(mqttClient.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } /* This function implements the publish to the channel (ThingSpeak). */ void mqttpublish() { /* Reading some data from sensor. You should modify it according to you sensors. */ float temp = dht.readTemperature(); float hum = dht.readHumidity(); /* Create data string to send to ThingSpeak. You could concatenate as many fields as you want (or as you have) */ String data = String("field1=" + String(temp, DEC) + "&field2=" + String(hum, DEC)); int length = data.length(); char msgBuffer[length]; data.toCharArray(msgBuffer, length + 1); Serial.println(msgBuffer); /* Create a topic string and publish data to ThingSpeak channel feed. */ String topicString = "channels/" + String( channelID ) + "/publish/" + String(writeAPIKey); length = topicString.length(); char topicBuffer[length]; topicString.toCharArray(topicBuffer, length + 1); mqttClient.publish( topicBuffer, msgBuffer ); lastConnectionTime = millis(); } /* Finally in this section we will use the orchestrated service. The service can be invoked with a simple REST call. Generally the loop() function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond. Use it to actively control the Arduino board. */ void loop() { /* Reconnect if MQTT client is not connected. */ if (!mqttClient.connected()) { reconnect(); } /* We should call the loop continuously to establish connection to the server.*/ mqttClient.loop(); /* If interval time has passed since the last connection, publish data to ThingSpeak */ if (millis() - lastConnectionTime > postingInterval) { mqttpublish(); } if (endpoint != "") { HTTPClient http_srv; http_srv.begin(endpoint); /* Specifying the content-type header */ http_srv.addHeader("Content-Type", "application/json"); /* Sending the actual GET request with the payload what is specified above.The return value will be an HTTP code.*/ int httpResponseCode_srv = http_srv.GET(); /* Getting the response to the request and then printing it for verification purposes. The printing step may omitted.*/ String srv_response = http_srv.getString(); Serial.println("Service Response:"); Serial.println(srv_response); http_srv.end(); /* Parsing the service response with the help of the ArduinoJSON library. In additon we will use the SenML (Sensor Markup Language) that aims to simplify gathering data from different devices across the network The "e" imply an event. The event object inside the events array contain a "v" field, which is a numeric value. In this example this is the actual temperature. Read more more about SenML: https://wiki.tools.ietf.org/id/draft-jennings-core-senml-04.html: */ JsonObject& srv_root = JSONBuffer_srv.parseObject(srv_response); const char* temp_raw = srv_root["e"][0]["v"]; String temp_str = String(temp_raw); Serial.println(""); Serial.println("The temperature is " + temp_str + "°C."); JSONBuffer_srv.clear(); delay(5000); } else { Serial.println("No endpoint to connect to!"); } } <file_sep>/* This is a skeleton and a reference application for a simple Arrowhead-compliant providing system. Read more about Arrowhead Framework: http://www.arrowhead.eu/ Here you can download the Arrowhead G3.2 Framework (Milestone 3): https://github.com/hegeduscs/arrowhead */ #include <WiFi.h> #include <HTTPClient.h> #include <FS.h> #include <AsyncTCP.h> #include <ESPAsyncWebServer.h> #include <NTPClient.h> #include <WiFiUdp.h> #include "DHTesp.h" /* We manage the time with the help of the NTPClient library. Read more and see examples: https://www.arduinolibraries.info/libraries/ntp-client */ #define NTP_OFFSET 1 * 60 * 60 // In seconds #define NTP_INTERVAL 60 * 1000 // In miliseconds #define NTP_ADDRESS "0.pool.ntp.org" / #define SERVER_PORT 8454 /* These two variables are required to access Wifi. Obviously, the values need to be changed according to our own data. */ const char* ssid = "Arrowhead-RasPi-IoT"; const char* password = "<PASSWORD>"; /* Parameters for MQTT connection to ThingSpeak Read more: https://thingspeak.com/ */ /* The username could be whatever you want*/ char mqttUserName[] = "testUserName"; /* Change this to your MQTT API Key (Account -> MyProfile)*/ char mqttPass[] = "YourMQTTAPIKey"; /* Change to your channel Write API Key (Channels -> MyChannels -> APIKeys) */ char writeAPIKey[] = "YourWriteAPIKey"; /* Change it to your own ChannelID (Channels -> MyChannels) */ long channelID = 123456; // /* This is used for the random generation of the clientID */ static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; // For random generation of client ID. /* The initialization of the Wifi Client Library and the PubSubClient library. The PubSubClient library offers an Arduino client for MQTT. Finally, we define the ThingSpeak MQTT broker. Read more: https://www.arduino.cc/en/Reference/WiFiClient https://pubsubclient.knolleary.net/api.html#state */ WiFiClient client; PubSubClient mqttClient(client); const char* mqttServer = "mqtt.thingspeak.com"; /* Define other global variables to track the last connection time and to define the time interval to publish the data. In this example we will post data in every 60 seconds, but you can modify it according to your needs */ unsigned long lastConnectionTime = 0; const unsigned long postingInterval = 60L * 1000L; /* The ServiceRegistryEntry strings which will used to register our services to Service Registry. You should modify this part according to your own services. Read more and see example ServiceRegistryEntry payloads in Arrowhead ServiceDiscovery M3 IDD REST-JSON-TLS.docx: https://github.com/hegeduscs/arrowhead/tree/M3/documentation/ServiceRegistry */ String SRentry1 = String("{\"providedService\":{\"serviceDefinition\": \"IndoorTemperature\",\"interfaces\": [\"json\"],\"serviceMetadata\": {\"unit\": \"celsius\"}},\"provider\": {\"systemName\": \"InsecureTemperatureSensor\",\"address\":\""); String SRentry2 = String("\",\"port\": 8454},\"port\": 8454,\"serviceURI\": \"temperature\",\"version\": 1}"); String senml_1 = String("{\"bn\": \"TemperatureSensors_InsecureTemperatureSensor\",\"bt\":"); //"base timestamp String senml_2 = String(",\"bu\": \"celsius\",\"ver\": 1,\"e\": [{\"n\": \"Temperature_IndoorTemperature\",\"v\":"); //+value String senml_3 = String(",\"t\":0}]}"); AsyncWebServer server(SERVER_PORT); WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, NTP_ADDRESS, NTP_OFFSET, NTP_INTERVAL); /* Initialize DHT sensor. This part will change in your code. */ DHTesp dht; /* This function implements the registering to the Service Registry. The Service Registry is one of the base systems in the Arrowhead Framework. If the service creation is failed, then you should remove your service and after reregister it as it shown below. Read more: https://github.com/hegeduscs/arrowhead/tree/M3/documentation/ServiceRegistry These registered service can be searched from Table service_registry and here we also have the opportunity to modify them. The databes can be managed and accessed easily through the internet using the phpMyAdmin tool. Read more: https://www.phpmyadmin.net/ */ void registerService(String SRentry) { HTTPClient http_sr; /* You can modify the IP address and the associated port according to your system's data, if needed.*/ http_sr.begin("http://192.168.42.1:8442/serviceregistry/register"); /* Specifying the content-type header */ http_sr.addHeader("Content-Type", "application/json"); /* Sending the actual POST request with the payload what is specified above.The return value will be an HTTP code.*/ int httpResponseCode_sr = http_sr.POST(String(SRentry)); Serial.print("Registered to SR with status code:"); Serial.println(httpResponseCode_sr); /* Free resources. */ http_sr.end(); if (httpResponseCode_sr != HTTP_CODE_CREATED) { HTTPClient http_remove; /* Sending the actual PUT request. */ http_remove.begin("http://192.168.42.1:8442/serviceregistry/remove"); //Specify destination for HTTP request /* Specifying the content-type header */ http_remove.addHeader("Content-Type", "application/json"); /* Sending the actual PUT request with the payload what is specified above.The return value will be an HTTP code.*/ int httpResponseCode_remove = http_remove.PUT(String(SRentry)); //Send the actual PUT request Serial.print("Removed previous entry with status code:"); Serial.println(httpResponseCode_remove); /* Getting the response to the request and then printing it for verification purposes. The printing step may omitted.*/ String response_remove = http_remove.getString(); Serial.println(response_remove); /* Free resources. */ http_remove.end(); delay(1000); HTTPClient http_renew; http_renew.begin("http://192.168.42.1:8442/serviceregistry/register"); /* Specifying the content-type header */ http_renew.addHeader("Content-Type", "application/json"); /* Sending the actual POST request with the payload what is specified above.The return value will be an HTTP code.*/ int httpResponseCode_renew = http_renew.POST(String(SRentry)); Serial.print("Re-registered with status code:"); Serial.println(httpResponseCode_renew); /* Getting the response to the request and then printing it for verification purposes. The printing step may omitted.*/ String response_renew = http_renew.getString(); Serial.println(response_renew); /* Free resources. */ http_renew.end(); //Free resources } /* Generally the setup() function initializes and sets the initial values The setup() function will only run once, after each powerup or reset of the Arduino board. */ void setup() { /* Initialize serial and wait for port to open */ Serial.begin(115200); delay(1000); //Delay needed before calling the WiFi.begin /* Building up a wifi connection and accessing the network. This section can be used without modification. Read more: https://www.arduino.cc/en/Reference/WiFiStatus */ WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } Serial.print("Connected, my IP is:"); Serial.println(WiFi.localIP()); /* Set the MQTT Broker details: host and port */ mqttClient.setServer(mqttServer, 1883); /* Building ServiceRegistryEntry and register our service to Service Registry. */ String SRentry = SRentry1 + WiFi.localIP().toString() + SRentry2; registerService(SRentry); /* Initialize NTP connection. */ timeClient.begin(); } /* Starting the DHT sensor on PIN0. You should modify it accourding to your setup*/ dht.setup(0); /* Starting a web server which will response to the REST calls. We may create more web server to the different services. */ server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest * request) { Serial.println("Received HTTP request, responding with:"); unsigned long currentTime = timeClient.getEpochTime(); /* Reading some data from sensor. You should modify it according to you sensors. */ float temperature = dht.getTemperature(); String response = senml_1 + currentTime + senml_2 + temperature + senml_3; Serial.print(response); request->send(200, "application/json", response); }); server.begin(); /* Prepare LED pin. */ pinMode(LED_BUILTIN, OUTPUT); } /* This function implements the reconnection to MQTT Broker It contains a loop what continuously trying to connect until we succeed. */ void reconnect() { char clientID[10]; while (!mqttClient.connected()) { Serial.print("Attempting MQTT connection..."); /* Generate a random ClientID based on alphanum global variable.*/ for (int i = 0; i < 8; i++) { clientID[i] = alphanum[random(51)]; } /* This character is very important, beacuse clientID strings are terminated with a null character (ASCII code 0). */ clientID[8] = '\0'; /* Connect to the MQTT Broker */ if (mqttClient.connect(clientID, mqttUserName, mqttPass)) { Serial.println("connected"); } else { Serial.print("failed, rc="); /* Printing the cause of the failure. For the failure code explanation visit this site: http://pubsubclient.knolleary.net/api.html#state */ Serial.print(mqttClient.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } /* This function implements the publish to the channel (ThingSpeak). */ void mqttpublish() { /* Reading some data from sensor. You should modify it according to you sensors. */ float temp = dht.readTemperature(); float hum = dht.readHumidity(); /* Create data string to send to ThingSpeak. You could concatenate as many fields as you want (or as you have) */ String data = String("field1=" + String(temp, DEC) + "&field2=" + String(hum, DEC)); int length = data.length(); char msgBuffer[length]; data.toCharArray(msgBuffer, length + 1); Serial.println(msgBuffer); /* Create a topic string and publish data to ThingSpeak channel feed. */ String topicString = "channels/" + String( channelID ) + "/publish/" + String(writeAPIKey); length = topicString.length(); char topicBuffer[length]; topicString.toCharArray(topicBuffer, length + 1); mqttClient.publish( topicBuffer, msgBuffer ); lastConnectionTime = millis(); } /* Finally in this section we will blink 1 kHz if everything is set up and connect to MQTT Broker. Generally the loop() function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond. Use it to actively control the Arduino board. */ int ledStatus = 0; void loop() { /* Reconnect if MQTT client is not connected. */ if (!mqttClient.connected()) { reconnect(); } /* We should call the loop continuously to establish connection to the server.*/ mqttClient.loop(); /* If interval time has passed since the last connection, publish data to ThingSpeak */ if (millis() - lastConnectionTime > postingInterval) { mqttpublish(); } timeClient.update(); if (ledStatus) { digitalWrite(LED_BUILTIN, HIGH); ledStatus = 0; } else { digitalWrite(LED_BUILTIN, LOW); ledStatus = 1; } delay(1000); } <file_sep># Arrowhead-Ref-App This is a skeleton and a reference application for simple Arrowhead-compliant systems.
e66222b96ec5935041978164d25d06d5aa51d37e
[ "Markdown", "C++" ]
3
C++
tramuntana/Arrowhead-Ref-App
9568de8913a9086f2471a1367581f3e3675472d1
7b9d9fd6da74a35ea33063d7816503043274806c
refs/heads/master
<repo_name>santerihanninen/markdown-thesis<file_sep>/README.md # markdown-thesis A simple setup I used to write my thesis in Markdown and export it to a PDF with Pandoc. The purpose is to be able to use Latex's citation and typography abilities without having to bother with its tedious syntax. Configuration happens mostly in `build.sh`. The PDF is generated with LuaTeX (`--pdf-engine=lualatex`) to allow the use of non-TeX fonts (e.g. OTF). LaTeX template is extracted to `config/default.latex` for editing. ![alt text](https://i.imgur.com/4T1ydpJ.png "output.pfd ") ## Installation ```bash # download latest pandoc release from https://github.com/jgm/pandoc/releases/latest $ sudo dpkg -i $DEB # "where $DEB is the path to the downloaded deb. This will install the pandoc and pandoc-citeproc executables and man pages." $ sudo apt-get update $ sudo apt-get -y install texlive python-pip texlive-luatex $ sudo pip install pandoc-latex-fontsize $ chmod +x ./build.sh $ ./build.sh ``` ## Usage Write chapters in `input/02-chapters/` and run `build.sh` to generate `output.pdf` in the root. Pandoc's Markdown syntax: ```pandoc <!-- Citations --> @march1971 [p. 28] <!-- Figures --> See figure \ref{graph-wright}. ![Figure title[@march1971, p. 27]\label{graph-wright}](input/figures/march1971p27f1.13.png "Wright house plans") <!-- Quotes, class is used for pandoc-latex-fontsize--> <div class="quote"> > Whilst they may look different, they are in fact topologically equivalent.[@march1971, p. 28] </div> ``` See [Pandoc User's Guide](https://pandoc.org/MANUAL.html). ## License [MIT](https://choosealicense.com/licenses/mit/) <file_sep>/build.sh #!/bin/bash pandoc input/*/*.md \ -V papersize:a4 \ -V documentclass:scrreprt \ -V classoption:egregdoesnotlikesansseriftitles \ -V bibliography=openstyle \ -V fontsize:11pt \ -V header-includes:'\setmainfont[Path = config/, BoldFont = ACaslonPro-Semibold.otf, ItalicFont = ACaslonPro-Italic.otf]{ACaslonPro-Regular.otf}' \ -V title:"Title" \ -V subtitle:"Subtitle" \ -V author:"Author" \ --table-of-contents \ -V date:"\today" \ -V linestretch:1.1 \ -V parskip:50pt \ -V hyphenate:true \ -V margin-left=5cm \ -V margin-right=5cm \ -V margin-top=2.5cm \ -V margin-bottom=2.5cm \ -V indent \ --template ./config/default.latex \ --filter pandoc-latex-fontsize \ --metadata link-citations=true \ --bibliography ./input/references.bib \ --filter pandoc-citeproc \ --csl ./config/chicago-note-bibliography.csl \ --pdf-engine=lualatex \ -o ./output.pdf <file_sep>/input/03-end-matter/01-bibliography.md # Bibliography <!-- invert indentation to keep entries on the left --> \indent \setlength{\parindent}{-0.2in} \setlength{\leftskip}{0.2in}<file_sep>/input/01-front-matter/00-latex.md --- pandoc-latex-fontsize: - classes: [quote, code] size: small linestretch: 1.0 --- <file_sep>/input/02-chapters/01-introduction.md # Introduction <div class="quote"> > Whilst they may look different, they are in fact topologically equivalent.[@march1971, p. 28] </div> <!-- This is a comment --> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam est orci, eleifend ut nibh sed, tristique porttitor risus. Fusce lobortis luctus mauris hendrerit auctor. Mauris porta ac neque ac vulputate. Vivamus id tortor posuere, ullamcorper nisl mattis, sodales mauris. Nulla sodales elit sed risus pulvinar consequat. Praesent quis pharetra nunc. In vehicula lectus lorem, ultricies commodo nibh vestibulum nec. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In at arcu placerat, scelerisque sem eu, interdum ligula. Mauris a lacinia ipsum. Integer tincidunt venenatis mi ut scelerisque. Duis aliquet hendrerit sapien ac placerat. Vivamus at egestas urna, scelerisque venenatis ante. Integer id rhoncus erat, vitae suscipit libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. See figure \ref{graph-wright}. ![Figure title[@march1971, p. 27]\label{graph-wright}](input/figures/march1971p27f1.13.png "Wright house plans")
b553e5db654eaea289632470ade282c4d6db99d1
[ "Markdown", "Shell" ]
5
Markdown
santerihanninen/markdown-thesis
e501b5eaf26f90a98248afb202d4d9fd3359a435
983bf52dea0a5f2732cd801281d0bf0310392494
refs/heads/master
<file_sep>package com.sprint.ride_along; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Spinner; public class DriverActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_driver); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_Driver); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } Spinner spinnerModels = (Spinner) findViewById(R.id.spinner_Models); ArrayAdapter<CharSequence> adapterModels = ArrayAdapter.createFromResource( this, R.array.models_array, android.R.layout.simple_spinner_item ); adapterModels.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerModels.setAdapter(adapterModels); Spinner spinnerSeats = (Spinner) findViewById(R.id.spinner_Seats); ArrayAdapter<CharSequence> adapterSeats = ArrayAdapter.createFromResource( this, R.array.seats_array, android.R.layout.simple_spinner_item ); adapterSeats.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerSeats.setAdapter(adapterSeats); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } public void driverMap(View view){ Intent intent = new Intent(this, DriverMapActivity.class); startActivity(intent); } }
1f9ac408a059f887d0e41c2834d1391f4b4810f2
[ "Java" ]
1
Java
AntonioSoto/ride-along
196f11764222551fd30f0432f72b5faff6557350
23ff5b05d2e2b5f7b7ba9cb66a42157c5f38397e
refs/heads/development
<repo_name>odekyc/FunFinder<file_sep>/public/script/social/socialService.js angular.module('funfinder.social')<file_sep>/public/script/volunteer/volunteerService.js angular.module('funfinder.volunteer')<file_sep>/public/script/entertain/entertainService.js angular.module('funfinder.entertain')
6fc72014ddde4d09bbd2f34feedfdaf5e637b3ca
[ "JavaScript" ]
3
JavaScript
odekyc/FunFinder
67d7b0a01a00055d3762e081893acdd40291ce5a
9ea1514e973e41501cb64456d6b4450968a2da3a
refs/heads/master
<repo_name>dafurApp/myAugmentedReality<file_sep>/myAugmentedReality/ViewController.swift // // ViewController.swift // myAugmentedReality // // Created by <NAME> on 06.02.19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import SceneKit import ARKit class ViewController: UIViewController, ARSCNViewDelegate { @IBOutlet var sceneView: ARSCNView! private var hud :MBProgressHUD! override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = true // Create a new scene let scene = SCNScene() // Set the scene to the view sceneView.scene = scene } //MARK: gets fired when a plane is detected func renderer(_renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor){ if anchor is ARPlaneAnchor{ // Is the detected anchor a plane: DispatchQueue.main.sync{ //does not run in the background) self.hud.label.text = "Plane detected" self.hud.hide(animated: true, afterDelay: 1.0) } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Create a session configuration - Plane detection let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = .horizontal // Run the view's session sceneView.session.run(configuration) //Detect a plane } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session sceneView.session.pause() } //MARK: renderer - gets fired, when a plane is detected func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { if anchor is ARPlaneAnchor { DispatchQueue.main.async { self.hud.label.text = "Plane Detected" self.hud.hide(animated: true, afterDelay: 1.0) } } } // MARK: - ARSCNViewDelegate /* // Override to create and configure nodes for anchors added to the view's session. func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { let node = SCNNode() return node } */ func session(_ session: ARSession, didFailWithError error: Error) { // Present an error message to the user } func sessionWasInterrupted(_ session: ARSession) { // Inform the user that the session has been interrupted, for example, by presenting an overlay } func sessionInterruptionEnded(_ session: ARSession) { // Reset tracking and/or remove existing anchors if consistent tracking is required } }
ce4cc09453640d12de0b5fd54379e96008f53956
[ "Swift" ]
1
Swift
dafurApp/myAugmentedReality
26eb78f9d705f9e9b6b55ec84d2504189b751ac6
a4b8e00b407c8e46cc36adcf8d7b74352ac04273
refs/heads/master
<file_sep>import React from "react"; import styles from "./Item.module.scss"; import ItemImage from "../../Assets/Images/image1.png"; import { Link } from "react-router-dom"; function Item({ itemDetails, loading }) { return ( <> <Link to="/detail" className={styles.link}> <div className={styles.card}> <img src={ItemImage} alt="title" className={styles.image} /> <div className={styles.info}> <div className={styles.row}> <div className={styles.title}>regular / child</div> <div className={styles.price}>free</div> </div> <div className={styles.category}>category</div> <div className={styles.detail}>Lorem ipsum dolor sit amet.</div> </div> </div> </Link> <div className={styles.card}> <img src={ItemImage} alt="title" className={styles.image} /> <div className={styles.info}> <div className={styles.row}> <div className={styles.title}>regular / child</div> <div className={styles.price}>$ 6.00</div> </div> <div className={styles.category}>category</div> <div className={styles.detail}>Lorem ipsum dolor sit amet.</div> </div> </div> </> ); } export default Item; <file_sep>import React from "react"; import styles from "./Categories.module.scss"; function Categories({ categories, loading }) { return ( <> <div className={styles.home}> <div className={styles.browse}>browse</div> <div className={styles.categories}> <div className={styles.active}>admissions</div> <div>tours</div> <div>events</div> <div>programmes</div> </div> </div> </> ); } export default Categories;
b8d3a9f80343fa40b3839387433e6fa20cd3e442
[ "JavaScript" ]
2
JavaScript
gilbertliem/vouch
8910ba7108599af4799190cc2d21ad235abc0762
6b6ef84de2890d4cbc28cdcf597790012b1b50b2
refs/heads/develop
<file_sep>## Deploy and configure Context-Aware Configuration in AEM [Apache Sling Context-Aware Configuration][sling-caconfig] is part of the AEM product since version 6.3. You can also use it in AEM 6.1 or 6.2 by deploying the required bundles and adding some basic configuration. And if you want to use the latest features provided by [wcm.io Context-Aware Configuration][wcmio-caconfig] you need to deploy some updated bundles from Sling in AEM 6.3 as well. ### Apache Sling Context-Aware Configuration Bundles Links to the latest versions of Apache Sling Context-Aware Configuration bundles: |---|---|---| | [Apache Sling Context-Aware Configuration API](https://maven-badges.herokuapp.com/maven-central/org.apache.sling/org.apache.sling.caconfig.api) | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.apache.sling/org.apache.sling.caconfig.api/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.apache.sling/org.apache.sling.caconfig.api) | | [Apache Sling Context-Aware Configuration SPI](https://maven-badges.herokuapp.com/maven-central/org.apache.sling/org.apache.sling.caconfig.spi) | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.apache.sling/org.apache.sling.caconfig.spi/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.apache.sling/org.apache.sling.caconfig.spi) | | [Apache Sling Context-Aware Configuration Implementation](https://maven-badges.herokuapp.com/maven-central/org.apache.sling/org.apache.sling.caconfig.impl) | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.apache.sling/org.apache.sling.caconfig.impl/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.apache.sling/org.apache.sling.caconfig.impl) | | [Apache Johnzon Wrapper Library](https://maven-badges.herokuapp.com/maven-central/org.apache.sling/org.apache.sling.commons.johnzon) | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.apache.sling/org.apache.sling.commons.johnzon/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.apache.sling/org.apache.sling.commons.johnzon) | ### Deploying Sling Context-Aware Configuration to AEM 6.1 or AEM 6.2 In AEM 6.1 or AEM 6.2 you need to deploy the latest version of these Sling bundles: * `org.apache.sling:org.apache.sling.caconfig.api` * `org.apache.sling:org.apache.sling.caconfig.spi` * `org.apache.sling:org.apache.sling.caconfig.impl` * `org.apache.sling:org.apache.sling.commons.johnzon` The Default Context Path Strategy needs an additional configuration to support `sling:configRef` properties stored in `jcr:content` subnodes of AEM content pages: ``` org.apache.sling.caconfig.resource.impl.def.DefaultContextPathStrategy configRefResourceNames=["jcr:content"] ``` You should also extend the filter settings for ignoring property names when reading and writing configuration data to also exclude properties with the `cq:` namespace: ``` org.apache.sling.caconfig.management.impl.ConfigurationManagementSettingsImpl ignorePropertyNameRegex=["^(jcr|cq):.+$"] ``` If you want to use the Web Console plugin for Sling Context-Aware configuration you also need to create a system user which has read access to `/conf` and `/content` and add an service user mapping for this user (named `sling-caconfig` in this example): ``` org.apache.sling.serviceusermapping.impl.ServiceUserMapperImpl.amended-sling-caconfig user.mapping=["org.apache.sling.caconfig.impl\=sling-caconfig"] ``` ### Updating Sling Context-Aware Configuration in AEM 6.3 In AEM 6.3 you should check which versions of the bundles mentioned above are already installed. If you have no service pack installed you need to update at least the SPI and Impl bundle to the latest version: * `org.apache.sling:org.apache.sling.caconfig.spi` * `org.apache.sling:org.apache.sling.caconfig.impl` * `org.apache.sling:org.apache.sling.commons.johnzon` The additional configuration steps for AEM 6.1 and 6.2 are not required for AEM 6.3 because they are already included, except this one: ``` org.apache.sling.caconfig.management.impl.ConfigurationManagementSettingsImpl ignorePropertyNameRegex=["^(jcr|cq):.+$"] ``` [sling-caconfig]: http://sling.apache.org/documentation/bundles/context-aware-configuration/context-aware-configuration.html [wcmio-caconfig]: http://wcm.io/caconfig/ <file_sep>/* * #%L * wcm.io * %% * Copyright (C) 2016 wcm.io * %% * 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. * #L% */ (function (angular) { "use strict"; angular.module("io.wcm.caconfig.modals", [ "io.wcm.caconfig.templates", "io.wcm.caconfig.utilities", "textAngular" ]) .config(['$provide', function ($provide) { $provide.decorator('taOptions', ['$delegate', function (taOptions) { taOptions.toolbar = [ ['h1', 'h2', 'h3', 'h4', 'p', 'pre', 'quote'], ['bold', 'italics', 'underline', 'strikeThrough', 'ul', 'ol', 'redo', 'undo', 'clear'], ['justifyLeft', 'justifyCenter', 'justifyRight', 'indent', 'outdent'], ['html','insertLink', 'wordcount', 'charcount'] ]; return taOptions; }]); }]) .run(initRun); initRun.$inject = ["$rootScope"]; function initRun($rootScope) { $rootScope.modalTemplates = { addCollectionItem: "addCollectionItemModal.html", addConfig: "addConfigModal.html", deleteConfig: "deleteConfigModal.html", error: "errorModal.html", saveConfig: "saveConfigModal.html", editor: "editorModal.html" }; } }(angular)); <file_sep>/* * #%L * wcm.io * %% * Copyright (C) 2016 wcm.io * %% * 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. * #L% */ (function (angular) { "use strict"; angular.module("io.wcm.caconfig.widgets") .directive("caconfigRichtexteditor", richtexteditor); richtexteditor.$inject = ["templateUrlList", "modalService"]; function richtexteditor(templateList, modalService) { var directive = { restrict: "E", replace: true, require: "^form", templateUrl: templateList.richtexteditor, scope: { parameter: "=caconfigParameter", isConfigInherited: "=caconfigIsConfigInherited" }, link: link }; return directive; function link(scope, element, attr, form) { scope.openPopup = function () { var modal_instance = modalService.getComponent(modalService.modal.EDITOR); modalService.setEditorValue(scope.parameter.value); var save = function(e, data) { form.$setDirty(true); scope.parameter.value = data.content; modal_instance.off('saved', scope.save); }; modal_instance.show(); modal_instance.on('saved', save); }; } } }(angular));
ee6783c2ad95477e71e3884babb255142d202b5a
[ "Markdown", "JavaScript" ]
3
Markdown
shadyeltobgy/wcm-io-caconfig
d7de835eba36e57d0419e0719c1e15059d1385e7
6b784d12210f1476c98fcdb15dcea9defd894200
refs/heads/master
<repo_name>MD-Shibli-Mollah/jsCodes<file_sep>/main.js //alert(greetz); //call(), apply(), bind() var person = { firstname: "<NAME>", lastname: "Mollah", getFullName: function () { //not global var fullname = this.firstname + " " + this.lastname; return fullname; } } var logName = function(lang1, lang2) { console.log ('logged ' + this.getFullName()); console.log(lang1 + " " + lang2); //looks for global } //var logn = logName.bind(person); //bind(), function isn't called logName.call(person, 'en', 'es'); //function is called logName.apply(person, ['en', 'bl']);//works as same as call but takes the arguments as array. //var logPersonName = logName.bind(person); //logPersonName(); //function currying function mul(a, b) { return a * b; } mul2 = mul.bind(this, 5); mul3 = mul.bind(this, 3); b = mul3(2); a = mul2(7); console.log(a); console.log(b); //proto var person = { firstname: "default", lastname: "Default", getFullName: function () { return this.firstname + ' ' + this.lastname; } } var shibli = { firstname: 'MD', lastname: 'Mollah' } shibli.__proto__ = person;//for demo purpose only console.log(shibli.getFullName()); // OBject from FUNCTION function Person() { this.firstname = 'MD'; this.lastname = 'Mollah' } var shibli = new Person(); console.log(shibli); //FUNCTION CONSTRUCTOR function Person(firstname, lastname) { console.log(this); this.firstname = firstname; this.lastname = lastname; console.log("found"); } var shibli = new Person('MD', 'Mollah'); console.log(shibli); //latest***** if person is an object person = { firstname: 'default', lastname: 'default', greet: function() { return 'Hi' + this.firstname + ' ' + this.lastname; } } var john = Object.create(Person); console.log(john); class Person1 { constructor(firstname, lastname) { this.firstname = firstname; this.lastname = lastname; } greet() { return 'Hi' + firstname; } } var john = new Person1('John', 'Doe');
f6b8ed167d9e7df7fee6edfa213f4cfdabcfc645
[ "JavaScript" ]
1
JavaScript
MD-Shibli-Mollah/jsCodes
770be7f3c2afaa9ba62b956d113b55d06f51de7b
3f58fc87199a339d5a9f039776bf0d00a94d8f96
refs/heads/master
<repo_name>varungoel123/scrape_utils<file_sep>/chrome_launch.py from selenium import webdriver import random seconds = 5 + (random.random() * 5) path_to_chromedriver = '/Users/wanderlust/Documents/scraping_utils/chromedriver' browser = webdriver.Chrome(executable_path = path_to_chromedriver) url = 'http://lus.dacnet.nic.in/dt_lus.aspx' browser.get(url) time_elements = [ "1998-99", "1999-00"] state_elements = [ "01", "02"] for state in state_elements: for time in time_elements: browser.find_element_by_xpath('//*[@id="DropDownList1"]/option[@value=state]').click() browser.find_element_by_xpath('//*[@id="DropDownList2"]/option[contains(text(), time)]').click() browser.find_element_by_xpath('//*[@id="DropDownList3"]/option[contains(text(), "MS Excel")]').click() seconds = 5 + (random.random() * 5) browser.find_element_by_xpath('//*[@id="TreeView1t2"]').click() time.sleep(seconds) browser.find_element_by_xpath('//*[@id="TreeView1t4"]').click() time.sleep(seconds) browser.find_element_by_xpath('//*[@id="TreeView1t5"]').click() time.sleep(seconds) browser.find_element_by_xpath('//*[@id="TreeView1t6"]').click() time.sleep(seconds) browser.find_element_by_xpath('//*[@id="TreeView1t7"]').click() time.sleep(seconds) browser.find_element_by_xpath('//*[@id="TreeView1t9"]').click() time.sleep(seconds) browser.find_element_by_xpath('//*[@id="TreeView1t10"]').click() time.sleep(seconds) browser.find_element_by_xpath('//*[@id="TreeView1t11"]').click() time.sleep(seconds) browser.find_element_by_xpath('//*[@id="TreeView1t12"]').click() time.sleep(seconds) browser.find_element_by_xpath('//*[@id="TreeView1t13"]').click() time.sleep(seconds) browser.find_element_by_xpath('//*[@id="TreeView1t14"]').click() time.sleep(seconds)<file_sep>/samp1.py from selenium import webdriver import random seconds = 5 + (random.random() * 5) path_to_chromedriver = '/Users/wanderlust/Documents/scraping_utils/chromedriver' browser = webdriver.Chrome(executable_path = path_to_chromedriver) url = 'http://lus.dacnet.nic.in/dt_lus.aspx' browser.get(url) time_elements = [ "1998-99", "1999-00", "2000-01", "2001-02", "2002-03", "2003-04", "2004-05", "2005-06", "2006-07", "2007-08", "2008-09", "2009-10", "2010-11", "2011-12", "2012-13", "2013-14", "2014-15"] state_elements = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40"] for state in state_elements: for timep in time_elements: browser.find_element_by_xpath('//*[@id="DropDownList1"]/option[@value=' + state + ']').click() browser.find_element_by_xpath('//*[@id="DropDownList2"]/option[@value=' + '"' + timep + '"' ']').click() browser.find_element_by_xpath('//*[@id="DropDownList3"]/option[contains(text(), "MS Excel")]').click() browser.find_element_by_xpath('//*[@id="TreeView1t2"]').click() browser.find_element_by_xpath('//*[@id="TreeView1t4"]').click() browser.find_element_by_xpath('//*[@id="TreeView1t5"]').click() browser.find_element_by_xpath('//*[@id="TreeView1t6"]').click() browser.find_element_by_xpath('//*[@id="TreeView1t7"]').click() browser.find_element_by_xpath('//*[@id="TreeView1t9"]').click() browser.find_element_by_xpath('//*[@id="TreeView1t10"]').click() browser.find_element_by_xpath('//*[@id="TreeView1t11"]').click() browser.find_element_by_xpath('//*[@id="TreeView1t12"]').click() browser.find_element_by_xpath('//*[@id="TreeView1t13"]').click() browser.find_element_by_xpath('//*[@id="TreeView1t14"]').click()
c08be8fe72e43816538c5d8f2aa196b66ebc0c6a
[ "Python" ]
2
Python
varungoel123/scrape_utils
189c7e4fc9381da28b880c499538d9ffe4691690
4de1f56e0bdd9b18bb7af7369836642701d1eae5
refs/heads/master
<repo_name>antonrodin/medjsalg<file_sep>/sorted-union/sorted-union.js /** * Sorted Union, using the ...args variables, with this one you can pass any number of aruments to a function * @param {...any} args one or more array */ function uniteUnique(...args) { console.log(args); let res = []; args.forEach(element => { element.forEach(element => { if(res.indexOf(element) == -1) { res.push(element); } }); }); return res; } uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);<file_sep>/search-and-replace/app.js function myReplace(str, before, after) { // If first letter is capitalized if (before.charAt(0) != before.charAt(0).toLowerCase()) { after = after.charAt(0).toUpperCase() + after.slice(1); } let res = str.replace(before, after); console.log(res); return res; } myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"); myReplace("He is Sleeping on the couch", "Sleeping", "sitting");<file_sep>/dna-pairing/README.md Solution DNA Pairing from Free Code Camp ======================================== Get stuck the first ten minutes, because did not undestand quite well the problem. But like the previous one, too easy. You just loop through the string and create the pair. If the letter is "A" the pair is ["A", "T"], if the letter is "G" the pair is ["G", "C"] and so on... You just need to create the object like that: ```javascript let pairs = { A: "T", T: "A", C: "G", G: "C" }; // You can access to it like so, // to get the missing one pairs[str.charAt(1)]; ``` The eficiency of this one I belive is O(N), where N is the number of the letters in the string argument.<file_sep>/search-and-replace/README.md Seek and Destroy Algorithm from Free Code Camp ============================================== Very easy one, feels like I did it wrong. Why I should seek and destroy, when exists "replace" function in JavaScript. You just check for first capitalize letter and nothing more, in the before argument, for preserve it. Also the eficiency of this one is linear, actually depends of the complexity of the replace function. But it just O(1)... Feels strange, but it pass all test.<file_sep>/camel-case/README.md Solution for Spinal Case Algorithm from FreeCodeCamp ==================================================== Common string "beautify" for create preaty urls in the real world. Feels bad about this one, but it pass the test. I belive that exists better solutions and whole libraries for this matter, because its important. For example this one dont remove special chars like "!&$" and so on, also its dont work for spanish letters like Ñ... I guess the efficiency of this one is something like O(N + k) in the worst scenario it depends of functions like replace() and toLowerCase();<file_sep>/drop-it/drop-it.js function dropElements(arr, func) { // Drop them elements. let res = []; let found = false; let i = 0; while(!found && i < arr.length) { if(func(arr[i])) { found = true; } else { i++; } } res = arr.splice(i, arr.length); return res; } //console.log(dropElements([1, 2, 3, 4], function(n) {return n >= 3;})); console.log(dropElements([1, 2, 3], function(n) {return n < 3; }));<file_sep>/fibonacci/fib.js function sumFibs(num) { return num; } sumFibs(4);<file_sep>/camel-case/app.js function spinalCase(str) { //StripTags from HTML let re = /<\/?[^>]+(>|$)/g; str = str.replace(re, ""); let result = ""; let prev = ""; let curr = ""; let i = 0; while(i < str.length) { curr = str[i]; curr = (curr == "_") ? "-" : curr; if (curr != curr.toLowerCase()) { if(prev != "-" && prev != "") { curr = "-" + curr.toLowerCase(); } else { curr = curr.toLowerCase(); } } else if (curr == " ") { curr = "-"; } prev = curr; result += curr; i++; } return result; } spinalCase('Teletubbies say Eh-oh'); spinalCase('This Is Spinal Tap'); spinalCase('The_Andy_Griffith_Show'); spinalCase('thisIsSpinal<wbr>Tap');<file_sep>/seek-and-destroy/app1.js function destroyer(arr) { // Remove all the values for(let i = 1; i < arguments.length; i++) { let j = 0; while(j < arr.length) { if(arguments[i] == arr[j]) { arr.splice(j, 1); } else { j++; } } } return arr; } destroyer([3, 5, 1, 2, 2], 2, 3, 5);<file_sep>/whatIsInName/README.md Look inside object collection ============================= My solution I belive have O(N*M) complexity, like any common nested loop. No idea if there a way to add beter eficiency. Maybe if there some way to check for "object" equality, without doing a loop. ```javascript function whatIsInAName(collection, source) { let arr = []; let keys = Object.keys(source); collection.forEach(elem => { let found = false; let i = 0; while(!found && i < keys.length) { if(elem[keys[i]] != source[keys[i]]) { found = true; } i++; } if (!found) { arr.push(elem); } }); return arr; } ``` Look inside of an object collection and return an array off ojects that match the "key, value" pair provided in the second arguments.<file_sep>/pig-latin/app.js function translatePigLatin(str) { let i = 0; let curr = ""; let acum = ""; let rest = ""; let found = false; let re = /[aeiuo]/; //Run until found the fist vowel while(!found && i<str.length) { curr = str.charAt(i); console.log(); if (re.test(curr)) { found = true; } else { acum += curr; i++; } } //Get the rest of the string rest = str.slice(i); //If the i == 0 is true, the first is vowel and should add way if(i == 0) { str = rest + acum + "way"; } else { str = rest + acum + "ay"; } return str; } translatePigLatin("eight"); translatePigLatin("dgfgh"); translatePigLatin("consonant"); translatePigLatin("paragraphs"); translatePigLatin("ppppggthhht"); translatePigLatin("glove");<file_sep>/whatIsInName/app.js function whatIsInAName(collection, source) { let arr = []; let keys = Object.keys(source); collection.forEach(elem => { let found = false; let i = 0; while(!found && i < keys.length) { if(elem[keys[i]] != source[keys[i]]) { found = true; } i++; } if (!found) { arr.push(elem); } }); console.log(arr); // Only change code above this line return arr; } //One of the tests should return [{ first: "Tybalt", last: "Capulet" }]. whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }); //Other test should return [{ "apple": 1, "bat": 2, "cookie": 2 }]. whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 }); //Third Test should return [] whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3})<file_sep>/README.md Some algorithms from FreeCodeCamp ================================= My solutions for "Intermediate Algorithm Scripting" from the JavaScript Part, and small analisis for complexity of each one. Also its going to be a first day of #100daysOfCod, till I get more fun project to code. Why? Maybe because Im bored and why not. Always loved this kind of stuff in my degree... If you know better solution, you know what to do. You can find all the challenges here: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/ Kisses. Anton <file_sep>/pig-latin/README.md Pig Latin Algorithm =================== Had some problems with this one, the problem was about "Should handle words without vowels", the thing is that "Y" is not a vowel... Also the FreeCodeCamp is not perfect, still pass all test and the last one, did not throw any "error" or "hint" besides of the f*ing "Should handle...". ```javascript // Correct let re = /[aeiuo]/; // Not Correct let re = /[aeyiuo]/; ``` The complexity of this algorithm in the worst scenario is like O(N), for example if there are no vowels at all... In the better case, then the vowel is the first one, I belive is something like that O(1) or O(k). Also "googling" for my problem found solution with only REGEX in about two lines of code... But in my opinion the "readability" of that kind off code is awfull: ```javascript function translatePigLatin(str) { return str .replace(/^([aeiou])(.*)/, '$1$2way') .replace(/^([^aeiou]+)(.*)/, '$2$1ay'); } ``` Thx for all people in the forum and stackoverflow...
9774e7fc5d55b5e1404d76cd165f4e56fceac770
[ "JavaScript", "Markdown" ]
14
JavaScript
antonrodin/medjsalg
b5e82c8c834e13afdb9b41cc42bd97980634c8d4
ac1a94019c72ab999deb7d2ed148638017cf6813
refs/heads/main
<repo_name>kazparaz/tribe-payments-test<file_sep>/src/pages/api/_helpers.ts import { NextApiRequest } from 'next' export type CmcResponseStatus = { credit_count: number elapsed: number error_code: number error_message: string | null timestamp: string } export type CmcResponseError = { status: CmcResponseStatus } export const CMC_PRO_API_KEY = 'f519c4c4-a383-4bf9-846f-4ac26a85d562' export function queryParamsToString( params: Record<string, string | number> ): string { return Object.entries(params) .map((entry) => entry.join('=')) .join('&') } export function parseQueryParam( paramName: string, query: NextApiRequest['query'] ): string | undefined { const value = query[paramName] return typeof value === 'string' ? value : undefined } <file_sep>/src/styles/variables.ts export const baseFontSize = 16 export const colors = { white: '#fff', gray: '#666', purple: '#572c5f', red: 'red', green: 'green', } export const breakpoints = { mobile: 480, tablet: 700, } <file_sep>/src/pages/api/_getCmcInfo.ts import { CMC_PRO_API_KEY, CmcResponseError, CmcResponseStatus, queryParamsToString, } from './_helpers' // https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyInfo type CmcInfoQueryParams = { id: number[] } // Not all properties typed type CmcInfoResponseSuccess = { data: Record< string, | { id: string // The unique CoinMarketCap ID for this cryptocurrency. name: string // The name of this cryptocurrency. symbol: string // The ticker symbol for this cryptocurrency. slug: string // The web URL friendly shorthand version of this cryptocurrency name. category: 'coin' | 'token' // The category for this cryptocurrency. logo: string // Link to a CoinMarketCap hosted logo png for this cryptocurrency. } | undefined > status: CmcResponseStatus } export function getCmcInfo(queryParams: CmcInfoQueryParams): Promise<{ json: CmcResponseError | CmcInfoResponseSuccess status: number }> { const queryString = queryParamsToString({ id: queryParams.id.join(','), }) return fetch( `https://pro-api.coinmarketcap.com/v1/cryptocurrency/info?${queryString}`, { headers: { Accept: 'application/json', 'Accept-Encoding': 'deflate, gzip', 'X-CMC_PRO_API_KEY': CMC_PRO_API_KEY, }, } ).then((r) => r.json().then((json: CmcResponseError | CmcInfoResponseSuccess) => ({ json, status: r.status, })) ) } <file_sep>/src/hooks.ts import { useEffect, useState } from 'react' import { breakpoints } from './styles/variables' // https://usehooks.com/useWindowSize/ type WindowSize = { width: number | undefined height: number | undefined } export function useWindowSize(): WindowSize { const [windowSize, setWindowSize] = useState<WindowSize>({ width: undefined, height: undefined, }) useEffect(() => { function handleResize(): void { setWindowSize({ width: window.innerWidth, height: window.innerHeight, }) } window.addEventListener('resize', handleResize) handleResize() return () => window.removeEventListener('resize', handleResize) }, []) // Empty array ensures that effect is only run on mount return windowSize } type Breakpoints = { [K in `is${Capitalize<keyof typeof breakpoints | 'desktop'>}`]: boolean } export function useBreakpoint(): Breakpoints { const { width } = useWindowSize() function getBreakpoints(): Breakpoints { const current = typeof width === 'number' && width <= breakpoints.mobile ? 'mobile' : typeof width === 'number' && width <= breakpoints.tablet ? 'tablet' : 'desktop' return { isMobile: current === 'mobile', isTablet: current === 'tablet', isDesktop: current === 'desktop', } } const [state, setState] = useState(getBreakpoints()) useEffect(() => { setState(getBreakpoints()) }, [width]) return state } <file_sep>/src/pages/api/getCurrencies.ts import { NextApiRequest, NextApiResponse } from 'next' import { getCmcInfo } from './_getCmcInfo' import { getCmcListingsLatest } from './_getCmcListingsLatest' import { parseQueryParam } from './_helpers' const PAGE_SIZE = 20 export type GetCurrenciesItem = { id: number name: string symbol: string logo: string price: number currency: string volume_24h: number percent_change_24h: number } export type GetCurrenciesResponse = | { nextPage: number | null items: GetCurrenciesItem[] } | string // our API wrapper error async function getCurrencies( req: NextApiRequest, res: NextApiResponse<GetCurrenciesResponse> ): Promise<void> { const pageAsString = parseQueryParam('page', req.query) const page = pageAsString ? parseInt(pageAsString, 10) : undefined if (page === undefined || isNaN(page)) { res.status(400).json('"page" param is missing or invalid') return } const listingResponse = await getCmcListingsLatest({ start: page * PAGE_SIZE - PAGE_SIZE + 1, limit: PAGE_SIZE, sort: 'volume_24h', // TODO sort_dir: 'desc', // TODO cryptocurrency_type: 'coins', }) if (listingResponse.status !== 200 || !('data' in listingResponse.json)) { res .status(listingResponse.status === 200 ? 400 : listingResponse.status) .json(listingResponse.json.status.error_message ?? 'Api error') return } if (listingResponse.json.data.length === 0) { res.status(200).json({ nextPage: null, items: [], }) } const infoResponse = await getCmcInfo({ id: listingResponse.json.data.map((item) => item.id), }) if (infoResponse.status !== 200 || !('data' in infoResponse.json)) { res .status(infoResponse.status === 200 ? 400 : infoResponse.status) .json(infoResponse.json.status.error_message ?? 'Api error') return } const combinedResponse = listingResponse.json.data.flatMap( (item): GetCurrenciesItem[] => { const quote = Object.entries(item.quote)[0] const info = 'data' in infoResponse.json ? infoResponse.json.data[item.id] : undefined return quote && info ? [ { id: item.id, name: item.name, symbol: item.symbol, logo: info.logo.replace('64x64', '32x32'), price: quote[1].price, currency: quote[0], volume_24h: quote[1].volume_24h, percent_change_24h: quote[1].percent_change_24h, }, ] : [] } ) const isLastPage = listingResponse.json.data.length < PAGE_SIZE res.status(200).json({ nextPage: isLastPage ? null : page + 1, items: combinedResponse, }) } export default function requestHandler( req: NextApiRequest, res: NextApiResponse<GetCurrenciesResponse> ): void { void getCurrencies(req, res) } <file_sep>/src/pages/api/_getCmcListingsLatest.ts import { CMC_PRO_API_KEY, CmcResponseError, CmcResponseStatus, queryParamsToString, } from './_helpers' // https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyListingsLatest type CmcListingsLatestQueryParams = { start?: number limit?: number sort?: 'name' | 'price' | 'volume_24h' | 'percent_change_24h' // some of the sort params sort_dir?: 'asc' | 'desc' cryptocurrency_type: 'all' | 'coins' | 'tokens' } // Not all properties typed type CmcListingsLatestResponseSuccess = { data: { id: number // The unique CoinMarketCap ID for this cryptocurrency. name: string // The name of this cryptocurrency. symbol: string // The ticker symbol for this cryptocurrency. slug: string // The web URL friendly shorthand version of this cryptocurrency name. quote: Record< string, { price: number volume_24h: number percent_change_24h: number } > }[] status: CmcResponseStatus } export function getCmcListingsLatest( queryParams: CmcListingsLatestQueryParams ): Promise<{ json: CmcResponseError | CmcListingsLatestResponseSuccess status: number }> { const queryString = queryParamsToString(queryParams) return fetch( `https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?${queryString}`, { headers: { Accept: 'application/json', 'Accept-Encoding': 'deflate, gzip', 'X-CMC_PRO_API_KEY': CMC_PRO_API_KEY, }, } ).then((r) => r .json() .then((json: CmcResponseError | CmcListingsLatestResponseSuccess) => ({ json, status: r.status, })) ) } <file_sep>/src/api.ts import { GetCurrenciesResponse } from './pages/api/getCurrencies' export const api = { getCurrencies: (page: number) => async (): Promise<GetCurrenciesResponse> => fetch(`/api/getCurrencies?page=${page}`).then( (r): Promise<GetCurrenciesResponse> => r.json() ), }
55a5f03da293a190ae4ba538cad67dcee0c0f574
[ "TypeScript" ]
7
TypeScript
kazparaz/tribe-payments-test
7a0c588ee0df2e6f41be3f996f7389ff606e29e8
cb13d39ff128925ca622b7f3912b2ce59def47c7
refs/heads/master
<file_sep>package com.fjdantas.cscmcourse.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.fjdantas.cscmcourse.domain.Category; /* * CategoryRepoitory Interface annotation by JpaRepository * interface of operation of data access by object type with id attribute for repository layer */ @Repository public interface CategoryRepository extends JpaRepository<Category, Integer> { } <file_sep>package com.fjdantas.cscmcourse.domain; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.MapsId; import javax.persistence.OneToOne; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fjdantas.cscmcourse.domain.enums.StatusPayment; /* * jpa entity class * mapping the inheritance with the @inheritance annotation * and defining the strategy to generate individual tables in the database with InheritanceType.JOINED */ @Entity @Inheritance(strategy=InheritanceType.JOINED) public abstract class Payment implements Serializable{ //class conversion in byte sequence //generating class version private static final long serialVersionUID = 1L; @Id private Integer id; private Integer status; /* * avoiding cyclic reference with @JsonIgnore annotation in the mapped attribute * mapping the Purchase attribute to the order_id field * and defining the same Purchase id with the @MapsId annotation */ @JsonIgnore @OneToOne @JoinColumn(name="purchase_id") @MapsId private Purchase purchase; public Payment() { } public Payment(Integer id, StatusPayment status, Purchase purchase) { super(); this.id = id; this.status = status.getCode(); this.purchase = purchase; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public StatusPayment getStatus() { return StatusPayment.toEnum(status); } public void setStatus(StatusPayment status) { this.status = status.getCode(); } public Purchase getPurchase() { return purchase; } public void setPurchase(Purchase purchase) { this.purchase = purchase; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Payment other = (Payment) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } } <file_sep>package com.fjdantas.cscmcourse.services; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fjdantas.cscmcourse.domain.Client; import com.fjdantas.cscmcourse.repositories.ClientRepository; import com.fjdantas.cscmcourse.services.exceptions.ObjectNotFoundException; /* * class of operation to fetch client by code for service layer */ @Service public class ClientService { /* * dependency for call operation of data access in the repository layer with auto instance by Spring with the Autowired annotation */ @Autowired private ClientRepository repo; // /* operation to find a client by code returning an optional object or a lambda expression * through a function without arguments that instantiates an exception */ public Client find(Integer id) { Optional<Client> obj = repo.findById(id); return obj.orElseThrow(() -> new ObjectNotFoundException( "Object not found! Id: " + id + ", Type: " + Client.class.getName())); } } <file_sep>package com.fjdantas.cscmcourse.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.fjdantas.cscmcourse.domain.City; /* * CityRepoitory Interface annotation by JpaRepository * interface of operation of data access by object type with id attribute for repository layer */ @Repository public interface CityRepository extends JpaRepository<City, Integer> { } <file_sep>package com.fjdantas.cscmcourse.services; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fjdantas.cscmcourse.domain.Category; import com.fjdantas.cscmcourse.repositories.CategoryRepository; import com.fjdantas.cscmcourse.services.exceptions.ObjectNotFoundException; /* * class of operation to fetch caterogy by code for service layer */ @Service public class CategoryService { /* * dependency for call operation of data access in the repository layer with auto instance by Spring with the Autowired annotation */ @Autowired private CategoryRepository repo; // /* operation to find a category by code returning an optional object or a lambda expression * through a function without arguments that instantiates an exception */ public Category find(Integer id) { Optional<Category> obj = repo.findById(id); return obj.orElseThrow(() -> new ObjectNotFoundException( "Object not found! Id: " + id + ", Type: " + Category.class.getName())); } } <file_sep>package com.fjdantas.cscmcourse.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.fjdantas.cscmcourse.domain.State; /* * StateRepoitory Interface annotation by JpaRepository * interface of operation of data access by object type with id attribute for repository layer */ @Repository public interface StateRepository extends JpaRepository<State, Integer> { } <file_sep>package com.fjdantas.cscmcourse.domain; import java.util.Date; import javax.persistence.Entity; import com.fasterxml.jackson.annotation.JsonFormat; import com.fjdantas.cscmcourse.domain.enums.StatusPayment; @Entity public class PaymentWithTicket extends Payment{ //generating class version private static final long serialVersionUID = 1L; @JsonFormat(pattern="dd/MM/yyyy", timezone="America/Sao_Paulo") private Date dueDate; @JsonFormat(pattern="dd/MM/yyyy", timezone="America/Sao_Paulo") private Date paymentDate; public PaymentWithTicket() { } public PaymentWithTicket(Integer id, StatusPayment status, Purchase purchase, Date dueDate, Date paymentDate) { super(id, status, purchase); this.dueDate = dueDate; this.paymentDate = paymentDate; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } public Date getPaymentDate() { return paymentDate; } public void setPaymentDate(Date paymentDate) { this.paymentDate = paymentDate; } } <file_sep>package com.fjdantas.cscmcourse.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.fjdantas.cscmcourse.domain.Payment; /* * PaymentRepository Interface annotation by JpaRepository * interface of operation of data access by object type with id attribute for repository layer */ @Repository public interface PaymentRepository extends JpaRepository<Payment, Integer> { }
795a32dd667bf4d2183db52719db0f1c2601b8f0
[ "Java" ]
8
Java
fabiojd/cscmcourse
d8c7b9f959ee55c80c573f2464ca9d69b21d053a
db3a5cc66c3e8834a047c00209667eaac2926f46
refs/heads/main
<repo_name>REngie-engineer/0x02<file_sep>/script/script.js console.log('hello world') let car = { make: 'ford', model: 'f-450', passengers: 6 } console.log('the ' + car.make + ' ' + car.model + ' carries' + ' ' + car.passengers + ' people')
d3b796b22b1ed029755cb9bf79a28ee11b01b95b
[ "JavaScript" ]
1
JavaScript
REngie-engineer/0x02
fb30c946040f46dda396d9d5dec2e46c1fd57189
7d3156790bcb0d7af99e471d73572cc07446d839
refs/heads/master
<repo_name>EsC369/Node.js-NodeModuleBasics<file_sep>/app.js // BEFORE: // var my_module = require('./node_modules/my_module'); // my_module.greet(); // my_module.add(5,6); // After: var my_module = require('./my_module')(); //notice the extra invocation parentheses! console.log(my_module); my_module.greet(); my_module.add(5,6);
65acd17edce83c035d8b8cc7bbee81a92881ef2b
[ "JavaScript" ]
1
JavaScript
EsC369/Node.js-NodeModuleBasics
22cf31728fd5e4bb5f2debebe463ddda19c9a8b7
b4e6bc62f669ce0421f54b59c6786e82afbf6451
refs/heads/master
<repo_name>Huentelemu/mcts-vis<file_sep>/app.js var width = (window.innerWidth > 0) ? window.innerWidth : screen.width; var height = 1100 var nMaxLayers = 10 var mainSVG = d3.select('body').append('svg').attr('width', width).attr('height', height) document.body.style.background = "#006400" var colorScale = d3.scaleLinear() .range(['red', 'white', 'blue']) // or use hex values .domain([0.25, 0.5, 0.75]); //var nodes_g = this.mainSVG.append("g") //var nodes = this.points_g.selectAll('circle').data(this.data) var nodes_g = [] var nodes = [] var links_g = [] var links = [] var UCB1Constant = 2 var nodeTransitionDuration = 500 var defaultUCB1Constant = 2 var UCB1Constant = defaultUCB1Constant var sliderUCB1Constant = d3.sliderBottom() .min(0) .max(10) .width(400) .ticks(10) .step(0.1) .default(defaultUCB1Constant) .on('onchange', val => { UCB1Constant = val printNodes(root.layers) }) var gUCB1Constant = d3 .select('body') .append('svg') .attr('width', 500) .attr('height', 100) .append('g') .attr('transform', 'translate(30,30)') gUCB1Constant.call(sliderUCB1Constant) // Initialize info tooltips var nodeInfo = new NodeInfo() var linkInfo = new LinkInfo() // Initialize MCTS with empty game root = new MCTS(new TicTacToe) printNodes(root.layers) var iterationButton = d3.select('body').append('button').text('1 Iteration') .on('click', () => iterationFunction(1)) var multiIterationButton1 = d3.select('body').append('button').text('20 Iterations') .on('click', () => iterationFunction(20)) var multiIterationButton2 = d3.select('body').append('button').text('1000 Iterations') .on('click', () => iterationFunction(1000)) var resetHighlightsButton = d3.select('body').append('button').text('Reset Highlights').attr('disabled', 'disabled') .on('click', () => { resetHighlightsButton.attr('disabled', 'disabled') root.resetHighlights() printNodes(root.layers) }) function iterationFunction(nIterations) { for (var i=0; i<nIterations; i++){ root.iteration(UCB1Constant) } printNodes(root.layers) console.log('Layers:', root.layers) console.log('Links:', links) console.log('Nodes:', nodes) } function printNodes(layers, highlights=false) { var width = (window.innerWidth > 0) ? window.innerWidth : screen.width; width *= 0.8 // Reorder nodes in layers for cleaner display of links for (var depth=0; depth<layers.length-1; depth++) { // Save in MCTS node its relative location in layers array for (var parentIndex=0; parentIndex<layers[depth].length; parentIndex++) { layers[depth][parentIndex].locationInLayer = parentIndex } // Recalculate mean location of parents for each child node for (var childIndex=0; childIndex<layers[depth+1].length; childIndex++) { var sumLocations = 0 var parents = layers[depth+1][childIndex].parents //console.log('parent', layers[depth+1][childIndex].parents) for (var childsParentIndex=0; childsParentIndex<parents.length; childsParentIndex++){ sumLocations += parents[childsParentIndex].parentNode.locationInLayer } layers[depth+1][childIndex].meanLocationParents = sumLocations / layers[depth+1][childIndex].parents.length } // Reorder nodes in layer according to mean locations of their respective parents layers[depth+1].sort(function (a, b) { return a.meanLocationParents - b.meanLocationParents }) } // Clean previous preselected status root.cleanPreselections() // Paint preselected status root.preselection(UCB1Constant) // Ensure nodes are initialized while (layers.length > nodes_g.length) { nodes_g.push(mainSVG.append("g")) nodes.push(null) links_g.push([]) links.push([]) } for (var depth=0; depth<layers.length; depth++) { var parentsSeparation = width / (layers[depth].length + 1) if (layers.length > depth + 1) { var childrenSeparation = width / (layers[depth+1].length + 1) } var vertSeparation = height / (nMaxLayers+1) var parentsYLocation = vertSeparation * (depth + 1) var childrenYLocation = vertSeparation * (depth + 2) // Build nodes nodes[depth] = nodes_g[depth].selectAll('circle').data(layers[depth]) nodes[depth].exit().remove() nodes[depth] = nodes[depth].enter().append("circle").merge(nodes[depth]) nodes[depth] = nodes[depth] .on('mouseover', function(d) { if (highlights) { if (!d.highlightedElement) return } d3.select(this).transition().duration(10) .attr('opacity', d => { if (d.preselected) { return 1 } return 0.5 }) .attr('r', function(d) { if (root.nVisits>0) { var relativeToRoot = d.nVisits/root.nVisits } else { var relativeToRoot = 1 } return Math.min((relativeToRoot*50 + 5) * 2, 80) }) nodeInfo.show(d, d3.select(this)) }) .on('mouseout', function(d) { if (highlights) { if (!d.highlightedElement) return } d3.select(this).transition().duration(300) .attr('opacity', d => { if (d.preselected) { return 1 } return 0.5 }) .attr('r', function(d) { if (root.nVisits>0) { var relativeToRoot = d.nVisits/root.nVisits } else { var relativeToRoot = 1 } return relativeToRoot*50 + 5 }) nodeInfo.hide() }) .on('click', (d) => { if (highlights) { if (!d.highlightedElement) return } resetHighlightsButton.attr('disabled', null) root.resetHighlights() d.highlightElement() printNodes(root.layers, true) }) nodes[depth] = nodes[depth] .attr('cx', function(d, i) { return parentsSeparation * (i + 1) }) .attr('cy', parentsYLocation) nodes[depth] = nodes[depth].transition().duration(nodeTransitionDuration) .attr('fill', function(d) { if (d.nVisits == 0) { return 'green' } else { return colorScale(d.nWins / d.nVisits) } }) .attr("stroke", d => { if (d.preselected){ return 'black' } else { return 'black' } }) .attr("stroke-width", 1) .attr("stroke-width", d => { if (d.preselected) { return 5 } return 1 }) .attr("opacity", d => { if (highlights) { if (!d.highlightedElement) { return 0 } } if (d.preselected) { return 1 } return 0.5 }) .attr('r', function(d) { if (root.nVisits>0) { var relativeToRoot = d.nVisits/root.nVisits } else { var relativeToRoot = 1 } return relativeToRoot*50 + 5 }) .style('position', 'absolute') // Build links while (layers[depth].length > links_g[depth].length) { links_g[depth].push(mainSVG.append("g")) links[depth].push(null) } for (var parentIndex=0; parentIndex<layers[depth].length; parentIndex++){ var parent = layers[depth][parentIndex] if (highlights) { var children = [] for (var c=0; c<parent.children.length; c++) { if (parent.children[c].node.highlightedElement) { children.push(parent.children[c]) } } } else { var children = parent.children } var parent = layers[depth][parentIndex] var parentXLocation = parentsSeparation * (parentIndex + 1) links[depth][parentIndex] = links_g[depth][parentIndex].selectAll('line').data(children) links[depth][parentIndex].exit().remove() links[depth][parentIndex] = links[depth][parentIndex].enter().append('line').merge(links[depth][parentIndex]) .on('mouseover', function(d) { if (highlights) { if (!d.highlightedElement) return } d3.select(this).transition().duration(10) .attr('opacity', 1) .attr('stroke-width', 10) linkInfo.show(d, d3.select(this), UCB1Constant) }) .on('mouseout', function(d) { if (highlights) { if (!d.highlightedElement) return } d3.select(this).transition().duration(300) .attr('opacity', d => { if (d.preselected) { return 1 } return 0.1 }) .attr('stroke-width', d => { if (d.preselected){ return 5 } return 3 }) linkInfo.hide() }) links[depth][parentIndex] = links[depth][parentIndex] .attr('x1', parentXLocation) .attr('y1', parentsYLocation) .attr('x2', d => { var sonIndex = layers[depth+1].findIndex(function(child) { return child.id == d.node.id }) return childrenSeparation * (sonIndex + 1) }) .attr('y2', childrenYLocation) .attr('stroke', 'black') .attr('fill', 'none') .attr('stroke-width', d => { if (d.preselected){ return 5 } return 3 }) .transition().duration(nodeTransitionDuration) .attr('opacity', d => { if (highlights) { if (!d.highlightedElement) { return 0 } } if (d.preselected) { return 1 } return 0.1 }) links_g[depth][parentIndex].lower() } } }<file_sep>/LinkInfo.js class LinkInfo { constructor () { this.tooltip = d3.select('body').append('div') .style('opacity', 0) .style('position', 'absolute') .style('border-radius', '8px') .style('box-shadow', '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)') .style('background', 'lightsteelblue') .style('pointer-events', 'none') this.tooltipText = this.tooltip.append('div') .style('font', '24px sans-serif') .style('text-align', 'center') this.tooltipSVG = this.tooltip.append('svg') .style('height', '200px') .style('width', '200px') } show(link, line, UCB1Constant) { const {value, bias} = link.UCB1Score() var UCB1Score = value + UCB1Constant*bias if (value == Infinity) { var valueString = '&#8734' var biasString = '&#8734' var UCB1String = '&#8734' } else { var valueString = value.toFixed(2) var biasString = bias.toFixed(2) var UCB1String = UCB1Score.toFixed(2) } this.tooltip.style('opacity', 0.9) .style('top', parseInt(line.attr('y2')) + 50 + 'px') .style('left', parseInt(line.attr('x2')) + 50 + 'px') this.tooltipText.html('N Visits: ' + link.nVisits + '<br/>Value: ' + valueString + '<br/>Bias: ' + biasString + '<br/>UCB1: ' + UCB1String) this.tooltipSVG.selectAll("*").remove() link.parentNode.state.drawImage(this.tooltipSVG, link.lastAction) } hide() { this.tooltip.style('opacity', 0) } }<file_sep>/TicTacToe.js class TicTacToe{ constructor(newTTT, turnX, nRemainingMoves){ if (newTTT){ this.ttt = newTTT this.turnX = turnX this.id = this.deriveID(this.ttt) this.nRemainingMoves = nRemainingMoves } else { this.ttt = [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ] this.turnX = true this.id = 0 this.nRemainingMoves = 9 } } deriveID(ttt) { var id = 0 for (var i=0; i<ttt.length; i++){ for (var j=0; j<ttt[i].length; j++){ if (ttt[i][j] == -1){ id += 1 * Math.pow(3, i*3 + j) } else if (ttt[i][j] == 1){ id += 2 * Math.pow(3, i*3 + j) } } } return id } copyTTT() { return this.ttt.map((arr) => { return arr.slice(); }) } rotateTTT(ttt) { var newTTT = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] newTTT[0][0] = ttt[0][2] newTTT[0][2] = ttt[2][2] newTTT[2][2] = ttt[2][0] newTTT[2][0] = ttt[0][0] newTTT[1][1] = ttt[1][1] newTTT[1][0] = ttt[0][1] newTTT[0][1] = ttt[1][2] newTTT[1][2] = ttt[2][1] newTTT[2][1] = ttt[1][0] return newTTT } transposeTTT() { var newTTT = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for (var i=0; i<this.ttt.length; i++){ for (var j=0; j<this.ttt[i].length; j++){ newTTT[i][j] = this.ttt[j][i] } } return newTTT } computeTranspositions() { // Rotations of original TTT var ttt = this.copyTTT() var transpositions = [ttt] ttt = this.rotateTTT(ttt) transpositions.push(ttt) ttt = this.rotateTTT(ttt) transpositions.push(ttt) ttt = this.rotateTTT(ttt) transpositions.push(ttt) // Rotations of transposed TTT ttt = this.transposeTTT() transpositions.push(ttt) ttt = this.rotateTTT(ttt) transpositions.push(ttt) ttt = this.rotateTTT(ttt) transpositions.push(ttt) ttt = this.rotateTTT(ttt) transpositions.push(ttt) // Derive IDs from ttt this.transpositionIDs = [] transpositions.forEach(ttt => { this.transpositionIDs.push(this.deriveID(ttt)) }) // Remove repeated IDs this.transpositionIDs = [...new Set(this.transpositionIDs)] } expansion() { var stateChildren = [] // Special case for first expansion // if (this.id == 0){ // stateChildren.push({ // state: new TicTacToe([[1, 0, 0], [0, 0, 0], [0, 0, 0]], false, 8), // lastAction: [0, 0] // }) // stateChildren.push({ // state: new TicTacToe([[0, 1, 0], [0, 0, 0], [0, 0, 0]], false, 8), // lastAction: [0, 1] // }) // stateChildren.push({ // state: new TicTacToe([[0, 0, 0], [0, 1, 0], [0, 0, 0]], false, 8), // lastAction: [1, 1] // }) // return stateChildren // } for (var i=0; i<this.ttt.length; i++){ for (var j=0; j<this.ttt[i].length; j++){ if (this.ttt[i][j] == 0){ // Copy new ttt var newTTT = this.copyTTT() if (this.turnX) { newTTT[i][j] = 1 } else { newTTT[i][j] = -1 } var lastAction = [i, j] stateChildren.push({ state: new TicTacToe(newTTT, !this.turnX, this.nRemainingMoves-1), lastAction: lastAction }) } } } return stateChildren } rollout() { var remainingMoves = [] for (var i=0; i<this.ttt.length; i++){ for (var j=0; j<this.ttt[i].length; j++){ if (this.ttt[i][j] == 0) { remainingMoves.push([i, j]) } } } remainingMoves = remainingMoves.sort(() => 0.5 - Math.random()) // Copy new ttt var rolloutState = this.copyTTT() var rolloutTurnX = this.turnX while (remainingMoves.length > 0){ var nextMove = remainingMoves.pop() if (rolloutTurnX) { rolloutState[nextMove[0]][nextMove[1]] = 1 } else { rolloutState[nextMove[0]][nextMove[1]] = -1 } //check win condition var result = this.checkEndGame(rolloutState) if (result != 0){ return result } rolloutTurnX = !rolloutTurnX } return 0 } checkEndGame(s=this.ttt) { for (var i=0; i<3; i++) { var result = s[i][0] + s[i][1] + s[i][2] if (result == 3) return 1 else if (result == -3) return -1 } for (var i=0; i<3; i++) { var result = s[0][i] + s[1][i] + s[2][i] if (result == 3) return 1 else if (result == -3) return -1 } var result = s[0][0] + s[1][1] + s[2][2] if (result == 3) return 1 else if (result == -3) return -1 var result = s[2][0] + s[1][1] + s[0][2] if (result == 3) return 1 else if (result == -3) return -1 return 0 } nextTurn() { sumValues = 0 for (var i=0; i<this.ttt.length; i++){ for (var j=0; j<this.ttt[i].length; j++){ sumValues += this.ttt[i][j] } } if (sumValues == 1) { return -1 } else return 1 } isEquals(other) { for (var i=0; i<this.ttt.length; i++){ for (var j=0; j<this.ttt[i].length; j++){ if (other.ttt[i][j] != this.ttt[i][j]){ return false } } } return true } print() { console.log('TTT1:', this.ttt[0]) console.log('TTT2:', this.ttt[1]) console.log('TTT3:', this.ttt[2]) console.log('-------------------------------') } drawImage(svg, lastAction=null) { var self = this // Remove all previous elements while (svg.lastChild) { svg.removeChild(svg.lastChild); } // Base lines svg.append('path').attr('d', 'M70,10L70,190 M130,10L130,190 M10,70L190,70 M10,130L190,130') .attr('stroke', 'black') .attr('stroke-width', 4) // Add circles and crosses for (var i=0; i<this.ttt.length; i++){ for (var j=0; j<this.ttt[i].length; j++){ if (this.ttt[j][i] == -1) { svg.append('circle') .attr('cx', i*60 + 40) .attr('cy', j*60 + 40) .attr('r', 15) .attr('stroke-width', 3) .attr('stroke', 'black') .attr('fill', 'none') } else if (this.ttt[j][i] == 1) { svg.append('path') .attr('d', () => { var o = 15 // offset var x = i*60 +40 var y = j*60 +40 return `M${x-o},${y-o}L${x+o},${y+o} M${x-o},${y+o}L${x+o},${y-o}` }) .attr('stroke-width', 4) .attr('stroke', 'black') .attr('fill', 'none') } if (lastAction){ if (lastAction[0] == j && lastAction[1] == i) { if (this.turnX) { svg.append('path') .attr('d', () => { var o = 15 // offset var x = i*60 +40 var y = j*60 +40 return `M${x-o},${y-o}L${x+o},${y+o} M${x-o},${y+o}L${x+o},${y-o}` }) .attr('stroke-width', 4) .attr('stroke', 'red') } else { svg.append('circle') .attr('cx', i*60 + 40) .attr('cy', j*60 + 40) .attr('r', 15) .attr('stroke-width', 3) .attr('stroke', 'red') .attr('fill', 'none') } } } } } } }<file_sep>/MCTS.js class MCTS{ constructor(state, layers = null, depth = 0){ this.parents = [] this.children = [] this.state = state this.state.computeTranspositions() this.id = state.id this.leaf = true this.nVisits = 0 this.nWins = 0 this.nLosses = 0 this.nTies = 0 this.depth = depth if (layers){ this.layers = layers } else { this.layers = [[this]] } this.locationInLayer = 0 this.meanLocationParents = 0 this.endGame = this.state.checkEndGame() this.highlightedElement = false } iteration(UCB1Constant) { if (this.endGame || this.state.nRemainingMoves == 0) { var result = this.endGame } else if (this.leaf) { if (this.nVisits < 1){ var result = this.rollout() } else { this.expansion() var selectedChild = this.selection(UCB1Constant) var result = selectedChild.iteration(UCB1Constant) } } else { var selectedChild = this.selection(UCB1Constant) var result = selectedChild.iteration(UCB1Constant) } this.backpropagation(result) return result } selection(UCB1Constant, returnArray=false) { var bestChildren = [] var bestChildUSB1 = -1 // Collect children with best score in a list for (var i=0; i<this.children.length; i++) { var childUSB1 = this.children[i].UCB1Score(UCB1Constant) if (childUSB1 > bestChildUSB1) { bestChildren = [this.children[i]] bestChildUSB1 = childUSB1 } else if (childUSB1 == bestChildUSB1) { bestChildren.push(this.children[i]) } } if (returnArray) { // Return all selected children return bestChildren } else { // Return one of the selected children chosen randomly return bestChildren[Math.floor(Math.random() * bestChildren.length)] } } expansion() { this.leaf = false // Ensure next layer exists if (this.layers.length-1 == this.depth) { this.layers.push([]) } var stateChildren = this.state.expansion() for (var i=0; i<stateChildren.length; i++) { var newState = stateChildren[i].state var lastAction = stateChildren[i].lastAction // Check if child already is present in layers var equalSibling = this.alreadyPresent(newState) if (equalSibling) { // If this sibling is already a child of the present node, skip it if (this.children.map(child => child.node.id).includes(equalSibling.id)) continue // If child is already present, create a new link connecting this parent and the already present child 'equalSibling' var newChildLink = new MCTSLink(equalSibling, this, lastAction) } else { // If not, create a new node and connect it with this parent var newNode = new MCTS(newState, this.layers, this.depth+1) var newChildLink = new MCTSLink(newNode, this, lastAction) this.layers[this.depth+1].push(newNode) } this.children.push(newChildLink) } } rollout() { var result = this.state.rollout() return result } backpropagation(result) { if (result == 1) { this.nWins++ } else if (result == -1){ this.nLosses++ } else { this.nTies++ } this.nVisits++ } alreadyPresent(child) { // Check if child state is has already a sibling var siblings = this.layers[this.depth+1] for (var i=0; i<siblings.length; i++){ if (siblings[i].state.transpositionIDs.includes(child.id)) { //if (siblings[i].state.id == child.id) { return siblings[i] } } return false } cleanPreselections() { // Reset all preselected states in nodes this.preselected = false this.children.forEach(childLink => { if (childLink.preselected) { childLink.cleanPreselections() } }) } preselection(UCB1Constant) { // function to paint links and nodes as preselected for display this.preselected = true var bestChildren = this.selection(UCB1Constant, true) bestChildren.forEach(childLink => { childLink.preselection(UCB1Constant) }) } highlightElement() { this.highlightedElement = true this.children.forEach(child => child.propagateHighlightToChildren()) this.parents.forEach(parent => parent.propagateHighlightToParents()) } propagateHighlightToChildren() { this.highlightedElement = true this.children.forEach(child => child.propagateHighlightToChildren()) } propagateHighlightToParents() { this.highlightedElement = true this.parents.forEach(parent => parent.propagateHighlightToParents()) } resetHighlights() { this.highlightedElement = false this.children.forEach(child => { if (child.highlightedElement) { child.resetHighlights() } }) } } class MCTSLink { constructor(node, parentNode, lastAction){ this.node = node this.node.parents.push(this) this.parentNode = parentNode this.lastAction = lastAction this.nVisits = 0 this.preselected = false this.highlightedElement = false } UCB1Score(UCB1Constant=null) { // Calculate node value if (this.node.nVisits == 0) { var value = Infinity } else { if (this.node.state.turnX) { var value = this.node.nLosses / this.node.nVisits } else { var value = this.node.nWins / this.node.nVisits } } // Calculate nVisits bias if (this.nVisits == 0) { var visitsBias = Infinity } else { var visitsBias = Math.sqrt(Math.log(this.parentNode.nVisits) / this.nVisits) } if (UCB1Constant) { return value + UCB1Constant*visitsBias } else { return { value: value, bias: visitsBias, } } } iteration(UCB1Constant) { var result = this.node.iteration(UCB1Constant) this.nVisits++ return result } cleanPreselections() { this.preselected = false this.node.cleanPreselections() } preselection(UCB1Constant) { // function to paint links and nodes as preselected for display this.preselected = true this.node.preselection(UCB1Constant) } propagateHighlightToChildren() { this.highlightedElement = true this.node.propagateHighlightToChildren() } propagateHighlightToParents() { this.highlightedElement = true this.parentNode.propagateHighlightToParents() } resetHighlights() { this.highlightedElement = false this.node.resetHighlights() } }
66f5b53b9d902826414f5c9cd14f307293c000cf
[ "JavaScript" ]
4
JavaScript
Huentelemu/mcts-vis
d2de04bac13afb0303d7ed62ac656b3c4dc2ec20
a5fce68d2a770ae9145a5c8d1e1947995a460ab2
refs/heads/master
<repo_name>faruqfadhil/learn-go-docs<file_sep>/shipper/binarysearch/main.go package main import ( "fmt" ) func main() { var testCases int fmt.Scan(&testCases) for i := 0; i < testCases; i++ { var N int fmt.Scan(&N) arr := make([]int, N) for i := 0; i < N; i++ { if _, err := fmt.Scan(&arr[i]); err != nil { panic(err) } } fmt.Println(getAnswer(arr)) } } func getAnswer(arr []int) string { out := linierSearch(arr) if len(out) < 1 { return "Not Found" } var aggsOut string for _, o := range out { aggsOut += fmt.Sprintf("%d ", o) } return aggsOut } func binarySearch(needle int, haystack []int) int { low := 0 high := len(haystack) - 1 for low <= high { median := (low + high) / 2 if haystack[median] < needle { low = median + 1 } else { high = median - 1 } } if low == len(haystack) || haystack[low] != needle { return -1 } return low } func linierSearch(arr []int) []int { out := []int{} for i, val := range arr { fmt.Println(val) if val == i+1 { out = append(out, i+1) } } return out } // func main() { // items := []int{1, 2, 9, 20, 31, 45, 63, 70, 100} // fmt.Println(binarySearch(20, items)) // } <file_sep>/gopay/main.go package main import "fmt" func main() { pivot := findPivot([]int{0, 1, 2, 3, 4, 5}) fmt.Println(pivot) pivot = findPivot([]int{1, 2, 3, 4, 5, 0}) fmt.Println(pivot) pivot = findPivot([]int{2, 3, 4, 5, 0, 1}) fmt.Println(pivot) pivot = findPivot([]int{3, 4, 5, 0, 1, 2}) fmt.Println(pivot) pivot = findPivot([]int{4, 5, 0, 1, 2, 3}) fmt.Println(pivot) pivot = findPivot([]int{5, 0, 1, 2, 3, 4}) fmt.Println(pivot) pivot = findPivot([]int{4, 1, 2, 3, 3}) fmt.Println(pivot) } func findPivot(nums []int) int { return findPivotUtil(nums, 0, len(nums)-1) } func findPivotUtil(nums []int, start, end int) int { if start > end { return -1 } mid := (start + end) / 2 if mid+1 <= end && nums[mid] > nums[mid+1] { return mid + 1 } if mid-1 >= start && nums[mid] < nums[mid-1] { return mid } if nums[mid] < nums[start] { return findPivotUtil(nums, start, mid-1) } return findPivotUtil(nums, mid+1, end) } func binarySearch(nums []int, start, end, target int) int { if start > end { return -1 } mid := (start + end) / 2 if nums[mid] == target { return mid } if target < nums[mid] { return binarySearch(nums, start, mid-1, target) } else { return binarySearch(nums, mid+1, end, target) } } <file_sep>/shipper/linkedlist/main.go package main import ( "fmt" ) type SingleLinkedList struct { Head *Node } type Node struct { Data int Next *Node } func (s *SingleLinkedList) Append(data int) { newNode := &Node{ Data: data, } newNode.Next = nil if s.Head == nil { s.Head = newNode return } temp := s.Head for temp.Next != nil { temp = temp.Next } temp.Next = newNode } func (s *SingleLinkedList) getCount() int { var count int current := s.Head for current != nil { fmt.Println(current.Data) count++ current = current.Next } return count } func main() { var testCases int fmt.Scan(&testCases) for i := 0; i < testCases; i++ { init := &SingleLinkedList{Head: &Node{}} var N int fmt.Scan(&N) arr := make([]int, N) for i := 0; i < N; i++ { if _, err := fmt.Scan(&arr[i]); err != nil { panic(err) } init.Append(arr[i]) } fmt.Println(init.getCount() - 1) } } <file_sep>/data-structures/linkedlist/linkedlist_test.go package main import ( "testing" "github.com/google/go-cmp/cmp" ) func TestPrint(t *testing.T) { tests := map[string]struct { req *SingleLinkedList out string err error }{ "success": { req: &SingleLinkedList{&Node{ Data: 1, Next: &Node{ Data: 2, Next: &Node{ Data: 3, }, }, }, }, out: "1->2->3", err: nil, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { out := test.req.Print() diff := cmp.Diff(test.out, out) if diff != "" { t.Fatalf(diff) } }) } } func TestInsertFront(t *testing.T) { tests := map[string]struct { init *SingleLinkedList req int out string err error }{ "success": { init: &SingleLinkedList{ Head: &Node{ Data: 1, Next: &Node{ Data: 2, Next: &Node{ Data: 3, }, }, }, }, req: 5, out: "5->1->2->3", err: nil, }, "success with nil": { init: &SingleLinkedList{ Head: nil, }, req: 5, out: "5", err: nil, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { test.init.InsertFront(test.req) out := test.init.Print() diff := cmp.Diff(test.out, out) if diff != "" { t.Fatalf(diff) } }) } } func TestInsertAfter(t *testing.T) { tests := map[string]struct { init *SingleLinkedList req int out string err error }{ "success": { init: &SingleLinkedList{ Head: &Node{ Data: 1, Next: &Node{ Data: 2, Next: &Node{ Data: 3, }, }, }, }, req: 5, out: "1->2->5->3", err: nil, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { test.init.InsertAfter(test.init.Head.Next, test.req) out := test.init.Print() diff := cmp.Diff(test.out, out) if diff != "" { t.Fatalf(diff) } }) } } func TestAppend(t *testing.T) { tests := map[string]struct { init *SingleLinkedList req int out string err error }{ "success": { init: &SingleLinkedList{ Head: &Node{ Data: 1, Next: &Node{ Data: 2, Next: &Node{ Data: 3, }, }, }, }, req: 5, out: "1->2->3->5", err: nil, }, "success with nil": { init: &SingleLinkedList{ Head: nil, }, req: 5, out: "5", err: nil, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { test.init.Append(test.req) out := test.init.Print() diff := cmp.Diff(test.out, out) if diff != "" { t.Fatalf(diff) } }) } } func TestDelete(t *testing.T) { type requestDelete string const ( middle requestDelete = "middle" head requestDelete = "head" ) tests := map[string]struct { init *SingleLinkedList req requestDelete out string err error }{ "success": { init: &SingleLinkedList{ Head: &Node{ Data: 1, Next: &Node{ Data: 2, Next: &Node{ Data: 3, }, }, }, }, req: middle, out: "1->3", err: nil, }, "success with head": { init: &SingleLinkedList{ Head: &Node{ Data: 1, Next: &Node{ Data: 2, Next: &Node{ Data: 3, }, }, }, }, req: head, out: "2->3", err: nil, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { switch test.req { case middle: test.init.Delete(test.init.Head.Next) case head: test.init.Delete(test.init.Head) } out := test.init.Print() diff := cmp.Diff(test.out, out) if diff != "" { t.Fatalf(diff) } }) } } <file_sep>/ruang-guru-interview/main.go package main import ( "bufio" "fmt" "io" "os" "sort" "strings" ) func main() { reader := bufio.NewReader(os.Stdin) var testCases int fmt.Scan(&testCases) for i := 0; i < testCases; i++ { strInput := strings.Split(readLine(reader), ",") fmt.Println(isAnagram(strInput)) } } func isAnagram(inputs []string) bool { mapKeys := map[string][]string{} for _, i := range inputs { sTemp := strings.Split(string(i), "") sort.Strings(sTemp) key := strings.Join(sTemp, "") mapKeys[key] = append(mapKeys[key], string(i)) } for key, v := range mapKeys { if len(v) > 1 { fmt.Printf("Found anagram words!:%s\t in slice:%s\n", v, key) return true } } return false } func readLine(reader *bufio.Reader) string { str, _, err := reader.ReadLine() if err == io.EOF { return "" } return strings.TrimRight(string(str), "\r\n") } <file_sep>/grpc-go-course/greet/greet_client/client.go package main import ( "context" "fmt" "io" "log" "time" "github.com/faruqfadhil/learn-go-docs/grpc-go-course/greet/greetpb" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) func main() { fmt.Println("hello Iam client") cc, err := grpc.Dial("localhost:50051", grpc.WithInsecure()) if err != nil { log.Fatalf("could not connect: %v", err) } defer cc.Close() c := greetpb.NewGreetServiceClient(cc) // doUnary(c) // doServerStreaming(c) // doClientStreaming(c) // doBidirectionalStreaming(c) doUnaryWithDeadline(c, 5*time.Second) // should be complete doUnaryWithDeadline(c, 1*time.Second) // should timeout } func doUnary(c greetpb.GreetServiceClient) { fmt.Println("starting to do unary RPC...") req := &greetpb.GreetRequest{ Greeting: &greetpb.Greeting{ FirstName: "faruq", LastName: "fadhil", }, } res, err := c.Greet(context.Background(), req) if err != nil { log.Fatalf("error while calling greet RPC: %v", err) } log.Printf("response from greet : %v", res.Result) } func doServerStreaming(c greetpb.GreetServiceClient) { fmt.Println("starting to do server streaming RPC...") res, err := c.GreetManyTimes(context.Background(), &greetpb.GreetManyTimesRequest{ Greeting: &greetpb.Greeting{ FirstName: "faruq", LastName: "fadhil", }, }) if err != nil { log.Fatalf("error while calling greetManyTimes RPC : %v", err) } for { msg, err := res.Recv() if err == io.EOF { break } if err != nil { log.Fatalf("error while reading stream %v", err) } log.Printf("response : %v", msg.GetResult()) } } func doClientStreaming(c greetpb.GreetServiceClient) { requests := []*greetpb.LongGreetRequest{ &greetpb.LongGreetRequest{ Greeting: &greetpb.Greeting{ FirstName: "faruq", }, }, &greetpb.LongGreetRequest{ Greeting: &greetpb.Greeting{ FirstName: "fadhil", }, }, &greetpb.LongGreetRequest{ Greeting: &greetpb.Greeting{ FirstName: "marfuah", }, }, } stream, err := c.LongGreet(context.Background()) if err != nil { log.Fatalf("error while calling logGreat %v", err) } for _, req := range requests { fmt.Printf("sending req : %v\n", req) stream.Send(req) time.Sleep(1000 * time.Millisecond) } msg, err := stream.CloseAndRecv() if err != nil { log.Fatalf("error while receiving response from long greet %v", err) } fmt.Printf("response : %v\n", msg) } func doBidirectionalStreaming(c greetpb.GreetServiceClient) { stream, err := c.GreetEveryone(context.Background()) if err != nil { log.Fatalf("error while creatiing stream: %v", err) return } requests := []*greetpb.GreetEveryoneRequest{ &greetpb.GreetEveryoneRequest{ Greeting: &greetpb.Greeting{ FirstName: "faruq", }, }, &greetpb.GreetEveryoneRequest{ Greeting: &greetpb.Greeting{ FirstName: "fadhil", }, }, &greetpb.GreetEveryoneRequest{ Greeting: &greetpb.Greeting{ FirstName: "marfuah", }, }, } waitChan := make(chan struct{}) go func() { for _, req := range requests { fmt.Printf("Sending req:%v\n", req) stream.Send(req) time.Sleep(1 * time.Second) } stream.CloseSend() }() go func() { for { msg, err := stream.Recv() if err == io.EOF { break } if err != nil { log.Printf("Error while receive data: %v", err) break } fmt.Printf("received : %v\n", msg.GetResult()) } close(waitChan) }() <-waitChan } func doUnaryWithDeadline(c greetpb.GreetServiceClient, timeOut time.Duration) { fmt.Println("starting to do unary with deadline RPC...") req := &greetpb.GreetWithDeadlineRequest{ Greeting: &greetpb.Greeting{ FirstName: "faruq", LastName: "fadhil", }, } ctx, cancel := context.WithTimeout(context.Background(), timeOut) defer cancel() res, err := c.GreetWithDeadline(ctx, req) if err != nil { statusErr, ok := status.FromError(err) if ok { if statusErr.Code() == codes.DeadlineExceeded { fmt.Println("Timeout") } else { fmt.Println("Unexpected err: ", statusErr) } } else { log.Fatalf("error while calling greetWithDeadline RPC: %v", err) } return } log.Printf("response from greetWithDeadline : %v", res.Result) } <file_sep>/shipper/palindrome/main.go // package main // import ( // "bufio" // "fmt" // "io" // "os" // "strconv" // "strings" // ) // /** To execute Go, please define "main()" as below **/ // func main() { // reader := bufio.NewReader(os.Stdin) // var testCases int // fmt.Scan(&testCases) // for i := 0; i < testCases; i++ { // strInput := strings.Split(readLine(reader), ",") // // fmt.Println(isPalindrome(strInput[0])) // i, _ := strconv.Atoi(strInput[0]) // fmt.Println(isPalindrome(i)) // } // } // func readLine(reader *bufio.Reader) string { // str, _, err := reader.ReadLine() // if err == io.EOF { // return "" // } // return strings.TrimRight(string(str), "\r\n") // } // func recur(n, i int) int { // if n == 0 { // return i // } // i = (i * 10) + (n % 10) // return recur(n/10, i) // } // func isPalindrome(n int) string { // out := recur(n, 0) // if out == n { // return "Yes" // } // return "No" // } package main import ( "bufio" "fmt" "io" "os" "strconv" "strings" ) /** To execute Go, please define "main()" as below **/ func main() { reader := bufio.NewReader(os.Stdin) var testCases int fmt.Scan(&testCases) for i := 0; i < testCases; i++ { strInput := strings.Split(readLine(reader), ",") i, _ := strconv.Atoi(strInput[0]) fmt.Println(isPalindrome(i)) } } func readLine(reader *bufio.Reader) string { str, _, err := reader.ReadLine() if err == io.EOF { return "" } return strings.TrimRight(string(str), "\r\n") } func recur(n, i int) int { if n == 0 { return i } i = (i * 10) + (n % 10) return recur(n/10, i) } func isPalindrome(n int) string { out := recur(n, 0) if out == n { return "Yes" } return "No" } // Your Previous Javascript code is preserved below: // /** // Default code for reading input data // // process.stdin.resume(); // process.stdin.setEncoding("utf-8"); // var stdin_input = ""; // process.stdin.on("data", function (input) { // stdin_input += input; // }); // process.stdin.on("end", function () { // main(stdin_input); // }); // /** // Below "main" function will be called with input as string argument // // function main(input) { // /** // NOTE: Start modifying below code // If necessary parse input as required in question and // print your program's output using console.log // // console.log("Code output is: " + input + "."); // } <file_sep>/grpc-go-course/calculator/calculator_server/server.go package main import ( "context" "fmt" "io" "log" "math" "net" "time" "github.com/faruqfadhil/learn-go-docs/grpc-go-course/calculator/calculatorpb" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type server struct{} func (*server) Calculate(ctx context.Context, req *calculatorpb.CalculatorRequest) (*calculatorpb.CalculatorResponse, error) { res := &calculatorpb.CalculatorResponse{ Result: req.GetCalculating().GetNumbOne() + req.GetCalculating().GetNumbTwo(), } return res, nil } func (*server) PrimeNumberDecomp(req *calculatorpb.PrimeNumberDecompRequest, stream calculatorpb.CalculatorService_PrimeNumberDecompServer) error { k := int32(2) N := req.GetPrimeNumber().GetPrime() for N > 1 { if N%k == 0 { res := &calculatorpb.PrimeNumberDecompResponse{ Result: k, } stream.Send(res) time.Sleep(1000 * time.Millisecond) N = N / k } else { k = k + 1 } } return nil } func (*server) ComputeAverage(stream calculatorpb.CalculatorService_ComputeAverageServer) error { var result float32 divider := 0 for { req, err := stream.Recv() if err == io.EOF { return stream.SendAndClose(&calculatorpb.ComputeAverageResponse{ Result: result / float32(divider), }) } if err != nil { log.Fatalf("error while reading client stream : %v", err) } number := req.GetNumber() divider++ result += float32(number) } } func (*server) FindMaximum(stream calculatorpb.CalculatorService_FindMaximumServer) error { maximum := int32(0) for { req, err := stream.Recv() if err == io.EOF { return nil } if err != nil { log.Fatalf("error while reading client stream: %v", err) return err } numb := req.GetNumber() if numb > maximum { maximum = numb err = stream.Send(&calculatorpb.FindMaximumResponse{ Result: numb, }) if err != nil { log.Fatalf("error while sending to client:%v", err) return err } } } } func (*server) SquareRoot(ctx context.Context, req *calculatorpb.SquareRootRequest) (*calculatorpb.SquareRootResponse, error) { number := req.GetNumber() if number < 0 { return nil, status.Errorf( codes.InvalidArgument, fmt.Sprintln("negative number : ", number), ) } res := math.Sqrt(float64(number)) return &calculatorpb.SquareRootResponse{ Result: res, }, nil } func main() { lis, err := net.Listen("tcp", "0.0.0.0:50051") if err != nil { log.Fatalf("failed to listen : %v", err) } s := grpc.NewServer() calculatorpb.RegisterCalculatorServiceServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve : %v", err) } } <file_sep>/go.mod module github.com/faruqfadhil/learn-go-docs go 1.13 require ( github.com/go-sql-driver/mysql v1.5.0 github.com/golang/protobuf v1.3.2 github.com/google/go-cmp v0.2.0 golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa // indirect golang.org/x/sys v0.0.0-20200116001909-b77594299b42 // indirect golang.org/x/text v0.3.2 // indirect google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba // indirect google.golang.org/grpc v1.26.0 ) <file_sep>/tiketinterview/aesthetictree/main.go package solution func Solution(A []int) int { isAesthetic := func(a []int) bool { for i := 1; i < len(a)-1; i++ { if (a[i] >= a[i-1] && a[i] <= a[i+1]) || (a[i] <= a[i-1] && a[i] >= a[i+1]) { return false } } return true } copyArr := func(originalArr []int, startIdx, endIdx int) []int { var out []int for i := startIdx; i <= endIdx; i++ { out = append(out, originalArr[i]) } return out } var cutWaysCount int if isAesthetic(A) { // return 0 if given trees already aesthetic. return 0 } // newT := copyArr(A, 0, len(A)-1) for i := 0; i < len(A)-1; i++ { newTrees := copyArr(A, 0, len(A)-1) newTrees = append(newTrees[:i], newTrees[i+1:]...) if isAesthetic(newTrees) { cutWaysCount++ } } if cutWaysCount == 0 { // return -1 if there's no ways to make the given trees aesthetic. return -1 } return cutWaysCount } <file_sep>/data-structures/stack/stack.go package main import ( "fmt" "strings" ) type Stack struct { Stack *StackNode } type StackNode struct { Data int Next *StackNode } func (s *Stack) Push(data int) { temp := &StackNode{ Data: data, } temp.Next = s.Stack s.Stack = temp } func (s *Stack) Pop() { if s.Stack != nil { s.Stack = s.Stack.Next } } func (s *Stack) Print() string { temp := s.Stack out := []string{} for temp != nil { out = append(out, fmt.Sprintf("%d", temp.Data)) temp = temp.Next } return strings.Join(out, ",") } func main() { stack := &Stack{} stack.Push(10) stack.Push(20) stack.Push(30) stack.Pop() fmt.Println(stack.Print()) } <file_sep>/telkom/main.go // Charles and the Necklace // Charles wants to buy a necklace in which. // 1. There is a minimum of 1 pearl and maximum of X pearls, such that each // pearl has its own magnificent coefficient // 2. The pearls should be in non-decreasing order of their magnificence power. // You are given the maximum number of pearls in a necklace and the range of // the magnificent coefficients of the pearls. Find the number of necklaces that // can be made that follow the mentioned conditions.​ // Input: N = 3, L = 6, R = 9 // Output: 34 // Explanation: // The necklace can be formed in the following ways: // The necklaces of length one that can be formed are { “6”, “7”, “8”, “9” }. // The necklaces of length two, that can be formed are { “66”, “67”, “68”, “69”, “77”, “78”, “79”, “88”, “89”, “99” }. // The necklaces of length three, that can be formed are { “666”, “667”, “668”, “669”, “677”, “678”, “679”, “688”, “689”, “699”, “777”, “778”, “779”, “788”, “789”, “799”, “888”, “889”, “899”, “999” }. // Thus, in total, the necklace can be formed in (4+10+20 = 34 ) ways. package main import "fmt" func main() { N := 3 L := 6 R := 9 // Initialize 2D Array. var dp [][]int for i := 0; i < N; i++ { temp := make([]int, N*(R-L+1)) dp = append(dp, temp) } count := 0 for i := 0; i < N; i++ { dp[i][0] = 1 } for i := 1; i < len(dp[0]); i++ { dp[0][i] = dp[0][i-1] + 1 } count = dp[0][R-L] for i := 1; i < N; i++ { for j := 1; j < len(dp[0]); j++ { dp[i][j] = dp[i-1][j] + dp[i][j-1] } count += dp[i][R-L] } fmt.Println(count) } <file_sep>/hackerrank/maximum-profit/main.go package main import ( "fmt" "sort" ) func main() { inventory := []int32{2, 5} order := int64(100) fmt.Println(maximumProfit(inventory, order)) } func maximumProfit(inventory []int32, order int64) int64 { // Author: Faruq // 22 may 2022 11:30 WIB. suppliersCountMappedByStockProfit := map[int32]int{} for _, stock := range inventory { for i := int32(1); i <= stock; i++ { suppliersCountMappedByStockProfit[i]++ } } uniqueStocksProfit := []int32{} for key, _ := range suppliersCountMappedByStockProfit { uniqueStocksProfit = append(uniqueStocksProfit, key) } sort.Slice(uniqueStocksProfit, func(i, j int) bool { return uniqueStocksProfit[i] > uniqueStocksProfit[j] }) profit := int64(0) supply := int64(0) for _, stockProfit := range uniqueStocksProfit { if supply == order { break } if suppliersCount, ok := suppliersCountMappedByStockProfit[stockProfit]; ok { diff := order - supply if diff >= int64(suppliersCount) { supply += int64(suppliersCount) profit += (int64(stockProfit) * int64(suppliersCount)) } else { supply += diff profit += (int64(stockProfit) * int64(diff)) } } } return profit } <file_sep>/grpc/common/config/config.go package config const ( // ServiceGaragePort port. ServiceGaragePort = ":7000" // ServiceUserPort port. ServiceUserPort = ":9000" ) <file_sep>/grpc-go-course/blog/blogclient/client.go package main import ( "context" "fmt" "log" "github.com/faruqfadhil/learn-go-docs/grpc-go-course/blog/blogpb" "google.golang.org/grpc" ) func main() { fmt.Println("hello Iam client") cc, err := grpc.Dial("localhost:50051", grpc.WithInsecure()) if err != nil { log.Fatalf("could not connect: %v", err) } defer cc.Close() c := blogpb.NewBlogServiceClient(cc) // createBlog(c) readBlog(c) // doServerStreaming(c) // doClientStreaming(c) // doBidirectionalStreaming(c) // doUnaryWithDeadline(c, 5*time.Second) // should be complete // doUnaryWithDeadline(c, 1*time.Second) // should timeout } func createBlog(c blogpb.BlogServiceClient) { req := &blogpb.CreateBlogRequest{ Blog: &blogpb.Blog{ Id: "sas", AuthorId: "fadhil", Content: "ehehe", Title: "s.Tr.Kom", }, } res, err := c.CreateBlog(context.Background(), req) if err != nil { log.Fatalf("error while calling greet RPC: %v", err) } log.Printf("response from greet : %v", res.GetBlog()) } func readBlog(c blogpb.BlogServiceClient) { req := &blogpb.ReadBlogRequest{ BlogId: "sas", } res, err := c.ReadBlog(context.Background(), req) if err != nil { log.Fatalf("error while calling greet RPC: %v", err) } log.Printf("response from greet : %v", res.GetBlog()) } <file_sep>/helloworld/helloworld.go package helloworld // GetAHelloWorld print a hello-world. func GetAHelloWorld() string { return "hello-world" } <file_sep>/data-structures/linkedlist/linkedlist.go package main import ( "fmt" "strings" ) type SingleLinkedList struct { Head *Node } type Node struct { Data int Next *Node } func (s *SingleLinkedList) Print() string { temp := s.Head out := []string{} for temp != nil { out = append(out, fmt.Sprintf("%d", temp.Data)) temp = temp.Next } return strings.Join(out, "->") } func (s *SingleLinkedList) InsertFront(data int) { newNode := &Node{ Data: data, } newNode.Next = s.Head s.Head = newNode } func (s *SingleLinkedList) InsertAfter(node *Node, data int) { newNode := &Node{ Data: data, } newNode.Next = node.Next node.Next = newNode } func (s *SingleLinkedList) Append(data int) { newNode := &Node{ Data: data, } newNode.Next = nil if s.Head == nil { s.Head = newNode return } temp := s.Head for temp.Next != nil { temp = temp.Next } temp.Next = newNode } func (s *SingleLinkedList) Delete(node *Node) { if s.Head.Data == node.Data { s.Head = node.Next return } prevNode := s.Head for prevNode.Next.Data != node.Data { prevNode = prevNode.Next } prevNode.Next = node.Next } <file_sep>/sorting/sort.go package main import "fmt" func main() { list := []int{30, 62, 53, 42, 17, 97, 91, 38} // fmt.Println(insertionSort(list)) fmt.Println(selectionSort(list)) // fmt.Println(bubbleSort(list)) // fmt.Println(shellSort(list)) } func insertionSort(nums []int) []int { n := len(nums) for i := 1; i <= n-1; i++ { j := i for j > 0 { if nums[j] < nums[j-1] { nums[j], nums[j-1] = nums[j-1], nums[j] } j-- } } return nums } func selectionSort(nums []int) []int { for i := 0; i < len(nums); i++ { smallestIdx := i for j := i + 1; j <= len(nums)-1; j++ { if nums[smallestIdx] > nums[j] { smallestIdx = j } } if nums[i] != nums[smallestIdx] { nums[i], nums[smallestIdx] = nums[smallestIdx], nums[i] } } return nums } func bubbleSort(nums []int) []int { didSwap := true for j := len(nums); j > 0; j-- { didSwap = false for i := 1; j > i; i++ { if nums[i-1] > nums[i] { nums[i-1], nums[i] = nums[i], nums[i-1] didSwap = true } } if !didSwap { break } } return nums } func shellSort(nums []int) []int { jarak := len(nums) for jarak > 1 { jarak = jarak / 2 didSwap := true for didSwap { didSwap = false for i := 0; i < len(nums)-jarak; i++ { if nums[i] > nums[i+jarak] { nums[i+jarak], nums[i] = nums[i], nums[i+jarak] didSwap = true } } } } return nums } func mergeSort(nums []int) []int { if len(nums) < 2 { return nums } mid := len(nums) / 2 leftSubArray := nums[:mid] rightSubArray := nums[mid:] return merge(mergeSort(leftSubArray), mergeSort(rightSubArray)) } func merge(left, right []int) []int { size := len(left) + len(right) l := 0 r := 0 newSlice := make([]int, size) for i := 0; i < size; i++ { if l > len(left)-1 && r <= len(right)-1 { newSlice[i] = right[r] r++ } else if r > len(right)-1 && l <= len(left)-1 { newSlice[i] = left[l] l++ } else if right[r] < left[l] { newSlice[i] = right[r] r++ } else { newSlice[i] = left[l] l++ } } return newSlice } <file_sep>/grpc-go-course/blog/blogserver/server.go package main import ( "context" "fmt" "log" "net" "os" "os/signal" "database/sql" "github.com/faruqfadhil/learn-go-docs/grpc-go-course/blog/blogpb" _ "github.com/go-sql-driver/mysql" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type server struct{} type blogItem struct { ID string AuthorID string Content string Title string } var db *sql.DB func (*server) CreateBlog(ctx context.Context, req *blogpb.CreateBlogRequest) (*blogpb.CreateBlogResponse, error) { fmt.Println("Create Request") blog := req.GetBlog() data := blogItem{ ID: blog.GetId(), AuthorID: blog.GetAuthorId(), Content: blog.GetContent(), Title: blog.GetTitle(), } stmtInsert, err := db.Prepare("Insert into blog_item(id,author_id,content,title) values(?,?,?,?)") if err != nil { return nil, status.Errorf( codes.Internal, fmt.Sprintf("Internal err %v", err), ) } _, err = stmtInsert.Exec(data.ID, data.AuthorID, data.Content, data.Title) if err != nil { return nil, status.Errorf( codes.Internal, fmt.Sprintf("Internal err %v", err), ) } return &blogpb.CreateBlogResponse{ Blog: &blogpb.Blog{ Id: data.ID, AuthorId: data.AuthorID, Content: data.Content, Title: data.Title, }, }, err } func (*server) ReadBlog(ctx context.Context, req *blogpb.ReadBlogRequest) (*blogpb.ReadBlogResponse, error) { fmt.Println("Read request") blogID := req.GetBlogId() sqlStmt := `Select * from blog_item where id=?` blog := db.QueryRow(sqlStmt, blogID) blogObj := blogItem{} var ( id string authorID string title string content string ) switch err := blog.Scan(&id, &authorID, &title, &content); err { case sql.ErrNoRows: return nil, status.Errorf( codes.NotFound, fmt.Sprintf("cannot found blog with specified ID"), ) case nil: blogObj.ID = id blogObj.AuthorID = authorID blogObj.Title = title blogObj.Content = content default: return nil, status.Errorf( codes.Internal, fmt.Sprintf("Internal error: %v", err), ) } return &blogpb.ReadBlogResponse{ Blog: &blogpb.Blog{ Id: blogObj.ID, AuthorId: blogObj.AuthorID, Title: blogObj.Title, Content: blogObj.Content, }, }, nil } func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) fmt.Println("Connecting to db...") var err error db, err = sql.Open("mysql", "frq:psswd@/blog_db") if err != nil { panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic } fmt.Println("Blog service started") lis, err := net.Listen("tcp", "0.0.0.0:50051") if err != nil { log.Fatalf("failed to listen : %v", err) } opts := []grpc.ServerOption{} s := grpc.NewServer(opts...) blogpb.RegisterBlogServiceServer(s, &server{}) go func() { fmt.Println("Starting server...") if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve : %v", err) } }() ch := make(chan os.Signal, 1) signal.Notify(ch, os.Interrupt) <-ch fmt.Println("Stopping server...") s.Stop() fmt.Println("Closing listenner...") lis.Close() defer db.Close() fmt.Println("End of program...") } <file_sep>/rekursif/rekursif.go package main import "fmt" func main() { // fmt.Println(faktorial(3)) // toFibonacci(11) toPrima(15) } func faktorial(n int) int { if n == 0 || n == 1 { return 1 } return n * faktorial(n-1) } func toFibonacci(n int) { for i := 1; i <= n; i++ { fmt.Println(fibonacci(i)) } } func fibonacci(n int) int { if n <= 2 { return 1 } return fibonacci(n-1) + fibonacci(n-2) } func toPrima(n int) { for i := 2; i <= n; i++ { if prima(i, i-1) == 1 { fmt.Println(i) } } } func prima(a int, n int) int { if n == 1 { return 1 } if a%n == 0 { return 0 } return prima(a, n-1) } <file_sep>/cmd/main.go package main import ( "fmt" "time" "github.com/faruqfadhil/learn-go-docs/channel" ) func main() { workerPoolMain() } func bufferedMain() { ch := make(chan int, 2) go channel.Write(ch) time.Sleep(2 * time.Second) for v := range ch { fmt.Println("read value", v, "from ch") time.Sleep(2 * time.Second) } } func workerPoolMain() { startTime := time.Now() noOfJobs := 100 go channel.Allocate(noOfJobs) done := make(chan bool) go channel.PrintResult(done) noOfWorkers := 10 channel.CreateWorkerPool(noOfWorkers) <-done endTime := time.Now() diff := endTime.Sub(startTime) fmt.Println("total time taken ", diff.Seconds(), "seconds") } <file_sep>/sayurboxintv/main.go package main import ( "bufio" "fmt" "io" "log" "os" "strconv" "strings" ) // // // ---------------------------------------------------------- // // // Q1: // // // make a function to solve a simple mathematic expression // // // that only consists of +, -, * operations and positive integers // // // input: String // // // output: integer // // // example // // // input: "0 - 5" // // // output: -5 // // // // input: "1 - 7 * 2 + 5" -> 1 - 14 + 5 -> -13 + 5 // // // output: -8 // // // input: "12 * 5 * 3" // // // output: 180 // // // ------------------------- func readLine(reader *bufio.Reader) string { str, _, err := reader.ReadLine() if err == io.EOF { return "" } return strings.TrimRight(string(str), "\r\n") } func main() { fmt.Println("Input the mathematical expression\nNote: between operand and operator should be separated by whitespace") reader := bufio.NewReader(os.Stdin) inputInArray := strings.Split(readLine(reader), " ") newArr := inputInArray needMultiplied := true for needMultiplied { needMultiplied = false last := false inputInArray = newArr for i := 1; i < len(newArr); i += 2 { firstNum := toNumber(newArr[i-1]) secondNum := toNumber(newArr[i+1]) // Handle if in the last operator. if i+2 > len(newArr)-1 { last = true } if newArr[i] == "*" { newArr = inputInArray[:i-1] newArr = append(newArr, fmt.Sprintf("%d", firstNum*secondNum)) if !last { newArr = append(newArr, inputInArray[i+2:]...) } inputInArray = newArr needMultiplied = true } else if newArr[i] == "/" { newArr = inputInArray[:i-1] newArr = append(newArr, fmt.Sprintf("%d", firstNum/secondNum)) if !last { newArr = append(newArr, inputInArray[i+2:]...) } inputInArray = newArr needMultiplied = true } } } agg, err := strconv.Atoi(newArr[0]) if err != nil { log.Fatalf(err.Error()) } for i := 1; i < len(newArr); i += 2 { num, err := strconv.Atoi(newArr[i+1]) if err != nil { log.Fatalf(err.Error()) } if newArr[i] == "-" { agg -= num } if newArr[i] == "+" { agg += num } } fmt.Println("Result = ", agg) } func toNumber(s string) int { num, err := strconv.Atoi(s) if err != nil { log.Fatalf("error when parsing to num: %s", err) } return num } <file_sep>/console-input/consoleinput.go package main import ( "bufio" "fmt" "io" "os" "strconv" "strings" ) func main() { // usingScanf() // usingScan() // usingScanLn() // usingBufio() // intoIntSlice() intoStringSlice() } func usingScanf() { var i int fmt.Scanf("%d", &i) fmt.Println("hasil = ", i) var j string fmt.Scanf("%s", &j) fmt.Println("hasil = ", j) } func usingScan() { var i int fmt.Scan(&i) fmt.Println("hasil = ", i) var j string fmt.Scan(&j) fmt.Println("hasil = ", j) } func usingScanLn() { var i int fmt.Scanln(&i) fmt.Println("hasil = ", i) var j string fmt.Scanln(&j) fmt.Println("hasil = ", j) } func usingBufio() { reader := bufio.NewReader(os.Stdin) text, _ := reader.ReadString('\n') fmt.Println(text) scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { fmt.Println(scanner.Text()) } } func intoIntSlice() { var n int fmt.Scan(&n) reader := bufio.NewReader(os.Stdin) for i := 0; i < n; i++ { text := strings.Split(readLine(reader), " ") anuInt := []int{} for _, n := range text { i, _ := strconv.Atoi(string(n)) anuInt = append(anuInt, i) } fmt.Println(anuInt) } } func intoStringSlice() { var n int fmt.Scan(&n) reader := bufio.NewReader(os.Stdin) for i := 0; i < n; i++ { text := strings.Split(readLine(reader), " ") fmt.Println(text) } } func readLine(reader *bufio.Reader) string { str, _, err := reader.ReadLine() if err == io.EOF { return "" } return strings.TrimRight(string(str), "\r\n") } <file_sep>/grpc-go-course/calculator/calculator_client/client.go package main import ( "context" "fmt" "io" "log" "time" "github.com/faruqfadhil/learn-go-docs/grpc-go-course/calculator/calculatorpb" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) func main() { cc, err := grpc.Dial("localhost:50051", grpc.WithInsecure()) if err != nil { log.Fatalf("could not connect : %v", err) } defer cc.Close() c := calculatorpb.NewCalculatorServiceClient(cc) // doUnary(c) // doServerStreaming(c) // doClientStreaming(c) // doBidirectionalStreaming(c) doErrorUnary(c) } func doUnary(c calculatorpb.CalculatorServiceClient) { req := &calculatorpb.CalculatorRequest{ Calculating: &calculatorpb.Calculating{ NumbOne: 3, NumbTwo: 10, }, } res, err := c.Calculate(context.Background(), req) if err != nil { log.Fatalf("error while calling calculator RPC: %v", err) } log.Printf("response = %v", res.Result) } func doServerStreaming(c calculatorpb.CalculatorServiceClient) { res, err := c.PrimeNumberDecomp(context.Background(), &calculatorpb.PrimeNumberDecompRequest{ PrimeNumber: &calculatorpb.PrimeNumber{ Prime: 120, }, }) if err != nil { log.Fatalf("error while calling primeDecomp %v", err) } for { msg, err := res.Recv() if err == io.EOF { break } if err != nil { log.Fatalf("error while reading streaming %v", err) } log.Printf("response : %v", msg.GetResult()) } } func doClientStreaming(c calculatorpb.CalculatorServiceClient) { requests := []*calculatorpb.ComputeAverageRequest{ &calculatorpb.ComputeAverageRequest{ Number: 1, }, &calculatorpb.ComputeAverageRequest{ Number: 2, }, &calculatorpb.ComputeAverageRequest{ Number: 3, }, &calculatorpb.ComputeAverageRequest{ Number: 4, }, } stream, err := c.ComputeAverage(context.Background()) if err != nil { log.Fatalf("error while calling compute avg %v", err) } for _, req := range requests { fmt.Printf("sending req : %v\n", req) stream.Send(req) time.Sleep(1000 * time.Millisecond) } msg, err := stream.CloseAndRecv() if err != nil { log.Fatalf("error while receiving response from compute avg %v", err) } fmt.Printf("response : %v\n", msg) } func doBidirectionalStreaming(c calculatorpb.CalculatorServiceClient) { reqs := []int32{1, 9, 2, 3, 16, 4, 32} stream, err := c.FindMaximum(context.Background()) if err != nil { log.Fatalf("error while creating stream:%v", err) } waitChan := make(chan struct{}) go func() { for _, req := range reqs { fmt.Println("sending req: ", req) stream.Send(&calculatorpb.FindMaximumRequest{ Number: req, }) time.Sleep(1 * time.Second) } stream.CloseSend() }() go func() { for { msg, err := stream.Recv() if err == io.EOF { break } if err != nil { log.Fatalf("error while receive data:%v", err) break } fmt.Println("received: ", msg.GetResult()) } close(waitChan) }() <-waitChan } func doErrorUnary(c calculatorpb.CalculatorServiceClient) { doErrorCall(c, 10) doErrorCall(c, -2) } func doErrorCall(c calculatorpb.CalculatorServiceClient, n int32) { res, err := c.SquareRoot(context.Background(), &calculatorpb.SquareRootRequest{ Number: n, }) if err != nil { respErr, ok := status.FromError(err) if ok { fmt.Println(respErr.Message()) fmt.Println(respErr.Code()) if respErr.Code() == codes.InvalidArgument { fmt.Println("we probably send a negative number !") } return } else { log.Fatalf("Big error calling SquareRoot:%v", err) } } fmt.Println("result = ", res.GetResult()) } <file_sep>/channel/buffered.go package channel import "fmt" // Write a channel. func Write(ch chan int) { for i := 0; i < 5; i++ { ch <- i fmt.Println("successfully wrote", i, "to ch") } close(ch) } <file_sep>/tiketinterview/usintv1/main.go package main import "fmt" // Input : // []{}() // {[(){}[]]} // [][[]]()(){}{} // [{]} // }{ // Output // []{}() = true // {[(){}[]]} = true // [][[]]()(){}{} = true // [{]} = false // }{ = false func main() { input := "[]{}()" fmt.Println(validate(input)) input = "{[(){}[]]}" fmt.Println(validate(input)) input = "[][[]]()(){}{}" fmt.Println(validate(input)) input = "[{]}" fmt.Println(validate(input)) input = "}{" fmt.Println(validate(input)) } func isIdentic(a, b string) bool { if a == "{" && b == "}" { return true } if a == "[" && b == "]" { return true } if a == "(" && b == ")" { return true } return false } func validate(input string) bool { charcter := map[string]string{ "[": "]", "]": "]", "{": "}", "}": "{", "(": ")", ")": "(", } characterClose := map[string]bool{ "]": true, "}": true, ")": true, } characterOpen := map[string]bool{ "{": true, "[": true, "(": true, } if _, ok := characterOpen[string(input[len(input)-1])]; ok { return false } // var resolve bool firstItem := string(input[0]) if _, ok := charcter[firstItem]; !ok { return false } if _, ok := characterClose[firstItem]; ok { return false } resolveCount := map[string]int{} var ( key1 string = "keyFor}" key2 string = "keyFor]" key3 string = "keyFor)" ) for i := 0; i < len(input); i++ { if _, ok := characterOpen[string(input[i])]; ok { if charSejenis, ok := charcter[string(input[i])]; ok { inp := string(input[i]) if charSejenis == key1 || inp == key1 { resolveCount[key1]++ } else if charSejenis == key2 || inp == key2 { resolveCount[key2]++ } else if charSejenis == key3 || inp == key3 { resolveCount[key3]++ } } } if _, ok := characterClose[string(input[i])]; ok { if charSejenis, ok := charcter[string(input[i])]; ok { inp := string(input[i]) if charSejenis == key1 || inp == key1 { resolveCount[key1]-- } else if charSejenis == key2 || inp == key2 { resolveCount[key2]-- } else if charSejenis == key3 || inp == key3 { resolveCount[key3]-- } } } // if i == len(input)-1 { // for , count := range resolveCount { // if count == 1 && string(input[i]) != { // } // } // if string(input[i]) != firstItem { // return false // } // } if i == len(input)-1 { a := string(input[len(input)-2]) b := string(input[len(input)-1]) for key, count := range resolveCount { if count == 1 { switch key { case key1: if !isIdentic("}", b) && !isIdentic("{", b) { return false } case key2: if !isIdentic("]", b) && !isIdentic("[", b) { return false } case key3: if !isIdentic("(", b) && !isIdentic(")", b) { return false } } // if !isIdentic(a, b) { // return false // } } } // charA := charcter[a] // charB := charcter[b] // if != ) { // return false // } } } allResolved := true for _, val := range resolveCount { if val != 0 { allResolved = false } } lastItem := string(input[len(input)-1]) if !allResolved && lastItem == firstItem { return false } // if allResolved && lastItem != firstItem { // return false // } // if notResolved { // lastItem := string(input[len(input)-1]) // if lastItem != firstItem { // return false // } // } // for resolve { // for i := 1; i < len(input); i++ { // // if not valid char // if _, ok := charcter[string(input[i])]; !ok { // return false // } // if _, ok := characterOpen[temp]; ok { // if _, ok := characterOpen[string(input[i])]; ok { // resolve = true // temp = string(input[i]) // } // } // // // if begin with char close. // // if _, ok := characterClose[string(input[i])]; ok && i == 0 { // // return false // // } // // if finished with open char. // // if _, ok := characterOpen[string(input[len(input)-1])]; ok { // // return false // // } // } // } return true } <file_sep>/data-structures/queue/queue.go package main import ( "fmt" "strings" ) type Queue struct { Queue *QueueNode } type QueueNode struct { Data int Next *QueueNode } func (q *Queue) Enqueue(data int) { newData := &QueueNode{ Data: data, } if q.Queue == nil { q.Queue = newData return } temp := q.Queue for temp.Next != nil { temp = temp.Next } temp.Next = newData } func (q *Queue) Dequeue() { if q.Queue == nil { fmt.Println("empty queue") } q.Queue = q.Queue.Next } func (q *Queue) Print() string { temp := q.Queue out := []string{} for temp != nil { out = append(out, fmt.Sprintf("%d", temp.Data)) temp = temp.Next } return strings.Join(out, ",") } func main() { queue := &Queue{} queue.Enqueue(10) queue.Enqueue(20) queue.Dequeue() queue.Dequeue() queue.Enqueue(30) queue.Enqueue(40) queue.Enqueue(50) queue.Dequeue() fmt.Println(queue.Print()) } <file_sep>/gudangada/gudangada.go package main import ( "fmt" "sort" ) func main() { n := []int{3, 1, 3} out := [][]int{} for i := 0; i < len(n); i++ { n[i] = n[i] * n[i] } sort.Ints(n) firtsNumIteration := 0 secondNumIteration := len(n) - 2 lastNumIteration := len(n) - 1 for firtsNumIteration < secondNumIteration { if n[firtsNumIteration]+n[secondNumIteration] == n[lastNumIteration] { out = append(out, []int{n[firtsNumIteration], n[secondNumIteration], n[lastNumIteration]}) firtsNumIteration++ secondNumIteration-- lastNumIteration-- } else { } } fmt.Println(out) }
a56752899522497bbc5390ef52b53261c3a72710
[ "Go Module", "Go" ]
28
Go
faruqfadhil/learn-go-docs
2c38fd9626ec0a9a2b14fdc75d0421904e632889
cbb44f9715a809d91e5def4a1b0a1f2f7a55be1d
refs/heads/main
<repo_name>TDuong90/DVD-Rental<file_sep>/Query.sql --Use SELECT statement to grab the first and last names of every customer and their email address. SELECT first_name, last_name, email FROM customer; --A customer wants to know the types of ratings we have in our database SELECT DISTINCT rating FROM film; --A customer wants know all the movies available where the length is less than 60 minutes SELECT * FROM film WHERE length < 60; --A customer wants to rent movie that cost less than $4.99 and is rated R SELECT film_id, title, description, release_year, rental_rate, rating FROM film WHERE rental_rate < 4.99 AND rating = 'R'; --A customer forgot their wallet at our store! What's the email for customer <NAME>? SELECT first_name, last_name, email FROM customer WHERE first_name = 'Nancy' AND last_name = 'Thomas'; --A customer wants to know what the movie "Outlaw Hanky" is about SELECT title, description from film WHERE title = 'Outlaw Hanky'; --A customer is late on their return, Can you get the phone number for the customer who lives at '259 Ipoh Drive'? SELECT phone FROM address WHERE address = '259 Ipoh Drive'; --What are the customer ids of the first 10 customers who created a payment? SELECT customer_id FROM payment WHERE amount != 0.00 ORDER BY payment_date ASC LIMIT 10; --What are the titles of the 5 shortest (in lenght of runtime) movies? SELECT title, length FROM film ORDER BY length ASC LIMIT 5; --How many movies are there with 50 mins or less run time. SELECT COUNT(length) from film WHERE length < 50; -- SELECT * FROM customer WHERE first_name IN ('John','Dennis'); -- SELECT * FROM customer WHERE first_name LIKE 'J%' AND last_name LIKE 'S%' ORDER BY last_name; --How many payment transactions were greater than $5.00? SELECT COUNT(* )FROM payment WHERE amount > 5.00; --How many actors have a first name that starts with the letter P? SELECT COUNT(*) FROM actor WHERE first_name LIKE ('P'); --How many unique districts are our customers from? SELECT COUNT(DISTINCT district) FROM address; --Retrieve the list of names for those distinct districts from the previous question SELECT DISTINCT district FROM address ORDER BY district; --How many films have a rating of R and a replacement cost between $5 and $15? SELECT COUNT(*) FROM film WHERE rating = 'R' AND replacement_cost BETWEEN 5 and 15; --How many films have the word Truman somewhere in the title? SELECT COUNT(*)FROM film WHERE title ILIKE '%Truman%'; --How many payments did each staff member handle and who gets the bonus? SELECT staff_id, COUNT(payment_id) AS total_transaction FROM payment GROUP BY staff_id ORDER BY total_transaction; --What is the average replacement cost per MPAA rating? SELECT rating, ROUND(AVG(replacement_cost),2) AS AVG_replacement_cost FROM film GROUP BY rating ORDER BY avg_replacement_cost; --What are the customer ids of the top 5 customers by total spend? SELECT customer_id, SUM(amount) FROM payment GROUP BY customer_id ORDER BY SUM(amount) DESC LIMIT 5; --What customer IDs are eligible for platinum status?(40 or more transaction payments) SELECT customer_id, COUNT(payment_id) FROM payment GROUP BY customer_id HAVING COUNT(payment_id) >= 40; --What are the customer ID of customers who have spent more than $100 in payment transactions with our staff_id 2? SELECT customer_id, staff_id, SUM(amount) FROM payment WHERE staff_id = 2 GROUP BY staff_id, customer_id HAVING SUM(amount) >100; --What's the customer IDS of customer who have spent at least $110 with the staff member ID 2 ? SELECT customer_id, staff_id, SUM(amount) FROM payment WHERE staff_id = 2 GROUP BY customer_id, staff_id HAVING SUM(amount) >110; --How many films begin with the letter J? SELECT COUNT(*) FROM film WHERE title ILIKE 'J%'; --What customer has the highest customer ID number whose name starts with an 'E' and has an address ID lower than 500? SELECT * FROM customer WHERE first_name ILIKE 'E%' AND address_id <500 ORDER BY customer_id DESC LIMIT 1; --What are the emails of the customers who live in California? SELECT email, district FROM customer INNER JOIN address ON customer.address_id = address.address_id WHERE district = 'California'; --Get a list of all the movies with the actor '<NAME>' has been in. SELECT film.title, actor.first_name, actor.last_name FROM film INNER JOIN film_actor ON film.film_id = film_actor.film_id INNER JOIN actor ON film_actor.actor_id = actor.actor_id WHERE actor.first_name = 'Nick' AND actor.last_name = 'Wahlberg';<file_sep>/README.md # DVD-Rental ### Use SQL to have more insight from a dvd store.
18b8c9fcbf518b06c7068169a51a8155ddbc9703
[ "Markdown", "SQL" ]
2
SQL
TDuong90/DVD-Rental
2a2c376ff93711def4b7857da2df9bfdb01fda9e
8576b339ba263fb16c803c35d50e2c510f009ac9
refs/heads/master
<file_sep> import numpy as np #Functions to be used in plots #Defining constants alpha = 1/137.036 #Fine-s[i]tructure cons[i]tant e = np.sqrt(4*np.pi*alpha) #Electron charge sinWein2 = 0.2397 #sin^2(theta_W) mw = 80.379 gw=e/(np.sqrt(sinWein2)) mH = 125.18 gammaH=0.013 mz = 91.1876 #gz = 0.7180 gz = e/((np.sqrt(sinWein2))*np.sqrt(1-sinWein2)) gammaz = 2.4952 muonBottom = 1# Set to 1 in case of mM->bB, 0 in case of eE->cC def particles(muonBottom): if(muonBottom == 1): m = 0.10566 #Muon mass in GeV M = 4.18 #Bottom quark mass in GeV c_vm = -0.04 c_am = -0.5 c_vb = -0.35 c_ab = -0.5 Q = -1/3*e #bottom quark charge return (m,M,c_vm,c_am,c_vb,c_ab,Q) else: m = 0.0005 #electron masss in GeV M = 1.3 #charm quark mass in GeV c_vm = -0.04 c_am = -0.5 c_vb = 0.19 c_ab = 0.5 Q = 2/3*e #charm quark charge return (m,M,c_vm,c_am,c_vb,c_ab,Q) (m,M,c_vm,c_am,c_vb,c_ab,Q) = particles(muonBottom) def pi(s): return np.sqrt(s/4 - m**2) def pf(s): return np.sqrt(s/4 - M**2) ######### def f_s(s): return (gz**2)/((s-mz**2)**2+mz**2*gammaz**2) def kappas(s): K_a = (8*e**2*Q**2)/(s**2) #K_gamma K_z1 = 8*gz**2*f_s(s)*((c_vm**2+c_am**2)*(c_vb**2+c_ab**2) + 4*c_vm*c_am*c_vb*c_ab) #K_Z1 K_z2 = 8*gz**2*f_s(s)*((c_vm**2+c_am**2)*(c_vb**2+c_ab**2) - 4*c_vm*c_am*c_vb*c_ab) #K_Z2 K_az1 = -(16*e*Q*(s-mz**2)/(3*s))*f_s(s)*(c_vm*c_vb+c_am*c_ab) #K_gammaz1 K_az2 = -(16*e*Q*(s-mz**2)/(3*s))*f_s(s)*(c_vm*c_vb-c_am*c_ab) #K_gammaz1 K_H = (gw**4*m**2*M**2)/(mw**4*((s-mH**2)**2+mH**2*gammaH**2)) return (K_a,K_z1,K_z2,K_az1,K_az2,K_H) #To help you with your ABC's def ABCs(s): (K_a,K_z1,K_z2,K_az1,K_az2,K_H) = kappas(s) A = (s/4 - m**2)*(s/4 - M**2)*(2*K_a + K_z1 + K_z2 + K_az1 + K_az2) B = 0.5*s*np.sqrt((s/4-m**2)*(s/4-M**2))*(-K_z1 + K_z2 -K_az1 + K_az2) C = 0.25*s*(m**2+M**2)*(K_az1+K_az2) + 0.25*s*(2*K_a + K_z1 + K_z2 + K_az1 + K_az2) A_a = 2*K_a*(s/4 - m**2)*(s/4-M**2) B_a = K_a*((s**2)/8+(s/2)*(m**2+M**2)) A_z = (pi(s)*pf(s))**2*(K_z1+K_z2) B_z = s/2*pi(s)*pf(s)*(K_z2-K_z1) C_z = s/4*(K_z1+K_z2) + 8*gz**2*f_s(s)*(-M**2*(c_vm**2+c_am**2)*c_vb**2+c_ab**2*(s/4+pi(s))-m**2*(c_vb**2+c_ab**2)*c_vm*c_am*(s/4+pf(s))+2*m**2*M**2*c_vm*c_am*c_vb*c_ab) A_az = (pi(s)*pf(s))**2*(K_az1+K_az2) B_az = s/2*pi(s)*pf(s)*(K_az2-K_az1) C_az = (s/4+pi(s)**2*pf(s)**2)*(K_az1+K_az2) -3*(16*e*Q*(s-mz**2)/(3*s))*f_s(s)*c_vm*c_vb*s/2*(m**2+M**2) #Spin-averaged matrix element for pure Higgs contribution MH = K_H*((s**2)/4 - s*(m**2+M**2)+4*m**2*M**2) return (A,B,C,A_a,B_a,A_z,B_z,C_z,A_az,B_az,C_az,MH) def readData(f): lines = f.readlines()[3:] n = len(lines) lines2=[None]*n lines3=[None]*2*n data1 = [0]*2*n #mantissa data2 = [0]*2*n #exponent # data3 = [0]*2*n #Product col1 = [0]*n col2 = [0]*n for i in range(0,n): a=lines[i] a=a[:-1] lines[i]=a lines2[i]=lines[i].split() k = 0 for j in range(0,n): lines3[k]=lines2[j][0].split('E') data1[k] = float(lines3[k][0]) data2[k] = float(lines3[k][1]) col1[j]=data1[k]*10**data2[k] lines3[k+1]=lines2[j][1].split('E') data1[k+1] = float(lines3[k+1][0]) data2[k+1] = float(lines3[k+1][1]) col2[j]=data1[k+1]*10**data2[k+1] k=k+2 return (col1,col2) print(col1) print(n) f.close <file_sep> import glob import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.optimize import least_squares from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split from functions import extractExpedition from functions import secondsToDates from functions import getWeatherData from functions import getHeaderData from functions import linearRegression import re import os test_header = pd.read_csv('/home/haakon/FYS5555/Project2/data/POLA01/POLA-01_2020-01-06_2020-01-07_summary_Header.csv') test_trending = pd.read_csv('/home/haakon/FYS5555/Project2/data/POLA01/POLA-01_2020-01-06_2020-01-07_summary_Trending.csv') test_weather = pd.read_csv('/home/haakon/FYS5555/Project2/data/POLA01/POLA-01_2020-01-06_2020-01-07_summary_Weather.csv') print(test_trending) ####################################################################### #Load weather files for 2018 ####################################################################### filenamesPOLA1 = glob.glob('/home/haakon/FYS5555/Project2/data/POLA01/POLA-01_2018*_summary_Weather.csv') filenamesPOLA2 = glob.glob('/home/haakon/FYS5555/Project2/data/POLA02/POLA-02_2018*_summary_Weather.csv') filenamesPOLA3 = glob.glob('/home/haakon/FYS5555/Project2/data/POLA03/POLA-03_2018*_summary_Weather.csv') ####################################################################### #Load header files ####################################################################### filenamesPOLA1_H = glob.glob('/home/haakon/FYS5555/Project2/data/POLA01/POLA-01_2018*_summary_Header.csv') filenamesPOLA2_H = glob.glob('/home/haakon/FYS5555/Project2/data/POLA02/POLA-02_2018*_summary_Header.csv') filenamesPOLA3_H = glob.glob('/home/haakon/FYS5555/Project2/data/POLA03/POLA-03_2018*_summary_Header.csv') ####################################################################### #Extract data taken during expedition and concatenate to a single array ####################################################################### weatherArr1 = extractExpedition(filenamesPOLA1) weatherArr2 = extractExpedition(filenamesPOLA2) weatherArr3 = extractExpedition(filenamesPOLA3) headerArr1 = extractExpedition(filenamesPOLA1_H) headerArr2 = extractExpedition(filenamesPOLA2_H) headerArr3 = extractExpedition(filenamesPOLA3_H) ####################################################################### #Date of each measurement ####################################################################### # timeArray1, dateArray1, contractedDateArray1 = secondsToDates(weatherArr1) # timeArray2, dateArray2, contractedDateArray2 = secondsToDates(weatherArr2) # timeArray3, dateArray3, contractedDateArray3 = secondsToDates(weatherArr3) ####################################################################### #Weather data ####################################################################### indoorTemp1, outdoorTemp1, pressure1 = getWeatherData(weatherArr1) indoorTemp2, outdoorTemp2, pressure2 = getWeatherData(weatherArr2) indoorTemp3, outdoorTemp3, pressure3 = getWeatherData(weatherArr3) ####################################################################### #Header data ####################################################################### print('timearray1 length: ', len(headerArr1[:,1])) print('timearray2 length: ', len(headerArr2[:,1])) timeArray1, dateArray1, contractedDateArray1 = secondsToDates(headerArr1) timeArray2, dateArray2, contractedDateArray2 = secondsToDates(headerArr2) timeArray3, dateArray3, contractedDateArray3= secondsToDates(headerArr3) rawRate1, longitude1, latitude1 = getHeaderData(headerArr1, 'POLA1') rawRate2, longitude2, latitude2 = getHeaderData(headerArr2, 'POLA2') rawRate3, longitude3, latitude3 = getHeaderData(headerArr3, 'POLA3') ####################################################################### #Plots ####################################################################### # fig0 = plt.figure(0) # ax = fig0.gca() # # legends.append(r'$\sigma_b$ numeric') # # legends.append(r'$\sigma_b$ analytic') # #plt.plot(exponent, sigma_k, linestyle = '-',label='$\sigma_k^2/n_k$') # plt.plot(timeArray, indoorTemp,'r',linestyle = '-',label='$indoor$') # plt.plot(timeArray, outdoorTemp,'b',linestyle = '-',label='$outdoor$') # # plt.xlabel('Date [d/m/2018]', size=14) # plt.ylabel('Indoor Temperature [$^\circ$C]', size=14) # # plt.legend(fontsize = 12) # ax.set_xticks(timeArray[0:-1:150]) # ax.set_xticklabels(contractedDateArray[0:-1:150], rotation='horizontal') # plt.grid('on') # ax.tick_params(axis='both', which='major', labelsize=14) # # Show the minor grid lines with very faint and almost transparent grey lines # plt.minorticks_on() # ax.tick_params(axis='x', which='minor', bottom=False) # plt.tight_layout() # # plt.show() # # fig1 = plt.figure(1) # ax = fig1.gca() # # legends.append(r'$\sigma_b$ numeric') # # legends.append(r'$\sigma_b$ analytic') # #plt.plot(exponent, sigma_k, linestyle = '-',label='$\sigma_k^2/n_k$') # plt.plot(timeArray, pressure,'k',linestyle = '-',label='$pressure$') # # # plt.xlabel('Date [d/m/2018]', size=14) # plt.ylabel('Pressure [hPa]', size=14) # # # plt.legend(fontsize = 12) # ax.set_xticks(timeArray[0:-1:150]) # ax.set_xticklabels(contractedDateArray[0:-1:150], rotation='horizontal') # plt.grid('on') # ax.tick_params(axis='both', which='major', labelsize=14) # # Show the minor grid lines with very faint and almost transparent grey lines # plt.minorticks_on() # ax.tick_params(axis='x', which='minor', bottom=False) # # # plt.show() ####################################################################### #POLA2 ####################################################################### ####################################################################### #Weather plots ####################################################################### fig0 = plt.figure(0) ax = fig0.gca() plt.title('POLA1', size = 14) plt.plot(timeArray1,indoorTemp1,c='r', label = 'Indoor temperature') plt.plot(timeArray1,[np.mean(indoorTemp1)]*len(indoorTemp1), 'r',linestyle = '--',label = 'Average indoor temperature') plt.plot(timeArray1,outdoorTemp1,c='b', label = 'Outdoor temperature') plt.plot(timeArray1,[np.mean(outdoorTemp1)]*len(outdoorTemp1), 'b',linestyle = '--',label = 'Average outdoor temperature') # plt.scatter(timeArray2,indoorTemp2,s=0.9,c='r', label = 'Indoor temperature') # plt.plot(timeArray2,[np.mean(indoorTemp2)]*len(indoorTemp2), 'r',label = 'Average indoor temperature') # plt.scatter(timeArray2,outdoorTemp2,s=0.9,c='b', label = 'Outdoor temperature') # plt.plot(timeArray2,[np.mean(outdoorTemp2)]*len(outdoorTemp2), 'b',label = 'Average outdoor temperature') # # plt.scatter(timeArray3,indoorTemp3,s=0.9,c='r', label = 'Indoor temperature') # plt.plot(timeArray3,[np.mean(indoorTemp3)]*len(indoorTemp3), 'r',label = 'Average indoor temperature') # plt.scatter(timeArray3,outdoorTemp3,s=0.9,c='b', label = 'Outdoor temperature') # plt.plot(timeArray3,[np.mean(outdoorTemp3)]*len(outdoorTemp3), 'b',label = 'Average outdoor temperature') plt.xlabel('Date [d/m/2018]', size=16) plt.ylabel('Indoor Temperature [$^\circ$C]', size=16) plt.legend(fontsize = 14) ax.set_xticks(timeArray1[0:-1:200]) ax.set_xticklabels(contractedDateArray1[0:-1:200], rotation='horizontal') plt.grid('on') ax.tick_params(axis='both', which='major', labelsize=16) # Show the minor grid lines with very faint and almost transparent grey lines plt.minorticks_on() ax.tick_params(axis='x', which='minor', bottom=False) plt.tight_layout() plt.show() ####################################################################### #pressure ####################################################################### fig1 = plt.figure(1) ax = fig1.gca() # legends.append(r'$\sigma_b$ numeric') # legends.append(r'$\sigma_b$ analytic') #plt.plot(exponent, sigma_k, linestyle = '-',label='$\sigma_k^2/n_k$') # plt.plot(timeArray, pressure,linestyle='dotted',label='$pressure$') plt.scatter(timeArray1,pressure1,s=0.9,c='g', label = 'POLA1') plt.plot(timeArray1, [np.mean(pressure1)]*len(pressure1), 'g', label = 'POLA1 average') plt.scatter(timeArray2,pressure2,s=0.9,c='b', label = 'POLA2') plt.plot(timeArray2, [np.mean(pressure2)]*len(pressure2), 'b', label = 'POLA2 average') plt.scatter(timeArray3,pressure3,s=0.9,c='r', label = 'POLA3') plt.plot(timeArray3, [np.mean(pressure3)]*len(pressure3), 'r', label = 'POLA3 average') plt.xlabel('Date [d/m/2018]', size=16) plt.ylabel('Pressure [hPa]', size=16) plt.legend(fontsize = 14) ax.set_xticks(timeArray2[0:-1:400]) ax.set_xticklabels(contractedDateArray2[0:-1:400], rotation='horizontal') plt.grid('on') ax.tick_params(axis='both', which='major', labelsize=14) # Show the minor grid lines with very faint and almost transparent grey lines plt.minorticks_on() ax.tick_params(axis='x', which='minor', bottom=False) plt.show() ####################################################################### #Header plots ####################################################################### fig2 = plt.figure(2) ax = fig2.gca() # legends.append(r'$\sigma_b$ numeric') # legends.append(r'$\sigma_b$ analytic') #plt.plot(exponent, sigma_k, linestyle = '-',label='$\sigma_k^2/n_k$') # plt.plot(timeArray1_H,rawRate1,linestyle='dotted',label='POLA1') # plt.plot(timeArray2_H,rawRate2,linestyle='dotted',label='POLA2') # plt.plot(timeArray3_H,rawRate3,linestyle='dotted',label='POLA3') #plot every 22th measurement (corresponding to approximately 12h since each measurement duration is about 2000s) plt.scatter(timeArray1[0:-1:8],rawRate1[0:-1:8],s=10,c='g', label = 'POLA1') plt.scatter(timeArray2[0:-1:22],rawRate2[0:-1:22],s=10, label = 'POLA2') plt.scatter(timeArray3[0:-1:22],rawRate3[0:-1:22],s=10,c='r', label = 'POLA3') # plt.plot(dateArray12h1,adjustedRawRate12h1,'g', label = 'POLA1') # plt.plot(dateArray12h2,adjustedRawRate12h2, label = 'POLA2') # plt.plot(dateArray12h3,adjustedRawRate12h3,'r', label = 'POLA3') plt.xlabel('Date [d/m/2018]', size=16) plt.ylabel('Raw rate [#events/s]', size=16) plt.legend(fontsize = 14) ax.set_ylim([0,50]) ax.set_xticks(timeArray2[0:-1:400]) ax.set_xticklabels(contractedDateArray2[0:-1:400], rotation='horizontal') plt.grid('on') ax.tick_params(axis='both', which='major', labelsize=16) # Show the minor grid lines with very faint and almost transparent grey lines plt.minorticks_on() ax.tick_params(axis='x', which='minor', bottom=False) plt.show() ####################################################################### #Latitude ####################################################################### fig3 = plt.figure(3) ax = fig3.gca() # legends.append(r'$\sigma_b$ numeric') # legends.append(r'$\sigma_b$ analytic') #plt.plot(exponent, sigma_k, linestyle = '-',label='$\sigma_k^2/n_k$') plt.plot(timeArray1,latitude1,'g',linestyle='-',label='POLA1') # plt.plot(timeArray2_H,rawRate2,linestyle='dotted',label='POLA2') # plt.plot(timeArray3_H,rawRate3,linestyle='dotted',label='POLA3') #plot every 22th measurement (corresponding to approximately 12h since each measurement duration is about 2000s) # plt.scatter(timeArray1_H,latitude1,s=10,c='g', label = 'POLA1') # plt.scatter(timeArray2_H[0:-1:22],rawRate2[0:-1:22],s=10, label = 'POLA2') # plt.scatter(timeArray3_H[0:-1:22],rawRate3[0:-1:22],s=10,c='r', label = 'POLA3') plt.xlabel('Date [d/m/2018]', size=16) plt.ylabel('Latitude [$^\circ$]', size=16) plt.legend(fontsize = 14) ax.set_ylim([60,90]) ax.set_xticks(timeArray2[0:-1:400]) ax.set_xticklabels(contractedDateArray2[0:-1:400], rotation='horizontal') plt.grid('on') ax.tick_params(axis='both', which='major', labelsize=16) # Show the minor grid lines with very faint and almost transparent grey lines plt.minorticks_on() ax.tick_params(axis='x', which='minor', bottom=False) plt.show() ####################################################################### #Longitude ####################################################################### fig4 = plt.figure(4) ax = fig4.gca() # legends.append(r'$\sigma_b$ numeric') # legends.append(r'$\sigma_b$ analytic') #plt.plot(exponent, sigma_k, linestyle = '-',label='$\sigma_k^2/n_k$') plt.plot(timeArray1,longitude1,'g',linestyle='-',label='POLA1') # plt.plot(timeArray2_H,rawRate2,linestyle='dotted',label='POLA2') # plt.plot(timeArray3_H,rawRate3,linestyle='dotted',label='POLA3') #plot every 22th measurement (corresponding to approximately 12h since each measurement duration is about 2000s) # plt.scatter(timeArray1_H[0:-1:5],latitude1[0:-1:5],s=10,c='g', label = 'POLA1') # plt.scatter(timeArray2_H[0:-1:22],rawRate2[0:-1:22],s=10, label = 'POLA2') # plt.scatter(timeArray3_H[0:-1:22],rawRate3[0:-1:22],s=10,c='r', label = 'POLA3') plt.xlabel('Date [d/m/2018]', size=14) plt.ylabel('Longitude [$^\circ$]', size=14) plt.legend(fontsize = 12) ax.set_ylim([-40,40]) ax.set_xticks(timeArray2[0:-1:400]) ax.set_xticklabels(contractedDateArray2[0:-1:400], rotation='horizontal') plt.grid('on') ax.tick_params(axis='both', which='major', labelsize=14) # Show the minor grid lines with very faint and almost transparent grey lines plt.minorticks_on() ax.tick_params(axis='x', which='minor', bottom=False) plt.show() ####################################################################### #Raw rate vs pressure ####################################################################### fig5 = plt.figure(5) ax = fig5.gca() # legends.append(r'$\sigma_b$ numeric') # legends.append(r'$\sigma_b$ analytic') #plt.plot(exponent, sigma_k, linestyle = '-',label='$\sigma_k^2/n_k$') # plt.plot(pressure1[0:-1:22],rawRate1[0:-1:22],'g',linestyle='-',label='POLA1') # plt.plot(timeArray2_H,rawRate2,linestyle='dotted',label='POLA2') # plt.plot(timeArray3_H,rawRate3,linestyle='dotted',label='POLA3') #plot every 22th measurement (corresponding to approximately 12h since each measurement duration is about 2000s) # plt.scatter(pressure1,rawRate1,s=10,c='g', label = 'POLA1') # plt.scatter(pressure2,rawRate2,s=10,c='b', label = 'POLA2') # plt.scatter(pressure3,rawRate3,s=10,c='r', label = 'POLA3') #Do a simple linear regression using least squares # Create linear regression object # fig9 = plt.figure(9) x1,y1,slope1,intercept1 = linearRegression(pressure1, rawRate1) x2,y2,slope2,intercept2 = linearRegression(pressure2, rawRate2) x3,y3,slope3,intercept3 = linearRegression(pressure3, rawRate3) # print(Y) print('slope1: ', slope1, 'y_intercept1: ', intercept1) print('slope2: ', slope2, 'y_intercept2: ', intercept2) print('slope3: ', slope3, 'y_intercept3: ', intercept3) plt.scatter(pressure1,rawRate1,s=10,c='g', label = 'POLA1') plt.scatter(pressure2,rawRate2,s=10,c='b', label = 'POLA2') plt.scatter(pressure3,rawRate3,s=10,c='r', label = 'POLA3') plt.plot(x1, y1,'k', label = 'POLA1 fitted') plt.plot(x2, y2, 'magenta', label = 'POLA2 fitted') plt.plot(x3, y3, 'cyan', label = 'POLA3 fitted') plt.xlabel('Pressure [hPa]', size=16) plt.ylabel('Raw rate [#events/s]', size=16) plt.legend(fontsize = 14) # ax.set_ylim([20,50]) ax.set_ylim([-1,50]) # ax.set_xticks(timeArray2_H[0:-1:400]) # ax.set_xticklabels(contractedDateArray2_H[0:-1:400], rotation='horizontal') plt.grid('on') ax.tick_params(axis='both', which='major', labelsize=16) # Show the minor grid lines with very faint and almost transparent grey lines plt.minorticks_on() ax.tick_params(axis='x', which='minor', bottom=False) plt.show() ####################################################################### #Corrected raw rate ####################################################################### fig6 = plt.figure(6) ax = fig6.gca() x1,y1,slope1,intercept1 = linearRegression(pressure1, rawRate1) x2,y2,slope2,intercept2 = linearRegression(pressure2, rawRate2) x3,y3,slope3,intercept3 = linearRegression(pressure3, rawRate3) # print(Y) print('slope1: ', slope1, 'y_intercept1: ', intercept1) print('slope2: ', slope2, 'y_intercept2: ', intercept2) print('slope3: ', slope3, 'y_intercept3: ', intercept3) p1_ref = 1011.86 p2_ref = 1008.53 p3_ref = 985.87 N1_ref = 32.8296 N2_ref = 32.886 N3_ref = 27.5751 beta1 = slope1/N1_ref print('beta1: ', beta1) beta2 = slope2/N2_ref print('beta2: ', beta2) beta3 = slope3/N3_ref print('beta3: ', beta3) rawRateCorrected1 = [0]*len(rawRate1) rawRateCorrected2 = [0]*len(rawRate2) rawRateCorrected3 = [0]*len(rawRate3) for i in range(0,len(pressure1)): rawRateCorrected1[i] = rawRate1[i] / (1 + beta1 * (pressure1[i] - p1_ref)) for i in range(0,len(pressure2)): rawRateCorrected2[i] = rawRate2[i] / (1 + beta2 * (pressure2[i] - p2_ref)) # print(1 + beta2 * (pressure2[i] - p2_ref)) for i in range(0,len(pressure3)): rawRateCorrected3[i] = rawRate3[i] / (1 + beta3 * (pressure3[i] - p3_ref)) print(len(dateArray3)) print(len(rawRateCorrected3)) plt.scatter(timeArray1[0:-1:8],rawRateCorrected1[0:-1:8],s=10,c='g', label = 'POLA1_corrected') plt.scatter(timeArray2[0:-1:22],rawRateCorrected2[0:-1:22],s=10,c='b', label = 'POLA2_corrected') plt.scatter(timeArray3[0:-1:22],rawRateCorrected3[0:-1:22],s=10,c='r', label = 'POLA3_corrected') plt.xlabel('Date [d/m/2018]', size=16) plt.ylabel('Corrected Raw rate [#events/s]', size=16) plt.legend(fontsize = 14) ax.set_ylim([0,50]) ax.set_xticks(timeArray2[0:-1:400]) ax.set_xticklabels(contractedDateArray2[0:-1:400], rotation='horizontal') plt.grid('on') ax.tick_params(axis='both', which='major', labelsize=16) # Show the minor grid lines with very faint and almost transparent grey lines plt.minorticks_on() ax.tick_params(axis='x', which='minor', bottom=False) plt.show() ####################################################################### #Raw rate vs temperature ####################################################################### fig7 = plt.figure(7) ax = fig7.gca() plt.scatter(outdoorTemp1,rawRate1,s=10,c='g', label = 'POLA1') plt.scatter(outdoorTemp2,rawRate2,s=10,c='b', label = 'POLA2') plt.scatter(outdoorTemp3,rawRate3,s=10,c='r', label = 'POLA3') plt.xlabel('Outdoor temperature [$^\circ$C]', size=16) plt.ylabel('Raw rate [#events/s]', size=16) plt.legend(fontsize = 14) ax.set_ylim([10,50]) plt.grid('on') ax.tick_params(axis='both', which='major', labelsize=16) # Show the minor grid lines with very faint and almost transparent grey lines plt.minorticks_on() plt.show() <file_sep> import numpy as np import matplotlib.pyplot as plt from functions2 import pi from functions2 import pf from functions2 import readData from functions2 import particles from functions2 import muonBottom #from functions import kappas from functions2 import ABCs #muonBottom = 1 # Set to 1 in case of mM->bB, 0 in case of eE->cC (m,M,c_vm,c_am,c_vb,c_ab,Q) = particles(muonBottom) #delta = (c_vm**2+c_am**2)*(c_vb*c_ab) #delta2= c_vm*c_am*c_vb*c_ab C_conv= (0.197)**2*10**(-2)*10**12 #Conversion factor for areas from NU to barn ########################################################################################### #Total Cross Section and asymmetry ########################################################################################### s_sqrt = np.arange(20,200,0.5) # Centre of mass energy in GeV s = s_sqrt**2 sigma_tot = [0]*s.size #print(sigma_tot.size) sigma_a = [0]*s.size sigma_z = [0]*s.size sigma_az = [0]*s.size sigma_H = [0]*s.size A_fb = [0]*s.size for i in range(0,s.size): # pi = np.sqrt(s[i]/4 - m**2) # pf = np.sqrt(s[i]/4-M**2) (A,B,C,A_a,B_a,A_z,B_z,C_z,A_az,B_az,C_az,MH) = ABCs(s[i]) sigma_tot[i]= C_conv*(3/(16*np.pi*s[i]))*(pf(s[i])/pi(s[i]))*((1/3)*A+C) sigma_a[i] = C_conv*(3/(16*np.pi*s[i]))*(pf(s[i])/pi(s[i]))*((1/3)*A_a+B_a) sigma_z[i] = C_conv*(3/(16*np.pi*s[i]))*(pf(s[i])/pi(s[i]))*((1/3)*A_z+B_z) sigma_H[i] = C_conv*(3/(16*np.pi*s[i]))*(pf(s[i])/pi(s[i]))*(MH) # A_fb[i] = 0.5*(B)/(1/3*A+C) ########################################################################################### #Differential Cross Section ########################################################################################### S_sqrt=130 S=S_sqrt**2 x = np.linspace(-1,1,100) #Cos(theta) dsigma_tot = [0]*x.size dsigma_a = [0]*x.size dsigma_z = [0]*x.size dsigma_az = [0]*x.size (A,B,C,A_a,B_a,A_z,B_z,C_z,A_az,B_az,C_az,MH) = ABCs(S) for i in range(0,x.size): dsigma_tot[i] = C_conv*(3/(32*np.pi*S))*(pf(S)/pi(S))*(A*x[i]**2+B*x[i]+C) dsigma_a[i] = C_conv*(3/(32*np.pi*S))*(pf(S)/pi(S))*(A_a*x[i]**2+B_a) dsigma_z[i] = C_conv*(3/(32*np.pi*S))*(pf(S)/pi(S))*(A_z*x[i]**2+B_z*x[i]+C_z) dsigma_az[i] = C_conv*(3/(32*np.pi*S))*(pf(S)/pi(S))*(A_az*x[i]**2+B_az*x[i]+C_az) print(gz) ###################################################################### #Reading in compHEP data ###################################################################### #Data for el.mag., electroweak and higgs diagrams filename1 = "sigma_tot_nh_100.txt" filename2 = "dsigma_a_100.txt" filename3 = "gammaplusz.txt" #No higgs filename4 = "dsigma_tot_nh.txt" #Z-prime included filename5 = "Afb_Zp_n100.txt" filename6 = "sigma_Zp_n100.txt" filename7 = "dsigma_Zp_s5000.txt" filename8 = "dsigma_Zp_s6000.txt" filename9 = "dsigma_tot_s130.txt" filename10= "dsigma_a_s130.txt" filename11= "dsigma_z_s130.txt" filename12="dsigma_H_s130.txt" f= open(filename10,"r") col1,col2 = readData(f) ######################################################################### #Plots ######################################################################### fig0=plt.figure(0) plt.xlabel('$\sqrt{s}[GeV]$',size=12) plt.ylabel('$\sigma[pb]$',size=12) plt.semilogy(s_sqrt, sigma_tot,'b',label = '$\sigma_{\gamma + Z +\gamma Z}$') plt.semilogy(s_sqrt, sigma_a,'r',label='$\sigma_{\gamma}$') plt.semilogy(s_sqrt, sigma_z,'g',label='$\sigma_{z}$') #plt.semilogy(s_sqrt, sigma_H,'m',label='$\sigma_{H}$') #plt.semilogy(col1,col2,'k',label='$\sigma_{CompHEP}$') #plt.semilogy(col1, col2,'m',label = '$\sigma_{\gamma + Z + H +Z\'}$') ax = fig0.gca() ax.set_xticks(np.arange(20, 210, 10)) #ax.set_yticks(np.arange(0, 1., 30)) #plt.scatter(x, y) plt.grid() plt.show() plt.legend() fig1=plt.figure(1) plt.title("$\sqrt{s} = 130$ GeV", size = 12 ) #plt.title("Total differential cross section") #plt.title("Differential cross section for $|M_{\gamma}|^2$ contribution") #plt.title("Differential cross section for $|M_{Z}|^2$ contribution") #plt.title("Diff. cross section for $M_\gamma*M_Z$ contr.") plt.xlabel('$\\cos{\\theta}[1]$',size=12) plt.ylabel('$d\sigma/d\\cos{\\theta}[pb/rad]$',size=12) #plt.ylabel('$\sigma[pb]$',size=14) plt.plot(x, dsigma_tot,'b',label = '$d\sigma_{\gamma + Z +\gamma*Z +H }$') plt.plot(x, dsigma_a,'r',label='$d\sigma_{\gamma}$') plt.plot(x, dsigma_z,'g',label='$d\sigma_{z}$') #plt.plot(x, dsigma_az,'m',label='$d\sigma_{\gamma}z}$') ax1 = fig1.gca() ax1.set_xticks(np.arange(-1, 1.1, 0.2)) #ax.set_yticks(np.arange(0, 1., 30)) #plt.scatter(x, y) plt.grid() plt.show() plt.legend() fig2=plt.figure(2) if (muonBottom == 1): plt.title("Forward-backward asymmetry for $\mu^{-},\mu^{+}\\rightarrow b,\\bar{b}$") plt.title("Forward-backward asymmetry") plt.xlabel('$\sqrt{s}[GeV]$',size=12) plt.ylabel('$A_{FB}[pb]$',size=12) plt.plot(s_sqrt, A_fb,'r',label = '$\mu^{-},\mu^{+}\\rightarrow b,\\bar{b}$') # ax.set_yticks(np.arange(0, 1., 30)) #plt.scatter(x, y) plt.grid() plt.show() plt.legend() else: plt.title("Forward-backward asymmetry for $e^{-},e^{+}\\rightarrow c,\\bar{c}$") plt.title("Forward-backward asymmetry") plt.xlabel('$\sqrt{s}[GeV]$',size=12) plt.ylabel('$A_{FB}[pb]$',size=12) plt.plot(s_sqrt, A_fb,'b',label = '$e^{-},e^{+}\\rightarrow c,\\bar{c}$') # ax = fig2.gca() # ax.set_xticks(np.arange(20, 210, 10)) # ax.set_yticks(np.arange(0, 1., 30)) #plt.scatter(x, y) plt.grid() plt.legend() plt.show() ############################################################################## #No Z prime ############################################################################## #fig3=plt.figure(3) #plt.title("Differential cross section, no Higgs, CompHEP") #plt.xlabel('$\sqrt{s}[GeV]$',size=12) #plt.ylabel('$dd\\cos{\\theta}[pb/rad]$',size=12) #plt.plot(col1, col2,'b',label = '$d\sigma_{\gamma + Z }$') #ax = fig3.gca() #ax.set_xticks(np.arange(-1,1,0.2)) ##ax.set_yticks(np.arange(0, 1., 30)) ##plt.scatter(x, y) #plt.grid() #plt.show() #plt.legend() #fig3=plt.figure(3) #plt.title("Total cross section, no Higgs, CompHEP") #plt.xlabel('$\sqrt{s}[GeV]$',size=12) #plt.ylabel('$\sigma[pb]$',size=12) #plt.semilogy(col1, col2,'b',label = '$\sigma_{\gamma + Z }$') #ax = fig3.gca() #ax.set_xticks(np.arange(20, 210, 10)) ##ax.set_yticks(np.arange(0, 1., 30)) ##plt.scatter(x, y) #plt.grid() #plt.show() #plt.legend() ############################# #Z prime ############################## #fig3=plt.figure(3) #plt.title("Total cross section, including Z'") #plt.xlabel('$\sqrt{s}[GeV]$',size=12) #plt.ylabel('$\sigma[pb]$',size=12) #plt.semilogy(col1, col2,'b',label = '$\sigma_{\gamma + Z + H +Z\'}$') #ax = fig3.gca() #ax.set_xticks(np.arange(50, 11000, 1000)) ##ax.set_yticks(np.arange(0, 1., 30)) ##plt.scatter(x, y) #plt.grid() #plt.show() #plt.legend() #fig4=plt.figure(4) #plt.title("Differential cross section with Z' included") #plt.xlabel('$\\cos{\\theta}[1]$',size=12) #plt.ylabel('$d\sigma_{\gamma + Z + H +Z\'}/d\\cos{\\theta}[pb/rad]$',size=12) #plt.plot(col1, col2,'r',label="$\sqrt{s} = 6TeV$") # #ax = fig4.gca() #ax.set_xticks(np.arange(-1, 1.2, 0.2)) ##ax.set_yticks(np.arange(0, 1., 30)) ##plt.scatter(x, y) #plt.grid() #plt.show() #plt.legend() #fig5=plt.figure(5) #plt.title("Forward-backward asymmetry with Z' included") #plt.xlabel('$\sqrt{s}[GeV]$',size=12) #plt.ylabel('$A_{FB}[pb]$',size=12) #plt.plot(col1, col2,'b') # #ax = fig5.gca() #ax.set_xticks(np.arange(50, 11000, 1000)) ##ax.set_yticks(np.arange(0, 1., 30)) ##plt.scatter(x, y) #plt.grid() #plt.show() fig6=plt.figure(6) plt.title("Differential cross sections from CompHEP, $\sqrt{s} = 130GeV$") plt.xlabel('$\\cos{\\theta}[1]$',size=12) plt.ylabel('$d\sigma/d\\cos{\\theta}[pb/rad]$',size=12) #plt.plot(col1, col2,'b',label="$d\sigma_{\gamma + Z + H}$") plt.plot(col1, col2,'r',label="$d\sigma_{\gamma}$") #plt.plot(col1, col2,'g',label="$d\sigma_{Z}$") #plt.plot(col1, col2,'m',label="$d\sigma_{ H}$") ax = fig6.gca() ax.set_xticks(np.arange(-1, 1.2, 0.2)) #ax.set_yticks(np.arange(0, 1., 30)) #plt.scatter(x, y) plt.grid() plt.show() plt.legend() #plt.figure(3) #plt.semilogy(s_sqrt, sigma_H,'m',label='$\sigma_{H}$') <file_sep>#from ROOT import * import ROOT import sys, os, time t0 = time.time() arg1 = sys.argv[1] if arg1 == 'Data': input_dir = '2lep/Data/' elif arg1 == 'MC': input_dir = '2lep/MC/' myChain = ROOT.TChain('mini') for filename in os.listdir(input_dir): if not '.root' in filename: continue print(filename) myChain.Add(input_dir+filename) if arg1 == 'MC': for filename in os.listdir(input_dir): if not '.root' in filename: continue print(filename) myChain.Add(input_dir+filename) if not os.path.exists('./Histograms_article'): #Needs to change directory according to mass range os.makedirs('./Histograms_article') if not os.path.exists('./Histograms_article/MC/'): os.makedirs('./Histograms_article/MC') if not os.path.exists('./Histograms_article/Data/'): os.makedirs('./Histograms_article/Data') entries = myChain.GetEntries() print("-------------------------------------------") if arg1 == 'Data': print("Running on real data!") else: print("Running on Monte Carlo!") print("Number of events to process: ", entries) print("-------------------------------------------") if arg1 == 'Data': myChain.Process("MySelector.C+", "Data") #Need to change which MySelector according to mass range else: myChain.Process("MySelector.C+", "MC") #Need to change which MySelector according to mass range t = int( time.time()-t0 )/60 print("Time spent: %d min" %t) <file_sep>import ROOT from ROOT import * import os, sys # import teststat as stat # import numpy as np from infofile import infos ROOT.gROOT.SetBatch(1) ROOT.gStyle.SetOptStat(0); ROOT.gStyle.SetPadLeftMargin(0.13) ROOT.gStyle.SetLegendBorderSize(0) ROOT.gStyle.SetPalette(1) ROOT.gStyle.SetGridStyle(2) ROOT.gStyle.SetPadLeftMargin(0.13) ROOT.TH1.AddDirectory(kFALSE) channel = sys.argv[1] # Variables variables = ['pt1', 'pt2', 'eta1', 'eta2', 'phi1', 'phi2', 'mll', 'met'] xtitles = {'pt1':'Leading lepton p_{T} (GeV)', 'pt2':'Subleading lepton p_{T} (GeV)', 'eta1':'Leading lepton #eta', 'eta2':'Subleading lepton #eta', 'phi1':'Leading lepton #phi', 'phi2':'Subleading lepton #phi', 'mll':'m_{ll} (GeV)', 'met':'E_{T}^{miss} (GeV)'} # Backgrounds backgrounds = ['Zjets', 'Top', 'Diboson', 'Wjets'] Zjets = [364100, 364101, 364102, 364103, 364104, 364105, 364106, 364107, 364108, 364109, 364110, 364111, 364112, 364113, 364114, 364115, 364116, 364117, 364118, 364119, 364120, 364121, 364122, 364123, 364124, 364125, 364126, 364127, 364128, 364129, 364130, 364131, 364132, 364133, 364134, 364135, 364136, 364137, 364138, 364139, 364140, 364141] Wjets = [364156, 364157, 364158, 364159, 364160, 364161, 364162, 364163, 364164, 364165, 364166, 364167, 364168, 364169, 364170, 364171, 364172, 364173, 364174, 364175, 364176, 364177, 364178, 364179, 364180, 364181, 364182, 364183, 364184, 364185, 364186, 364187, 364188, 364189, 364190, 364191, 364192, 364193, 364194, 364195, 364196, 364197] Diboson = [363356, 363358, 363359, 363360, 363489, 363490, 363491, 363492, 363493] Top = [410000, 410011, 410012, 4100013, 410014, 410025, 410026] # Signals signals = ['Zprime2000', 'Zprime3000', 'Zprime4000', 'Zprime5000'] #Have to be adjusted according to Z' mass #Zprime2000 = [301215, 301220]; #Zprime3000 = [301216, 301221]; #Zprime4000 = [301217, 301222]; #Zprime5000 = [301218, 301223]; if channel == "ee": Zprime2000 = [301215]; Zprime3000 = [301216]; Zprime4000 = [301217]; Zprime5000 = [301218]; else: Zprime2000 = [301220]; Zprime3000 = [301221]; Zprime4000 = [301222]; Zprime5000 = [301223]; fileIDs = {'Diboson':Diboson, 'Zjets':Zjets, 'Wjets':Wjets, 'Top':Top, 'Zprime2000':Zprime2000, 'Zprime3000':Zprime3000, 'Zprime4000':Zprime4000, 'Zprime5000':Zprime5000} #Have to be adjusted according to Z' mass hist_bkg = {} for var in variables: hist_bkg[var] = {} for bkg in backgrounds: hist_bkg[var][bkg] = TH1F() hist_sig = {} for var in variables: hist_sig[var] = {} for sig in signals: hist_sig[var][sig] = TH1F() #colours = dict(Diboson=kAzure+1, Top=kRed+1, Zjets=kOrange-2, Wjets=kGray, Zprime3000=kBlue) #Have to be adjusted according to Z' mass colours = dict(Diboson=kAzure+1, Top=kRed+1, Zjets=kOrange-2, Wjets=kGray, Zprime2000=kBlue, Zprime3000=kBlack, Zprime4000=kSpring, Zprime5000=kTeal) # kWhite = 0, kBlack = 1, kGray = 920, kRed = 632, kGreen = 416, # kBlue = 600, kYellow = 400, kMagenta = 616, kCyan = 432, kOrange = 800, # kSpring = 820, kTeal = 840, kAzure = 860, kViolet = 880, kPink = 900 # Extract info about cross section and sum of weights from infofile info = {} for key in infos.keys(): ID = infos[key]['DSID'] info[ID] = {} info[ID]['xsec'] = infos[key]['xsec'] info[ID]['sumw'] = infos[key]['sumw'] info[ID]['events'] = infos[key]['events'] # Function for making histograms L = 10.6 # integrated luminosity = 10.6 fb^-1 or 10.06? def fill_hist(h, h_name, key, ID): h_midl = infile.Get(h_name).Clone("h_midl") #The histogram is specified by the TFile infile (the var, bkg and ID). h_name is a title, it describes the channel and var (but not ID) xsec = 1000*info[ID]['xsec'] nev = info[ID]['sumw'] N_mc = xsec*L sf = N_mc/nev # We need to scale the simulated MC background to the number of events in our dataset if not h.GetName(): #If the histrogram of a given variable has not been filled before h=infile.Get(h_name) h.Scale(sf) n = h.GetNbinsX() for i in range(n): bc = h.GetBinContent(i) if bc < 0: h.SetBinContent(i,0) h.SetFillColor(colours[key]) h.SetLineColor(colours[key]) else: h_midl.Scale(sf) n = h_midl.GetNbinsX() for i in range(n): bc = h_midl.GetBinContent(i) if bc < 0: h_midl.SetBinContent(i,0) h.Add(h_midl) return h # Loop over files in MC directory for filename in os.listdir('Histograms_article/MC/'): #Adjust according to histogram folder if '.root' in filename: filepath = 'Histograms_article/MC/'+filename #Adjust according to histogram folder infile = TFile(filepath) file_id = int(filename.split('.')[2]) #print filename for var in variables: #Do the below for every variable for bkg in backgrounds: if file_id in fileIDs[bkg]: hist_bkg[var][bkg] = fill_hist(hist_bkg[var][bkg], 'h_'+channel+'_'+var, bkg, file_id) for sig in signals: if file_id in fileIDs[sig]: hist_sig[var][sig] = fill_hist(hist_sig[var][sig], 'h_'+channel+'_'+var, sig, file_id) # Get data data = TFile('Histograms_article/Data/hist.Data.2016.root') #Adjust according to histogram folder hist_d ={} for var in variables: hist_d[var] = data.Get('h_'+channel+'_'+var) hist_d[var].SetMarkerStyle(20) hist_d[var].SetMarkerSize(0.7) hist_d[var].SetLineColor(kBlack) hist_d[var].GetYaxis().SetTitle("Events") hist_d[var].GetXaxis().SetTitle(xtitles[var]) hist_d[var].GetXaxis().SetTitleFont(43) hist_d[var].GetXaxis().SetTitleSize(16) hist_d[var].GetYaxis().SetTitleFont(43) hist_d[var].GetYaxis().SetTitleSize(16) hist_d[var].GetXaxis().SetLabelFont(43) hist_d[var].GetXaxis().SetLabelSize(16) hist_d[var].GetYaxis().SetLabelFont(43) hist_d[var].GetYaxis().SetLabelSize(16) hist_d[var].GetXaxis().SetTitleOffset(4) hist_d[var].GetYaxis().SetTitleOffset(1.5) if var=='mll': hist_d[var].GetXaxis().SetRangeUser(225.,6000.) # Style histograms, make stack and histograms with full background stack = {} hist_r = {} #Histogram for the data to background ratio to be plotted at the bottom hist_mc = {} for var in variables: stack[var] = THStack(var, "") hist_mc[var] = TH1F() hist_r[var] = TH1F() for bkg in reversed(backgrounds): hist_bkg[var][bkg].GetYaxis().SetTitle("Events") hist_bkg[var][bkg].GetXaxis().SetTitle(xtitles[var]) hist_bkg[var][bkg].GetXaxis().SetTitleFont(43) hist_bkg[var][bkg].GetXaxis().SetTitleSize(16) hist_bkg[var][bkg].GetYaxis().SetTitleFont(43) hist_bkg[var][bkg].GetYaxis().SetTitleSize(16) hist_bkg[var][bkg].GetXaxis().SetLabelFont(43) hist_bkg[var][bkg].GetXaxis().SetLabelSize(16) hist_bkg[var][bkg].GetYaxis().SetLabelFont(43) hist_bkg[var][bkg].GetYaxis().SetLabelSize(16) hist_bkg[var][bkg].GetXaxis().SetTitleOffset(4) hist_bkg[var][bkg].GetYaxis().SetTitleOffset(1.5) if var == 'mll': hist_bkg[var][bkg].GetXaxis().SetRangeUser(225., 6000.) stack[var].Add(hist_bkg[var][bkg]) if not hist_mc[var].GetName(): hist_mc[var] = hist_bkg[var][bkg].Clone() else: hist_mc[var].Add(hist_bkg[var][bkg]) hist_r[var] = hist_d[var].Clone() hist_r[var].Divide(hist_mc[var]) hist_r[var].SetTitle("") hist_r[var].GetXaxis().SetTitle(xtitles[var]) hist_r[var].GetYaxis().SetTitle("Data/#SigmaMC") hist_r[var].GetYaxis().SetNdivisions(506) hist_r[var].SetMarkerStyle(20) hist_r[var].SetMarkerSize(0.7) if var=='mll': hist_r[var].GetXaxis().SetRangeUser(225.,6000.) # Make plot legend leg = TLegend(0.70,0.50,0.88,0.88) leg.SetFillStyle(4000) leg.SetFillColor(0) leg.SetTextFont(42) leg.SetBorderSize(0) bkg_labels = {'Zjets':'Z+jets', 'Top':'Top', 'Diboson':'Diboson', 'Wjets':'W+jets'} sig_labels = {'Zprime2000':"Z' (2 TeV)",'Zprime3000':"Z' (3 TeV)",'Zprime4000':"Z' (4 TeV)", 'Zprime5000':"Z' (5 TeV)" } for bkg in backgrounds: leg.AddEntry(hist_bkg['pt1'][bkg], bkg_labels[bkg], "f") for sig in signals: leg.AddEntry(hist_sig['pt1'][sig], sig_labels[sig], "f") leg.AddEntry(hist_d['pt1'],"Data","ple") selection = "" if channel == "ee": selection = "ee" if channel == "uu": selection = "#mu#mu" # Make plots for var in variables: cnv = TCanvas("cnv_"+var,"", 500, 500) cnv.SetTicks(1,1) cnv.SetLeftMargin(0.13) #cnv.SetLogy() p1 = TPad("p1", "", 0, 0.35, 1, 1) p2 = TPad("p2", "", 0, 0.0, 1, 0.35) p1.SetLogy() p1.SetBottomMargin(0.0) p1.Draw() p1.cd() stack[var].Draw("hist") stack[var].SetMinimum(10E-4) #Set this to 10E-3 for ee and 10E-4 for uu stack[var].GetYaxis().SetTitle("Events") stack[var].GetYaxis().SetTitleFont(43) stack[var].GetYaxis().SetTitleSize(16) stack[var].GetYaxis().SetLabelFont(43) stack[var].GetYaxis().SetLabelSize(16) stack[var].GetYaxis().SetTitleOffset(1.5) if var in ['eta1', 'eta2', 'phi1', 'phi2']: maximum = stack[var].GetMaximum() stack[var].SetMaximum(maximum*10E4) hist_d[var].Draw("same e0") leg.Draw("same") for sig in signals: hist_sig[var][sig].SetFillColor(0); hist_sig[var][sig].Draw("same hist"); s = TLatex() s.SetNDC(1); s.SetTextAlign(13); s.SetTextColor(kBlack); s.SetTextSize(0.044); s.DrawLatex(0.4,0.86,"#font[72]{ATLAS} Open Data"); s.DrawLatex(0.4,0.81,"#bf{#sqrt{s} = 13 TeV,^{}%.1f^{}fb^{-1}}" % (L)); s.DrawLatex(0.4,0.76,"#bf{"+selection+" selection}"); p1.Update() p1.RedrawAxis() cnv.cd() # Change directory to the canvas p2.Draw() p2.cd() #Change directory to pad 2 p2.SetGridy() hist_r[var].SetMaximum(1.99) hist_r[var].SetMinimum(0.01) hist_r[var].Draw("0PZ") p2.SetTopMargin(0) p2.SetBottomMargin(0.35) p2.Update() p2.RedrawAxis() cnv.cd() cnv.Update() cnv.Print('Plots/'+channel+'_'+var+'.png') cnv.Close() # Find number of events within a mass region def GetNumberEvents(hist, xmin, xmax): # entries = np.zeros(2) error = ROOT.Double() axis = hist.GetXaxis(); bmin = axis.FindBin(xmin); bmax = axis.FindBin(xmax); # print "Bins: ", bmin, bmax integral = hist.IntegralAndError(bmin,bmax, error, ""); # integral -= hist.GetBinContent(bmin)*(xmin-axis.GetBinLowEdge(bmin))/axis.GetBinWidth(bmin); # integral -= hist.GetBinContent(bmax)*(axis.GetBinUpEdge(bmax)-xmax)/axis.GetBinWidth(bmax); # entries[0] = integral; # entries[1] = error; return integral, error # xminA = 1400 # xmaxA = 2600 #xmin_2TeV = [1900, 1800, 1700, 1600, 1500, 1400, 1300, 1200, 1100, 1000] #xmax_2TeV = [2100, 2200, 2300, 2400, 2500, 2600, 2700, 2800, 2900, 3000] xmin_2TeV = [1900, 1800, 1700, 1600, 1500, 1400, 1300, 1200, 1100, 1000] xmax_2TeV = [5900, 5900, 5900, 5900, 5900, 5900, 5900, 5900, 5900, 5900] xmin_3TeV = [1900, 1800, 1700, 1600, 1500, 1400, 1300, 1200, 1100, 1000] xmax_3TeV = [5900, 5900, 5900, 5900, 5900, 5900, 5900, 5900, 5900, 5900] xmin_4TeV = [1900, 1800, 1700, 1600, 1500, 1400, 1300, 1200, 1100, 1000] xmax_4TeV = [5900, 5900, 5900, 5900, 5900, 5900, 5900, 5900, 5900, 5900] xmin_5TeV = [1900, 1800, 1700, 1600, 1500, 1400, 1300, 1200, 1100, 1000] xmax_5TeV = [5900, 5900, 5900, 5900, 5900, 5900, 5900, 5900, 5900, 5900] #f3ee = open("binCuts_3ee.txt", "w") #f3uu = open("binCuts_3uu.txt", "w") #Zprime2000 = [301215, 301220]; #Zprime3000 = [301216, 301221]; #Zprime4000 = [301217, 301222]; #Zprime5000 = [301218, 301223]; #signals = ['Zprime2000', 'Zprime3000', 'Zprime4000', 'Zprime5000'] # print("2TeV ee peak cuts: ") if channel == "ee": fee = open("binCuts_article_ee.txt", "w") fee.write("2TeV ee bin cuts" +"\n") fee.write("xmin xmax sig b error_b N_obs" +"\n") for i in range(0,9): # print("cut: ", xmin_2TeV[i], "-", xmax_2TeV[i]) integral_b, error_b = GetNumberEvents(hist_mc['mll'], xmin_2TeV[i], xmax_2TeV[i]) integral_obs, error_obs = GetNumberEvents(hist_d['mll'], xmin_2TeV[i], xmax_2TeV[i]) integral_sig, error_sig = GetNumberEvents(hist_sig['mll']['Zprime2000'], xmin_2TeV[i], xmax_2TeV[i]) print("2TeV cut: ", xmin_2TeV[i], xmax_2TeV[i], "sig: ", integral_sig, "error_sig: ", error_sig, "b: ", integral_b, "Error_b:" , error_b, "N_obs: ", integral_obs) fee.write(str(xmin_2TeV[i]) +" " + str(xmax_2TeV[i]) + " " + str(integral_sig) + " " + str(integral_b) + " " + str(error_b) + " " + str(integral_obs) +"\n") fee.write("\t " +"Sig_err: " +str(error_sig)+ "\n") fee.write("3TeV ee bin cuts" + "\n") fee.write("xmin xmax sig b error_b N_obs" + "\n") for i in range(0,9): print("cut: ", xmin_3TeV[i], "-", xmax_3TeV[i]) integral_b, error_b = GetNumberEvents(hist_mc['mll'], xmin_3TeV[i], xmax_3TeV[i]) integral_obs, error_obs = GetNumberEvents(hist_d['mll'], xmin_3TeV[i], xmax_3TeV[i]) integral_sig, error_sig = GetNumberEvents(hist_sig['mll']['Zprime3000'], xmin_3TeV[i], xmax_3TeV[i]) fee.write(str(xmin_3TeV[i]) +" " + str(xmax_3TeV[i]) + " " + str(integral_sig) + " " + str(integral_b) + " " + str(error_b) + " " + str(integral_obs) + "\n") fee.write( "\t " + "Sig_err: " + str(error_sig) + "\n") fee.write("4TeV ee bin cuts" + "\n") fee.write("xmin xmax sig b error_b N_obs" + "\n") for i in range(0,9): print("cut: ", xmin_4TeV[i], "-", xmax_4TeV[i]) integral_b, error_b = GetNumberEvents(hist_mc['mll'], xmin_4TeV[i], xmax_4TeV[i]) integral_obs, error_obs = GetNumberEvents(hist_d['mll'], xmin_4TeV[i], xmax_4TeV[i]) integral_sig, error_sig = GetNumberEvents(hist_sig['mll']['Zprime4000'], xmin_4TeV[i], xmax_4TeV[i]) fee.write(str(xmin_4TeV[i]) +" " + str(xmax_4TeV[i]) + " " + str(integral_sig) + " " + str(integral_b) + " " + str(error_b) + " " + str(integral_obs) + "\n") fee.write( "\t " + "Sig_err: " + str(error_sig) + "\n") fee.write("5TeV ee bin cuts" + "\n") fee.write("xmin xmax sig b error_b N_obs" + "\n") for i in range(0,9): print("cut: ", xmin_5TeV[i], "-", xmax_5TeV[i]) integral_b, error_b = GetNumberEvents(hist_mc['mll'], xmin_5TeV[i], xmax_5TeV[i]) integral_obs, error_obs = GetNumberEvents(hist_d['mll'], xmin_5TeV[i], xmax_5TeV[i]) integral_sig, error_sig = GetNumberEvents(hist_sig['mll']['Zprime5000'], xmin_5TeV[i], xmax_5TeV[i]) fee.write(str(xmin_5TeV[i]) +" " + str(xmax_5TeV[i]) + " " + str(integral_sig) + " " + str(integral_b) + " " + str(error_b) + " " + str(integral_obs) + "\n") fee.write( "\t " + "Sig_err: " + str(error_sig) + "\n") fee.close() if channel == "uu": fuu = open("binCuts_article_uu.txt", "w") fuu.write("2TeV uu bin cuts" +"\n") fuu.write("xmin xmax sig b error_b N_obs" +"\n") for i in range(0,9): # print("cut: ", xmin_2TeV[i], "-", xmax_2TeV[i]) integral_b, error_b = GetNumberEvents(hist_mc['mll'], xmin_2TeV[i], xmax_2TeV[i]) integral_obs, error_obs = GetNumberEvents(hist_d['mll'], xmin_2TeV[i], xmax_2TeV[i]) integral_sig, error_sig = GetNumberEvents(hist_sig['mll']['Zprime2000'], xmin_2TeV[i], xmax_2TeV[i]) print("2TeV cut: ", xmin_2TeV[i], xmax_2TeV[i], "sig: ", integral_sig, "error_sig: ", error_sig, "b: ", integral_b, "Error_b:" , error_b, "N_obs: ", integral_obs) fuu.write(str(xmin_2TeV[i]) +" " + str(xmax_2TeV[i]) + " " + str(integral_sig) + " " + str(integral_b) + " " + str(error_b) + " " + str(integral_obs) +"\n") fuu.write("\t " +"Sig_err: " +str(error_sig)+ "\n") fuu.write("3TeV uu bin cuts" + "\n") fuu.write("xmin xmax sig b error_b N_obs" + "\n") for i in range(0,9): print("cut: ", xmin_3TeV[i], "-", xmax_3TeV[i]) integral_b, error_b = GetNumberEvents(hist_mc['mll'], xmin_3TeV[i], xmax_3TeV[i]) integral_obs, error_obs = GetNumberEvents(hist_d['mll'], xmin_3TeV[i], xmax_3TeV[i]) integral_sig, error_sig = GetNumberEvents(hist_sig['mll']['Zprime3000'], xmin_3TeV[i], xmax_3TeV[i]) fuu.write(str(xmin_3TeV[i]) +" " + str(xmax_3TeV[i]) + " " + str(integral_sig) + " " + str(integral_b) + " " + str(error_b) + " " + str(integral_obs) + "\n") fuu.write( "\t " + "Sig_err: " + str(error_sig) + "\n") fuu.write("4TeV uu bin cuts" + "\n") fuu.write("xmin xmax sig b error_b N_obs" + "\n") for i in range(0,9): print("cut: ", xmin_4TeV[i], "-", xmax_4TeV[i]) integral_b, error_b = GetNumberEvents(hist_mc['mll'], xmin_4TeV[i], xmax_4TeV[i]) integral_obs, error_obs = GetNumberEvents(hist_d['mll'], xmin_4TeV[i], xmax_4TeV[i]) integral_sig, error_sig = GetNumberEvents(hist_sig['mll']['Zprime4000'], xmin_4TeV[i], xmax_4TeV[i]) fuu.write(str(xmin_4TeV[i]) +" " + str(xmax_4TeV[i]) + " " + str(integral_sig) + " " + str(integral_b) + " " + str(error_b) + " " + str(integral_obs) + "\n") fuu.write( "\t " + "Sig_err: " + str(error_sig) + "\n") fuu.write("5TeV uu bin cuts" + "\n") fuu.write("xmin xmax sig b error_b N_obs" + "\n") for i in range(0,9): print("cut: ", xmin_5TeV[i], "-", xmax_5TeV[i]) integral_b, error_b = GetNumberEvents(hist_mc['mll'], xmin_5TeV[i], xmax_5TeV[i]) integral_obs, error_obs = GetNumberEvents(hist_d['mll'], xmin_5TeV[i], xmax_5TeV[i]) integral_sig, error_sig = GetNumberEvents(hist_sig['mll']['Zprime5000'], xmin_5TeV[i], xmax_5TeV[i]) fuu.write(str(xmin_5TeV[i]) +" " + str(xmax_5TeV[i]) + " " + str(integral_sig) + " " + str(integral_b) + " " + str(error_b) + " " + str(integral_obs) + "\n") fuu.write( "\t " + "Sig_err: " + str(error_sig) + "\n") fuu.close() # if channel == "uu": # f2uu = open("binCuts_2uu.txt", "w") # f2uu.write("2TeV uu bin cuts" +"\n") # f2uu.write("xmin xmax sig b error_b N_obs" +"\n") # for i in range(0,9): # # print("cut: ", xmin_2TeV[i], "-", xmax_2TeV[i]) # integral_b, error_b = GetNumberEvents(hist_mc['mll'], xmin_3TeV[i], xmax_3TeV[i]) # integral_obs, error_obs = GetNumberEvents(hist_d['mll'], xmin_3TeV[i], xmax_3TeV[i]) # integral_sig, error_sig = GetNumberEvents(hist_sig['mll']['Zprime2000'], xmin_3TeV[i], xmax_3TeV[i]) # print("2TeV cut: ", xmin_3TeV[i], xmax_3TeV[i], "sig: ", integral_sig, "b: ", integral_b, "Error_b:" , error_b, "N_obs: ", integral_obs) # f2uu.write(str(xmin_2TeV[i]) +" " + str(xmax_2TeV[i]) + " " + str(integral_sig) + " " + str(integral_b) + " " + str(error_b) + " " + str(integral_obs) +"\n") # f2uu.close() # integral_b, error_b = GetNumberEvents(hist_mc['mll'], xmin_3TeV[i], xmax_3TeV[i]) #integral_obs, error_obs = GetNumberEvents(hist_d['mll'], xmin_2TeV[i], xmin_3TeV[i]) #integral_sig, error_sig = GetNumberEvents(hist_d['mll'], xmin_3TeV[i], xmin_3TeV[i]) #print("3TeV cut: ", xmin_3TeV[i], xmax_3TeV[i], "sig: ", integral_sig, "b: ", integral_b, "Error_b:" , error_b, "N_obs: ", integral_obs) <file_sep>import glob import pandas as pd import numpy as np from scipy.optimize import least_squares from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split #Sorts filenames in dates (ascending) and extracts the files containing measurements during the expedition def extractExpedition(filenames): f1= [None]*len(filenames) #split filenames in order to sort by dates def splitter(filenames): for i in range(0,len(filenames)): f1[i] = filenames[i].split('_') # f1[i][1].split('-') # print(f1[i][1]) return f1 splitNames= splitter(filenames) def dateSorter(splitnames): return splitnames[2] # def daySorter(splitnames): # return splitnames[2] #Sort filenames in dates (ascending) filenamesList = sorted(splitNames,key=dateSorter) for i in range(0,len(filenamesList)): filenames[i] = '{}_{}_{}_{}_{}'.format(filenamesList[i][0],filenamesList[i][1],filenamesList[i][2],filenamesList[i][3],filenamesList[i][4]) # print(filenames[i]) indices = [] # words = ['2018-07-22','2018-09-04'] #find indices of files corresponding to start and end date of the expedition # matches = [] # for c in filenamesList: # if c in words: # indices.append(c) # for i, elem in enumerate(filenamesList): # if '2018-07-22' in elem: # indices.append(i) # if '2018-09-04' in elem: # indices.append(i) for i, elem in enumerate(filenamesList): if '2018-07-22' in elem: indices.append(i) if '2018-09-04' in elem: indices.append(i) # print(indices) # for i in range(indices[0],indices[-1]): # print(filenames[i]) # print(indices[-1]) #construct pandas frames from every file in from the expedition frames=[None]*(indices[-1]-indices[0]) for i in range(0,indices[-1]-indices[0]): frames[i] = pd.read_csv(filenames[i+indices[0]]) #Concatenate the frames expeditionFrame = pd.concat(frames, ignore_index=True) #To array for further manipulation and plotting of data expeditionArr = expeditionFrame.to_numpy() return expeditionArr ####################################################################### #Construct array corresponding to the date of the measurements ####################################################################### def secondsToDates(weatherArr): dateArray = np.zeros((len(weatherArr), 2), int) contractedDateArray = list() monthStartDays = [22, 1, 1] dayCounter = 0 # Is to be subtracted from the amount of days since start of measurements to produce day in month monthCounter = 0 timeArray = [] for i in range(0,len(weatherArr)): if(i==0): time = 0 timeArray.append(time) dateArray[i][0]=22 dateArray[i][1]=7 else: time += weatherArr[i][0] - weatherArr[i - 1][0] timeArray.append(time) dateArray[i][0] = monthStartDays[monthCounter] + int((timeArray[i] - timeArray[0]) / (60 * 60 * 24)) - dayCounter # print(int((timeArray[i] - timeArray[0]) / (60 * 60 * 24))) if((i!=0) & (dateArray[i][0]%32==0)): dateArray[i][1] = dateArray[i-1][1] +1 dateArray[i][0] = 1 monthCounter += 1 if(monthCounter == 1): dayCounter = 31-22+1 #Number of measurement days in July elif(monthCounter ==2 ): dayCounter = 31+10 #Number of measurement days in August else: dateArray[i][1] = dateArray[i-1][1] contractedDateArray.append(str(dateArray[i][0]) + '/' + str(dateArray[i][1])) # print(str(dateArray[i][0]) + '/' + str(dateArray[i][1])) # indoorTemp.append(weatherArr[i][1]) # outdoorTemp.append(weatherArr[i][2]) # pressure.append(weatherArr[i][3]) return (timeArray, dateArray, contractedDateArray) def getWeatherData(weatherArr): indoorTemp = [] outdoorTemp = [] pressure = [] for i in range(0,len(weatherArr)): indoorTemp.append(weatherArr[i][1]) outdoorTemp.append(weatherArr[i][2]) pressure.append(weatherArr[i][3]) return indoorTemp,outdoorTemp,pressure def getHeaderData(headerArr, headerArrString): rawRateArr = [] longitudeArr = [] latitudeArr = [] runtimes = [] numEvents = [] # print(type(headerArr)) meanTime = np.mean(headerArr[:,3]) sigma = np.std(headerArr[:,4]/headerArr[:,3]) for i in range(0,len(headerArr)): rawRate = (headerArr[i][4])/(headerArr[i][3]) # print(type(headerArr[i][4]), ' ', type(headerArr[i][3])) runtimes.append(float(headerArr[i][3])) numEvents.append(float(headerArr[i][4])) # print(rawRate) # rawRateArr.append(rawRate) #Adjust for "wrong" data in POLA1 if(headerArrString == 'POLA1'): if(i<len(headerArr[:,3])-5): if(rawRate>100): rawRateArr.append(headerArr[i][4]/2050) else: rawRateArr.append(headerArr[i][4]/headerArr[i][3]) else: rawRateArr.append(rawRate) else: rawRateArr.append(rawRate) latitudeArr.append(headerArr[i][19]) longitudeArr.append(headerArr[i][20]) print('minimum runtime: ', min(runtimes)) print('sorted: ', np.sort(rawRateArr)[0:20]) print('maximum numEvents: ', max(numEvents)) print('sorted events: ', np.sort(numEvents)[-20:]) print('Ratio: ', len(rawRateArr)/len(longitudeArr)) return rawRateArr, longitudeArr, latitudeArr def linearRegression(x,y): regr = linear_model.LinearRegression() # x_train,x_test,y_train,y_test = train_test_split(pressure3,rawRate3,test_size=0.2,random_state=4) # # x = np.arange(0, 20, 1) # y = np.arange(0, 40, 2) # Train the model using the training sets sigma = np.std(y) deleteIndices = [] #delete values that deviate too much for i in range(0,len(y)): if (abs(y[i])>200): deleteIndices.append(i) x = np.delete(x, deleteIndices) y = np.delete(y, deleteIndices) regr.fit(np.array(x).reshape(-1, 1), y) # Make predictions using the testing set # diabetes_y_pred = regr.predict(diabetes_X_test) slope = regr.coef_ y_intercept = regr.intercept_ # print('Coefficients: \n', regr.coef_) # # # print(regr.intercept_) x_arr = np.array(x) y_fitted = y_intercept + slope * x return x_arr,y_fitted,slope,y_intercept
e6a86459d641a6e21f1359b578a70dccaa7ed3aa
[ "Python" ]
6
Python
fosheimdet/FYS5555
ee2002fb71684a62c2ca15ea206e14180eef89da
058ea6ce539bb98125f81a3b3645947180494c2f
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> <!-- link to external files --> <link rel="stylesheet" href="./style.css"> <link rel="shortcut icon" type="image/x-icon" href="images/Brand_Favicon.png"> <!-- added for temporary navbar --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="./navPlaceholder.js"></script> <!-- added for syntax highlighting (Prism.js) --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.5.0/themes/prism.min.css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.5.0/prism.min.js"></script> <script src="./prism-r.min.js"></script> <link rel="stylesheet" href="./styles-prism-rstudio.css"> <script src="./prism-rconsole.js"></script> <title>R: Basics</title> </head> <body> <div id="navPlaceholder"></div> <div class="content-wrapper"> <h1>Using R/RStudio.</h1> <p>Some text.</p> <p>Broom, View</p> <h2>RStudio's 4 Panels</h2> <h2>Console vs. Script</h2> <p>Some text.</p> <h2>Stuff</h2> <p>There are 4 types of functionality:</p> <ol> <li>Basic calculations</li> <li>Built-in functions</li> <li>Custom functions</li> <li>Someone Else's Custom functions (Libraries)</li> </ol> <h3>1. Basic Calculations</h3> <p>The simplest functionality that R has is the ability to do basic calculator math using operators such as <code class="language-r">+</code>, <code class="language-r">-</code>, <code class="language-r">*</code>, <code class="language-r">/</code>, and <code class="language-r">^</code>. </p> <p>You can try this for yourself by typing a basic calculation such as <code class="language-rconsole">1 + 1</code> in the console and pressing enter to run it. You should see an output like so:</p> <pre><code class="language-rconsole">> 1 + 1 [1] 2</code></pre> <p>In R, spacing doesn't matter so you will get the same answer no matter where you put the spaces.</p> <p>tip here about how spacing doesn't matter? common mistake where you don't complete a line and either finish it or hit esc</p> <h3>2. Built-In Functions</h3> <p>The next level of functionality are built-in functions such as:</p> <ul> <li><code class="language-r">abs</code></li> <li><code class="language-r">sqrt</code></li> <li><code class="language-r">round</code></li> </ul> <p>Start to type function and see pop-up</p> <img src="https://user-images.githubusercontent.com/194400/49531010-48dad180-f8b1-11e8-8d89-1e61320e1d82.png" alt="Screenshot of function tooltip"></img> <p>For a list of all of the built-in functions in R, run <code class="language-r">builtins()</code> in the console.</p> <pre><code class="language-rconsole">> 1 + 1 [1] 2</code></pre> <p>abs, round, ceiling, floor</p> <h3>3. (User-defined) Custom Functions</h3> <p>The next level of functionality is.</p> <p>You can use the <code class="language-r">print()</code> function.</p> <pre><code class="language-r">print("Hello World!")</code></pre> <pre><code class="language-r">[1] "Hello World!"</code></pre> <h3>4. Someone Else's Custom Functions (Libraries)</h3> <p>The last level of functionality is.</p> <h2>Graphing (next section)</h2> <pre><code class="language-r">1 + 1 # C = (F - 32) / 1.8 tempF <- 57 (tempF - 32) / 1.8 # function to convert F to C fahr_to_celsius <- function(randomVariableNAme) { tempC <- (randomVariableNAme - 32) / 1.8 return(tempC) } fahr_to_celsius(57) fahr_to_celsius(tempF) %>%</code></pre> <pre><code class="language-rconsole">> fahr_to_celsius(57)</code></pre> <pre><code class="language-rconsole">> fahr_to_celsius(57) [1] 13.88889 > fahr_to_celsius(tempF) Error in fahr_to_celsius(tempF) : object 'tempF' not found</code></pre> <div class="prevNext"> <a href="R_Install.html" class="previous">&#10094; Previous</a> <a href="R_Troubleshooting.html" class="next">Next &#10095;</a> </div> </div> </body> </html><file_sep>(function (Prism) { var string = /("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/; Prism.languages.rconsole = { 'input': />.*/, 'error': /(Error).*/ }; }(Prism));<file_sep><!DOCTYPE html> <html> <head> <!-- link to external files --> <link rel="stylesheet" href="./style.css"> <link rel="shortcut icon" type="image/x-icon" href="images/Brand_Favicon.png"> <!-- added for temporary navbar --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="./navPlaceholder.js"></script> <title>R: Installing</title> </head> <body> <div id="navPlaceholder"></div> <div class="content-wrapper"> <h1>Installing R/RStudio</h1> <p>To use R and RStudio, you need 2 things:</p> <ol> <li>R</li> <li>RStudio</li> </ol> <p>If for any reason you can't install R/RStudio right now or you would like to use a temporary version to experiment with, you may <a href="https://mybinder.org/v2/gh/KNortheastern/R-Sandbox/HEAD?urlpath=rstudio" target="_blank">use this R Sandbox.</a> Please note that the sandbox is intended as a temporary solution and may take a while to load, may not always be available, and will not save your work.</p> <h2>Install R</h2> <ol> <li>Go to this <a href="https://repo.miserver.it.umich.edu/cran/">website to download R.</a> <p>Note: R is downloaded from websites called "CRAN mirrors." These "mirror" websites are copies of a master website that contains the latest version of R. CRAN stands for "Comprehensive R Archive Network" and refers to the entire group of mirror sites with copies of R. Dividing the distribution of R between these mirror sites helps reduce traffic, improve access speed, and ensure ____. If the CRAN mirror linked above does not work, please <a href="https://cran.r-project.org/mirrors.html">choose a new CRAN mirror here</a>.</p> </li> <li>Click on the download link for your operating system.</li> <li>Next step.</li> </ol> <h2>Install RStudio</h2> <ol> <li>Go to this <a href="https://rstudio.com/products/rstudio/download/#download">website to download RStudio.</a></li> <li>Click on the download link for your operating system.</li> <li>Run the downloaded installer and follow the instructions it provides.</li> </ol> <div class="prevNext"> <a href="R_Intro.html" class="previous">&#10094; Previous</a> <a href="R_Basics.html" class="next">Next &#10095;</a> </div> </div> </body> </html><file_sep>$(function() { $("#navPlaceholder").load("navPlaceholder.html"); });
1968e7865627cfc86ba682dde2b83734910c5ace
[ "JavaScript", "HTML" ]
4
HTML
KNortheastern/Speed-Dataing
784a9b61f25fdfed06d823abe1d6d6b64d4067fd
b015a525d8a31f4f10101bbe51487099e517c092
refs/heads/master
<repo_name>AldemirGomesDev/react-bootstrap<file_sep>/src/ui/Footer.js import React from 'react'; import {Link} from 'react-router'; const Footer = (props) => { return ( <footer className="container col-12 pt-3 footer bg-dark text-light text-center"> <container className="container col-6 col-md-2 d-flex justify-content-around"> <i className="fab fa-facebook-square"></i> <i className="fab fa-linkedin"></i> <i class="fab fa-instagram"></i> </container> </footer> ); }; export default Footer;<file_sep>/src/container/Sprints.js import React, {Component}from 'react'; export default class Sprints extends Component { constructor(props) { super(props) this.state = { photos: [] } } componentDidMount(){ fetch('https://jsonplaceholder.typicode.com/photos?albumId=1') .then(response => response.json()) .then(json => this.setState({photos: json})) } render() { return ( <section className="container p-3 mt-5 mb-5"> <ul className="list-unstyled"> { this.state.photos.map(photo => { return ( <li className="media pt-2"> <img src={photo.thumbnailUrl} alt="" className="mr-3" /> <div className="media-body"> <h5 className="mt-0 mb-1">{photo.title}</h5> <p>Título: {photo.title}</p> </div> </li> ) }) } </ul> </section> ); } }
9768006585b66afefcb4fa4265f0ba9fadeb49f6
[ "JavaScript" ]
2
JavaScript
AldemirGomesDev/react-bootstrap
c0205524e4ab2540010e48e9266999fbe50b6df4
d81d7d80cf64ff2ef30240dc159af6b9848fc242
refs/heads/master
<repo_name>senamit2708/GuessTheWord<file_sep>/app/src/main/java/com/example/android/guesstheword/screens/score/ScoreViewModel.kt package com.example.android.guesstheword.screens.score import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class ScoreViewModel: ViewModel() { private val TAG = ScoreViewModel::class.java.simpleName var score = 0 }
f1c96d76f92652a52e096df6d2159c9ece0f7a8b
[ "Kotlin" ]
1
Kotlin
senamit2708/GuessTheWord
86f6e7732d680c2b0be8aa2c3e72e36e1e2cf637
73ed398de1ed5efb9dcb9e4b72f7b7a8c1618f5e
refs/heads/master
<file_sep>import urllib.request from bs4 import BeautifulSoup ''' Scrapes all links and images from a user provided url and prints them out based on user's request. ''' def print_list(lst): print('\n'.join(lst)) print('\n====================\n') # protect for import if __name__ == '__main__': url = input('\nEnter a URL \n' + 'Must include ' + r"'https://'" ' header if applicable: \n(ex. https://www.google.com)\n' + '> ') urlSoup = BeautifulSoup(urllib.request.urlopen(url).read()) choice = input('\nWhat to scrape? \n' '1. Links \n' '2. Images \n' '3. Both \n' 'Choice: ') if choice not in ["1","2","3"]: print("\nInvalid Scrape Option. \n") else: print('\n====================\n') if ((choice == "1") or (choice == "3")): links = [link.get('href') for link in urlSoup.findAll('a')] print("URLs:\n-----") print_list(links) if ((choice == "2") or (choice == "3")): images = [image['src'] for image in urlSoup.findAll("img")] print ("Images:\n-------") print_list(images) <file_sep>Webscraper ========== Scrapes a user inputted webpage and gathers all links/images to be printed based on user's request. Utilizes: --------- * Python3 * BeautifulSoup 4 HTML Parser * Python urllib module
0c62fb1443244c55195d313d734f2afd8ea4c44a
[ "Markdown", "Python" ]
2
Python
clui951/WebScraper
ad257a694ebc6d64d05b01c7f64791a747522f65
790d4d217834bd8c3919e5e4e9d077474ac1486d
refs/heads/master
<repo_name>YimiCGH/LightmapTest<file_sep>/Assets/Script/MouseManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class MouseManager : MonoBehaviour { public LayerMask m_clickableLayer; public EventVector3 OnClickEnvironemnt; private Camera m_camera; void Start() { m_camera = Camera.main; } // Update is called once per frame void Update() { RaycastHit hit; if (Physics.Raycast(m_camera.ScreenPointToRay(Input.mousePosition),out hit, 50, m_clickableLayer.value)) { if (Input.GetMouseButtonDown(0)) { OnClickEnvironemnt.Invoke(hit.point); } } } } [System.Serializable] public class EventVector3 : UnityEvent<Vector3> { }
dcc8df23ed777ebe95168bbf5c533dafbe55e04a
[ "C#" ]
1
C#
YimiCGH/LightmapTest
1a235de37fa6457052311651b020221ec236f9d4
2c21786557760051aa014896b47f45f750957d29
refs/heads/master
<repo_name>canyugs/pyuia-example-wordpress<file_sep>/lib/wpauto/android/__init__.py from .signin import * from .main import * <file_sep>/lib/wpauto/android/signin.py from pyuia.appium import AppiumPageObject as AppiumPO __all__ = ['SignInScreen'] class SignInScreen(AppiumPO): def _username_field(self): return self._driver.find_elements_by_class_name('android.widget.EditText')[0] def _password_field(self): return self._driver.find_elements_by_class_name('android.widget.EditText')[1] def _signin_button(self): return self._driver.find_element_by_name('Sign in') def assert_on_this_page(self): self._assert_visible(self._signin_button) def sign_in(self, username, password): self._username_field().send_keys(username) self._password_field().send_keys(<PASSWORD>) self._press_back() # to reveal 'Sign in' button self._signin_button().click() <file_sep>/lib/SettingsScreen.py from pyuia.robot import BasePageLibrary from wpauto import android class SettingsScreen(BasePageLibrary): _page_class_android = android.SettingsScreen def __init__(self): BasePageLibrary.__init__(self, 'WordPress') def should_be_on_settings_screen(self): self._page_object.assert_on_this_page() def get_username(self): return self._page_object.get_username() def back_to_main_screen(self): return self._page_object.back_to_main_screen() <file_sep>/lib/SignInScreen.py from pyuia.robot import BasePageLibrary from wpauto import android class SignInScreen(BasePageLibrary): _page_class_android = android.SignInScreen def __init__(self): BasePageLibrary.__init__(self, 'WordPress') def should_be_on_sign_in_screen(self): self._page_object.assert_on_this_page() def sign_in(self, username, password): self._page_object.sign_in(username, password) <file_sep>/lib/WordPress.py from appium import webdriver from pyuia.robot import BaseAppLibrary, BasePageLibrary from pyuia.appium import AppiumContext __all__ = ['WordPress', 'WPPageLibrary'] PATH_TO_WORDPRESS_APK = '/path/to/wordpress.apk' class WordPress(BaseAppLibrary): def _init_context(self, device_id): return AppiumContext(self._init_driver(device_id)) def _init_driver(self, device_id): desired_caps = { 'udid': device_id, 'deviceName': 'My Phone', 'platformName': 'Android', 'platformVersion': '4.3', 'app': PATH_TO_WORDPRESS_APK, 'appPackage': 'org.wordpress.android', 'appActivity': '.ui.posts.PostsActivity', 'appWaitActivity': '.ui.accounts.WelcomeActivity', 'newCommandTimeout': 10 * 60, } driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) driver.implicitly_wait(3) return driver class WPPageLibrary(BasePageLibrary): def __init__(self): BasePageLibrary.__init__(self, 'WordPress') <file_sep>/lib/MainScreen.py from pyuia.robot import BasePageLibrary from wpauto import android class MainScreen(BasePageLibrary): _page_class_android = android.MainScreen def __init__(self): BasePageLibrary.__init__(self, 'WordPress') def should_be_on_main_screen(self): self._page_object.assert_on_this_page() def go_to_settings(self): self._page_object.go_to_settings() def sign_out(self): self._page_object.sign_out() <file_sep>/lib/wpauto/android/main.py from pyuia.appium import AppiumPageObject as AppiumPO __all__ = ['MainScreen', 'PostsScreen', 'PagesScreen', 'SettingsScreen'] ACTION_BAR_OPEN = 'Open' ACTION_BAR_CLOSE = 'Close' ACTION_BAR_UP = 'Up' class ActionBar(object): def _action_bar(self): return self._driver.find_element_by_id('android:id/action_bar') def _action_indicator(self): return self._action_bar().find_element_by_class_name('android.widget.LinearLayout') def _action_title(self): return self._driver.find_element_by_id('android:id/action_bar_title') def _action_menu_item(self, item): # werid? all menu items have the same content description 'Posts' xpath = "//android.widget.ListView[2]//android.widget.TextView[@text='%s']" % item return self._driver.find_element_by_xpath(xpath) def _navigation_type(self): indicator = self._action_indicator() # http://stackoverflow.com/questions/26049651/appium-unable-to-get-content-desc-attribute-data label = indicator.get_attribute('name') # 'content-desc' doesn't work if label.endswith(', Navigation up'): navtype = ACTION_BAR_UP elif label.endswith(', Open drawer'): navtype = ACTION_BAR_OPEN elif label.endswith(', Close drawer'): navtype = ACTION_BAR_CLOSE else: assert False, label return navtype, indicator @property def _title(self): return self._action_title().text def _open_navigation_drawer(self): navtype, indicator = self._navigation_type() assert navtype in [ACTION_BAR_OPEN, ACTION_BAR_CLOSE], navtype if navtype == ACTION_BAR_OPEN: indicator.click() def _close_navigation_drawer(self): navtype, indicator = self._navigation_type() assert navtype in [ACTION_BAR_OPEN, ACTION_BAR_CLOSE], navtype if navtype == ACTION_BAR_CLOSE: indicator.click() class MainScreen(AppiumPO, ActionBar): def _menu_settings(self): return self._driver.find_element_by_name('Settings') def _context_menu_item(self, item): self._press_menu() self._log_screenshot('Context menu opened.') return self._driver.find_element_by_name(item) def _signout_accept(self): return self._driver.find_elements_by_name('Sign out')[1] def go_to_posts(self): self._open_navigation_drawer() self._action_menu_item('Posts').click() return self._page_object(PostsScreen) def go_to_pages(self): self._open_navigation_drawer() self._action_menu_item('Pages').click() return self._page_object(PagesScreen) def go_to_settings(self): self._press_menu() self._menu_settings().click() return self._page_object(SettingsScreen) def sign_out(self): self._context_menu_item('Sign out').click() self._log_screenshot('Confirmation dialog appeared.') self._signout_accept().click() from .signin import SignInScreen return self._page_object(SignInScreen) class PagesScreen(AppiumPO, ActionBar): def assert_on_this_page(self): title = self._title assert title == 'Pages', title class PostsScreen(AppiumPO, ActionBar): def assert_on_this_page(self): title = self._title assert title == 'Posts', title class SettingsScreen(AppiumPO, ActionBar): def _username_label(self): xpath = "//android.widget.TextView[@text='Username']/following-sibling::android.widget.TextView" return self._driver.find_element_by_xpath(xpath) def assert_on_this_page(self): title = self._title assert title == 'Settings', title def get_username(self): return self._username_label().text def back_to_main_screen(self): self._action_indicator().click() return self._page_object(MainScreen) <file_sep>/README.md PyUIA Example - WordPress ========================= Test Case in Natural Language ----------------------------- [`test/sigin.txt`](test/signin.txt) ``` *** Test Cases *** Sign in with valid credentials. Open the app, and the sign-in screen appears. Sign in with a valid username and password, and the main screen appears. Go to 'Settings', and check if the username is correct. Sign out, and the sign-in screen appears again. [Teardown] Close App ``` Setup ----- 1. Clone this repository. 2. Install [Appium](http://appium.io/getting-started.html) and start an Appium server. ```shell $ appium info: Welcome to Appium v1.2.1 (REV 2a4b624a708e580709006b697dc4c9c4e3007863) info: Appium REST http interface listener started on 0.0.0.0:4723 info: LogLevel: debug ``` 3. Get the APK file of [WordPress for Android](https://play.google.com/store/apps/details?id=org.wordpress.android&hl=en). You can either extract the APK file from the device, or build it from [source](https://github.com/wordpress-mobile/WordPress-Android). 4. Install [PyUIA](https://github.com/imsardine/pyuia) and [Appium client](https://github.com/appium/python-client): ``` pip install pyuia pip install Appium-Python-Client ``` 5. Replace placeholders in [test/resource.txt](test/resource.txt) with your credentials and the serialno of your Android device. ``` *** Variables *** ${username} <USERNAME> ${password} <<PASSWORD>> ${device_id} <SERIALNO> ``` 6. Provide APK location in [lib/WordPress.py](lib/WordPress.py). ```python PATH_TO_WORDPRESS_APK = '/path/to/wordpress.apk' ``` Run the Test ------------ ```shell export VERSIONER_PYTHON_PREFER_32_BIT=yes export PYTHONPATH=lib/ pybot --loglevel TRACE --outputdir output test/signin.txt ``` Then you will get a detailed log file like [this](https://cdn.rawgit.com/imsardine/pyuia-example-wordpress/master/output/log.html).
69afcb1a0ef209925174b0efcd83f382c3571201
[ "Markdown", "Python" ]
8
Python
canyugs/pyuia-example-wordpress
18d7bd0f68b222658d856ac40ff6569d80ce5e24
b889913f9313f771508b78573c40e52468c510a2
refs/heads/master
<file_sep>/* global $ */ $(document).ready(function() { // Point Variables var outboxerPoints = 0; var swarmerPoints = 0; var sluggerPoints = 0; var boxerPuncherPoints = 0; var highestOfTwo = 0; var highestOfAll = 0; var highestOfThree = 0; // Slide Id Variables var introSlide = "s1"; var activeSlideId = introSlide; var name; var outBoxerSlideId = 11; var swarmerSlideId = 12; var sluggerSlideId = 13; var boxerPuncherSlideId =14; $(".outBoxer").click(function() { outboxerPoints = pointSystem(outboxerPoints); console.log("slugger:" + sluggerPoints); nextSlideFunction(); }); $(".swarmer").click(function() { swarmerPoints = pointSystem(swarmerPoints); console.log("swarmer:" + swarmerPoints); nextSlideFunction(); }); $(".slugger").click(function() { sluggerPoints = pointSystem(sluggerPoints); console.log("slugger:" + sluggerPoints); nextSlideFunction(); }); $(".boxerPuncher").click(function() { boxerPuncherPoints = pointSystem(boxerPuncherPoints); console.log("boxerPuncher:"+outboxerPoints); nextSlideFunction(); }); $(".nextQuestion button").click(function(){ var slideNum = parseInt(activeSlideId.substring(1,2)); $("#"+activeSlideId).removeClass("active"); slideNum++; activeSlideId="s"+slideNum; $("#"+activeSlideId).addClass("active"); name = $("#name").val(); $(".inputName").text(name); }); function nextSlideFunction (){ var slideNum = parseInt(activeSlideId.substring(1,2)); $("#"+activeSlideId).removeClass("active"); if (slideNum===9){ gameLogic(); slideNum=gameLogic(); } else{ slideNum++; } activeSlideId="s"+slideNum; $("#"+activeSlideId).addClass("active"); } function pointSystem (typeOfPoints){ return typeOfPoints + 1; } function maxOfTwoNum (numOne,numTwo){ if(numOne>numTwo){ return numOne; } else{ return numTwo; } } function gameLogic(){ highestOfTwo = maxOfTwoNum(outboxerPoints,swarmerPoints); highestOfThree = maxOfTwoNum(highestOfTwo,sluggerPoints); highestOfAll = maxOfTwoNum(highestOfTwo,boxerPuncherPoints); if(highestOfAll === outboxerPoints){ console.log(highestOfTwo); console.log("style: out boxer"); return outBoxerSlideId; } else if(highestOfAll === swarmerPoints){ console.log(highestOfTwo); console.log("style: swarmer"); return swarmerSlideId; } else if (highestOfAll === sluggerPoints){ console.log(highestOfTwo); console.log("style: slugger"); return sluggerSlideId; } else{ return boxerPuncherSlideId; } } });
d79dddd47ceb72e3b9ec1f358af501bacba0f75f
[ "JavaScript" ]
1
JavaScript
gio1880/quiz
3d12fb583e2d4b74f362945f5deceaf2c3f9dc92
e80a74c506adaf664543b1b75912c09c2a311d30
refs/heads/master
<file_sep><?php namespace Pepe\GameOfLife; class GameOfLife { private $array; /** * GameOfLife constructor. * @param array $array */ public function __construct(array $array) { $this->array = $array; } /** * @return array */ public function getData() { return $this->array; } /** * @param $array * @param $x * @param $y * @return int */ private function checkNeighbours($array, $x, $y) { $n = 0; for ($i = $x - 1; $i <= $x + 1; $i++) { for ($ii = $y - 1; $ii <= $y + 1; $ii++) { if (isset($array[$i][$ii]) && [$x, $y] !== [$i, $ii]) { if ($array[$i][$ii] == 1) { $n++; } } } } return $n; } /** * @param $array * @param $x * @param $y * @return bool */ private function checkAlive($array, $x, $y) { $n = $this->checkNeighbours($array, $x, $y); if ($array[$x][$y] == 1) { return 3 === $n || 2 === $n; } else { return 3 === $n; } } /** * @param $array * @return static */ public function nextGen($array) { $narray = []; foreach ($array as $y => $row) { foreach ($row as $x => $cell) { $this->checkAlive($array, $x, $y) ? $narray[$x][$y] = 1 : $narray[$x][$y] = 0; } } return new static($narray); } }<file_sep><?php if (isset($_POST['width']) && isset($_POST['height']) && isset($_POST['generations'])) { echo "<form action=\"gif.php?width=" . $_POST['width'] . "&height=" . $_POST['height'] . "&gene=" . $_POST['generations'] . "\" method = \"post\">"; echo "<table>"; for ($y = 0; $y < $_POST['height']; $y++) { echo "<tr>"; for ($x = 0; $x < $_POST['width']; $x++) { echo "<td><input type=\"checkbox\" name=\"xxx[$x][$y]\"></td>"; } echo "</tr>"; } echo "<input type=\"submit\" name = \"submit\">"; echo "</form>"; } else { echo "Nejsou zadany hodnoty"; } <file_sep><?php namespace Pepe\GameOfLife; class GameOfLifeFactory { /** * @param $width * @param $height * @param $checked * @return GameOfLife */ function create($width, $height, $checked) { $array = []; for ($y = 0; $y < $height; $y++) { for ($x = 0; $x < $width; $x++) { $array[$x][$y] = isset($checked[$x][$y]) && $checked[$x][$y] ? 1 : 0; } } return new GameOfLife($array); } }<file_sep><?php include __DIR__ . '/vendor/autoload.php'; use Pepe\GameOfLife\GameOfLifeFactory; use Pepe\GameOfLife\GameOfLifeGif; use Pepe\GameOfLife\GIFEncoder; $gol = new GameOfLifeFactory(); $g = $gol->create($_GET['width'], $_GET['height'], $_POST['xxx']); $gif = new GameOfLifeGif($g); $gif->create($_GET['gene']); <file_sep># GameOfLife Conways Game of Life Using PHP and gif output <file_sep><?php namespace Pepe\GameOfLife; class GameOfLifeGif { /** * * * @var GameOfLife */ private $gol; /** * GameOfLifeGif constructor. * * @param GameOfLife $gol */ public function __construct(GameOfLife $gol) { $this->gol = $gol; } /** * * * @param int $gene * return void */ public function create($gene) { $frames = []; $framed = []; $gol = $this->gol; for ($i = 0; $i < $gene; $i++) { $data = $gol->getData(); ob_start(); $snap = $this->createSnap($data); imagegif($snap); $frames[]=ob_get_contents(); $framed[]=40; ob_end_clean(); $gol = $gol->nextGen($data); } $gif = new GIFEncoder($frames, $framed, 0, 2, 0, 0, 0, 'bin'); $name = 'g' . time() . '.gif'; $fp = fopen($name, 'wb'); fwrite($fp, $gif->GetAnimation()); fclose($fp); } private function createSnap($array) { $height = count($array); $width = max(array_map('count', $array)); $image = imagecreatetruecolor($width * 5, $height * 5); $white = imagecolorallocate($image, 255, 255, 255); $black = imagecolorallocate($image, 0, 0, 0); for ($y = 0; $y < $height; $y++) { for ($x = 0; $x < $width; $x++) { $v = $x * 5; $s = $y * 5; if ($array[$x][$y] == 1) { for ($i = 0; $i <= 4; $i++) { for ($ii = 0; $ii <= 4; $ii++) { imagesetpixel($image, $v + $i, $s + $ii, $black); } } } else { for ($i = 0; $i <= 4; $i++) { for ($ii = 0; $ii <= 4; $ii++) { imagesetpixel($image, $v + $i, $s + $ii, $white); } } } } } return $image; } }
e77595678bc4dc11b541522e12f279962b85fde0
[ "Markdown", "PHP" ]
6
PHP
KeeYoMEE/GameOfLife
d72d70d78d3b3c3c9ba598625ec5840f9b674eef
a58597e4e99a00ce7cb1d6c3089f92b9566eb3f9
refs/heads/master
<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/8/27 14:06 # @Author : way # @Site : # @Describe: 通过 ip 获取所在省份 import sys import requests AK = "" # 百度 ak 自行申请 http://lbsyun.baidu.com/index.php?title=webapi/ip-api def ip2province(ip): url = f"https://api.map.baidu.com/location/ip?ak={AK}&ip={ip}&coor=bd09ll" try: province = requests.get(url).json()['address'].split('|')[1] return province except: return 'ERROR' if __name__ == '__main__': for line in sys.stdin: cols = line.replace('\n', '').split('\t') cols = [cols[0], ip2province(cols[0])] sys.stdout.write('\t'.join(cols) + '\n') <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/8/27 19:32 # @Author : way # @Site : # @Describe: import pandas as pd from sqlalchemy import create_engine from ironman.data import SourceDataDemo ENGINE_CONFIG = 'mysql+pymysql://root:root@127.0.0.1:3306/test?charset=utf8' class SourceData(SourceDataDemo): def __init__(self): self.ENGINE = create_engine(ENGINE_CONFIG) @property def china(self): sql = "select province, count(distinct remote_addr) from fact_nginx_log where device <> 'Spider' group by province;" df = pd.read_sql(sql, self.ENGINE) data = [{"name": row[0], "value": row[1]} for row in df.values] return data @property def line(self): sql = """ select case when device='Spider' then 'Spider' else 'Normal' end, hour(time_local), count(1) from fact_nginx_log group by case when device='Spider' then 'Spider' else 'Normal' end, hour(time_local); """ df = pd.read_sql(sql, self.ENGINE) data = { '正常访问量': [row[2] for row in df.values if row[0] == 'Normal'], '爬虫访问量': [row[2] for row in df.values if row[0] == 'Spider'], 'legend': [row[1] for row in df.values if row[0] == 'Normal'] } return data @property def bar(self): sql = """ select case when device='Spider' then 'Spider' else 'Normal' end, DATE_FORMAT(time_local, '%Y%m%d'), count(1) from fact_nginx_log where time_local > date_add(CURRENT_DATE, interval - 7 day) group by case when device='Spider' then 'Spider' else 'Normal' end, DATE_FORMAT(time_local, '%Y%m%d'); """ df = pd.read_sql(sql, self.ENGINE) data = { '正常访问量': [row[2] for row in df.values if row[0] == 'Normal'], '爬虫访问量': [row[2] for row in df.values if row[0] == 'Spider'], 'legend': [row[1] for row in df.values if row[0] == 'Normal'] } return data @property def pie(self): sql = """ select device, count(1) from fact_nginx_log where device not in ('Other', 'Spider') -- 过滤掉干扰数据 group by device order by 2 desc limit 10 """ df = pd.read_sql(sql, self.ENGINE) client_data = [{'name': row[0].strip(), 'value': row[1]} for row in df.values] return client_data @property def wordcloud(self): sql = "select browser, count(1) from fact_nginx_log where device = 'Spider' group by browser;" df = pd.read_sql(sql, self.ENGINE) spider_data = [{'name': row[0].strip(), 'value': row[1]} for row in df.values] return spider_data <file_sep># bigdata_practice ![](https://img.shields.io/badge/hive-1.1-green) ![](https://img.shields.io/badge/python-3.6%2B-brightgreen) ![](https://img.shields.io/badge/flask-1.1%2B-orange) ![](https://img.shields.io/badge/echarts-4.7-yellowgreen) 大数据实践项目 - nginx 日志分析可视化 ## 功能说明 通过流、批两种方式,分析 nginx 日志,将分析结果通过 flask + echarts 进行可视化展示 ## 数据收集分析过程 ![image-20201104093541868](https://gitee.com/TurboWay/blogimg/raw/master/img/image-20201104093541868.png) [方式一:离线批处理 hive + datax + mysql](http://blog.turboway.top/article/bigdata_practice_batch/) [方式二:实时流处理 flume + kafka + python + mysql](http://blog.turboway.top/article/bigdata_practice_stream/) ## 配置 * 安装依赖 ``` pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt ``` * 修改 ironman/data_db.py 的数据库配置 ```python ENGINE_CONFIG = 'mysql+pymysql://root:root@127.0.0.1:3306/test?charset=utf8' ``` * mysql 建表 ``` -- nginx_log 日志表 create table fact_nginx_log( `id` int(11) NOT NULL AUTO_INCREMENT, `remote_addr` VARCHAR(20), `time_local` TIMESTAMP(0), `province` VARCHAR(20), `request` varchar(300), `device` varchar(50), `os` varchar(50), `browser` varchar(100), PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 ; -- ip 地区映射表 create table dim_ip( `id` int(11) NOT NULL AUTO_INCREMENT, `ip` VARCHAR(20), `province` VARCHAR(20), `addtime` TIMESTAMP(0) default now(), PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 ; ``` ## 运行 运行 cd ironman; python app.py 打开 http://127.0.0.1:5000/ ## 效果图 ### 24 小时访问趋势 ![image](https://gitee.com/TurboWay/blogimg/raw/master/img/image-20201104095828851.png) ### 每日访问情况 ![image](https://gitee.com/TurboWay/blogimg/raw/master/img/image-20201104095850250.png) ### 客户端设备占比 ![image](https://gitee.com/TurboWay/blogimg/raw/master/img/image-20201104095903233.png) ### 用户分布 ![image](https://gitee.com/TurboWay/blogimg/raw/master/img/image-20201104095914602.png) ### 爬虫词云 ![image](https://gitee.com/TurboWay/blogimg/raw/master/img/image-20201104095933091.png) <file_sep>certifi==2020.6.20 chardet==3.0.4 click==7.1.2 Flask==1.1.2 idna==2.10 itsdangerous==1.1.0 Jinja2==2.11.2 kafka==1.3.5 MarkupSafe==1.1.1 numpy==1.19.1 pandas==1.1.1 PyMySQL==0.10.1 python-dateutil==2.8.1 pytz==2020.1 PyYAML==5.3.1 requests==2.24.0 six==1.15.0 SQLAlchemy==1.3.20 ua-parser==0.10.0 urllib3==1.25.10 user-agents==2.2.0 Werkzeug==1.0.1 xlrd==1.2.0 <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/8/27 14:06 # @Author : way # @Site : # @Describe: 分析 ua ; 安装 pip install pyyaml ua-parser user-agents import sys from user_agents import parse from datetime import datetime def ua_parse(ua): user_agent = parse(ua) return str(user_agent).split(' / ') def format(dt): dt = datetime.strptime(dt, '%d/%b/%Y:%H:%M:%S +0800') return str(dt) if __name__ == '__main__': for line in sys.stdin: cols = line.replace('\n', '').split('\t') cols = cols[:-1] + ua_parse(cols[-1]) cols[1] = format(cols[1]) sys.stdout.write('\t'.join(cols) + '\n') <file_sep>-- nginx_log 日志表 create table fact_nginx_log( `id` int(11) NOT NULL AUTO_INCREMENT, `remote_addr` VARCHAR(20), `time_local` TIMESTAMP(0), `province` VARCHAR(20), `request` varchar(300), `device` varchar(50), `os` varchar(50), `browser` varchar(100), PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 ; -- ip 地区映射表 create table dim_ip( `id` int(11) NOT NULL AUTO_INCREMENT, `ip` VARCHAR(20), `province` VARCHAR(20), `addtime` TIMESTAMP(0) default now(), PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 ;<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/11/2 16:10 # @Author : way # @Site : # @Describe: import re import requests import pandas as pd from datetime import datetime from user_agents import parse from kafka import KafkaConsumer from sqlalchemy import create_engine AK = "" # 百度 ak 自行申请 http://lbsyun.baidu.com/index.php?title=webapi/ip-api ENGINE_CONFIG = 'mysql+pymysql://root:root@127.0.0.1:3306/spider?charset=utf8' ENGINE = create_engine(ENGINE_CONFIG) class NginxLog: def __init__(self, *args): self.remote_addr = args[0] # self.remote_user = args[1] self.time_local = datetime.strptime(args[2], '%d/%b/%Y:%H:%M:%S +0800') self.request = args[3] # self.status = args[4] # self.body_bytes_sent = args[5] # self.http_referer = args[6] http_user_agent = args[7] self.device, self.os, self.browser = str(parse(http_user_agent)).split(' / ') def get_province_baidu(self): url = f"https://api.map.baidu.com/location/ip?ak={AK}&ip={self.remote_addr}&coor=bd09ll" try: province = requests.get(url).json()['address'].split('|')[1] return province except: return 'ERROR' def get_province(self): sql = f"select province from dim_ip where ip = '{self.remote_addr}' limit 1;" data = pd.read_sql(sql, ENGINE) if data.values: return data.values[0][0] else: province = self.get_province_baidu() value = {'ip': self.remote_addr, 'province': province} df = pd.DataFrame([value]) df.to_sql('dim_ip', con=ENGINE, index=False, if_exists='append') return province def save(self): if not re.findall('\.[css|js|woff|TTF|png|jpg|ico]', log.request): province = self.get_province() value = { 'remote_addr': self.remote_addr, 'time_local': self.time_local, 'province': province, 'request': self.request, 'device': self.device, 'os': self.os, 'browser': self.browser } df = pd.DataFrame([value]) print(value) df.to_sql('fact_nginx_log', con=ENGINE, index=False, if_exists='append') servers = ['172.16.122.23:9092', ] consumer = KafkaConsumer( bootstrap_servers=servers, auto_offset_reset='latest', # 重置偏移量 earliest移到最早的可用消息,latest最新的消息,默认为latest ) consumer.subscribe(topics=['nginxlog']) for msg in consumer: info = re.findall('(.*?) - (.*?) \[(.*?)\] "(.*?)" (\\d+) (\\d+) "(.*?)" "(.*?)" .*', msg.value.decode()) log = NginxLog(*info[0]) log.save()
ccb699e8d5566d0dbfbe982585871793f36d96ba
[ "Markdown", "SQL", "Python", "Text" ]
7
Python
JasonHans/bigdata_practice
dbd100cb61f2389c279a30b8735aa4e8fc6f0624
bebdf4a5b02d141c9bcb63ecb04a513a1d92a44b
refs/heads/master
<repo_name>Mcprince12/bookSantaApp<file_sep>/components/AppTabNavigator.js import React, { Component } from 'react'; import { StyleSheet, Text, View, Image } from 'react-native'; import {createBottomTabNavigator} from 'react-navigation-tabs' import {createAppContainer} from 'react-navigation' import BookRequestScreen from '../screens/BookRequestScreen'; import {AppStackNavigator} from './AppStackNavigator' export const AppTabNavigator = createBottomTabNavigator({ DonateBooks:{ screen:AppStackNavigator, navigationOptions:{ tabBarIcon:<Image source={require('../assets/request-list.png')} style={{width:20, height:20}} />, tabBarLabel:"Donate Books" } }, BookRequest:{ screen:BookRequestScreen, navigationOptions:{ tabBarIcon:<Image source={require('../assets/request-book.png')} style={{width:20, height:20}} />, tabBarLabel:"Book Request" } } })<file_sep>/screens/BookRequestScreen.js import React from 'react'; import { KeyboardAvoidingView, StyleSheet, Text, View, TextInput, TouchableOpacity } from 'react-native'; import MyHeader from '../components/MyHeader'; import db from '../config'; import firebase from 'firebase' export default class BookRequestScreen extends React.Component { constructor () { super(); this.state = { userId: firebase.auth().currentUser.email, bookName: "", reasonToRequest: '', } } createUniqueId () { return Math.random().toString(36).substring(7) } addRequest = (bookName, reasonToRequest) => { var userId = this.state.userId var randomRequestId = this.createUniqueId() db.collection( "requested_books" ).add( { "user_id": userId, "book_name": bookName, "reason_to_request": reasonToRequest, "request_id":randomRequestId } ) this.setState( { bookName: '', reasonToRequest:'', } ) return alert("Book Requested Successfully") } render () { return ( <View style={{flex:1}}> <MyHeader title="Request Book" /> <KeyboardAvoidingView style={styles.keyBoardStyle}> <TextInput style={styles.fromTextInput} placeholder={"Enter Book Name"} onChangeText={(text) => { this.setState( { bookName:text, }) }} value={this.state.bookName} /> <TextInput style={[styles.fromTextInput, {height:300}]} placeholder={"Why do You want the Book?"} multiline={true} numberOfLines={8} onChangeText={(text) => { this.setState( { reasonToRequest:text, }) }} value={this.state.reasonToRequest} /> <TouchableOpacity style={styles.button} onPress={() => { this.addRequest(this.state.bookName, this.state.reasonToRequest) }} > <Text> Request </Text> </TouchableOpacity> </KeyboardAvoidingView> </View> ) } } const styles = StyleSheet.create( { keyBoardStyle: { flex: 1, alignItems: 'center', justifyContent: 'center' }, formTextInput: { width: "75%", height: 35, alignSelf: 'center', borderColor: '#ffab91', borderRadius: 10, borderWidth: 1, marginTop: 20, padding: 10, }, button: { width: "75%", height: 50, justifyContent: 'center', alignItems: 'center', borderRadius: 10, backgroundColor: "#ff5722", shadowColor: "#000", shadowOffset: { width: 0, height: 8, }, shadowOpacity: 0.44, shadowRadius: 10.32, elevation: 16, marginTop: 20 }, } )
6cd3b1d4802d57b4083c35a2b79d5c2e83675af4
[ "JavaScript" ]
2
JavaScript
Mcprince12/bookSantaApp
e8081a1768b9e622d19e9c540a760fbf120812f8
53334a90676fa14e478010c758ec6aa12f469606
refs/heads/master
<file_sep>import datetime import sys import subprocess import os from glob import glob import shutil import numpy as np local_tmp_save_dir = "/local/tmp/bmmorris/stsp_tmp/" stsp_executable = "/astro/users/bmmorris/git/STSP/bin/stsp" stsp_executable_astrolab = "/astro/users/bmmorris/git/STSP/bin/stsp_astrolab" run_name = 'kepler17' top_level_output_dir = os.path.join('/astro/store/scratch/tmp/bmmorris/stsp', run_name) def find_windows_to_continue(output_dir_path): """ Parameters ---------- output_dir_path : str Path to outputs Returns ------- runs_ready_to_begin : list Runs that are ready to be begun """ runs_ready_to_begin = [] completed_runs = [] runs_in_progress = [] window_dirs = sorted(glob(os.path.join(output_dir_path, 'window*'))) for window_dir in window_dirs: window_index = int(window_dir.split('window')[1]) run_dirs = sorted(glob(os.path.join(window_dir, 'run*'))) this_window_is_running_or_assigned = False for run_dir in run_dirs: run_index = int(run_dir.split('run')[1]) run_id = (window_index, run_index) current_finalparam_path = os.path.join(run_dir, "window{0:03d}_run{1:03d}_finalparam.txt".format(window_index, run_index)) current_initalized_path = os.path.join(run_dir, "initialized.txt") # If the current directory has its own finalparam.txt file, the run # has been completed if os.path.exists(current_finalparam_path): completed_runs.append(run_id) # If the current directory doesn't have its own finalparam.txt file, # but it has an initialized.txt file, the run is in progress elif os.path.exists(current_initalized_path): runs_in_progress.append(run_id) this_window_is_running_or_assigned = True # If run is not complete or in progress, it is uninitialized: elif not this_window_is_running_or_assigned: runs_ready_to_begin.append(run_id) this_window_is_running_or_assigned = True return runs_ready_to_begin def begin_new_run(output_dir_path, window_index, run_index, job_id=None): """ Parameters ---------- output_dir_path : str Path to output directory window_ind : int Index of window for new job run_ind : int Index of run for new job """ print(os.uname()) print("Job ID: {0}".format(job_id)) scratch_run_dir = os.path.join(output_dir_path, "window{0:03d}/run{1:03d}/" .format(window_index, run_index)) initialized_path = os.path.join(scratch_run_dir, "initialized.txt" .format(window_index, run_index)) local_window_dir = os.path.join(local_tmp_save_dir, 'window{0:03d}' .format(window_index)) local_run_dir = os.path.join(local_tmp_save_dir, 'window{0:03d}/run{1:03d}' .format(window_index, run_index)) if not os.path.exists(initialized_path): with open(initialized_path, 'w') as init: init.write('Initialized at {0}'.format(datetime.datetime.utcnow())) in_file = os.path.join(output_dir_path, "window{0:03d}/run{1:03d}/window{0:03d}_run{1:03d}.in" .format(window_index, run_index)) dat_file = os.path.join(output_dir_path, "window{0:03d}/window{0:03d}.dat" .format(window_index)) if not os.path.exists(local_run_dir): os.makedirs(local_run_dir) # Copy .in, .dat files shutil.copy(in_file, local_run_dir) shutil.copy(dat_file, local_run_dir) # If run is seeded, grab seed from previous run: if run_index != 0: seed_finalparam = os.path.join(output_dir_path, "window{0:03d}/run{1:03d}/window{0:03d}_run{1:03d}_finalparam.txt" .format(window_index, run_index-1)) shutil.copy(seed_finalparam, local_run_dir) os.chdir(local_run_dir) p = subprocess.Popen([stsp_executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE) o,e = p.communicate() if e=='': print('init job: ', stsp_executable, "window{0:03d}_run{1:03d}.in" .format(window_index, run_index)) subprocess.call([stsp_executable, "window{0:03d}_run{1:03d}.in" .format(window_index, run_index)], cwd=local_run_dir) else: subprocess.call([stsp_executable_astrolab, "window{0:03d}_run{1:03d}.in" .format(window_index, run_index)], cwd=local_run_dir) # copy data from /local/tmp dir back to shared dir for txt_file in glob(os.path.join(local_run_dir, "*.txt")): shutil.copy(txt_file, scratch_run_dir) # clean up after the script #os.system('rm /local/tmp/bmmorris/stsp_tmp//'+(sys.argv[1])[0:-3]+'*') shutil.rmtree(local_window_dir) else: with open(initialized_path, 'a') as init: init.write('Another initialization attempted at {0}'.format(datetime.datetime.utcnow())) available_windows = find_windows_to_continue(top_level_output_dir) if len(available_windows) < 1: raise ValueError("No available windows to run") random_integer = np.random.randint(len(available_windows)) window_index, run_index = available_windows[random_integer] print("Now beginning: (window, run) = ({0}, {1})".format(window_index, run_index)) begin_new_run(top_level_output_dir, window_index, run_index, sys.argv[-1]) <file_sep> import os import numpy as np import matplotlib.pyplot as plt from scipy.optimize import fmin ######################################################## # Import dev version of friedrich: import sys sys.path.insert(0, "/astro/users/bmmorris/git/friedrich/") from friedrich.stsp import STSP, friedrich_results_to_stsp_inputs from friedrich.lightcurve import hat11_params_morris ######################################################## friedrich_results_to_stsp_inputs('/local/tmp/friedrich/hat11', hat11_params_morris()) <file_sep>""" Tools for fitting a transit model to the clean "spotless" transits generated in `clean_lightcurves.ipynb` Fix period, ecc, w. Use params from fiducial least sq fit in `datacleaner.TransitLightCurve.fiducial_transit_fit` to seed the run. """ import emcee import numpy as np import batman import matplotlib.pyplot as plt import astropy.units as u def T14b2aRsi(P, T14, b): ''' Convert from duration and impact param to a/Rs and inclination ''' i = np.arccos( ( (P/np.pi)*np.sqrt(1 - b**2)/(T14*b) )**-1 ) aRs = b/np.cos(i) return aRs, np.degrees(i) def aRsi2T14b(P, aRs, i): ''' Convert from a/Rs and inclination to duration and impact param ''' b = aRs*np.cos(i) T14 = (P/np.pi)*np.sqrt(1-b**2)/aRs return T14, b def generate_model_lc_short(times, t0, depth, dur, b, q1, q2): # LD parameters from Deming 2011 http://adsabs.harvard.edu/abs/2011ApJ...740...33D rp = depth**0.5 exp_time = (1*u.min).to(u.day).value # Short cadence params = batman.TransitParams() params.t0 = t0 #time of inferior conjunction params.per = 4.8878018 #orbital period params.rp = rp #planet radius (in units of stellar radii) a, inc = T14b2aRsi(params.per, dur, b) params.a = a #semi-major axis (in units of stellar radii) params.inc = inc #orbital inclination (in degrees) params.ecc = 0 #eccentricity params.w = 90. #longitude of periastron (in degrees) u1 = 2*np.sqrt(q1)*q2 u2 = np.sqrt(q1)*(1 - 2*q2) params.u = [u1, u2] #limb darkening coefficients params.limb_dark = "quadratic" #limb darkening model m = batman.TransitModel(params, times, supersample_factor=7, exp_time=exp_time) model_flux = m.light_curve(params) return model_flux def lnlike(theta, x, y, yerr): model = generate_model_lc_short(x, *theta) return -0.5*(np.sum((y-model)**2/yerr**2)) def lnprior(theta, bestfitt0=2454605.89132): t0, depth, dur, b, q1, q2 = theta if (0.001 < depth < 0.005 and 0.05 < dur < 0.15 and 0 < b < 1 and bestfitt0-0.1 < t0 < bestfitt0+0.1 and 0.0 < q1 < 1.0 and 0.0 < q2 < 1.0): return 0.0 return -np.inf def lnprob(theta, x, y, yerr): lp = lnprior(theta) if not np.isfinite(lp): return -np.inf return lp + lnlike(theta, x, y, yerr) def run_emcee(p0, x, y, yerr, n_steps, n_threads=4, burnin=0.4): ndim = len(p0) nwalkers = 80 n_steps = int(n_steps) burnin = int(burnin*n_steps) pos = [p0 + 1e-3*np.random.randn(ndim) for i in range(nwalkers)] pool = emcee.interruptible_pool.InterruptiblePool(processes=n_threads) sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(x, y, yerr), pool=pool) sampler.run_mcmc(pos, n_steps) samples = sampler.chain[:, burnin:, :].reshape((-1, ndim)) return samples, sampler def plot_triangle(samples): import triangle fig = triangle.corner(samples, labels=["$t_0$", r"depth", r"duration", r"$b$", "$q_1$", "$q_2$"]) plt.show() <file_sep>from __future__ import (absolute_import, division, print_function, unicode_literals) import os from utils import (STSPRun, get_transit_parameters, quadratic_to_nonlinear_ld, load_friedrich_params) from glob import glob import sys import numpy as np h11 = load_friedrich_params() h11['t0'] += 0.25 * h11['per'] ecosw = h11['ecc'] * np.cos(np.radians(h11['w'])) esinw = h11['ecc'] * np.sin(np.radians(h11['w'])) ld_params = ' '.join(map(str, quadratic_to_nonlinear_ld(*h11['u']))) planet_properties = dict(n_planets=1, first_mid_transit_time=h11['t0'], period=h11['per'], transit_depth=h11['rp']**2, transit_duration_days=h11['duration'], impact_parameter=h11['b'], inclination=h11['inc'], orbit_lambda=h11['lam'], ecosw=ecosw, esinw=esinw ) stellar_properties = dict(mean_stellar_density=h11['rho_star'], stellar_rotation_period=h11['per_rot'], stellar_temperature=4780, stellar_metallicity=0, tilt_stellar_rotation_axis=90-h11['inc_stellar'], four_param_limb_darkening=ld_params, n_ld_rings=40 ) spot_properties = dict(lightcurve_path=None, flattened_flag=1, n_spots=2, fractional_spot_contrast=0.7, sigma_radius=0.002, sigma_angle=0.01, ) n_hours = 4.0 n_seconds = int(n_hours*60*60) # For an unseeded run: action_properties = dict(random_seed=74384338, a_scale=1.25, n_chains=300, n_steps=-n_seconds, calc_brightness=1 ) if __name__ == '__main__': run_name = 'sun_active-osg' executable_path = '/home/bmorris/git/STSP/stsp_20160816' top_level_output_dir = os.path.join('/local-scratch/bmorris/sun_active/', run_name) transit_paths = glob('/local-scratch/bmorris/sun_active/friedrich/sun_active/lc*.txt') spot_param_paths = glob('/local-scratch/bmorris/sun_active/friedrich/sun_active/stsp_spots*.txt') run = STSPRun(parameter_file_path=None, light_curve_path=None, output_dir_path=top_level_output_dir, initial_dir=top_level_output_dir, condor_config_path=os.path.join('./', run_name+'.condor'), planet_properties=planet_properties, stellar_properties=stellar_properties, spot_properties=spot_properties, action_properties=action_properties, n_restarts=25) run.copy_data_files(transit_paths=transit_paths, spot_param_paths=spot_param_paths) run.create_runs() #run.make_condor_config() <file_sep>""" Tools for fitting a transit model to the clean "spotless" transits generated in `clean_lightcurves.ipynb` Fix period, ecc, w. Use params from fiducial least sq fit in `datacleaner.TransitLightCurve.fiducial_transit_fit` to seed the run. MCMC methods here have been adapted to allow input with either quadratic or nonlinear (four parameter) limb-darkening parameterizations. """ import emcee import numpy as np import batman import matplotlib.pyplot as plt import astropy.units as u def T14b2aRsi(P, T14, b, RpRs, eccentricity, omega): ''' Convert from duration and impact param to a/Rs and inclination ''' beta = (1 - eccentricity**2)/(1 + eccentricity*np.sin(np.radians(omega))) C = np.sqrt(1 - eccentricity**2)/(1 + eccentricity*np.sin(np.radians(omega))) i = np.arctan(beta * np.sqrt((1 + RpRs)**2 - b**2)/(b*np.sin(T14*np.pi/(P*C)))) aRs = b/(np.cos(i) * beta) return aRs, np.degrees(i) ecosw = 0.261# ? 0.082 esinw = 0.085# ? 0.043 eccentricity = np.sqrt(ecosw**2 + esinw**2) omega = np.degrees(np.arccos(ecosw/eccentricity)) #ecosw = 0.228 #esinw = 0.056 #ecentricity = np.sqrt(ecosw**2 + esinw**2) #omega = np.degrees(np.arccos(ecosw/eccentricity)) def generate_model_lc_short(times, t0, depth, dur, b, q1, q2, q3=None, q4=None, P=4.8878018, e=eccentricity, w=omega): # LD parameters from Deming 2011 http://adsabs.harvard.edu/abs/2011ApJ...740...33D rp = depth**0.5 exp_time = (1*u.min).to(u.day).value # Short cadence params = batman.TransitParams() params.t0 = t0 #time of inferior conjunction params.per = P #orbital period params.rp = rp #planet radius (in units of stellar radii) params.ecc = e #eccentricity params.w = w #longitude of periastron (in degrees) a, inc = T14b2aRsi(params.per, dur, b, rp, e, w) params.a = a #semi-major axis (in units of stellar radii) params.inc = inc #orbital inclination (in degrees) u1 = 2*np.sqrt(q1)*q2 u2 = np.sqrt(q1)*(1 - 2*q2) if q3 is None and q4 is None: params.u = [u1, u2] #limb darkening coefficients params.limb_dark = "quadratic" #limb darkening model else: params.u = [q1, q2, q3, q4] params.limb_dark = "nonlinear" m = batman.TransitModel(params, times, supersample_factor=7, exp_time=exp_time) model_flux = m.light_curve(params) return model_flux def generate_model_lc_short_full(times, depth, dur, b, ecosw, esinw, q1, q2, q3=None, q4=None, fixed_P=None, fixed_t0=None): # LD parameters from Deming 2011 http://adsabs.harvard.edu/abs/2011ApJ...740...33D rp = depth**0.5 exp_time = (1*u.min).to(u.day).value # Short cadence params = batman.TransitParams() params.t0 = fixed_t0 #time of inferior conjunction params.per = fixed_P #orbital period params.rp = rp #planet radius (in units of stellar radii) eccentricity = np.sqrt(ecosw**2 + esinw**2) omega = np.degrees(np.arccos(ecosw/eccentricity)) a, inc = T14b2aRsi(params.per, dur, b, rp, eccentricity, omega) params.a = a #semi-major axis (in units of stellar radii) params.inc = inc #orbital inclination (in degrees) params.ecc = eccentricity #eccentricity params.w = omega #longitude of periastron (in degrees) u1 = 2*np.sqrt(q1)*q2 u2 = np.sqrt(q1)*(1 - 2*q2) if q3 is None and q4 is None: params.u = [u1, u2] #limb darkening coefficients params.limb_dark = "quadratic" #limb darkening model else: params.u = [q1, q2, q3, q4] params.limb_dark = "nonlinear" m = batman.TransitModel(params, times, supersample_factor=7, exp_time=exp_time) model_flux = m.light_curve(params) return model_flux #### Tools for fitting spotless transits def lnlike(theta, x, y, yerr, P): model = generate_model_lc_short(x, *theta, P=P) return -0.5*(np.sum((y-model)**2/yerr**2)) def lnprior(theta, bestfitt0=2454605.89132): if len(theta) == 6: t0, depth, dur, b, q1, q2 = theta if (0.001 < depth < 0.005 and 0.05 < dur < 0.15 and 0 < b < 1 and bestfitt0-0.1 < t0 < bestfitt0+0.1 and 0.0 < q1 < 1.0 and 0.0 < q2 < 1.0): return 0.0 elif len(theta) == 8: t0, depth, dur, b, q1, q2, q3, q4 = theta if (0.001 < depth < 0.005 and 0.05 < dur < 0.15 and 0 < b < 1 and bestfitt0-0.1 < t0 < bestfitt0+0.1 and 0.0 < q1 < 1.0 and 0.0 < q2 < 1.0 and 0.0 < q3 < 1.0 and 0.0 < q4 < 1.0): return 0.0 return -np.inf def lnprob(theta, x, y, yerr, P): lp = lnprior(theta) if not np.isfinite(lp): return -np.inf return lp + lnlike(theta, x, y, yerr, P) def run_emcee(p0, x, y, yerr, n_steps, n_threads=4, burnin=0.4, P=4.8878018, n_walkers=50): """Run emcee on the spotless transits""" ndim = len(p0) nwalkers = n_walkers n_steps = int(n_steps) burnin = int(burnin*n_steps) pos = [p0 + 1e-3*np.random.randn(ndim) for i in range(nwalkers)] pool = emcee.interruptible_pool.InterruptiblePool(processes=n_threads) sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(x, y, yerr, P), pool=pool) sampler.run_mcmc(pos, n_steps) samples = sampler.chain[:, burnin:, :].reshape((-1, ndim)) return samples, sampler ## Tools for fitting for the transit ephemeris with fixed transit light curve def lnlike_ephemeris(theta, x, y, yerr, bestfit_transit_parameters): depth, dur, b, q1, q2 = bestfit_transit_parameters model = generate_model_lc_short(x, theta[0], depth, dur, b, q1, q2, P=theta[1]) return -0.5*(np.sum((y-model)**2/yerr**2)) def lnprior_ephemeris(theta, bestfitt0=2454605.89132): t0, P = theta if (bestfitt0-0.1 < t0 < bestfitt0+0.1 and 4.5 < P < 5.5): return 0.0 return -np.inf def lnprob_ephemeris(theta, x, y, yerr, bestfit_transit_parameters): lp = lnprior_ephemeris(theta) if not np.isfinite(lp): return -np.inf return lp + lnlike_ephemeris(theta, x, y, yerr, bestfit_transit_parameters) def run_emcee_ephemeris(p0, x, y, yerr, n_steps, bestfit_transit_parameters, n_threads=4, burnin=0.4, n_walkers=20): """ Run emcee to calculate the ephemeris bestfit_transit_parameters : list depth, duration, b, q1, q2 """ ndim = len(p0) nwalkers = int(n_walkers) n_steps = int(n_steps) burnin = int(burnin*n_steps) pos = [p0 + 1e-5*np.random.randn(ndim) for i in range(nwalkers)] pool = emcee.interruptible_pool.InterruptiblePool(processes=n_threads) sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob_ephemeris, args=(x, y, yerr, bestfit_transit_parameters), pool=pool) sampler.run_mcmc(pos, n_steps) samples = sampler.chain[:, burnin:, :].reshape((-1, ndim)) return samples, sampler #### Tools for fitting spotless transits with ephemeris fixed def lnlike_fixed_ephem(theta, x, y, yerr): model = generate_model_lc_short_full(x, *theta) return -0.5*(np.sum((y-model)**2/yerr**2)) def lnprior_fixed_ephem(theta, bestfitt0=2454605.89132): if len(theta) == 6: depth, dur, b, q1, q2 = theta if (0.001 < depth < 0.005 and 0.05 < dur < 0.15 and 0 < b < 1 and 0.0 < q1 < 1.0 and 0.0 < q2 < 1.0): return 0.0 elif len(theta) == 8: t0, depth, dur, b, q1, q2, q3, q4 = theta if (0.001 < depth < 0.005 and 0.05 < dur < 0.15 and 0 < b < 1 and bestfitt0-0.1 < t0 < bestfitt0+0.1 and 0.0 < q1 < 1.0 and 0.0 < q2 < 1.0 and 0.0 < q3 < 1.0 and 0.0 < q4 < 1.0): return 0.0 return -np.inf def lnprob_fixed_ephem(theta, x, y, yerr): lp = lnprior_fixed_ephem(theta) if not np.isfinite(lp): return -np.inf return lp + lnlike_fixed_ephem(theta, x, y, yerr) # # def run_emcee(p0, x, y, yerr, n_steps, n_threads=4, burnin=0.4): # """Run emcee on the spotless transits""" # ndim = len(p0) # nwalkers = 80 # n_steps = int(n_steps) # burnin = int(burnin*n_steps) # pos = [p0 + 1e-3*np.random.randn(ndim) for i in range(nwalkers)] # # pool = emcee.interruptible_pool.InterruptiblePool(processes=n_threads) # sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob_fixed_ephem, args=(x, y, yerr), # pool=pool) # # sampler.run_mcmc(pos, n_steps) # samples = sampler.chain[:, burnin:, :].reshape((-1, ndim)) # return samples, sampler def plot_triangle(samples): import triangle if samples.shape[1] == 2: fig = triangle.corner(samples, labels=["$t_0$", "$P$"]) if samples.shape[1] == 6: fig = triangle.corner(samples, labels=["$t_0$", r"depth", r"duration", r"$b$", "$q_1$", "$q_2$"]) elif samples.shape[1] == 8: fig = triangle.corner(samples, labels=["$t_0$", r"depth", r"duration", r"$b$", "$q_1$", "$q_2$", "$q_3$", "$q_4$"]) plt.show() def print_emcee_results(samples): if samples.shape[1] == 6: labels = ["t_0", r"depth", r"duration", r"b", "q_1", "q_2"] elif samples.shape[1] == 8: labels = ["t_0", r"depth", r"duration", r"b", "q_1", "q_2", "q_3", "q_4"] all_results = "" for i, label in enumerate(labels): mid, minus, plus = np.percentile(samples[:,i], [50, 16, 84]) lower = mid - minus upper = plus - mid if i==0: latex_string = "{0}: {{{1}}}_{{-{2:0.6f}}}^{{+{3:0.6f}}} \\\\".format(label, mid, lower, upper) elif i==1: latex_string = "{0}: {{{1:.5f}}}_{{-{2:.5f}}}^{{+{3:.5f}}} \\\\".format(label, mid, lower, upper) elif i==2: latex_string = "{0}: {{{1:.04f}}}_{{-{2:.04f}}}^{{+{3:.04f}}} \\\\".format(label, mid, lower, upper) elif i==3: latex_string = "{0}: {{{1:.03f}}}_{{-{2:.03f}}}^{{+{3:.03f}}} \\\\".format(label, mid, lower, upper) elif i==4: latex_string = "{0}: {{{1:.2f}}}_{{-{2:.2f}}}^{{+{3:.2f}}} \\\\".format(label, mid, lower, upper) elif i==5: latex_string = "{0}: {{{1:.2f}}}_{{-{2:.2f}}}^{{+{3:.2f}}} \\\\".format(label, mid, lower, upper) elif i==6: latex_string = "{0}: {{{1:.2f}}}_{{-{2:.2f}}}^{{+{3:.2f}}} \\\\".format(label, mid, lower, upper) elif i==7: latex_string = "{0}: {{{1:.2f}}}_{{-{2:.2f}}}^{{+{3:.2f}}} \\\\".format(label, mid, lower, upper) all_results += latex_string return "$"+all_results+"$" <file_sep>""" To be used after you've used `datacleaner` to produce normalized light curves, i.e. the ones that should be saved as `normalized_long` & `normalized_short` """ <file_sep> import os import numpy as np from scipy.ndimage import gaussian_filter output_file_path = 'chunk16.in' template_file_path = 'fill_in.in' template_file = open(template_file_path, 'r').read() stellar_rotation_period = np.loadtxt('../params/stellar_rotation_period.txt').item() light_curve_path = '../lightcurves/c16.txt' light_curve = np.loadtxt(light_curve_path) t0 = 2454605.89135 per = 4.88780296 ecosw = 0.261 esinw = 0.085 eccentricity = np.sqrt(ecosw**2 + esinw**2) w = np.arccos(ecosw/eccentricity) #w += np.pi offset = np.pi/2 ecosw = eccentricity*np.cos(w + offset) esinw = eccentricity*np.sin(w + offset) planet_properties = dict(n_planets=1, first_mid_transit_time=t0, # From fits in data/fit_transit.ipynb period=4.88780296, # From fits in data/fit_transit.ipynb transit_depth=0.00347, # From fits in data/fit_transit.ipynb transit_duration_days=0.1031, # From fits in data/fit_transit.ipynb impact_parameter=0.278, # From fits in data/fit_transit.ipynb inclination=88.9027452976, # From fits in data/fit_transit.ipynb orbit_lambda=103, # Winn 2010 ecosw=ecosw, #=0.261, # Winn 2010 esinw=esinw#=0.085 # Winn 2010 ) stellar_properties = dict(mean_stellar_density=2.41, # From fits in data/fit_transit.ipynb stellar_rotation_period=stellar_rotation_period, # from data/periodogram.ipynb stellar_temperature=4780, # Bakos 2010 stellar_metallicity=0.31, # Bakos 2010 tilt_stellar_rotation_axis=80, # Sanchis-Ojeda 2011, i_s four_param_limb_darkening=' '.join(map(str, [0.000, 0.727, 0.000, -0.029])), # From fits in data/fit_transit.ipynb n_ld_rings=100 ) spot_properties = dict(lightcurve_path=os.path.abspath(light_curve_path), start_fit_time=light_curve[0, 0], fit_duration_days=light_curve[-1, 0] - light_curve[0, 0], noise_corrected_max=np.max(gaussian_filter(light_curve[:, 1], 50)), flattened_flag=0, n_spots=4, fractional_spot_contrast=0.7 ) # For an unseeded run: action_properties = dict(action='M', random_seed=74384338, a_scale=1.25, n_chains=2, n_steps=100, calc_brightness=1 ) # M ; M= unseeded mcmc # 74384338 ; random seed # 1.25000 ; ascale # 40 ; number of chains # 5000 ; mcmc steps # 1 ; 0= use downfrommax normalization, 1= calculate brightness factor for every model assert action_properties['n_chains'] % 2 == 0, "`n_chains` must be even." all_dicts = planet_properties for d in [stellar_properties, spot_properties, action_properties]: all_dicts.update(d) in_string = open('fill_in.in').read() with open(output_file_path, 'w') as out: out.write(in_string.format(**all_dicts)) <file_sep>import numpy as np import os from glob import glob from scipy.ndimage import gaussian_filter import shutil import stat import json python_executable = 'python' falconer_path = '/home/bmorris/git/hat-11/osg/falconer.py' config_file_text = """ getenv = true Notification = never Executable = {executable} Initialdir = {initial_dir} Universe = vanilla Log = {log_file_path} Error = {error_file_path} Output = {output_file_path} """ def get_transit_parameters(parameter_file_path): """ Load transit parameters from JRAD's file """ # BJDREF = 2454833. # params = np.loadtxt(parameter_file_path, unpack=True, skiprows=4, usecols=[0]) # p_orb = str(params[0]) # t_0 = str(params[1] - BJDREF) # tdur = str(params[2]) # p_rot = str(params[3]) # Rp_Rs = str(params[4]**2.) # impact = str(params[5]) # incl_orb = str(params[6]) # Teff = str(params[7]) # sden = str(params[8]) # return p_orb, t_0, tdur, p_rot, Rp_Rs, impact, incl_orb, Teff, sden BJDREF = 2454833. params = np.loadtxt(parameter_file_path, unpack=True, skiprows=4, usecols=[0]) p_orb = params[0] t_0 = params[1] - BJDREF tdur = params[2] p_rot = params[3] Rp_Rs = params[4]**2. impact = params[5] incl_orb = params[6] Teff = params[7] sden = params[8] return p_orb, t_0, tdur, p_rot, Rp_Rs, impact, incl_orb, Teff, sden class STSPRun(object): def __init__(self, parameter_file_path=None, light_curve_path=None, executable_path=None, output_dir_path=None, initial_dir=None, condor_config_path=None, n_restarts=None, planet_properties=None, stellar_properties=None, spot_properties=None, action_properties=None): """ Parameters ---------- parameter_file_path : str Path to the parameter file with transit properties light_curve_path : str Path to the raw input light curve (whitened Kepler data) executable_path : str Path to the python executable file that will be written by this object output_dir_path : str Path to the outputs (*.in, *.dat files and their results) initial_dir : str Path to the directory where condor jobs will start condor_config_path : str Path to the condir .cfg file that will be written by this object n_steps : int Number of steps per small MCMC chain segment n_restarts : int Number of times to repeat the small MCMC chain segments n_walkers : int (even) Number of MCMC walkers """ self.parameter_file_path = parameter_file_path self.light_curve_path = light_curve_path self.executable_path = executable_path self.output_dir_path = output_dir_path self.initial_dir = initial_dir self.condor_config_path = condor_config_path self.planet_properties = planet_properties self.stellar_properties = stellar_properties self.spot_properties = spot_properties self.action_properties = action_properties self.n_restarts = n_restarts print(self.stellar_properties['tilt_stellar_rotation_axis']) if not self.action_properties['n_chains'] % 2 == 0: raise ValueError("Number of walkers must be even, got {0}" .format(self.action_properties['n_chains'])) if not os.path.exists(output_dir_path): os.mkdir(output_dir_path) def get_transit_parameters(self): p_orb = self.planet_properties['period'] t_0 = self.planet_properties['first_mid_transit_time'] tdur = self.planet_properties['transit_duration_days'] p_rot = self.stellar_properties['stellar_rotation_period'] Rp_Rs = self.planet_properties['transit_depth'] impact = self.planet_properties['impact_parameter'] incl_orb = self.planet_properties['inclination'] Teff = self.stellar_properties['stellar_temperature'] sden = self.stellar_properties['mean_stellar_density'] return p_orb, t_0, tdur, p_rot, Rp_Rs, impact, incl_orb, Teff, sden # # def get_downsampled_data(self, FLATMODE=False): # """ # Load the whitened Kepler data, downsample it out of transit. # # Parameters # ---------- # FLATMODE : bool (optional) # False by default because: what does this do? (TODO) # """ # # where is the original data file to analyze? # tt0, ff0, ee0 = np.loadtxt(self.light_curve_path, unpack=True) # # p_orb, t_0, tdur, p_rot, Rp_Rs, impact, incl_orb, Teff, sden = self.get_transit_parameters() # toff = float(tdur) / float(p_orb) # the transit duration in % (phase) units # # # down-sample the out-of-transit data # # define the region +/- 1 transit duration for in-transit # OOT = np.where( ((((tt0-float(t_0)) % float(p_orb))/float(p_orb)) > toff) & # ((((tt0-float(t_0)) % float(p_orb))/float(p_orb)) < 1-toff) ) # ITT = np.where( ((((tt0-float(t_0)) % float(p_orb))/float(p_orb)) <= toff) | # ((((tt0-float(t_0)) % float(p_orb))/float(p_orb)) >= 1-toff) ) # # # the factor to down-sample by # Nds = 30 # for Kepler 17 # # Nds = 10 # for Joe's data # # # down sample out-of-transit, grab every N'th data point # OOT_ds = OOT[0][np.arange(0,np.size(OOT), Nds)] # # if FLATMODE is True: # # just use in-transit data # idx = ITT[0][0:] # idx.sort() # elif FLATMODE is False: # # use in- and out-of-transit data # idx = np.concatenate((ITT[0][0:], OOT_ds)) # idx.sort() # # # these arrays are the final, down-sampled data # tt = tt0[idx] # ff = ff0[idx] # ee = ee0[idx] # # return tt, ff, ee # def make_condor_config(self): # """ # Write a condor config file. # # Parameters # ---------- # condor_config_path : str # Path to config file to create # # executable_path : str # Path to executable shell script # # initial_dir : str # Path to directory to work in # """ # with open(self.condor_config_path, 'w') as condor_config: # # condor_config.write(config_file_text.format(log_file_path=os.path.join(self.initial_dir, # 'log.txt'), # error_file_path=os.path.join(self.initial_dir, # 'err.txt'), # output_file_path=os.path.join(self.initial_dir, # 'out.txt'), # initial_dir=self.initial_dir, # executable=self.executable_path).lstrip()) # #for window in self.window_dirs: # # for restart in range(self.n_restarts): # n_jobs_to_queue = int(1.7*len(self.window_dirs)*self.n_restarts) # for i in range(n_jobs_to_queue): # condor_config.write("Arguments = {0}\nQueue\n".format(i)) # # condor_wrapper_path = self.condor_config_path.split('.condor')[0] + '.csh' # with open(condor_wrapper_path, 'w') as wrapper: # # MUST have newline character at the end of the CSH file # wrapper.write("#!/bin/csh\n{0} {1} $1\n".format(python_executable, falconer_path)) # # #permissions = stat.S_IRWXU + stat.S_IXOTH + stat.S_IROTH # permissions = stat.S_IRWXO + stat.S_IRWXG + stat.S_IRWXU # os.chmod(condor_wrapper_path, permissions) # os.chmod(self.condor_config_path, permissions) # # def write_data_files(self): # """ # Create the *.dat data files for each time window # """ # p_orb, t_0, tdur, p_rot, Rp_Rs, impact, incl_orb, Teff, sden = self.get_transit_parameters() # tt, ff, ee = self.get_downsampled_data(FLATMODE=False) # # ddur = float(p_rot) * 0.9 # # ddur = float(p_rot) * 1.2 # # # of time windows, shift each window by 1/2 window size # ntrials = np.floor((np.max(tt)-np.min(tt))*2.0/float(p_rot)) # #nspot_list = ['8'] # #nspots = np.tile(nspot_list, ntrials) # nspot_list = [str(self.spot_properties['n_spots'])] # dstart_all = np.repeat(np.min(tt) + float(p_rot)/2.*np.arange(ntrials), # len(nspot_list)) # # # # main loop for .in file writing of each time window & #spots # for n in range(len(dstart_all)): # dstart = dstart_all[n] # npts = np.sum((tt >= dstart) & (tt <= dstart+ddur)) # wndw = np.where((tt >= dstart) & (tt <= dstart+ddur)) # this could be combined w/ above... # # # only run STSP on line if more than N epoch of data # if npts >= 500: # # window_dir = os.path.join(self.output_dir_path, # "window{0:03d}".format(n)) # data_path = os.path.join(window_dir, # "window{0:03d}.dat".format(n)) # if not os.path.exists(window_dir): # os.mkdir(window_dir) # # # write small chunk of LC to operate on # dfn = open(data_path, 'w') # for k in range(0,npts-1): # dfn.write(str(tt[wndw[0][k]]) + ' ' + # str(ff[wndw[0][k]]) + ' ' + # str(ee[wndw[0][k]]) + '\n') # dfn.close() def copy_data_files(self, transit_paths, spot_param_paths): """ Create the *.dat data files for each time window, using time windows that cover only one transit """ # p_orb, t_0, tdur, p_rot, Rp_Rs, impact, incl_orb, Teff, sden = self.get_transit_parameters() # for transit_path in transit_paths: # if 'transit' in transit_path: # n = int(transit_path.split("transit")[-1].split(".")[0]) # else: # n = int(transit_path.split("lc")[-1].split(".")[0]) # window_dir = os.path.join(self.output_dir_path, # "window{0:03d}".format(n)) for spot_path in spot_param_paths: n = int(spot_path.split("stsp_spots")[-1].split(".")[0]) window_dir = os.path.join(self.output_dir_path, "window{0:03d}".format(n)) spot_param_path = os.path.join(window_dir, "stsp_spots{0:03d}.txt".format(n)) data_path = os.path.join(window_dir, "window{0:03d}.dat".format(n)) if not os.path.exists(window_dir): os.mkdir(window_dir) shutil.copyfile(transit_path, data_path) shutil.copyfile(spot_path, spot_param_path) # tt, ff, ee = self.get_downsampled_data(FLATMODE=False) # # ddur = float(p_rot) * 0.9 # # ddur = float(p_rot) * 1.2 # # # of time windows, shift each window by 1/2 window size # ntrials = np.floor((np.max(tt)-np.min(tt))*2.0/float(p_rot)) # #nspot_list = ['8'] # #nspots = np.tile(nspot_list, ntrials) # nspot_list = [str(self.spot_properties['n_spots'])] # dstart_all = np.repeat(np.min(tt) + float(p_rot)/2.*np.arange(ntrials), # len(nspot_list)) # # # # main loop for .in file writing of each time window & #spots # for n in range(len(dstart_all)): # dstart = dstart_all[n] # npts = np.sum((tt >= dstart) & (tt <= dstart+ddur)) # wndw = np.where((tt >= dstart) & (tt <= dstart+ddur)) # this could be combined w/ above... # # # only run STSP on line if more than N epoch of data # if npts >= 500: # # window_dir = os.path.join(self.output_dir_path, # "window{0:03d}".format(n)) # data_path = os.path.join(window_dir, # "window{0:03d}.dat".format(n)) # if not os.path.exists(window_dir): # os.mkdir(window_dir) # # # write small chunk of LC to operate on # dfn = open(data_path, 'w') # for k in range(0,npts-1): # dfn.write(str(tt[wndw[0][k]]) + ' ' + # str(ff[wndw[0][k]]) + ' ' + # str(ee[wndw[0][k]]) + '\n') # dfn.close() @property def window_dirs(self): """Get all of the window??? directory paths, sort them""" return sorted(glob(os.path.join(self.output_dir_path, 'window*'))) def create_runs(self): """ Make run??? dirs in each window??? dir. """ for window in self.window_dirs: for restart in range(self.n_restarts): new_dir_path = os.path.join(window, 'run{0:03d}'.format(restart)) if not os.path.exists(new_dir_path): os.mkdir(new_dir_path) upper_level_light_curve_path = glob(os.path.join(window, '*.dat'))[0] shutil.copy(upper_level_light_curve_path, new_dir_path) in_file_name = '_'.join(new_dir_path.split(os.sep)[-2:]) + '.in' stsp_spot_path = glob(os.path.join(window, 'stsp_spots*.txt')) if restart == 0: # If there's a friedrich-generated STSP spot param file, use it # to seed the job lower_level_light_curve_path = glob(os.path.join(new_dir_path, '*.dat'))[0] if len(stsp_spot_path) > 0: self.write_friedrich_seeded_in_file(os.path.join(new_dir_path, in_file_name), lower_level_light_curve_path, stsp_spot_path[0]) # If friedrich didn't produce spot parameters, create unseeded # run else: self.write_unseeded_in_file(os.path.join(new_dir_path, in_file_name), lower_level_light_curve_path) else: initialized_path = os.path.join(new_dir_path, 'initialized.txt') if not os.path.exists(initialized_path): previous_dir_path = os.path.join(window, 'run{0:03d}'.format(restart-1)) previous_in_file = glob(os.path.join(previous_dir_path, '*.in'))[0] seed_finalparam_file = os.path.basename(previous_in_file.split('.in')[0] + '_finalparam.txt') #seed_finalparam_dir = os.path.dirname(previous_in_file).split(os.sep)[-1] seed_finalparam_path = seed_finalparam_file if len(stsp_spot_path) > 0: self.write_seeded_in_file(os.path.join(new_dir_path, in_file_name), lower_level_light_curve_path, seed_finalparam_path, spot_param_path=stsp_spot_path[0]) else: self.write_seeded_in_file(os.path.join(new_dir_path, in_file_name), lower_level_light_curve_path, seed_finalparam_path) def write_unseeded_in_file(self, output_path, light_curve_path): """ Parameters ---------- output_path : str Path to the .in file to write light_curve_path : str Path to input light curve """ all_dicts = dict(self.planet_properties) for d in [self.stellar_properties, self.spot_properties, self.action_properties]: all_dicts.update(d) light_curve = np.loadtxt(light_curve_path) all_dicts['action'] = 'M' all_dicts['lightcurve_path'] = light_curve_path.split(os.sep)[-1] all_dicts['start_fit_time'] = light_curve[0, 0] all_dicts['fit_duration_days'] = light_curve[-1, 0] - light_curve[0, 0] all_dicts['noise_corrected_max'] = np.max(gaussian_filter(light_curve[:, 1], 10)) template = open('unseeded.in').read() in_file = template.format(**all_dicts) with open(output_path, 'w') as f: f.write(in_file) ## For spots with fixed latitudes at the equator: #for spot in range(all_dicts['n_spots']): # f.write("1.57079632679\n") def write_friedrich_seeded_in_file(self, output_path, light_curve_path, spot_param_path): """ Parameters ---------- output_path : str Path to the .in file to write light_curve_path : str Path to input light curve """ all_dicts = dict(self.planet_properties) for d in [self.stellar_properties, self.spot_properties, self.action_properties]: all_dicts.update(d) light_curve = np.loadtxt(light_curve_path) # Seed options: all_dicts['action'] = 's' # all_dicts['sigma_radius'] = spot_radius_sigma # all_dicts['sigma_angle'] = spot_angle_sigma # Normal options: all_dicts['lightcurve_path'] = light_curve_path.split(os.sep)[-1] all_dicts['start_fit_time'] = light_curve[0, 0] all_dicts['fit_duration_days'] = light_curve[-1, 0] - light_curve[0, 0] all_dicts['noise_corrected_max'] = np.max(gaussian_filter(light_curve[:, 1], 10)) all_dicts['spot_params'] = open(spot_param_path).read().strip() all_dicts['n_spots'] = all_dicts['spot_params'].count('spot radius') template = open('init_seeded.in').read() in_file = template.format(**all_dicts) with open(output_path, 'w') as f: f.write(in_file) def write_seeded_in_file(self, output_path, light_curve_path, seed_finalparam_path, spot_param_path=None): """ Parameters ---------- output_path : str Path to the .in file to write light_curve_path : str Path to input light curve """ all_dicts = self.planet_properties for d in [self.stellar_properties, self.spot_properties, self.action_properties]: all_dicts.update(d) light_curve = np.loadtxt(light_curve_path) # Seed options: all_dicts['action'] = 'T' # all_dicts['spot_radius_sigma'] = spot_radius_sigma # all_dicts['spot_angle_sigma'] = spot_angle_sigma all_dicts['seed_finalparam_path'] = seed_finalparam_path # Normal options: all_dicts['lightcurve_path'] = light_curve_path.split(os.sep)[-1] all_dicts['start_fit_time'] = light_curve[0, 0] all_dicts['fit_duration_days'] = light_curve[-1, 0] - light_curve[0, 0] all_dicts['noise_corrected_max'] = np.max(gaussian_filter(light_curve[:, 1], 10)) if spot_param_path is not None: n_spots = open(spot_param_path).read().strip().count('spot radius') all_dicts['n_spots'] = n_spots template = open('seeded.in').read() in_file = template.format(**all_dicts) with open(output_path, 'w') as f: f.write(in_file) # For spots with fixed latitudes at the equator: # for spot in range(all_dicts['n_spots']): # f.write("1.57079632679\n") def quadratic_to_nonlinear_ld(u1, u2): a1 = a3 = 0 a2 = u1 + 2*u2 a4 = -u2 return (a1, a2, a3, a4) def load_friedrich_params(): j = json.load(open(os.path.join(os.path.expanduser('~'), 'git', 'friedrich', 'friedrich', 'hat11_parameters.json'))) return j <file_sep>import os from glob import glob import shutil import numpy as np run_name = 'kepler17' top_level_output_dir = os.path.join('/astro/store/scratch/tmp/bmmorris/stsp', run_name) from progress import find_windows_to_continue completed_runs, runs_in_progress = find_windows_to_continue(top_level_output_dir) print("Runs to remove inits from:", runs_in_progress) message = "Are you sure you want to remove all dangling init files? Enter 'yes': " if not raw_input(message).strip().lower() == 'yes': raise ValueError('Killing `{0}`.'.format(__file__)) for window, run in runs_in_progress: init_path = os.path.join(top_level_output_dir, "window{0:03d}".format(window), "run{0:03d}".format(run), "initialized.txt") os.remove(init_path) print("Init files removed.")<file_sep># Prep light curves and curate planet properties for `STSP` with Kepler This is an under-construction code base for interfacing with Professor <NAME>'s starspot forward-model `STSP`. <file_sep>import os from glob import glob import shutil import numpy as np run_name = 'hat11-osg' top_level_output_dir = os.path.join('/local-scratch/bmorris/hat11/', run_name) #finished_runs = glob(os.path.join(top_level_output_dir, # "window???/run???/*parambest.txt")) def find_windows_to_continue(output_dir_path): """ Parameters ---------- output_dir_path : str Path to outputs Returns ------- runs_ready_to_begin : list Runs that are ready to be begun """ runs_ready_to_begin = [] completed_runs = [] runs_in_progress = [] window_dirs = sorted(glob(os.path.join(output_dir_path, 'window*'))) for window_dir in window_dirs: window_index = int(window_dir.split('window')[1]) run_dirs = sorted(glob(os.path.join(window_dir, 'run*'))) this_window_is_running_or_assigned = False for run_dir in run_dirs: run_index = int(run_dir.split('run')[1]) run_id = (window_index, run_index) current_finalparam_path = os.path.join(run_dir, "window{0:03d}_run{1:03d}_finalparam.txt".format(window_index, run_index)) current_initalized_path = os.path.join(run_dir, "initialized.txt") # If the current directory has its own finalparam.txt file, the run # has been completed if os.path.exists(current_finalparam_path): completed_runs.append(run_id) # If the current directory doesn't have its own finalparam.txt file, # but it has an initialized.txt file, the run is in progress elif os.path.exists(current_initalized_path): runs_in_progress.append(run_id) this_window_is_running_or_assigned = True # If run is not complete or in progress, it is uninitialized: elif not this_window_is_running_or_assigned: runs_ready_to_begin.append(run_id) this_window_is_running_or_assigned = True return completed_runs, runs_in_progress if __name__ == '__main__': completed_runs, runs_in_progress = find_windows_to_continue(top_level_output_dir) print("Runs in progress ({0}): {1}".format(len(runs_in_progress), runs_in_progress)) # print("Total runs in progress:", len(runs_in_progress)) import matplotlib.pyplot as plt last_completed_runs = dict() for window, run in completed_runs: if window not in last_completed_runs or last_completed_runs[window] < run: last_completed_runs[window] = run in_progress_runs = [run for window, run in runs_in_progress] window_number, run_number = zip(*last_completed_runs.items()) fig, ax = plt.subplots(1, 2, figsize=(12, 6)) ax[0].plot(window_number, run_number, lw=2)#ls='steps', lw=2) ax[0].set_xlabel('Window') ax[0].set_ylabel('Run') ax[0].axhline(np.mean(run_number)) ax[1].hist(run_number, max(run_number), range=[0, max(run_number)], label='Last Completed', color='k', alpha=0.5) if len(in_progress_runs) > 0: ax[1].hist(in_progress_runs, max(in_progress_runs), range=[0, max(in_progress_runs)], label='In Progress', color='r', alpha=0.5) ax[1].set_xlabel('Latest completed runs') ax[1].legend(loc='upper center') plt.show() <file_sep>import datetime import sys import subprocess import os from glob import glob import shutil import numpy as np local_tmp_save_dir = "/local/tmp/bmmorris/stsp_tmp/" stsp_executable = "/home/bmorris/git/STSP/stsp_20161201" run_name = 'hat11-osg' top_level_output_dir = os.path.join('/local-scratch/bmorris/hat11/', run_name) os.chdir('/home/bmorris/git/hat-11/osg') condor_template = open('template.osg-xsede', 'r').read() condor_submit_path = 'condor_submit.osg-xsede' falconer_log_path = 'falconer_log.txt' def find_windows_to_continue(output_dir_path): """ Parameters ---------- output_dir_path : str Path to outputs Returns ------- runs_ready_to_begin : list Runs that are ready to be begun """ runs_ready_to_begin = [] completed_runs = [] runs_in_progress = [] window_dirs = sorted(glob(os.path.join(output_dir_path, 'window*'))) for window_dir in window_dirs: window_index = int(window_dir.split('window')[1]) run_dirs = sorted(glob(os.path.join(window_dir, 'run*'))) this_window_is_running_or_assigned = False for run_dir in run_dirs: run_index = int(run_dir.split('run')[1]) run_id = (window_index, run_index) current_finalparam_path = os.path.join(run_dir, "window{0:03d}_run{1:03d}_finalparam.txt".format(window_index, run_index)) current_initalized_path = os.path.join(run_dir, "initialized.txt") # If the current directory has its own finalparam.txt file, the run # has been completed if (os.path.exists(current_finalparam_path) and os.path.getsize(current_finalparam_path) > 0): completed_runs.append(run_id) # If the current directory doesn't have its own finalparam.txt file, # but it has an initialized.txt file, the run is in progress elif os.path.exists(current_initalized_path): runs_in_progress.append(run_id) this_window_is_running_or_assigned = True # If run is not complete or in progress, it is uninitialized: elif not this_window_is_running_or_assigned: runs_ready_to_begin.append(run_id) this_window_is_running_or_assigned = True return runs_ready_to_begin def begin_new_run(output_dir_path, window_index, run_index): """ Parameters ---------- output_dir_path : str Path to output directory window_ind : int Index of window for new job run_ind : int Index of run for new job """ print(os.uname()) run_dir = os.path.join(output_dir_path, "window{0:03d}/run{1:03d}/" .format(window_index, run_index)) initialized_path = os.path.join(run_dir, "initialized.txt" .format(window_index, run_index)) if not os.path.exists(initialized_path): with open(initialized_path, 'w') as init: init.write('Initialized at {0}'.format(datetime.datetime.utcnow())) in_file = os.path.join(output_dir_path, "window{0:03d}/run{1:03d}/window{0:03d}_run{1:03d}.in" .format(window_index, run_index)) dat_file = os.path.join(output_dir_path, "window{0:03d}/window{0:03d}.dat" .format(window_index)) # If run is seeded, grab seed from previous run: seed_finalparam_source = None if run_index != 0: seed_finalparam_source = os.path.join(output_dir_path, "window{0:03d}/run{1:03d}/window{0:03d}_run{1:03d}_finalparam.txt" .format(window_index, run_index-1)) seed_finalparam_dest = os.path.join(output_dir_path, "window{0:03d}/run{1:03d}/" .format(window_index, run_index)) shutil.copy(seed_finalparam_source, seed_finalparam_dest) output_files = ["window{0:03d}_run{1:03d}_{2}.txt".format(window_index, run_index, out) for out in ["mcmc", "lcbest", "finalparam", "parambest"]] input_files = [i for i in [seed_finalparam_source, dat_file, in_file] if i is not None] condor_in = dict(xsede_allocation_name = 'TG-AST160046', initial_directory = run_dir, stsp_executable = '/home/bmorris/git/STSP/stsp_login', dot_in_file = in_file.split(os.sep)[-1], transfer_input_files = ", ".join(input_files), transfer_output_files = ", ".join(output_files), stdout_path = 'myout.txt', stderr_path = 'myerr.txt', log_path = 'mylog.txt') with open(condor_submit_path, 'w') as submit: submit.write(condor_template.format(**condor_in)) with open(falconer_log_path, 'a') as fl: fl.write("Submitting: window{0:03d}_run{1:03d}\n".format(window_index, run_index)) os.system('condor_submit {0}'.format(condor_submit_path)) else: with open(initialized_path, 'a') as init: init.write('Another initialization attempted at {0}'.format(datetime.datetime.utcnow())) available_windows = find_windows_to_continue(top_level_output_dir) if len(available_windows) < 1: raise ValueError("No available windows to run") random_integer = np.random.randint(len(available_windows)) #window_index, run_index = available_windows[0]#[random_integer] #begin_new_run(top_level_output_dir, window_index, run_index, sys.argv[-1]) for available_window in available_windows: window_index, run_index = available_window begin_new_run(top_level_output_dir, window_index, run_index) <file_sep>from __future__ import (absolute_import, division, print_function, unicode_literals) import os from utils import (STSPRun, get_transit_parameters) run_name = 'kepler17' top_level_output_dir = os.path.join('/astro/store/scratch/tmp/bmmorris/stsp', run_name) light_curve_path = 'kepler17_whole.dat' parameter_file_path = 'kep17.params' p_orb, t_0, tdur, p_rot, Rp_Rs, impact, incl_orb, Teff, sden = get_transit_parameters(parameter_file_path) planet_properties = dict(n_planets=1, first_mid_transit_time=t_0, period=p_orb, transit_depth=Rp_Rs, transit_duration_days=tdur, impact_parameter=impact, inclination=incl_orb, orbit_lambda=0, ecosw=0.0, esinw=0.0 ) stellar_properties = dict(mean_stellar_density=sden, stellar_rotation_period=p_rot, stellar_temperature=Teff, stellar_metallicity=0, tilt_stellar_rotation_axis=0, four_param_limb_darkening=' '.join(map(str, [0.59984, -0.165775, 0.6876732, -0.349944])), n_ld_rings=100 ) spot_properties = dict(lightcurve_path=os.path.abspath(light_curve_path), flattened_flag=0, n_spots=5, fractional_spot_contrast=0.7 ) # For an unseeded run: action_properties = dict(random_seed=74384338, a_scale=2.5, n_chains=50, n_steps=1000, calc_brightness=1 ) run = STSPRun(parameter_file_path=parameter_file_path, light_curve_path=light_curve_path, executable_path='/astro/users/bmmorris/git/hat-11/kepler17/{0}.csh'.format(run_name), output_dir_path=top_level_output_dir, initial_dir=top_level_output_dir, condor_config_path=os.path.join('./', run_name+'.condor'), planet_properties=planet_properties, stellar_properties=stellar_properties, spot_properties=spot_properties, action_properties=action_properties, n_restarts=20) #run.write_data_files() run.create_runs() run.make_condor_config() <file_sep>from __future__ import (absolute_import, division, print_function, unicode_literals) import os from utils import (STSPRun, get_transit_parameters) from glob import glob planet_properties = dict(n_planets=1, first_mid_transit_time=2454605.89154, period=4.88780236, transit_depth=0.00343, transit_duration_days=0.0982, impact_parameter=0.121, inclination=89.45042, orbit_lambda=106, ecosw=0.261, esinw=0.085 ) stellar_properties = dict(mean_stellar_density=1.81004, stellar_rotation_period=29.984, stellar_temperature=4780, stellar_metallicity=0, tilt_stellar_rotation_axis=90-80, four_param_limb_darkening=' '.join(map(str, [0, 0.86730, 0, -0.15162])), n_ld_rings=40 ) spot_properties = dict(lightcurve_path=None, flattened_flag=1, n_spots=2, fractional_spot_contrast=0.7 ) n_hours = 1.0 #4.0 n_seconds = int(n_hours*60*60) # For an unseeded run: action_properties = dict(random_seed=74384338, a_scale=2.5, n_chains=100, #250, n_steps=-n_seconds, calc_brightness=1 ) if __name__ == '__main__': run_name = 'hat11-osg' executable_path = '/home/bmorris/git/STSP/stsp_20160125' top_level_output_dir = os.path.join('/local-scratch/bmorris/hat11/', run_name) transit_paths = glob('/local-scratch/bmorris/hat11/friedrich/lc*.txt') spot_param_paths = glob('/local-scratch/bmorris/hat11/friedrich/stsp_spots*.txt') # executable_path = '/astro/users/bmmorris/git/STSP/stsp_20160125' # top_level_output_dir = os.path.join('/local/tmp/tmp/', # run_name) # transit_paths = glob('/local/tmp/friedrich/hat11/lc*.txt') # spot_param_paths = glob('/local/tmp/friedrich/hat11/stsp_spots*.txt') run = STSPRun(parameter_file_path=None, light_curve_path=None, output_dir_path=top_level_output_dir, initial_dir=top_level_output_dir, condor_config_path=os.path.join('./', run_name+'.condor'), planet_properties=planet_properties, stellar_properties=stellar_properties, spot_properties=spot_properties, action_properties=action_properties, n_restarts=3) run.copy_data_files(transit_paths=transit_paths, spot_param_paths=spot_param_paths) run.create_runs() #run.make_condor_config() <file_sep>import os from glob import glob import shutil import numpy as np import datetime run_name = 'kepler17' top_level_output_dir = os.path.join('/astro/store/scratch/tmp/bmmorris/stsp', run_name) from progress import find_windows_to_continue completed_runs, runs_in_progress = find_windows_to_continue(top_level_output_dir) remove_runs_after_this_time = datetime.datetime(2015, 12, 1, 13) message = "Are you sure you want to remove all files created after {0}? Enter 'yes': ".format(remove_runs_after_this_time) if not raw_input(message).strip().lower() == 'yes': raise ValueError('Killing `{0}`.'.format(__file__)) for completed_run in completed_runs: window_ind, run_ind = completed_run run_dir = os.path.join(top_level_output_dir, 'window{0:03d}'.format(window_ind), 'run{0:03d}'.format(run_ind)) finalparam_path = os.path.join(run_dir, "window{0:03d}_run{1:03d}_finalparam.txt".format(window_ind, run_ind)) made_after_cutoff = datetime.datetime.fromtimestamp(os.path.getctime(finalparam_path)) > remove_runs_after_this_time #print(finalparam_path, made_after_cutoff) if made_after_cutoff: txt_files = glob(os.path.join(run_dir,'*.txt')) for txt_file in txt_files: os.remove(txt_file) <file_sep> import os from glob import glob import sys sys.path.insert(0, '../data/') import matplotlib.pyplot as plt from datacleaner import LightCurve from results import BestLightCurve, MCMCResults, plot_star from cleanfit import T14b2aRsi import batman import numpy as np #results_dir = '/astro/store/scratch/tmp/bmmorris/stsp/kepler17/window229/run002/' window_ind, run_ind = sys.argv[-2:] # results_dir = ('/astro/store/scratch/tmp/bmmorris/stsp/kepler17/window{0:03d}/run{1:03d}/' #results_dir = ('/local/tmp/osg/hat11-osg/window{0:03d}/run{1:03d}/' #results_dir = ('/local/tmp/osg/hat11-osg/window{0:03d}/run{1:03d}/' results_dir = ('/local/tmp/osg/tmp/hat11-osg/window{0:03d}/run{1:03d}/' .format(int(window_ind), int(run_ind))) #if not os.path.exists(results_dir): print('Results from: {0}'.format(results_dir)) #results_dir = '/astro/store/scratch/tmp/bmmorris/stsp/kepler17/window101/run009/' #results_dir = os.path.abspath('../condor/tmp/') files_in_dir = glob(os.path.join(results_dir, '*.txt')) for output_file in files_in_dir: if output_file.endswith('_errstsp.txt'): error_path = output_file elif output_file.endswith('_finalparam.txt'): final_params_path = output_file elif output_file.endswith('_lcbest.txt'): best_lc_path = output_file elif output_file.endswith('_mcmc.txt'): mcmc_path = output_file elif output_file.endswith('_parambest.txt'): best_params_path = output_file window_dir = os.sep.join(results_dir.split(os.sep)[:-2]) mcmc_paths = glob(window_dir + '/run???/*_mcmc.txt') try: print(best_lc_path) except NameError: raise ValueError("{0} doesn't exist.".format(results_dir)) def hat11_params(): from hat11 import planet_properties, stellar_properties params = batman.TransitParams() params.t0 = planet_properties['first_mid_transit_time'] #time of inferior conjunction params.per = planet_properties['period'] #orbital period params.rp = planet_properties['transit_depth'] #planet radius (in units of stellar radii) b = planet_properties["impact_parameter"] #inclination = 88.94560#np.arccos(b/params.a) params.inc = planet_properties['inclination'] #orbital inclination (in degrees) params.duration = planet_properties['transit_duration_days'] ecosw = planet_properties['ecosw'] esinw = planet_properties['esinw'] eccentricity = np.sqrt(ecosw**2 + esinw**2) omega = np.degrees(np.arccos(ecosw/eccentricity)) a, _ = T14b2aRsi(params.per, params.duration, b, params.rp, eccentricity, omega) params.a = a #semi-major axis (in units of stellar radii) params.ecc = eccentricity #eccentricity params.w = omega #longitude of periastron (in degrees) params.u = map(float, stellar_properties['four_param_limb_darkening'].split(' ')) #limb darkening coefficients params.limb_dark = "nonlinear" #limb darkening model return params transit_params = hat11_params()#get_basic_kepler17_params() blc = BestLightCurve(best_lc_path, transit_params=transit_params) blc.plot_whole_lc() #blc.plot_transits() #plt.show() mcmc = MCMCResults(mcmc_paths) print('Acceptance rate: {0}'.format(str(mcmc.acceptance_rates))) mcmc.plot_chi2() mcmc.plot_chains() #mcmc.plot_star() #mcmc.plot_corner() #mcmc.plot_each_spot() plt.show() <file_sep> import os import numpy as np from glob import glob import matplotlib #matplotlib.use('agg') from matplotlib import pyplot as plt import astropy.units as u from astropy.constants import R_sun from astropy.time import Time from astropy.coordinates import SphericalRepresentation, CartesianRepresentation from datacleaner import LightCurve import corner results_dir = os.path.abspath('../condor/tmp_long/') #results_dir = os.path.abspath('../condor/tmp/') files_in_dir = glob(os.path.join(results_dir, '*.txt')) for output_file in files_in_dir: if output_file.endswith('_errstsp.txt'): error_path = output_file elif output_file.endswith('_finalparam.txt'): final_params_path = output_file elif output_file.endswith('_lcbest.txt'): best_lc_path = output_file elif output_file.endswith('_mcmc.txt'): mcmc_path = output_file elif output_file.endswith('_parambest.txt'): best_params_path = output_file class BestLightCurve(object): def __init__(self, path, transit_params=None): self.path = path self.default_figsize = (12, 8)#(20, 8) times, fluxes_kepler, errors, fluxes_model, flags = np.loadtxt(path, unpack=True) self.times = times if times.mean() > 2450000 else times + 2454833. self.fluxes_kepler = fluxes_kepler self.errors = errors self.fluxes_model = fluxes_model self.flags = flags self.kepler_lc = LightCurve(times=self.times, fluxes=fluxes_kepler, errors=errors) self.model_lc = LightCurve(times=self.times, fluxes=fluxes_model) self.transit_params = transit_params def plot_whole_lc(self): # Whole light curve fig, ax = plt.subplots(2, 1, figsize=self.default_figsize, sharex='col') ax[0].plot_date(self.kepler_lc.times.plot_date, self.fluxes_kepler, 'k.', label='Kepler') ax[0].plot_date(self.model_lc.times.plot_date, self.fluxes_model, 'r', label='STSP') #ax[0].legend(loc='lower left') ax[0].set(ylabel='Flux') ax[1].plot_date(self.kepler_lc.times.plot_date, self.fluxes_kepler - self.fluxes_model, 'k.') ax[1].set(ylabel='Residuals') ax[1].axhline(0, color='r') label_times = Time(ax[1].get_xticks(), format='plot_date') ax[1].set_xticklabels([lt.strftime("%H:%M") for lt in label_times.datetime]) ax[1].set_xlabel('Time on {0} UTC'.format(label_times[0].datetime.date())) ax[0].set_title(os.path.basename(self.path)) # for l in ax[1].get_xticklabels(): # l.set_rotation(45) # l.set_ha('right') return fig, ax def plot_whole_lc(self): # Whole light curve errorbar_color = '#b3b3b3' fig, ax = plt.subplots(2, 1, figsize=self.default_figsize, sharex='col') ax[0].errorbar(self.kepler_lc.times.plot_date, self.fluxes_kepler, self.kepler_lc.errors, fmt='.', color='k', ecolor=errorbar_color, capsize=0, label='Kepler') ax[0].plot(self.model_lc.times.plot_date, self.fluxes_model, 'r', label='STSP') #ax[0].legend(loc='lower left') ax[0].set(ylabel='Flux') ax[1].errorbar(self.kepler_lc.times.plot_date, self.fluxes_kepler - self.fluxes_model, self.kepler_lc.errors, fmt='.', color='k', ecolor=errorbar_color, capsize=0) ax[1].set(ylabel='Residuals') ax[1].axhline(0, color='r') label_times = Time(ax[1].get_xticks(), format='plot_date') ax[1].set_xticklabels([lt.strftime("%H:%M") for lt in label_times.datetime]) ax[1].set_xlabel('Time on {0} UTC'.format(label_times[0].datetime.date())) ax[0].set_title(os.path.basename(self.path)) # for l in ax[1].get_xticklabels(): # l.set_rotation(45) # l.set_ha('right') return fig, ax # def plot_whole_lc(self): # # # Whole light curve # fig, ax = plt.subplots(2, 1, figsize=self.default_figsize, # sharex='col') # ax[0].plot_date(self.kepler_lc.times.plot_date, self.fluxes_kepler, # 'k.', label='Kepler') # ax[0].plot_date(self.model_lc.times.plot_date, self.fluxes_model, # 'r', label='STSP') # #ax[0].legend(loc='lower left') # ax[0].set(ylabel='Flux') # # ax[1].plot_date(self.kepler_lc.times.plot_date, # self.fluxes_kepler - self.fluxes_model, 'k.') # ax[1].set(ylabel='Residuals') # ax[1].axhline(0, color='r') # # label_times = Time(ax[1].get_xticks(), format='plot_date') # ax[1].set_xticklabels([lt.strftime("%H:%M") for lt in label_times.datetime]) # # ax[1].set_xlabel('Time on {0} UTC'.format(label_times[0].datetime.date())) # # ax[0].set_title(os.path.basename(self.path)) # # # for l in ax[1].get_xticklabels(): # # l.set_rotation(45) # # l.set_ha('right') # # return fig, ax def plot_transits(self): if self.transit_params is not None: kepler_transits = LightCurve(**self.kepler_lc.mask_out_of_transit(params=self.transit_params) ).get_transit_light_curves(params=self.transit_params) model_transits = LightCurve(**self.model_lc.mask_out_of_transit(params=self.transit_params) ).get_transit_light_curves(params=self.transit_params) else: kepler_transits = LightCurve(**self.kepler_lc.mask_out_of_transit() ).get_transit_light_curves() model_transits = LightCurve(**self.model_lc.mask_out_of_transit() ).get_transit_light_curves() # Whole light curve if len(kepler_transits) > 0: fig, ax = plt.subplots(2, len(kepler_transits), figsize=self.default_figsize, sharex='col') scale_factor = 0.4e-6 for i in range(len(kepler_transits)): ax[0, i].plot_date(kepler_transits[i].times.plot_date, scale_factor*kepler_transits[i].fluxes, 'k.', label='Kepler') ax[0, i].plot_date(model_transits[i].times.plot_date, scale_factor*model_transits[i].fluxes, 'r', label='STSP') ax[0, i].set(yticks=[]) ax[1, i].axhline(0, color='r', lw=2) ax[1, i].plot_date(kepler_transits[i].times.plot_date, scale_factor*(kepler_transits[i].fluxes - model_transits[i].fluxes), 'k.') xtick = Time(kepler_transits[i].times.jd.mean(), format='jd') #ax[1, i].set(xticks=[xtick.plot_date], xticklabels=[xtick.iso.split('.')[0]], # yticks=[]) #ax[1, i].set(xlabel='Time') #ax[0, 0].legend(loc='lower left') ax[0, 0].set(ylabel=r'Flux')# $\times \, 10^{{{0:.1f}}}$'.format(np.log10(scale_factor))) ax[1, 0].set(ylabel=r'Residuals')# $\times \, 10^{{{0:.1f}}}$'.format(np.log10(scale_factor))) #fig.subplots_adjust(wspace=0.5) fig.tight_layout() return fig, ax else: return None, None class MCMCResults(object): def __init__(self, paths, burnin=0.8): self.table = [] self.chain_ind = [] self.burnin = burnin #self.step_ind = [] self.acceptance_rates = [] for path in sorted(paths): print(path) table = np.loadtxt(path) if table.size > 0: n_walkers = len(np.unique(table[:, 0])) n_accepted_steps = np.count_nonzero(table[:, 2] != 0) n_steps_total = np.max(table[:, 2]) self.acceptance_rates.append(n_accepted_steps/n_steps_total/n_walkers) if len(self.table) == 0: self.table = table else: self.table = np.vstack([self.table, table]) self.chain_ind = np.concatenate([self.chain_ind, table[:, 0]]) #offset = 0 if len(self.step_ind) == 0 else self.step_ind[-1] #plt.figure() #plt.plot(self.step_ind) #self.step_ind = np.concatenate([self.step_ind, table[:, 1] + offset]) self.n_properties_per_spot = 3 self.col_offset = 4 self.n_spots = (self.table.shape[1] - self.col_offset)/self.n_properties_per_spot # Note: latitude is defined on (0, pi) rather than (-pi/2, pi/2) self.radius = self.table[:, self.col_offset+self.n_properties_per_spot*np.arange(self.n_spots)] self.lat = self.table[:, self.col_offset+1+self.n_properties_per_spot*np.arange(self.n_spots)] self.lon = self.table[:, self.col_offset+2+self.n_properties_per_spot*np.arange(self.n_spots)] self.radius_col = self.col_offset+self.n_properties_per_spot*np.arange(self.n_spots) self.lat_col = self.col_offset+1+self.n_properties_per_spot*np.arange(self.n_spots) self.lon_col = self.col_offset+2+self.n_properties_per_spot*np.arange(self.n_spots) self.burnin_int = int(self.burnin*self.table.shape[0]) def plot_chains(self): #fig, ax = plt.subplots(5) n_walkers = len((set(self.chain_ind))) # fig, ax = plt.subplots(1, 3, figsize=(16, 8)) # # for i in range(n_walkers): # chain_i = self.chain_ind == i # radius = self.table[chain_i, :][:, self.col_offset+self.n_properties_per_spot*np.arange(self.n_spots)] # lat = self.table[chain_i, :][:, self.col_offset+1+self.n_properties_per_spot*np.arange(self.n_spots)] # lon = self.table[chain_i, :][:, self.col_offset+2+self.n_properties_per_spot*np.arange(self.n_spots)] # # cmap = plt.cm.winter # kwargs = dict(color=cmap(float(i)/n_walkers), alpha=0.3) # ax[0].plot(radius, **kwargs) # ax[1].plot(lat, **kwargs) # ax[2].plot(lon, **kwargs) # ax[0].set(title='Radius', xlabel='Step') # ax[1].set(title='Latitude', xlabel='Step') # ax[2].set(title='Longitude', xlabel='Step') # fig.tight_layout() #plt.show() n_spots = self.radius.shape[1] fig, ax = plt.subplots(n_spots, 3, figsize=(16, 8)) n_bins = 30 low = 4 high = 96 for i in range(self.radius.shape[1]): r_range = np.percentile(self.radius[self.burnin_int:, i], [low, high]) lat_range = np.percentile(self.lat[self.burnin_int:, i], [low, high]) lon_range = np.percentile(self.lon[self.burnin_int:, i], [low, high]) ax[i, 0].hist(self.radius[self.burnin_int:, i], n_bins, color='k', range=r_range)#, alpha=0.3) ax[i, 1].hist(self.lat[self.burnin_int:, i], n_bins, color='k', range=lat_range)#, log=True, alpha=0.3) ax[i, 2].hist(self.lon[self.burnin_int:, i], n_bins, color='k', range=lon_range)#, log=True, alpha=0.3) ax[i, 0].set_ylabel('Spot {0}'.format(i)) ax[0, 0].set(title='Radius') ax[0, 1].set(title='Latitude') ax[0, 2].set(title='Longitude') ax[1, 0].set_xlabel('$R_s/R_\star$') ax[1, 1].set_xlabel('[radians]') ax[1, 2].set_xlabel('[radians]') fig.tight_layout() def plot_each_spot(self): #fig, ax = plt.subplots(5) n_spots = self.radius.shape[1] burn_in_to_index = int(self.burnin*self.radius.shape[0]) for i in range(n_spots): samples = np.array([self.radius[burn_in_to_index:, i], self.lon[burn_in_to_index:, i]]).T # self.lat[:, i], corner.corner(samples) # cmap = plt.cm.winter # ax[0].plot(radius, color=cmap(float(i)/n_walkers)) # ax[1].plot(lat, color=cmap(float(i)/n_walkers)) # ax[2].plot(lon, color=cmap(float(i)/n_walkers)) # ax[0].set(title='Radius', xlabel='Step') # ax[1].set(title='Latitude', xlabel='Step') # ax[2].set(title='Longitude', xlabel='Step') def plot_star(self, fade_out=True): spots_spherical = SphericalRepresentation(self.lon*u.rad, (self.lat - np.pi/2)*u.rad, 1*R_sun) self.spots_spherical = spots_spherical fig, ax = plot_star(spots_spherical, fade_out=fade_out) #plt.show() def plot_corner(self): #fig = plt.figure(figsize=(14, 14)) exclude_columns = np.array([0, 1, 2, 3, 5, 8, 11, 14, 17]) include_columns = np.ones(self.table.shape[1]) include_columns[exclude_columns] = 0 fig = corner.corner(self.table[:, include_columns.astype(bool)])#, fig=fig) return fig def plot_chi2(self): n_walkers = len((set(self.chain_ind))) fig, ax = plt.subplots(figsize=(12, 12)) n_spots = self.radius.shape[1] for i in range(n_walkers): chain_i = self.chain_ind == i chi2 = self.table[chain_i, 3] #ax.semilogx(range(len(chi2)), chi2) ax.semilogx(range(len(chi2)), np.log10(chi2), alpha=0.6) ax.set(xlabel='Step', ylabel=r'$\log_{10} \, \chi^2$') # def acceptance_rate(self): def plot_star(spots_spherical, fade_out=False): """ Parameters ---------- spots_spherical : `~astropy.coordinates.SphericalRepresentation` Points in spherical coordinates that represent the positions of the star spots. """ oldrcparams = matplotlib.rcParams matplotlib.rcParams['font.size'] = 18 fig, ax = plt.subplots(2, 3, figsize=(16, 16)) positive_x = ax[0, 0] negative_x = ax[1, 0] positive_y = ax[0, 1] negative_y = ax[1, 1] positive_z = ax[0, 2] negative_z = ax[1, 2] axes = [positive_z, positive_x, negative_z, negative_x, positive_y, negative_y] axes_labels = ['+z', '+x', '-z', '-x', '+y', '-y'] # Set black background plot_props = dict(xlim=(-1, 1), ylim=(-1, 1), xticks=(), yticks=()) drange = np.linspace(-1, 1, 100) y = np.sqrt(1 - drange**2) bg_color = 'k' for axis in axes: axis.set(xticks=(), yticks=()) axis.fill_between(drange, y, 1, color=bg_color) axis.fill_between(drange, -1, -y, color=bg_color) axis.set(**plot_props) axis.set_aspect('equal') # Set labels positive_x.set(xlabel='$\hat{z}$', ylabel='$\hat{y}$') # title='+x', positive_x.xaxis.set_label_position("top") positive_x.yaxis.set_label_position("right") negative_x.set(xlabel='$\hat{z}$', ylabel='$\hat{y}$') # title='-x', negative_x.xaxis.set_label_position("top") positive_y.set(xlabel='$\hat{z}$', ylabel='$\hat{x}$') positive_y.xaxis.set_label_position("top") negative_y.set(xlabel='$\hat{z}$', ylabel='$\hat{x}$') negative_y.xaxis.set_label_position("top") negative_y.yaxis.set_label_position("right") negative_z.set(xlabel='$\hat{y}$', ylabel='$\hat{x}$') # title='-z', negative_z.yaxis.set_label_position("right") positive_z.set(xlabel='$\hat{y}$', ylabel='$\hat{x}$') # title='+z', positive_z.yaxis.set_label_position("right") positive_z.xaxis.set_label_position("top") for axis, label in zip(axes, axes_labels): axis.annotate(label, (-0.9, 0.9), color='w', fontsize=14, ha='center', va='center') # Plot gridlines n_gridlines = 9 print("lat grid spacing: {0} deg".format(180./(n_gridlines-1))) n_points = 35 pi = np.pi latitude_lines = SphericalRepresentation(np.linspace(0, 2*pi, n_points)[:, np.newaxis]*u.rad, np.linspace(-pi/2, pi/2, n_gridlines).T*u.rad, np.ones((n_points, 1)) ).to_cartesian() longitude_lines = SphericalRepresentation(np.linspace(0, 2*pi, n_gridlines)[:, np.newaxis]*u.rad, np.linspace(-pi/2, pi/2, n_points).T*u.rad, np.ones((n_gridlines, 1)) ).to_cartesian() for i in range(latitude_lines.shape[1]): for axis in [positive_z, negative_z]: axis.plot(latitude_lines.x[:, i], latitude_lines.y[:, i], ls=':', color='silver') for axis in [positive_x, negative_x, positive_y, negative_y]: axis.plot(latitude_lines.y[:, i], latitude_lines.z[:, i], ls=':', color='silver') for i in range(longitude_lines.shape[0]): for axis in [positive_z, negative_z]: axis.plot(longitude_lines.y[i, :], longitude_lines.x[i, :], ls=':', color='silver') for axis in [positive_x, negative_x, positive_y, negative_y]: axis.plot(longitude_lines.y[i, :], longitude_lines.z[i, :], ls=':', color='silver') # Plot spots spots_cart = spots_spherical.to_cartesian() spots_x = spots_cart.x/R_sun spots_y = spots_cart.y/R_sun spots_z = spots_cart.z/R_sun if fade_out: n = float(len(spots_x)) alpha_range = np.arange(n) alpha = (n - alpha_range)/n else: alpha = 0.5 for spot_ind in range(spots_x.shape[1]): above_x_plane = spots_x[:, spot_ind] > 0 above_y_plane = spots_y[:, spot_ind] > 0 above_z_plane = spots_z[:, spot_ind] > 0 below_x_plane = spots_x[:, spot_ind] < 0 below_y_plane = spots_y[:, spot_ind] < 0 below_z_plane = spots_z[:, spot_ind] < 0 positive_x.plot(spots_y[above_x_plane, spot_ind], spots_z[above_x_plane, spot_ind], '.', alpha=alpha) negative_x.plot(-spots_y[below_x_plane, spot_ind], spots_z[below_x_plane, spot_ind], '.', alpha=alpha) positive_y.plot(-spots_x[above_y_plane, spot_ind], spots_z[above_y_plane, spot_ind], '.', alpha=alpha) negative_y.plot(spots_x[below_y_plane, spot_ind], spots_z[below_y_plane, spot_ind], '.', alpha=alpha) positive_z.plot(spots_x[above_z_plane, spot_ind], spots_y[above_z_plane, spot_ind], '.', alpha=alpha) negative_z.plot(spots_x[below_z_plane, spot_ind], -spots_y[below_z_plane, spot_ind], '.', alpha=alpha) matplotlib.rcParams = oldrcparams return fig, ax # blc = BestLightCurve(best_lc_path) # blc.plot_whole_lc() # blc.plot_transits() # plt.show() #mcmc = MCMCResults(mcmc_path) #mcmc.plot_chains() #mcmc.plot_star() #plt.show() <file_sep> import os from glob import glob import sys sys.path.insert(0, '../data/') import matplotlib.pyplot as plt from datacleaner import LightCurve from results import BestLightCurve, MCMCResults, plot_star import batman import numpy as np #results_dir = '/astro/store/scratch/tmp/bmmorris/stsp/kepler17/window229/run002/' window_ind, run_ind = sys.argv[-2:] results_dir = ('/astro/store/scratch/tmp/bmmorris/stsp/kepler17/window{0:03d}/run{1:03d}/' .format(int(window_ind), int(run_ind))) #if not os.path.exists(results_dir): print('Results from: {0}'.format(results_dir)) #results_dir = '/astro/store/scratch/tmp/bmmorris/stsp/kepler17/window101/run009/' #results_dir = os.path.abspath('../condor/tmp/') files_in_dir = glob(os.path.join(results_dir, '*.txt')) for output_file in files_in_dir: if output_file.endswith('_errstsp.txt'): error_path = output_file elif output_file.endswith('_finalparam.txt'): final_params_path = output_file elif output_file.endswith('_lcbest.txt'): best_lc_path = output_file elif output_file.endswith('_mcmc.txt'): mcmc_path = output_file elif output_file.endswith('_parambest.txt'): best_params_path = output_file window_dir = os.sep.join(results_dir.split(os.sep)[:-2]) mcmc_paths = glob(window_dir + '/run???/*_mcmc.txt') try: print(best_lc_path) except NameError: raise ValueError("{0} doesn't exist.".format(results_dir)) def get_basic_kepler17_params(): # http://exoplanets.org/detail/HAT-P-11_b params = batman.TransitParams() params.t0 = 2455185.678035 #time of inferior conjunction params.per = 1.4857108 #orbital period params.rp = 0.13413993 #planet radius (in units of stellar radii) b = 0.1045441 #inclination = 88.94560#np.arccos(b/params.a) params.inc = 88.94560 #orbital inclination (in degrees) inclination = np.radians(params.inc) params.inclination = params.inc params.a = b/np.cos(inclination) #semi-major axis (in units of stellar radii) params.ecc = 0. #eccentricity params.w = 90. #longitude of periastron (in degrees) params.u = [0.1, 0.3] #limb darkening coefficients params.limb_dark = "quadratic" #limb darkening model params.duration = params.per/np.pi*np.arcsin(np.sqrt((1+params.rp)**2 + b**2) / np.sin(inclination)/params.a) return params transit_params = get_basic_kepler17_params() blc = BestLightCurve(best_lc_path, transit_params=transit_params) blc.plot_whole_lc() blc.plot_transits() #plt.show() mcmc = MCMCResults(mcmc_paths) mcmc.plot_chi2() mcmc.plot_chains() #mcmc.plot_star() #mcmc.plot_corner() #mcmc.plot_each_spot() plt.show()
279c4a3ad46e2a56cb2cd389f19cb730360b1918
[ "Markdown", "Python" ]
18
Python
bmorris3/hat-11
28737f4158e3f57fc015f7db169bab52d4c2fefd
c50fbad00bcd8fa856e27996408502096af47c4e
refs/heads/master
<repo_name>peytondodd/EithonCop<file_sep>/README.md # EithonCop A Cop plugin for Minecraft. ## Release history ### 2.4 (2016-12-29) * CHANGE: Bukkit 1.11. ### 2.3 (2016-08-20) * CHANGE: Refactored the DB parts. ### 2.2 (2016-06-30) * CHANGE: Minecraft 1.10 ### 2.1.2 (2016-06-04) * BUG: Frozen players could still change servers. ### 2.1.1 (2016-06-04) * BUG: Frozen players could log out/in to avoid the freeze. ### 2.1 (2016-05-21) * CHANGE: Not dependent on HeroChat anymore ### 2.0 (2016-02-28) * NEW: Save profanities in a database ### 1.6.2 (2016-01-24) * BUG: Wrong parameter name for tempmute <reason> ### 1.6.1 (2016-01-24) * BUG: Compiled with the wrong version of EithonLibrary ### 1.6 (2016-01-24) * CHANGE: Moved to EithonLibrary 4.0 ### 1.5 (2016-01-22) * NEW: Moved the freeze command here from EithonFixes. * CHANGE: Now teleports frozen players back to their original location every second. * CHANGE: Frozen players are now set to fly mode while frozen. * CHANGE: A number of changes to make the player really frozen. ### 1.4.3 (2016-01-10) * BUG: All messages was censored twice, leading to spam filter actions. ### 1.4.2 (2016-01-10) * BUG: Links with capital letters could trigger a conversion to lowercase. ### 1.4.1 (2016-01-02) * BUG: Did not catch messages to IRC via PurpleIRC. ### 1.4 (2015-10-18) * CHANGE: Refactoring EithonLibrary. ### 1.3.4 (2015-09-17) * BUG: Could not handle text instead of boolean in commands gracefully. ### 1.3.3 (2015-09-08) * BUG: Now has new condition for private channels; < 3 channel members and channel name starting with "convo". ### 1.3.2 (2015-08-30) * BUG: No blacklisted word was handled. Added debug messages. ### 1.3.1 (2015-08-30) * BUG: Any message was considered to be too fast. ### 1.3 (2015-08-30) * CHANGE: Added cool down for number of chat messages per second. * CHANGE: Now only censors messages that comes through HeroChat. * BUG: Could not remove blacklisted words. ### 1.2 (2015-08-28) * CHANGE: Should work better with plugman. ### 1.1.3 (2015-08-28) * BUG: Could not remove blacklisted words. ### 1.1.2 (2015-08-24) * BUG: Could not give a multi word explanation to the tempmute command. ### 1.1.1 (2015-08-23) * BUG: A new blacklisted words that was similar to existing word could not be added. ### 1.1 (2015-08-19) * CHANGE: Now ignores the word "I" when considering upper and lower case words. * CHANGE: Now has configurable documentation for the unmute command. * CHANGE: Now accepts new blacklisted words that are similar to existing words. * BUG: Could get problem when muting players because of a formatting error. * MISC: Added debug printouts to find out how the event sequence for chat events looks like ### 1.0.2 (2015-08-16) * CHANGE: Now has configurable documentation for the tempmute command. ### 1.0.1 (2015-08-16) * BUG: Censor method could not handle null messages. ### 1.0 (2015-08-11) * NEW: No censoring of private (one-to-one) chats. * NEW: Added an API for other plugins to use copbot. ### 0.12 (2015-08-10) * CHANGE: All time span configuration values are now in the general TimeSpan format instead of hard coded to seconds or minutes or hours. * BUG: The blacklist command without synonyms resulted in a null pointer exception. ### 0.11 (2015-08-06) * NEW: unmute command * CHANGE: tempmute and unmute commands are now issued from the sender, not from console. ### 0.10 (2015-08-05) * NEW: tempmute command. Added configurations DefaultTempMuteInSeconds, DefaultTempMuteReason and MutedCommands. * CHANGE: Added configuration MaxNumberOfRepeatedLines for spam. ### 0.9 (2015-08-03) * NEW: Added configuration MaxNumberOfUpperCaseLettersInLine to limit the allowed number of upper case letters when chatting * NEW: Added configuration MaxNumberOfUpperCaseWordsInLine to limit the allowed number of upper case words when chatting * NEW: Checks for duplicate chat messages (configuration LineIsProbablyDuplicate and SecondsToRememberLines). ### 0.8 (2015-08-03) * NEW: Added "add" and "remove" for the commands "blacklist" and "whitelist" ### 0.7 (2015-07-24) * NEW: ProfanityBuildingBlocks is a list of words that, if part of a word, the word is considered blacklisted. ### 0.6.1 (2015-07-24) * BUG: Ignored the level. Similar was always replaced. ### 0.6 (2015-07-24) * NEW: Logs offender messages in offender.log ### 0.5 (2015-07-23) * NEW: Completely rewritten profanity finder. * NEW: Can detect the profanity in "i f u c k" and "f u c k u" ### 0.4 (2015-07-23) * CHANGE: Inform players with a certain permission when a player has used a blacklisted word. * CHANGE: Inform players with a certain permission when a player has used a similar word. ### 0.3 (2015-07-22) * CHANGE: Added individual synonyms for profanities. * CHANGE: Whitelist and similar are now listed alphabetically. ### 0.2 (2015-07-22) * NEW: Now recognizes plural s (both "dicks" and "bitches" are recognized as dick and bitch respectively). * NEW: Now has an isLiteral property for profanities. * BUG: Save blacklist duplicated values. ### 0.1 (2015-07-21) * NEW: First Eithon release <file_sep>/src/main/java/net/eithon/plugin/cop/spam/OldLine.java package net.eithon.plugin.cop.spam; import java.time.LocalDateTime; import net.eithon.plugin.cop.Config; class OldLine { private String _line; private LocalDateTime _time; private int _duplicates; OldLine(String line) { this._line = line; this._time = LocalDateTime.now(); this._duplicates = 0; } boolean isTooOld() { return this._time.plusSeconds(Config.V.secondsToRememberLines).isBefore(LocalDateTime.now()); } String getLine() { return this._line; } public void addDuplicate() { this._duplicates++; } public int numberOfDuplicates() { return this._duplicates; } } <file_sep>/src/main/java/net/eithon/plugin/cop/logic/FrozenPlayer.java package net.eithon.plugin.cop.logic; import java.util.UUID; import net.eithon.library.facades.PermissionsFacade; import net.eithon.library.plugin.Logger; import net.eithon.library.time.TimeMisc; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public class FrozenPlayer { private static final String PERMISSION_SERVER_ACCESS = "eithonbungee.access.server"; private static final String PROHIBIT_SERVER_ACCESS = "-" + PERMISSION_SERVER_ACCESS; private UUID _playerId; private float _walkSpeed; private float _flySpeed; private int _fireTicks; private int _foodLevel; private boolean _isFlying; private Location _location; private boolean _canTeleport; private boolean _allowFlight; private boolean _isFrozen; private boolean _hasAccessServerPermission; public FrozenPlayer(Player player) { this._isFrozen = false; this._playerId = player.getUniqueId(); this._location = player.getLocation(); freeze(); this._isFrozen = true; } public Player getPlayer() { return Bukkit.getPlayer(this._playerId); } public OfflinePlayer getOfflinePlayer() { return Bukkit.getOfflinePlayer(this._playerId); } public String getName() { return getOfflinePlayer().getName(); } public void freeze() { Player player = getPlayer(); this._hasAccessServerPermission = player.hasPermission(PERMISSION_SERVER_ACCESS); this._canTeleport = false; this._allowFlight = player.getAllowFlight(); this._isFlying = player.isFlying(); this._walkSpeed = player.getWalkSpeed(); this._flySpeed = player.getFlySpeed(); this._fireTicks = player.getFireTicks(); this._foodLevel = player.getFoodLevel(); refreeze(); } public void refreeze() { Player player = getPlayer(); if (player == null) return; try { player.setAllowFlight(true); player.setFlying(true); } catch (Exception e) {} Logger.libraryInfo("FrozenPlayer.refreeze(): Set walk speed 0 for player %s", player.getName()); player.setWalkSpeed(0); player.setFlySpeed(0); player.setFireTicks(0); player.setFoodLevel(20); PermissionsFacade.addPlayerPermissionAsync(player, PROHIBIT_SERVER_ACCESS); player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, (int) TimeMisc.secondsToTicks(5), 128)); } public void thaw() { Player player = getPlayer(); if (player == null) return; this._isFrozen = false; this._canTeleport = true; if (this._hasAccessServerPermission) PermissionsFacade.removePlayerPermissionAsync(player, PROHIBIT_SERVER_ACCESS); player.setWalkSpeed(this._walkSpeed); player.setFlySpeed(this._flySpeed); player.setFireTicks(this._fireTicks); player.setFoodLevel(this._foodLevel); try { player.setAllowFlight(this._allowFlight); player.setFlying(this._isFlying); } catch (Exception e) {} player.removePotionEffect(PotionEffectType.JUMP); } public static void restore(Player player, float walkSpeed, float flySpeed) { if (!player.isOnline()) return; try { player.setWalkSpeed(walkSpeed); } catch (Exception e) {} try { player.setFlySpeed(flySpeed); } catch (Exception e) {} player.setFireTicks(0); player.setFoodLevel(20); PermissionsFacade.removePlayerPermissionAsync(player, PROHIBIT_SERVER_ACCESS); player.removePotionEffect(PotionEffectType.JUMP); } public void telePortBack() { Player player = getPlayer(); if ((player == null) || !player.isOnline()) return; player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, (int) TimeMisc.secondsToTicks(5), 128)); if (this._location.distance(player.getLocation()) < 1.0) return; try { this._canTeleport = true; player.teleport(this._location); } finally { this._canTeleport = false; } } public boolean canTeleport() { return this._canTeleport; } public boolean isFrozen() { return this._isFrozen; } } <file_sep>/src/main/java/net/eithon/plugin/cop/profanity/ProfanityFilter.java package net.eithon.plugin.cop.profanity; import java.util.ArrayList; import java.util.StringTokenizer; import net.eithon.plugin.cop.Config; import org.bukkit.entity.Player; class ProfanityFilter { private String _inMessage; private String _transformedInMessage; private StringTokenizer _tokenizer; private int _position = 0; private ArrayList<Token> _queue; private Player _player; private StringBuilder _outMessage; private ProfanityFilterController _controller; ProfanityFilter(ProfanityFilterController controller, Player player, String message) { this._controller = controller; this._player = player; this._inMessage = message; this._transformedInMessage = Profanity .normalize(this._inMessage) .replaceAll("[^a-z]", " "); this._tokenizer = new StringTokenizer(this._transformedInMessage, " ", true); this._queue = new ArrayList<Token>(); this._outMessage = new StringBuilder(); } boolean hasMoreTokens() { return this._tokenizer.hasMoreTokens(); } String getFilteredMessage() { while (hasMoreTokens()) { Token token = getNextToken(); if (token.equalsIgnoreCase(" ")) { if (queueIsEmpty()) handleToken(token); else addToQueue(token); } else if (token.length() < Config.V.profanityWordMinimumLength) { addToQueue(token); } else { handleQueue(); handleToken(token); } } handleQueue(); return this._outMessage.toString(); } private boolean queueIsEmpty() { return this._queue.size() == 0; } private Token getNextToken() { String transformed = this._tokenizer.nextToken(); int tokenLength = transformed.length(); int beginIndex = this._position; this._position += tokenLength; int endIndex = this._position; String in = this._inMessage.substring(beginIndex, endIndex); return new Token(in, transformed); } private void addToQueue(Token token) { this._queue.add(token); } private void handleQueue() { int length = this._queue.size(); StringBuilder tail = new StringBuilder(""); StringBuilder front = new StringBuilder(""); String out = null; for (int i = 0; i < length; i++) { int beginning = i; int end = length-i-1; Token tokensWithTail = this._queue.get(end); Token tokensWithFront = this._queue.get(beginning); if (!tokensWithTail.getTransformed().equalsIgnoreCase(" ")) { out = replaceProfanityInSubpart(0, end); if (out != null) { this._outMessage.append(out); this._outMessage.append(tail); verbose("ProfanityFilter.handleQueue", "out=\"%s\", tail=\"%s\", outmessage=\"%s\"", out, tail, this._outMessage); break; } } tail.insert(0, tokensWithTail.getIn()); front.append(tokensWithFront.getIn()); if (!tokensWithFront.getTransformed().equalsIgnoreCase(" ")) { out = replaceProfanityInSubpart(beginning+1, length-1); if (out != null) { this._outMessage.append(front); this._outMessage.append(out); verbose("ProfanityFilter.handleQueue", "front=\"%s\", out=\"%s\", outmessage=\"%s\"", front, out, this._outMessage); break; } } } if (out == null) { this._outMessage.append(tail); verbose("ProfanityFilter.handleQueue", "front=\"%s\", tail=\"%s\", outmessage=\"%s\"", front, tail, this._outMessage); } this._queue = new ArrayList<Token>(); } private String replaceProfanityInSubpart(int start, int end) { if (end-start+1 < Config.V.profanityWordMinimumLength) return null; String in = ""; String transformed = ""; Token token; for (int j = start; j <= end; j++) { token = this._queue.get(j); in += token.getIn(); String t = token.getTransformed(); if (!t.equalsIgnoreCase(" ")) transformed += t; } token = new Token(in, transformed); return replaceProfanity(token); } private void handleToken(Token token) { String out = replaceProfanity(token); if (out == null) out = token.getIn(); this._outMessage.append(out); verbose("ProfanityFilter.handleToken", "out = \"%s\", outmessage=\"%s\"", out, this._outMessage); } private String replaceProfanity(Token token) { String outWord = replaceWithSynonym(token.getTransformed(), token.getIn(), true); if (outWord == null) return null; String result = casifyAsReferenceWord(outWord, token.getIn()); if (Leet.isLeet(token.getIn())) return Leet.encode(result); return result; } private String replaceWithSynonym(String transformedWord, String originalWord, boolean checkPlural) { String outWord = replaceWithSynonym(transformedWord, originalWord); if ((outWord != null) || !checkPlural) return outWord; String withoutPlural = withoutPlural(transformedWord); if (transformedWord.equalsIgnoreCase(withoutPlural)) return null; return replaceWithSynonym(withoutPlural, originalWord); } private String replaceWithSynonym(String transformedWord, String originalWord) { if (transformedWord.length() < Config.V.profanityWordMinimumLength) { return null; } if (this._controller.isWhitelisted(transformedWord)) { return null; } String result = this._controller.replaceIfBlacklisted(this._player, transformedWord, originalWord); verbose("Controller.replaceWithSynonym", "transformedWord=\"%s\", Leave = \"%s\"", transformedWord, result); return result; } private String withoutPlural(String transformedWord) { if (transformedWord.endsWith("es")) return transformedWord.substring(0, transformedWord.length()-2); if (transformedWord.endsWith("s")) return transformedWord.substring(0, transformedWord.length()-1); return transformedWord; } private String casifyAsReferenceWord(String outWord, String referenceWord) { char[] charArray = referenceWord.toCharArray(); char c = charArray[0]; boolean firstCharacterIsUpperCase = Character.isAlphabetic(c) && Character.isUpperCase(c); if (!firstCharacterIsUpperCase) return outWord.toLowerCase(); for (int i = 1; i < charArray.length; i++) { c = charArray[i]; if (Character.isAlphabetic(c)) { if (Character.isUpperCase(c)) return outWord.toUpperCase(); else { StringBuilder result = new StringBuilder(); result.append(outWord.substring(0, 1).toUpperCase()); result.append(outWord.substring(1).toLowerCase()); return result.toString(); } } } return outWord.toLowerCase(); } private void verbose(String method, String format, Object... args) { this._controller.verboseLog("ProfanityFilter", method, format, args); } } <file_sep>/src/main/java/net/eithon/plugin/cop/profanity/ProfanityFilterController.java package net.eithon.plugin.cop.profanity; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.List; import net.eithon.library.exceptions.FatalException; import net.eithon.library.exceptions.TryAgainException; import net.eithon.library.extensions.EithonPlugin; import net.eithon.library.file.FileMisc; import net.eithon.library.mysql.Database; import net.eithon.library.time.TimeMisc; import net.eithon.plugin.cop.Config; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitScheduler; public class ProfanityFilterController { static int profanityWordMinimumLength = 3; private EithonPlugin _eithonPlugin; private Blacklist _blacklist; private Whitelist _whitelist; public ProfanityFilterController(EithonPlugin eithonPlugin, Database database) throws FatalException{ this._eithonPlugin = eithonPlugin; Profanity.initialize(database); Blacklist.initialize(database); Whitelist.initialize(database); this._blacklist = new Blacklist(eithonPlugin); this._blacklist.delayedLoad(); this._whitelist = new Whitelist(eithonPlugin, this._blacklist); this._whitelist.delayedLoad(1); delayedLoadSeed(4); } public void disable() { } private void delayedLoadSeed(double delaySeconds) { BukkitScheduler scheduler = Bukkit.getServer().getScheduler(); scheduler.scheduleSyncDelayedTask(this._eithonPlugin, new Runnable() { public void run() { loadSeed(); } }, TimeMisc.secondsToTicks(delaySeconds)); } void loadSeed() { File fileIn = getSeedInStorageFile(); if (!fileIn.exists()) return; File fileOut = getSeedOutStorageFile(); try (BufferedReader br = new BufferedReader(new FileReader(fileIn))) { String line; while ((line = br.readLine()) != null) { String filtered = profanityFilter(null, line); FileMisc.appendLine(fileOut, line); FileMisc.appendLine(fileOut, filtered); FileMisc.appendLine(fileOut, ""); } } catch (FileNotFoundException e) { this._eithonPlugin.logError("(1) Could not read from file %s: %s", fileIn.getName(), e.getMessage()); e.printStackTrace(); } catch (IOException e) { this._eithonPlugin.logError("(2) Could not read from file %s: %s", fileIn.getName(), e.getMessage()); e.printStackTrace(); } } public String profanityFilter(Player player, String message) { if (message == null) return null; ProfanityFilter filter = new ProfanityFilter(this, player, message); String filteredMessage = filter.getFilteredMessage(); this._blacklist.delayedSaveOffenderMessage(player, message, filteredMessage); return filteredMessage; } private File getSeedInStorageFile() { File file = this._eithonPlugin.getDataFile("seedin.txt"); return file; } private File getSeedOutStorageFile() { File file = this._eithonPlugin.getDataFile("seedout.txt"); return file; } public String addProfanity(CommandSender sender, String word, boolean isLiteral) throws FatalException, TryAgainException { if (word.length() < profanityWordMinimumLength) { Config.M.blackListWordMinimalLength.sendMessage(sender, profanityWordMinimumLength); return null; } Profanity profanity = this._blacklist.getProfanity(word); if ((profanity != null) && word.equalsIgnoreCase(profanity.getWord())) { profanity.setIsLiteral(isLiteral); profanity.save(); return profanity.getWord(); } if (profanity != null) { Config.M.probablyDuplicateProfanity.sendMessage(sender, word, profanity.getWord()); } profanity = this._blacklist.add(word, isLiteral); return profanity.getWord(); } public String removeProfanity(CommandSender sender, String word) throws FatalException, TryAgainException { if (word.length() < profanityWordMinimumLength) { Config.M.blackListWordMinimalLength.sendMessage(sender, profanityWordMinimumLength); return null; } Profanity profanity = this._blacklist.getProfanity(word); if (profanity == null) { Config.M.profanityNotFound.sendMessage(sender, word); return null; } String found = profanity.getWord(); if (!word.equalsIgnoreCase(found)) { Config.M.profanityNotFoundButSimilarFound.sendMessage(sender, word, found); return null; } this._blacklist.remove(word); return found; } public String normalize(String word) { return Profanity.normalize(word); } public String addAccepted(CommandSender sender, String word) throws FatalException, TryAgainException { if (word.length() < profanityWordMinimumLength) { Config.M.whitelistWordMinimalLength.sendMessage(sender, profanityWordMinimumLength); return null; } String normalized = Profanity.normalize(word); if (this._whitelist.isWhitelisted(normalized)) { Config.M.duplicateAcceptedWord.sendMessage(sender, word); return null; } Profanity profanity = this._blacklist.getProfanity(normalized); if (profanity != null) { if (normalized.equalsIgnoreCase(profanity.getWord())) { Config.M.acceptedWordWasBlacklisted.sendMessage(sender, word); return null; } this._whitelist.create(word); return profanity.getWord(); } Config.M.acceptedWordWasNotBlacklisted.sendMessage(sender, word); return null; } public String removeAccepted(CommandSender sender, String word) throws FatalException, TryAgainException { if (word.length() < profanityWordMinimumLength) { Config.M.whitelistWordMinimalLength.sendMessage(sender, profanityWordMinimumLength); return null; } String normalized = Profanity.normalize(word); if (!this._whitelist.isWhitelisted(normalized)) { Config.M.acceptedWordNotFound.sendMessage(sender, word); return null; } this._whitelist.remove(normalized); return normalized; } boolean isWhitelisted(String word) { return this._whitelist.isWhitelisted(word); } String replaceIfBlacklisted(Player player, String normalized, String originalWord) { return this._blacklist.replaceIfBlacklisted(player, normalized, originalWord); } public List<String> getAllBlacklistedWords() { return Arrays.asList(this._blacklist.getAllWords()); } public List<String> getAllWhitelistedWords() { return Arrays.asList(this._whitelist.getAllWords()); } void verboseLog(String className, String method, String format, Object... args) { this._eithonPlugin.dbgVerbose(className, method, format, args); } }<file_sep>/src/main/java/net/eithon/plugin/cop/EithonCopPlugin.java package net.eithon.plugin.cop; import net.eithon.library.exceptions.FatalException; import net.eithon.library.extensions.EithonPlugin; import net.eithon.library.mysql.Database; import net.eithon.plugin.cop.logic.Controller; import net.eithon.plugin.cop.CommandHandler; public final class EithonCopPlugin extends EithonPlugin { private Controller _controller; private EventListener _eventListener; @Override public void onEnable() { super.onEnable(); Config.load(this); try { this._controller = new Controller(this, new Database( Config.V.databaseUrl, Config.V.databaseUsername, Config.V.databasePassword)); } catch (FatalException e) { e.printStackTrace(); } CommandHandler commandHandler = new CommandHandler(this, this._controller); this._eventListener = new EventListener(this, this._controller); this.logInfo("Event listener has been created"); EithonCopApi.initialize(this._controller); super.activate(commandHandler.getCommandSyntax(), this._eventListener); this.logInfo("Event listener has been activated"); } @Override public void onDisable() { super.onDisable(); this._controller.disable(); this._controller = null; } } <file_sep>/src/main/java/net/eithon/plugin/cop/profanity/Leet.java package net.eithon.plugin.cop.profanity; class Leet { public static boolean isLeet(String message) { return !message.equalsIgnoreCase(decode(message)); } static String decode(String message) { StringBuilder result = new StringBuilder(); char[] input = message.toCharArray(); char newC; for (int i = 0; i < input.length; i++) { char c1 = input[i]; char c2 = i+1 < input.length ? input[i+1] : ' '; char c3 = i+2 < input.length ? input[i+2] : ' '; switch (c1) { case '4': case '@': case '^': case '*': newC = 'a'; break; case '8': newC = 'b'; break; case '(': case '<': newC = 'c'; break; case '3': newC = 'e'; break; case '6': case '&': newC = 'g'; break; case '#': newC = 'h'; break; case '1': case '!': newC = 'i'; break; case '0': newC = 'o'; break; case '5': case '$': newC = 's'; break; case '7': case '+': newC = 't'; break; case '%': newC = 'x'; break; case '[': switch (c2) { case ')': newC = 'd'; i++; break; default: newC = c1; break; } break; case '/': switch (c2) { case '\\': newC = 'a'; i++; break; case '-': if (c3 == '\\') { newC = 'a'; i += 2; } else newC = c1; break; default: newC = c1; break; } break; case '\\': if (c2 == '/') { newC = 'v'; i++; break; } else newC = c1; break; default: newC = c1; } result.append(newC); } return result.toString(); } public static String encode(String message) { StringBuilder result = new StringBuilder(); char[] input = message.toCharArray(); char newC; for (int i = 0; i < input.length; i++) { char c1 = input[i]; switch (c1) { case 'a': newC = '4'; break; case 'b': newC = '8'; break; case 'e': newC = '3'; break; case 'g': newC = '6'; break; case 'h': newC = '#'; break; case 'i': newC = '1'; break; case 'o': newC = '0'; break; case 's': newC = '5'; break; case 't': newC = '7'; break; default: newC = c1; } result.append(newC); } return result.toString(); } }<file_sep>/src/main/java/net/eithon/plugin/cop/Config.java package net.eithon.plugin.cop; import java.util.List; import net.eithon.library.extensions.EithonPlugin; import net.eithon.library.plugin.ConfigurableCommand; import net.eithon.library.plugin.ConfigurableMessage; import net.eithon.library.plugin.Configuration; public class Config { public static void load(EithonPlugin plugin) { Configuration config = plugin.getConfiguration(); V.load(config); C.load(config); M.load(config); } public static class V { public static String[] profanityBuildingBlocks; public static String[] categoryUnknown; public static String[] categoryBodyContent; public static String[] categoryBodyPart; public static String[] categoryLocation; public static String[] categoryOffensive; public static String[] categoryProfession; public static String[] categoryRacist; public static String[] categorySexualNoun; public static String[] categorySexualVerb; public static String[] categoryDerogative; public static int profanityLevel; public static boolean saveSimilar; public static boolean markReplacement; public static String markReplacementPrefix; public static String markReplacementPostfix; public static boolean markSimilar; public static String markSimilarPrefix; public static String markSimilarPostfix; public static int profanityWordMinimumLength = 3; public static long profanityRecentOffenderCooldownInSeconds; public static long profanityOffenderCooldownInSeconds; public static boolean logOffenderMessages; public static int maxNumberOfUpperCaseLettersInLine; public static int maxNumberOfUpperCaseWordsInLine; public static double lineIsProbablyDuplicate; public static long secondsToRememberLines; public static int maxNumberOfRepeatedLines; public static long defaultTempMuteInSeconds; public static String defaultTempMuteReason; public static List<String> mutedCommands; public static long chatCoolDownInSeconds; public static int chatCoolDownAllowedTimes; public static double freezeRestoreWalkSpeed; public static double freezeRestoreFlySpeed; public static String databaseUrl; public static String databaseUsername; public static String databasePassword; static void load(Configuration config) { profanityBuildingBlocks = config.getStringList("ProfanityBuildingBlocks").toArray(new String[0]); categoryUnknown = config.getStringList("CategoryUnknown").toArray(new String[0]); categoryBodyContent = config.getStringList("CategoryBodyContent").toArray(new String[0]); categoryBodyPart = config.getStringList("CategoryBodyPart").toArray(new String[0]); categoryLocation = config.getStringList("CategoryLocation").toArray(new String[0]); categoryOffensive = config.getStringList("CategoryOffensive").toArray(new String[0]); categoryProfession = config.getStringList("CategoryProfession").toArray(new String[0]); categoryRacist = config.getStringList("CategoryRacist").toArray(new String[0]); categorySexualNoun = config.getStringList("CategorySexualNoun").toArray(new String[0]); categorySexualVerb = config.getStringList("CategorySexualVerb").toArray(new String[0]); categoryDerogative = config.getStringList("CategoryDerogative").toArray(new String[0]); profanityLevel = config.getInt("ProfanityLevel", 0); logOffenderMessages = config.getInt("LogOffenderMessages", 0) != 0; profanityRecentOffenderCooldownInSeconds = config.getSeconds("ProfanityRecentOffenderCooldownTimeSpan", 20); profanityOffenderCooldownInSeconds = config.getSeconds("ProfanityOffenderCooldownTimeSpan", "1h"); saveSimilar = config.getInt("SaveSimilar", 0) != 0; markReplacement = config.getInt("MarkReplacement", 0) != 0; markReplacementPrefix = config.getString("MarkReplacementPrefix", "'"); markReplacementPostfix = config.getString("MarkReplacementPostfix", "'"); markSimilar = config.getInt("MarkSimilar", 0) != 0; markSimilarPrefix = config.getString("MarkSimilarPrefix", "<"); markSimilarPostfix = config.getString("MarkSimilarPostfix", ">"); maxNumberOfUpperCaseLettersInLine = config.getInt("spam.MaxNumberOfUpperCaseLettersInLine", 15); maxNumberOfUpperCaseWordsInLine = config.getInt("spam.MaxNumberOfUpperCaseWordsInLine", 3); // Spam lineIsProbablyDuplicate = config.getDouble("spam.LineIsProbablyDuplicate", 0.9); secondsToRememberLines = config.getSeconds("spam.TimeSpanToRememberLines", 30); maxNumberOfRepeatedLines = config.getInt("spam.MaxNumberOfRepeatedLines", 2); chatCoolDownInSeconds = config.getSeconds("spam.ChatCoolDownTimeSpan", "30s"); chatCoolDownAllowedTimes = config.getInt("spam.ChatCoolDownAllowedTimes", 15); // Mute defaultTempMuteInSeconds = config.getSeconds("mute.DefaultTempMuteTimeSpan", 10); defaultTempMuteReason = config.getString("mute.DefaultTempMuteReason", "Unspecified"); mutedCommands = config.getStringList("mute.MutedCommands"); // Freeze freezeRestoreWalkSpeed = config.getDouble("freeze.FreezeRestoreWalkSpeed", 0.2); freezeRestoreFlySpeed = config.getDouble("freeze.FreezeRestoreFlySpeed", 0.2); getDatabase(config); } private static void getDatabase(Configuration config) { final String databaseHostname = config.getString("database.Hostname", null); final String databasePort = config.getString("database.Port", null); final String databaseName = config.getString("database.Name", null); databaseUrl = "jdbc:mysql://" + databaseHostname + ":" + databasePort + "/" + databaseName; databaseUsername = config.getString("database.Username", null); databasePassword = config.getString("database.Password", null); } } public static class C { public static ConfigurableCommand tempMutePlayer; public static ConfigurableCommand unutePlayer; static void load(Configuration config) { tempMutePlayer = config.getConfigurableCommand("commands.mute.TempMutePlayer", 3, "tempmute %s %ds %s"); unutePlayer = config.getConfigurableCommand("commands.mute.UnmutePlayer", 1, "unmute %s"); } } public static class M { public static ConfigurableMessage probablyDuplicateProfanity; public static ConfigurableMessage profanityNotFound; public static ConfigurableMessage profanityNotFoundButSimilarFound; public static ConfigurableMessage duplicateProfanity; public static ConfigurableMessage profanityAdded; public static ConfigurableMessage profanityRemoved; public static ConfigurableMessage acceptedWordWasNotBlacklisted; public static ConfigurableMessage acceptedWordAdded; public static ConfigurableMessage acceptedWordNotFound; public static ConfigurableMessage acceptedWordRemoved; public static ConfigurableMessage acceptedWordWasBlacklisted; public static ConfigurableMessage duplicateAcceptedWord; public static ConfigurableMessage blackListWordMinimalLength; public static ConfigurableMessage whitelistWordMinimalLength; public static ConfigurableMessage notifyAboutProfanity; public static ConfigurableMessage notifyAboutComposed; public static ConfigurableMessage notifyAboutSimilar; public static ConfigurableMessage tempMutedPlayer; public static ConfigurableMessage unmutedPlayer; public static ConfigurableMessage tempMuteCommandDoc; public static ConfigurableMessage unmuteCommandDoc; public static ConfigurableMessage chattingTooFast; public static ConfigurableMessage chatDuplicateMessage; public static ConfigurableMessage playerAlreadyFrozen; public static ConfigurableMessage playerNotFrozen; public static ConfigurableMessage playerFrozen; public static ConfigurableMessage playerThawn; public static ConfigurableMessage frozenPlayerCannotTeleport; public static ConfigurableMessage playerRestored; static void load(Configuration config) { profanityNotFound = config.getConfigurableMessage("messages.ProfanityNotFound", 1, "The word \"%s\" was not blacklisted."); profanityNotFoundButSimilarFound = config.getConfigurableMessage("messages.ProfanityNotFoundButSimilarFound", 2, "The word \"%s\" was not blacklisted. Did you mean \"%s\"?"); duplicateProfanity = config.getConfigurableMessage("messages.DuplicateProfanity", 1, "The word \"%s\" has already been blacklisted."); probablyDuplicateProfanity = config.getConfigurableMessage("messages.ProbablyDuplicateProfanity", 2, "You specified the word \"%s\", please note that it is similar to the existing blacklisted word \"%s\"."); profanityAdded = config.getConfigurableMessage("messages.ProfanityAdded", 1, "The word \"%s\" has been added to the blacklist."); profanityRemoved = config.getConfigurableMessage("messages.ProfanityRemoved", 1, "The word \"%s\" has been removed from the blacklist."); acceptedWordWasNotBlacklisted = config.getConfigurableMessage("messages.AcceptedWordWasNotBlacklisted", 1, "The word \"%s\" is not blacklisted, so it will not be added as whitelisted."); acceptedWordNotFound = config.getConfigurableMessage("messages.AcceptedWordNotFound", 1, "The word \"%s\" was not whitelisted."); acceptedWordAdded = config.getConfigurableMessage("messages.AcceptedWordAdded", 2, "The word \"%s\" is now whitelisted, to prevent it from being mixed up with the blacklisted word \"%s\"."); acceptedWordRemoved = config.getConfigurableMessage("messages.AcceptedWordRemoved", 1, "The word \"%s\" is no longer whitelisted."); acceptedWordWasBlacklisted = config.getConfigurableMessage("messages.AcceptedWordWasBlacklisted", 1, "You can't whitelist \"%s\" because it is blacklisted with that spelling."); duplicateAcceptedWord = config.getConfigurableMessage("messages.DuplicateAcceptedWord", 1, "The word \"%s\" has already been whitelisted."); blackListWordMinimalLength = config.getConfigurableMessage("messages.BlacklistWordMinimalLength", 1, "A word that should be blacklisted must have at least %d characters."); whitelistWordMinimalLength = config.getConfigurableMessage("messages.WhitelistWordMinimalLength", 1, "A word that should be whitelisted must have at least %d characters."); notifyAboutProfanity = config.getConfigurableMessage("messages.NotifyAboutProfanity", 3, "Player %s used the word \"%s\" (%s) which is blacklisted."); notifyAboutComposed = config.getConfigurableMessage("messages.NotifyAboutComposed", 4, "Player %s used the word \"%s\" (%s), that contains the blacklisted building block \"%s\"."); notifyAboutSimilar = config.getConfigurableMessage("messages.NotifyAboutSimilar", 4, "Player %s used the word \"%s\" (%s), that is similar to the blacklisted word \"%s\"."); // Spam chattingTooFast = config.getConfigurableMessage("messages.spam.ChattingTooFast", 3, "You can't chat for another %d seconds (you are limited to %d messages per %d seconds)"); chatDuplicateMessage = config.getConfigurableMessage("messages.spam.ChatDuplicateMessage", 0, "You are not allowed to enter the same message many times."); // Mute tempMutedPlayer = config.getConfigurableMessage("messages.mute.TempMutedPlayer", 3, "Player %s has been muted %s with reason \"%s\"."); unmutedPlayer = config.getConfigurableMessage("messages.mute.UnmutedPlayer", 1, "Player %s has been unmuted."); // Doc tempMuteCommandDoc = config.getConfigurableMessage("messages.doc.TempMuteCommand", 0, "/eithoncop tempmute <player> [<time>] [<reason>]"); unmuteCommandDoc = config.getConfigurableMessage("messages.doc.UnmuteCommand", 0, "/eithoncop unmute <player>"); // Freeze playerAlreadyFrozen = config.getConfigurableMessage("messages.freeze.PlayerAlreadyFrozen", 1, "The player %s has already been frozen."); playerNotFrozen = config.getConfigurableMessage("messages.freeze.PlayerNotFrozen", 1, "The player %s can't be thawn - was not frozen."); playerFrozen = config.getConfigurableMessage("messages.freeze.PlayerFrozen", 1, "The player %s has now been frozen."); playerThawn = config.getConfigurableMessage("messages.freeze.PlayerThawn", 1, "The player %s has now been thawn."); playerRestored = config.getConfigurableMessage("messages.freeze.PlayerRestored", 1, "The player %s has now been restored."); frozenPlayerCannotTeleport = config.getConfigurableMessage("messages.freeze.FrozenPlayerCannotTeleport", 0, "You have been frozen and are not allowed to teleport."); } } }
356bf7ab15b269da92803e9cd5f9c0623f7d2480
[ "Markdown", "Java" ]
8
Markdown
peytondodd/EithonCop
342fa63591d988e868efea18b6306f65cf445c63
1333a23e4071b38fe8aa393c62164b772f596ac8
refs/heads/master
<file_sep>#include<iostream> #include<cstring> #include<cstdlib> using namespace std; #include"myqueue.h" myqueue::myqueue(int queuecapacity) { m_queuecapacity = queuecapacity; m_ihead = 0; m_pqueue = new customer[m_queuecapacity]; m_tail = 0; m_queuelen = 0; } void myqueue::clearqueue() { m_ihead = 0; m_tail = 0; m_queuelen = 0; } bool myqueue::queueempty()const { if (m_queuelen == 0) { return true; } else { return false; } } int myqueue::queuelength()const { return m_queuelen; } bool myqueue::queuefull() const { if (m_queuelen == m_queuecapacity) { return true; } else { return false; } } bool myqueue::enqueue(customer element) { if (queuefull()) { return false; } else { m_pqueue[m_tail] = element; m_tail++; m_tail = m_tail % m_queuecapacity; m_queuelen++; return true; } } bool myqueue::dequeue(customer &element) { if (queueempty()) { return false; } else { element = m_pqueue[m_ihead]; m_ihead++; m_ihead = m_ihead % m_queuecapacity; m_queuelen--; return true; } } void myqueue::queuetraverse() { for (int i = m_ihead; i < m_queuelen+m_ihead; i++) { m_pqueue[i%m_queuecapacity].printinfo(); cout << (i - m_ihead) << " person waiting..." << endl; } } myqueue::~myqueue(){ delete[]m_pqueue; m_pqueue = NULL; }<file_sep>#include<iostream> #include<cstring> #include<stdio.h> #include<math.h> #include<stdlib.h> #include<queue> #include<vector> #include<map> #include<algorithm> using namespace std; int xulie[11][1010]; int number[1010][1010]; int biaoji[1010][1010]; int LCSa(int x[],int y[],int p,int q){ memset(number,0,sizeof(number)); memset(biaoji,0,sizeof(biaoji)); for(int i=0;i<=p;i++){ number[i][0]=0; } for(int j=0;j<=q;j++){ number[0][j]=0; } for(int i=1;i<=p;i++){ for(int j=1;j<=q;j++){ if(x[i-1]==y[j-1]){ number[i][j]=number[i-1][j-1]+1; biaoji[i][j]=0; } else if (number[i-1][j]>=number[i][j-1]){ number[i][j]=number[i-1][j]; biaoji[i][j]=1; } else{ number[i][j]=number[i][j-1]; biaoji[i][j]=-1; } } } memset(y,0,sizeof(y)); int m=0; for(int i=0;i<p;i++){ for(int j=0;j<q;j++){ if(biaoji[i][j]==1){ y[m++]=x[i]; } } } return number[p][q]; } int main(){ int N=0; int M=0; while(cin>>N>>M){ memset(xulie,0,sizeof(xulie)); for(int k=0;k<N;k++){ for(int i=0;i<M;i++){ cin>>xulie[k][i]; } } int mmm=0; for(int i=0;i<N-1;i++){ mmm=LCSa(xulie[i],xulie[i+1],M,M); //cout<<xulie[i]<<" "<<xulie[i+1]<<endl; } cout<<mmm<<endl; } return 0; } <file_sep>#include <conio.h> #include <assert.h> #include <iostream> #include <fstream> #include <stdlib.h> #include <string.h> #include <stdio.h> #ifndef DoubleLinkList_H #define DoubleLinkList_H using namespace std; struct NodeType { char name[20]; char tel[20]; int age; int index; }; template< class NodeType > class Node; template< class NodeType > class DoubleLinkList; /***************************************************************/ template< class NodeType > class Node //结点类 { friend class DoubleLinkList< NodeType >; //友元类 private : NodeType Data; //结点数据 Node< NodeType > *NextNode; //后向指针 Node< NodeType > *PreviousNode; //前向指针 public : void Show(); Node(); //默认构造函数 Node( NodeType &Value ); //拷贝构造函数 ~Node(); //析构函数 }; /********************************************************/ template< class NodeType > class DoubleLinkList //双向链表类 { private : Node< NodeType > *FirstNode; //首结点 Node< NodeType > *RearNode; //尾结点 public : DoubleLinkList(); //默认构造函数 ~DoubleLinkList(); //析构函数 bool IsEmpty(); //判断链表是否为空 Node< NodeType > *CreateNode( NodeType &Value); //生成一个新结点 void AddNode(NodeType Value1); //排序插入结点 void ShowForward(); //向前输出链表 void ShowBackwards(); //向后输出链表 int LenghtOfDoubleLinkList(); //链表结点个数 void DelByName(char *Name); //根据姓名删除结点 void DelByTel(char *Tel); //根据电话删除结点 void DelByIndex(int Index); //根据序号删除结点 bool SearchByTel(char *Tel); //根据号码查寻 bool SearchByIndex(int index); //根据序号查询 bool CompSearch(char *Name); //通配符查找 bool UpdataByName(char *Name); //根据姓名修改结点 bool UpdataByTel(char *Tel); //根据号码修改 bool UpdataByIndex(int Index); //根据序号修改结点 bool LoadFromFile(char *filename); //从文件中输出数据 bool SaveToFile(char *filename); //将数据保存到文件中 }; #endif /*******************************************************/ int main() { cout<<"\2017141461363 朱嘉宁\n"; int Index; char Tel[20]; char Name1[20]; char Filename[20]; int Option,Option1,Option2,Option3,Option4; DoubleLinkList<NodeType> List; do { cout<<"\n\t 电话簿 " <<"\n\t 1:插入电话簿数据 " <<"\n\t 2:查找电话簿数据(1姓名, 2号码,3序号) " <<"\n\t 3:删除电话簿数据(1姓名,2号码,3序号) " <<"\n\t 4:修改电话簿数据(1姓名,2号码,3序号) " <<"\n\t 5:输出电话簿数据(1从前往后,2从后往前)" <<"\n\t 6:把数据存储到文件 " <<"\n\t 7:从文件中读取数据 " <<"\n\t 0:退出 " <<"\n请输入你的选择:"; cin>>Option; switch(Option) { case 1:NodeType Value; cout<<"请输入姓名:(0退出 )"; cin>>Value.name; while(strcmp(Value.name,"0")!=0) { cout<<"请输入号码:"; cin>>Value.tel; cout<<"请输入年龄:"; cin>>Value.age; List.AddNode(Value); cout<<"\n请输入姓名:"; cin>>Value.name; } break; case 2: cout<<"查找途径.\n1.根据姓名,\n2.根据号码,\n3.根据序号.\n请选择:"; cin>>Option1; switch(Option1) { case 1: cout<<"请输入姓名:"; cin>>Name1; List.CompSearch(Name1); break; case 2: cout<<"请输入号码:"; cin>>Tel; List.SearchByTel(Tel); break; case 3: cout<<"请输入序号:"; cin>>Index; List.SearchByIndex(Index); break; default : cout<<"错误"; break; } break; case 3: cout<<"删除途径.\n1.根据姓名,\n2.根据号码,\n3.根据序号.\n请选择:"; cin>>Option2; switch(Option2) { case 1: cout<<"请输入姓名:"; cin>>Name1; List.DelByName(Name1); break; case 2: cout<<"请输入号码:"; cin>>Tel; List.DelByTel(Tel); break; case 3: cout<<"请输入序号:"; cin>>Index; List.DelByIndex(Index); break; default : cout<<"错误"; break; } break; case 4: cout<<"修改方式.\n1.根据姓名,\n2.根据号码,\n3.根据序号.\n请选择:"; cin>>Option3; switch(Option3) { case 1: cout<<"请输入姓名:"; cin>>Name1; List.UpdataByName(Name1); break; case 2: cout<<"请输入号码:"; cin>>Tel; List.UpdataByTel(Tel); break; case 3: cout<<"请输入序号:"; cin>>Index; List.UpdataByIndex(Index); break; default :cout<<"错误"; break; } break; case 5: cout<<"查看方式.\n1.从前向后输出,\n2.从后向前输出.\n请选择:"; cin>>Option4; switch(Option4) { case 1:cout<<"链表数据个数:"<<List.LenghtOfDoubleLinkList()<<"\n"; List.ShowForward(); break; case 2:cout<<"链表数据个数:"<<List.LenghtOfDoubleLinkList()<<"\n"; List.ShowBackwards(); break; default :cout<<"错误"; break; } break; case 6: cout<<"请输入文件途径:"; cin>>Filename; List.SaveToFile(Filename); break; case 7: cout<<"请输入文件途径:"; cin>>Filename; List.LoadFromFile(Filename); break; case 0: break; default :Option=0; break; } } while(Option!=0); return 0; } /**********************************************************************/ template< class NodeType >//输出函数 void Node< NodeType >::Show() { cout<<Data.index<<"."<<Data.name<<" "<<Data.tel<<" "<<Data.age<<endl; } /**********************************************************************/ template< class NodeType > Node< NodeType >::Node() :Data( NULL ),NextNode( NULL ),PreviousNode( NULL ) {} /**********************************************************************/ template< class NodeType > Node< NodeType >::Node( NodeType &Value ) { strcpy(Data.name,Value.name); strcpy(Data.tel,Value.tel); Data.age=Value.age; Data.index=1; NextNode=NULL; PreviousNode=NULL; } /**********************************************************************/ template< class NodeType > Node< NodeType >::~Node() { cout<<"\n 释放了结点."; } /**********************************************************************/ template< class NodeType > DoubleLinkList< NodeType >::DoubleLinkList() :FirstNode( NULL ),RearNode( NULL ) {} /**********************************************************************/ template< class NodeType > DoubleLinkList< NodeType >::~DoubleLinkList() { Node< NodeType > *CurrentNode = FirstNode, *TempNode ; while( CurrentNode != NULL ) { TempNode = CurrentNode; CurrentNode = CurrentNode->NextNode; TempNode->Show(); delete TempNode; } cout<<"\n 释放了一个双向链表." <<"\n 按任意键继续!"; getch(); } /**********************************************************************/ template< class NodeType > bool DoubleLinkList< NodeType >::IsEmpty()//判断链表是否为空 { if( FirstNode == NULL ) return true; else return false; } /**********************************************************************/ template< class NodeType > Node< NodeType > *DoubleLinkList< NodeType >::CreateNode( NodeType &Value )//生成一个新结点,返回节点指针 { Node< NodeType > *NewNode = new Node< NodeType >( Value ); assert( NewNode != NULL ); return NewNode ; } /**********************************************************************/ template< class NodeType > void DoubleLinkList< NodeType >::AddNode( NodeType Value ) //添加结点 { Node< NodeType > *CurrentNode=FirstNode,*TempNode,*TEMPNode; Node< NodeType > *NewNode = CreateNode(Value); //根据数据生成节点 if ( IsEmpty() ) //链表为空,节点为唯一节点 { cout<<"\n 添加在空链表中。"; FirstNode = RearNode = NewNode; } else { if(strcmp(FirstNode->Data.name,NewNode->Data.name)>0) //添加在头结点 { FirstNode->PreviousNode = NewNode; //与头节点的前向指针连接起来 NewNode->NextNode = FirstNode; //节点的后向指针与头节点连接起来 FirstNode = NewNode; //新节点成为头节点 FirstNode->PreviousNode = NULL; //头节点的前向指针为空 TEMPNode=FirstNode->NextNode; //将头节点赋给另一个指针,用于修改序号 while(TEMPNode!=NULL) { (TEMPNode->Data.index)++; TEMPNode=TEMPNode->NextNode; } } else { while(strcmp(NewNode->Data.name,CurrentNode->Data.name)!=0&&CurrentNode->NextNode!=NULL) CurrentNode=CurrentNode->NextNode; if(CurrentNode->NextNode==NULL) //添加在尾结点 { NewNode->PreviousNode = RearNode; //连接新节点的前向指针 RearNode->NextNode = NewNode; //连接节点的后向指针 NewNode->Data.index=(RearNode->Data.index)+1; //设定新节点的序号 RearNode = NewNode; //将新节点赋值为尾节点 RearNode->NextNode = NULL; //将尾节点的后向指针赋为0 } if(strcmp(NewNode->Data.name,CurrentNode->Data.name)<0) //添加在中间结点 { TempNode = CurrentNode; //节点插在当前节点之前 NewNode->PreviousNode = CurrentNode->PreviousNode; //连接新节点的前向指针 NewNode->NextNode = CurrentNode; //连接新节点的后向指针 CurrentNode = CurrentNode->PreviousNode; //当前节点指向新节点的前节点 CurrentNode->NextNode = NewNode ; //连接新节点的前节点的后向指针 TempNode->PreviousNode = NewNode; //连接新节点后节点的前向指针 TEMPNode=NewNode; //将新节点赋值给另一节点 TEMPNode->Data.index=CurrentNode->Data.index; //给新节点之后重新编序号 while(TEMPNode!=NULL) { (TEMPNode->Data.index)++; TEMPNode=TEMPNode->NextNode; } } } } cout<<"\n添加成功!"; cout<<"\n添加的结点为:\n"; NewNode->Show(); } /**********************************************************************/ template<class NodeType> void DoubleLinkList<NodeType>::DelByName(char *Name) //根据姓名删除 { char choice; if( IsEmpty() ) { cout<<"链表为空,删除失败!"<<"\n按任意键继续."; getch(); return ; } else { Node< NodeType > *CurrentNode = FirstNode,*TempNode=RearNode,*TEmpNode,*TEMPNode; if(strcmp(FirstNode->Data.name,Name)==0) //删除头结点 { cout<<"删除的结点为:"; FirstNode->Show(); //展示要删除的节点 cout<<"是否删除(YorN)"; //询问是否确认删除 cin>>choice; if(choice=='Y'||choice=='y') { if( FirstNode == RearNode ) //链表有唯一节点 FirstNode = RearNode = NULL; else { FirstNode = FirstNode->NextNode; //头节点后移 FirstNode->PreviousNode = NULL ; //新的头节点前向指针赋值为空 TEMPNode=FirstNode; //将头节点赋值给新节点 while(TEMPNode!=NULL) { (TEMPNode->Data.index)--; TEMPNode=TEMPNode->NextNode; } } delete CurrentNode; cout<<"\n删除成功!"; return ; } cout<<"\n按任意键继续."; getch(); } if(strcmp(RearNode->Data.name,Name)==0) //删除尾结点 { cout<<"删除的结点为:"; RearNode->Show(); //展示要删除的节点 cout<<"是否删除(Y/N)"; //询问是否确认删除 cin>>choice; if(choice=='Y'||choice=='y') { RearNode = RearNode->PreviousNode; //尾节点前移 RearNode->NextNode = NULL; //尾节点的后向指针赋值空 delete TempNode; cout<<"\n删除成功!"; return ; } cout<<"\n按任意键继续."; getch(); } else //删除中间结点 { while(strcmp(CurrentNode->Data.name,Name)!=0&&CurrentNode->NextNode!=NULL) CurrentNode=CurrentNode->NextNode; if(CurrentNode->NextNode==NULL) { cout<<"删除的结点不存在!"; return ; cout<<"\n按任意键继续."; getch(); } else { cout<<"欲删除的结点为:"; CurrentNode->Show(); //展示要删除的节点 cout<<"是否删除(Y/N)"; //询问是否确认删除 cin>>choice; if(choice=='Y'||choice=='y') { TempNode = CurrentNode ; //TempNode为欲删除的节点 CurrentNode = CurrentNode->NextNode ; //欲删除节点的后节点 CurrentNode->PreviousNode = TempNode->PreviousNode ; /*连接删除节点的前后两个节点*/ TEmpNode = TempNode->PreviousNode ; //欲删除节点的前节点 TEmpNode->NextNode = CurrentNode ; //连接前节点的后向指针 while(CurrentNode!=NULL) { (CurrentNode->Data.index)--; CurrentNode=CurrentNode->NextNode; } delete TempNode; } cout<<"\n删除成功!"<<"\n按任意键继续."; getch(); return ; } } } } /**********************************************************************/ template< class NodeType > void DoubleLinkList<NodeType>::DelByTel(char *Tel)//根据号码删除(同上) { char choice; if( IsEmpty() ) { cout<<"链表为空,删除失败!"<<"\n按任意键继续."; getch(); return ; } else { Node< NodeType > *CurrentNode = FirstNode,*TempNode=RearNode,*TEmpNode,*TEMpNode; if (strcmp(FirstNode->Data.tel,Tel)==0) { cout<<"删除的结点为:"; FirstNode->Show(); cout<<"是否删除(Y/N)"; cin>>choice; if(choice=='Y'||choice=='y') { if( FirstNode == RearNode ) FirstNode = RearNode = NULL; else { FirstNode = FirstNode->NextNode; FirstNode->PreviousNode = NULL ; TEMpNode=FirstNode; while(TEMpNode!=NULL) { (TEMpNode->Data.index)--; TEMpNode=TEMpNode->NextNode; } } delete CurrentNode; cout<<"\n删除成功!"; return ; } cout<<"\n按任意键继续."; cout<<endl; getch(); } if(strcmp(RearNode->Data.tel,Tel)==0) { cout<<"删除的结点为:"; RearNode->Show(); cout<<"是否删除(Y/N)"; cin>>choice; if(choice=='Y'||choice=='y') { RearNode = RearNode->PreviousNode; RearNode->NextNode = NULL; delete TempNode; cout<<"\n删除成功!"; return ; } cout<<"\n按任意键继续."; getch(); } else { while(strcmp(CurrentNode->Data.tel,Tel)!=0&&CurrentNode->NextNode) CurrentNode=CurrentNode->NextNode; if(CurrentNode->NextNode==NULL) { cout<<"删除的结点不存在!"; return ; cout<<"\n按任意键继续."; getch(); } else { cout<<"删除的结点为:"; CurrentNode->Show(); cout<<"是否删除(Y/N)"; cin>>choice; if(choice=='Y'||choice=='y') { TempNode = CurrentNode ; CurrentNode = CurrentNode->NextNode ; CurrentNode->PreviousNode = TempNode->PreviousNode ; TEmpNode = TempNode->PreviousNode ; TEmpNode->NextNode = CurrentNode ; while(CurrentNode!=NULL) { (CurrentNode->Data.index)--; CurrentNode=CurrentNode->NextNode; } delete TempNode; } cout<<"\n删除成功!"<<"\n按任意键继续."; getch(); return ; } } } } /**********************************************************************/ template< class NodeType > void DoubleLinkList<NodeType>::DelByIndex(int Index)//根据序号删除(同上) { char choice; if( IsEmpty() ) { cout<<"链表为空,删除失败!"<<"\n按任意键继续."; getch(); return ; } else { Node< NodeType > *CurrentNode = FirstNode,*TempNode=RearNode,*TEmpNode,*TEMpNode; if (FirstNode->Data.index==Index) { cout<<"删除的结点为:"; FirstNode->Show(); cout<<"是否删除(Y/N)"; cin>>choice; if(choice=='Y'||choice=='y') { if( FirstNode == RearNode ) FirstNode = RearNode = NULL; else { FirstNode = FirstNode->NextNode; FirstNode->PreviousNode = NULL ; TEMpNode=FirstNode; while(TEMpNode!=NULL) { (TEMpNode->Data.index)--; TEMpNode=TEMpNode->NextNode; } } delete CurrentNode; cout<<"\n删除成功!"; return ; } cout<<"\n按任意键继续."; cout<<endl; getch(); } if(RearNode->Data.index==Index) { cout<<"删除的结点为:"; RearNode->Show(); cout<<"是否删除(Y/N)"; cin>>choice; if(choice=='Y'||choice=='y') { RearNode = RearNode->PreviousNode; RearNode->NextNode = NULL; delete TempNode; cout<<"\n删除成功!"; return ; } cout<<"\n按任意键继续."; getch(); } else { while(CurrentNode->Data.index==Index&&CurrentNode->NextNode) CurrentNode=CurrentNode->NextNode; if(CurrentNode->NextNode==NULL) { cout<<"删除的结点不存在!"; return ; cout<<"\n按任意键继续."; getch(); } else { cout<<"删除的结点为:"; CurrentNode->Show(); cout<<"是否删除(Y/N)"; cin>>choice; if(choice=='Y'||choice=='y') { TempNode = CurrentNode ; CurrentNode = CurrentNode->NextNode ; CurrentNode->PreviousNode = TempNode->PreviousNode ; TEmpNode = TempNode->PreviousNode ; TEmpNode->NextNode = CurrentNode ; while(CurrentNode!=NULL) { (CurrentNode->Data.index)--; CurrentNode=CurrentNode->NextNode; } delete TempNode; } cout<<"\n删除成功!"<<"\n按任意键继续."; getch(); return ; } } } } /**********************************************************************/ template< class NodeType > void DoubleLinkList< NodeType >::ShowForward() //向前输出链表 { Node< NodeType > *CurrentNode = FirstNode ; cout<<"\n 链表如下:\n"; if(CurrentNode == NULL) cout<<"链表为空!"; else{ while ( CurrentNode != NULL) { CurrentNode->Show(); CurrentNode = CurrentNode->NextNode; } cout<<"\n 按任意键继续."; getch(); } } /**********************************************************************/ template< class NodeType > void DoubleLinkList< NodeType >::ShowBackwards() //向后输出链表 { Node< NodeType > *CurrentNode = RearNode ; cout<<"\n 链表如下:\n"; while ( CurrentNode != NULL) { CurrentNode->Show(); CurrentNode = CurrentNode->PreviousNode; } cout<<"\n 按任意键继续."; getch(); } /**********************************************************************/ template< class NodeType > int DoubleLinkList< NodeType >::LenghtOfDoubleLinkList() //链表结点个数 { int NosOfNodes = 0 ; Node< NodeType > *CurrentNode = FirstNode ; while ( CurrentNode != NULL) { NosOfNodes++; CurrentNode = CurrentNode->NextNode; } return NosOfNodes; } /**********************************************************************/ template<class NodeType> bool DoubleLinkList<NodeType>::CompSearch(char *Name) //通配符查询 { int i,j=0,k=0; Node< NodeType > *CurrentNode=FirstNode; for(i=0;i<strlen(Name);i++) //利用循环算法来历遍每一个字符 if(Name[i]=='?') break; //找到?跳出 if(Name[i]!='?') { {while(strcmp(CurrentNode->Data.name,Name)!=0&&CurrentNode->NextNode!=NULL) CurrentNode=CurrentNode->NextNode;} if(strcmp(CurrentNode->Data.name,Name)==0) { cout<<"查找的结点为:"; CurrentNode->Show(); cout<<"按任意键继续."; getch(); } else {cout<<"查找的结点不存在!"<<endl;} } if(Name[i]=='?') { while(CurrentNode!=NULL) { int j=0; while((Name[j]=='?'||CurrentNode->Data.name[j]==Name[j])&&CurrentNode->Data.name[j]) j++; //匹配带有?的字符和原字符串 if(j==strlen(CurrentNode->Data.name)) { cout<<"查找的结点为:\n"; CurrentNode->Show(); k++; } CurrentNode=CurrentNode->NextNode; } if(k) return true; else return false; } } /**********************************************************************/ template<class NodeType> bool DoubleLinkList<NodeType>::SearchByTel(char *Tel) //根据号码查询 { Node< NodeType > *CurrentNode=FirstNode; while(strcmp(CurrentNode->Data.tel,Tel)!=0&&CurrentNode->NextNode!=NULL) CurrentNode=CurrentNode->NextNode; if(strcmp(CurrentNode->Data.tel,Tel)==0) { cout<<"查找的结点为:"; CurrentNode->Show(); return true; } else { cout<<"查找结点不存在!"<<endl; return false; } } /**********************************************************************/ template<class NodeType> bool DoubleLinkList<NodeType>::SearchByIndex(int Index) //根据序号查询 { Node< NodeType > *CurrentNode=FirstNode; while(CurrentNode->Data.index!=Index&&CurrentNode->NextNode!=NULL) CurrentNode=CurrentNode->NextNode; if(CurrentNode->Data.index==Index) { cout<<"查找的结点为:"; CurrentNode->Show(); return true; } else { cout<<"查找结点不存在!"<<endl; return false; } } /**********************************************************************/ template<class NodeType> bool DoubleLinkList<NodeType>::UpdataByName(char *Name) //根据姓名修改 { int Option5,Age; char Tel[20],choice; Node< NodeType > *CurrentNode=FirstNode; while(strcmp(CurrentNode->Data.name,Name)!=0&&CurrentNode->NextNode!=NULL) CurrentNode=CurrentNode->NextNode; //寻找需要修改的节点 if(strcmp(CurrentNode->Data.name,Name)==0) { cout<<"修改的结点为:"; CurrentNode->Show(); cout<<"修改内容.\n1.修改电话,\n2.修改年龄.\n请选择:"; cin>>Option5; switch(Option5) { case 1: cout<<"请输入电话:"; cin>>Tel; cout<<"改为:"<<endl <<CurrentNode->Data.index<<"."<<CurrentNode->Data.name<<" " <<Tel<<" "<<CurrentNode->Data.age<<endl <<"是否修改(YorN)"; cin>>choice; if(choice=='Y'||choice=='y') { strcpy(CurrentNode->Data.tel,Tel); cout<<"修改成功!"; } break; case 2: cout<<"请输入序年龄:"; cin>>Age; cout<<"改为:"<<endl <<CurrentNode->Data.index<<"."<<CurrentNode->Data.name<<" " <<CurrentNode->Data.tel<<" "<<Age<<endl <<"是否修改(YorN)"; cin>>choice; if(choice=='Y'||choice=='y') { CurrentNode->Data.age=Age; cout<<"修改成功!"; } break; default :cout<<"错误!"; break; } return true; } else { cout<<"修改的结点不存在!"<<endl; return false; } } /**********************************************************************/ template<class NodeType> bool DoubleLinkList<NodeType>::UpdataByTel(char *Tel)//根据号码修改 { int Option5,Age; char choice; Node< NodeType > *CurrentNode=FirstNode; while(strcmp(CurrentNode->Data.tel,Tel)!=0&&CurrentNode->NextNode!=NULL) CurrentNode=CurrentNode->NextNode; if(strcmp(CurrentNode->Data.tel,Tel)==0) { cout<<"修改的结点为:"; CurrentNode->Show(); cout<<"修改内容.\n1.修改电话,\n2.修改年龄.\n请选择:"; cin>>Option5; switch(Option5) { case 1: cout<<"请输入电话:"; cin>>Tel; cout<<"改为:"<<endl <<CurrentNode->Data.index<<"."<<CurrentNode->Data.name<<" " <<Tel<<" "<<CurrentNode->Data.age<<endl <<"是否修改(YorN)"; cin>>choice; if(choice=='Y'||choice=='y') { strcpy(CurrentNode->Data.tel,Tel); cout<<"修改成功!"; } break; case 2: cout<<"请输入序年龄:"; cin>>Age; cout<<"改为:"<<endl <<CurrentNode->Data.index<<"."<<CurrentNode->Data.name<<" " <<CurrentNode->Data.tel<<" "<<Age<<endl <<"是否修改(YorN)"; cin>>choice; if(choice=='Y'||choice=='y') { CurrentNode->Data.age=Age; cout<<"修改成功!"; } break; default :cout<<"错误!"; break; } return true; } else { cout<<"修改的结点不存在!"<<endl; return false; } } /**********************************************************************/ template<class NodeType> bool DoubleLinkList<NodeType>::UpdataByIndex(int Index)//根据序号修改 { int Option6,Age; char Tel[20],choice; Node< NodeType > *CurrentNode=FirstNode; while(CurrentNode->Data.index!=Index&&CurrentNode->NextNode!=NULL) CurrentNode=CurrentNode->NextNode; if(CurrentNode->Data.index==Index) { cout<<"修改的结点为:"; CurrentNode->Show(); cout<<"修改内容.\n1.修改电话,\n2.修改年龄.\n请选择:"; cin>>Option6; switch(Option6) { case 1: cout<<"请输入电话:"; cin>>Tel; cout<<"改为:"<<endl <<CurrentNode->Data.index<<"."<<CurrentNode->Data.name<<" " <<Tel<<" "<<CurrentNode->Data.age<<endl <<"是否修改(YorN)"; cin>>choice; if(choice=='Y'||choice=='y') { strcpy(CurrentNode->Data.tel,Tel); cout<<"修改成功!"; } break; case 2: cout<<"请输入序年龄:"; cin>>Age; cout<<"改为:"<<endl <<CurrentNode->Data.index<<"."<<CurrentNode->Data.name<<" " <<CurrentNode->Data.tel<<" "<<Age<<endl <<"是否修改(YorN)"; cin>>choice; if(choice=='Y'||choice=='y') { CurrentNode->Data.age=Age; cout<<"修改成功!"; } break; default :cout<<"错误!"; break; } return true; } else { cout<<"修改的结点不存在!"<<endl; return false; } } /**********************************************************************/ template<class NodeType> bool DoubleLinkList<NodeType>::LoadFromFile(char *filename) //从文件中提取数据 { NodeType VAlue; ifstream infile; infile.open(filename); if(!infile) { cout<<"打开文件错误!\n"; exit(0); } while(infile>>VAlue.index) { infile>>VAlue.name>>VAlue.tel>>VAlue.age; //将数据输出到节点中 AddNode(VAlue); //将节点按序加入链表中 } infile.close(); cout<<"文件读取完毕!"; return true; } /**********************************************************************/ template<class NodeType> bool DoubleLinkList<NodeType>::SaveToFile(char *filename) //将数据保存到文件中 { ofstream outfile; outfile.open(filename); if(!outfile) { cout<<"打开文件错误!\n"; exit(0); } Node<NodeType>*CurrentNode=FirstNode; while(CurrentNode) { outfile<<CurrentNode->Data.index<<" "<<CurrentNode->Data.name<<" " <<CurrentNode->Data.tel<<" "<<CurrentNode->Data.age<<endl; CurrentNode=CurrentNode->NextNode; } cout<<"文件存储完毕!"; return true; } <file_sep>#include<iostream> #include<cstring> #include<cstdlib> #include"myqueue.h" #include"customer.h" //队列 先进先出 有内存限制 //向前进位 对头指针改变 //普通队列内存浪费 //改用环形队列 队列头 队列尾 //顺时针 逆时针 指针 using namespace std; int main() { /*myqueue *p = new myqueue(4); p->enqueue(12); p->enqueue(100); p->enqueue(199); p->enqueue(122); p->queuetraverse(); int e = 0; p->dequeue(e); cout << e << endl; p->dequeue(e); cout << e << endl; p->queuetraverse();//遍历存在问题 cout << "clear" << endl; p->clearqueue(); p->queuetraverse(); p->enqueue(2002); p->enqueue(1998); p->queuetraverse(); int i = p->queuelength(); cout << i << endl; delete p; p = NULL;*/ myqueue *p =new myqueue(4); customer c1("zhangsan", 20); customer c2("zhangsan1", 21); customer c3("zhangsan2", 19); p->enqueue(c1); p->enqueue(c2); p->enqueue(c3); p->queuetraverse(); customer c4; p->dequeue(c4); c4.printinfo(); system("pause"); return 0; }<file_sep>#include<stdio.h> #include<iostream> using namespace std; int a[100][100]={0}; int main(){ int m=0,n=0,tot=1,x=0,y=0; int i,j; cin>>n>>m; a[0][0]=1; while(tot<n*m){ if(y+1<m){ a[x][++y]=++tot; } else if(x+1<n){ a[++x][y]=++tot; } while(x+1<n && y>0){ a[++x][--y]=++tot; } if(x+1<n){ a[++x][y]=++tot; } else if(y+1<m){ a[x][++y]=++tot; } while(y+1<m && x>0){ a[--x][++y]=++tot; } } for ( i=0; i<n; i++) { for ( j=0; j<m; j++) cout<<a[i][j]<<" "; cout<<endl; } return 0; } <file_sep>#ifndef TIMEFOR_H #define TIMEFOR_H #include<iostream> using namespace std; class time { friend void printtime(time &t); public: time(int hour, int min, int sec); private: int m_hour; int m_min; int m_sec; }; #endif<file_sep>#include<iostream> #include<cstring> #include<cmath> #include<cstdio> #include<stdio.h> #include"tree.h" using namespace std; //数组实现 用零代表无子节点 /*int tree[n] 3 5 8 2 6 7 9 3[0] 5[1] 8[2] 2[3] 6[4] 9[5] 7[6] */ int main() { int root = 3; tree *ptree = new tree(10,&root); int node1 = 5; int node2 = 8; int node3 = 2; int node4 = 6; ptree->addnode(0, 0, &node1); ptree->addnode(0, 1, &node2); ptree->addnode(1, 0, &node3); ptree->addnode(1, 1, &node4); int node5 = 9; int node6 = 7; ptree->addnode(2, 0, &node5); ptree->addnode(2, 1, &node6); int node = 0; //ptree->deletenode(6, &node); cout << endl; cout << node << endl; ptree->treetraverse(); int *p=ptree->searchnode(2); cout << endl; cout << *p << endl; delete ptree; getchar(); return 0; }<file_sep>#include<iostream> #include<string> #include<math.h> using namespace std; class Prime { public: Prime(int num); ~Prime(); bool isPrime(); private: const int mNum; }; class SuperPrime : public Prime { public: SuperPrime(int num); ~SuperPrime(); bool isPrime(); Prime sumBit(); Prime multiBit(); Prime sqaureSumBit(); private: const int num; }; int main() { SuperPrime sp(113); if(sp.isPrime()) { //cout<<sp.isPrime()<<endl; cout<<"do something//is SuperPrime"<<endl; // do something } return 0; } Prime::Prime(int num):mNum(num){} bool Prime::isPrime(){ int flag=0; for(int i=2;i<=sqrt(mNum);i++){ if(mNum%i==0){ flag=1; break; } } if(flag==1){ return false; } else{ return true; } } SuperPrime::SuperPrime(int num):num(num),Prime(num){ } bool SuperPrime::isPrime(){ if(sumBit().isPrime()&&multiBit().isPrime()&&sqaureSumBit().isPrime()){ return true; } else{ return false; } } SuperPrime::~SuperPrime(){ } Prime::~Prime(){ } Prime SuperPrime::sumBit(){ int m=this->num; int sum=0; while(m!=0){ sum+=m%10; m=m/10; } return Prime(sum); } Prime SuperPrime::multiBit(){ int m=this->num; int sum=1; while(m!=0){ sum*=m%10; m=m/10; } return Prime(sum); } Prime SuperPrime::sqaureSumBit(){ int m=this->num; int sum=0; while(m!=0){ sum+=(m%10)*(m%10); m=m/10; } return Prime(sum); } <file_sep>#include <iostream> #include <stdlib.h> #include <string> using namespace std; /** * 定义工人类: Worker * 数据成员: m_strName * 成员函数: work() */ class Worker { public: Worker(string name) { m_strName = name; cout << "Worker" << endl; } ~Worker() { cout << "~Worker" << endl; } void work() { cout << m_strName << endl; cout << "work" << endl; } protected: string m_strName; }; /** * 定义儿童类: Children * 数据成员: m_iAge * 成员函数: play() */ class Children { public: Children(int age) { m_iAge = age; cout << "Children" << endl; } ~Children() { cout << "~Children" << endl; } void play() { cout << m_iAge << endl; cout << "play" << endl; } protected: int m_iAge; }; /** * 定义童工类: ChildLabourer * 公有继承工人类和儿童类 */ class ChildLabourer : public Worker, public Children { public: ChildLabourer(string name, int age) :Worker(name), Children(age) { cout << "ChildLabourer" << endl; } ~ChildLabourer() { cout << "~ChildLabourer" << endl; } }; int main(void) { // 使用new关键字创建童工类对象 ChildLabourer *p = new ChildLabourer("gaoxiao", 12); // 通过童工对象调用父类的work()和play()方法 p->work(); p->play(); // 释放 delete p; p = NULL; return 0; }<file_sep>#ifndef COORDINATE_H #define COORDINATE_H #include<iostream> using namespace std; //举一反三 - - 同样可以写出; //<<输出函数重载只能用友元函数重载; //[]索引重载只能用成员函数重载; class coordinate { friend coordinate operator+(coordinate c1,coordinate c2);//友元函数重载; friend ostream &operator<<(ostream &output, coordinate &coor); friend coordinate &operator-(coordinate &c);//友元函数重载; public: coordinate(int x, int y); int getx(); int gety(); int operator[](int index); coordinate &operator++();//成员函数前置++;&自身 coordinate operator++(int); //coordinate operator+(coordinate &s);//成员函数二元运算符重载; //coordinate& operator-();//成员函数重载 private: int m_ix; int m_iy; }; /*coordinate& coordinate::operator-() { m_ix = -m_ix; this->m_iy = -this->m_iy;//与上面写法等同; return *this;//返回注意 }*/ coordinate coordinate::operator++(int) { coordinate old(*this);//用拷贝构造函数 下一次返回的新对象; this->m_ix++; this->m_iy++; return old; } coordinate &coordinate::operator++(){ m_ix++; m_iy++; return *this; } coordinate &operator-(coordinate &c) { c.m_ix = -c.m_ix; c.m_iy = -c.m_iy; return c; } coordinate::coordinate(int x, int y) { m_ix = x; m_iy = y; } int coordinate::getx() { return m_ix; } int coordinate::gety() { return m_iy; } /*coordinate coordinate::operator+(coordinate &s) {//成员函数二元运算符重载 coordinate temp(0,0); temp.m_ix = this->m_ix + s.m_ix; temp.m_iy = this->m_iy + s.m_iy; return temp; }*/ coordinate operator+(coordinate c1, coordinate c2) { coordinate temp(0, 0); temp.m_ix = c1.m_ix + c2.m_ix; temp.m_iy = c1.m_iy + c2.m_iy; return temp; } ostream &operator<<(ostream &output, coordinate &coor) { output << coor.m_ix << " " << coor.m_iy; return output; } int coordinate::operator[](int index) { if (index == 0) { return m_ix; } if (index == 1) { return m_iy; } } #endif <file_sep>#include<time.h> #include <stdlib.h> #include<stdio.h> int main() { time_t rawtime; time_t now; struct tm * timeinfo; long before=time ( &rawtime ); long now_time=time(&now); while(1) { timeinfo = localtime ( &now ); now_time=time(&now); if( (now_time-before) >=1 ) { before=time(&now); system("cls"); printf ( "The current date/time is: %s", asctime (timeinfo) ); } } } <file_sep>#include<iostream> #include<cstdio> #include<cmath> #include<cstring> //引用做函数参数 void fun(int *a, int *b) { int c = 0; c = *a; *a = *b; *b = c; } void fun1(int &a, int &b) { int c = 0; c = a; a = b; b = c; }//引用可以直接替换; using namespace std; //指针类型应用:类型 *&指针引用名 =指针: //创建结构体 typedef struct { int x; int y; }Coor; const int x = 3;//不可被改变值; const int *pp = NULL; int const *pp1 = NULL;//与上面等价; int * const pp2 = NULL;//not equvilant; //const he yinyong //指针指向const 修饰的变量 应该是const int a=3 const int const *p=&a; //函数默认值 实参会覆盖默认值 默认值必须放在最后面 关于函数重载;在相同作用域下(同名 参数个数或类型不同) //int getmax(int x,int y,int z); //int getmax(double x,double y); //内联函数 编译时就替代函数调用语句 递归不可使用 inline int ... //内存管理:资源 操作系统 申请 归还 //申请new 释放delete //int *p=new int[10] ; //if (NULL==p){ // //内存分配失败了; //} //delete []p; //c void *malloc(size_t size); //c void free(void *malloc);配套使用 int main() { int a = 3; int *p = &a; int *&q = p; //指针类型引用;*&q=p *q赋值; *q = 20; cout << a << endl; int &b = a;//引用必须初始化 b = 10; Coor c1; Coor &c = c1;//结构体的应用类型 别名的操作 c.x = 10; c.y = 20; cout << c1.x << " " << c1.y << endl; a = 20; int cc = 30; cout << a << endl; cout << b << endl; fun1(a, cc); cout << a << endl; cout << cc << endl; getchar(); return 0; }<file_sep>#ifndef MYQUEUE_H #define MYQUEUE_H #include"customer.h" class myqueue { public: myqueue(int queuecapacity); //创建队列 virtual ~myqueue();//销毁队列 void clearqueue();//清空队列 bool queueempty() const;//判断是否为空 bool queuefull() const; int queuelength() const;//队列长度 bool enqueue(customer element);//新元素队尾 bool dequeue(customer &element);//首元素出列 void queuetraverse();//遍历队列visit function private: customer *m_pqueue;//队列数组指针 int m_queuelen;//元素个数 int m_queuecapacity;//数组容量 int m_ihead; int m_tail; }; #endif <file_sep>#include<iostream> #include<stdio.h> #include"timefor.h" #include"coordinate.h" using namespace std; //友元全局函数:1 //友元成员函数:2 需要两个类来进行 //运算符重载本质是函数重载 //一元运算符重载 一个操作数;eg:-,++;//后置重载用(int)来标识; //友元函数重载和成员函数重载; void printtime(time &t);//1 int main() { time t(123, 213, 12); printtime(t); coordinate coor1(3, 5); /* -coor1; int p1 = coor1.getx(); int p2 = coor1.gety(); cout << p1 << p2 << endl; ++coor1; p1 = coor1.getx(); p2 = coor1.gety(); cout << p1 << p2 << endl;*/ coordinate coor2(2, 3); /* cout << coor2.getx() << " " << coor2.gety() << endl; cout << (coor2++).getx() << endl; cout << (coor2++).gety() << endl;*/ coordinate coor3(0, 0); coor3 = coor2 + coor1; // cout << coor1.getx() << " " << coor1.gety() << endl; //cout << coor2.getx() << " " << coor2.gety() << endl; // cout << coor3.getx() << " " << coor3.gety() << endl; cout << coor1 <<endl; cout << coor2 <<endl; cout << coor3[0] <<" "<< coor3[1] << endl; getchar(); return 0; } void printtime(time &t){ cout << t.m_hour <<":"<< t.m_min << ":"<<t.m_sec << endl; } <file_sep>#include<iostream> #include<queue> #include<vector> using namespace std; int main(){ priority_queue<int,deque<int>,greater<int> >pq;//最小优先队列; int N; cin>>N; while(N--){ char s; getchar(); scanf("%c",&s); if(s=='I'){ int x=0; scanf("%d",&x); pq.push(x); } else if(s=='Q'){ cout<<pq.top() <<endl; } else if(s=='D'){ pq.pop(); } } return 0; } <file_sep>#include<iostream> #include<stdlib.h> #include<string.h> #include<stdio.h> #include<algorithm> using namespace std; int put(int arr[], int l, int r, int key)//在arr[l...r]中二分查找插入位置 { int mid; if (arr[r] < key) return r + 1; while (l < r) { mid = l + (r - l) / 2; if (arr[mid] < key) l = mid + 1; else r = mid; } return l; } int LIS(int A[], int n) { int i = 0, len = 1 ,next; int* B = (int *)alloca(sizeof(int) * (n + 1)); B[1] = A[0]; for (i = 1;i < n;i++) { int next = put(B, 1, len, A[i]); B[next] = A[i]; if (len < next) len = next; } return len; } int b[1000001]; int main(){ int N; cin>>N; if(N==0){ cout<<"0"<<endl; } else{ for(int k=0;k<N;k++){ scanf("%d",&b[k]); } int ll=LIS(b,N); cout<<ll<<endl; } return 0; } <file_sep>#include<iostream> #include<cstdio> #include<string> //string 类型讲解 //string s1 s1为空串; //string s2("abc") 初始化 //string s3(s2) 初始化为s2的一个副本 //stirng s4(n,"c") 初始化为字符“c”的n个副本; //s.empty() true or false; //s.size(); s+s1 ; s=s2; s==s1 ;s!=s1;s[n]从零开始; //双引号相加不可以 //构造函数 构造函数重载 // using namespace std; class TV { public: TV():type(10){};//初始化列表(只用于构造函数)类型:数据{};; TV(const TV& tv1){}//拷贝构造函数 引用 //拷贝构造函数复制时可用 //分浅拷贝和深拷贝 区别指针 char name[20]; int type; void changevol1() { cout << type << endl; } void power1() { cout << name << endl; } }; //深拷贝实例 class array1 { public: array1() { m_icount = 5; m_parr = new int[m_icount]; } array1(const array1& arr) { m_icount = arr.m_icount; m_parr = new int[m_icount];//在拷贝函数内部重新申请内存; for (int i = 0; i < m_icount; i++) { m_parr[i] = arr.m_parr[i]; } } ~array1(); private: int m_icount; int *m_parr; }; //对象成员 sizeof 是所有总和; //this 指针 参数和数据成员同名 this -> something int main() { TV tv[3];//从栈实例化对象 TV *p = new TV[20]; //从堆中实例化对象 tv[0].type = 0;//栈中访问点运算符 (*p).type = 22; p->type = 1;//堆中访问用指针箭头访问 string na = "zhangsan"; string hobby("football"); cout << na << " " << hobby << endl; cout << hobby.size() << endl; cout << na.empty() << endl; cout << tv[0].type << endl; cout << p->type << endl; delete[]p; p = NULL; getchar(); return 0; }<file_sep>/*满足下列条件的自然数称为超级素数:该数本身,所有数字之和,所有数字之积以及所有数字的平方和都是素数.例如113就是一个超级素数.求[100,9999]之内: (1)超级素数的个数. (2)所有超级素数之和. (3)最大的超级素数.*/ #include<stdio.h> #include<math.h> int sum_bit(int num) { int sum1=0; while(num!=0){ sum1+=num%10; num/=10; } return sum1; } int multi_bit(int num) { int mul=1; while(num!=0){ mul*=num%10; num/=10; } return 0; } int square_sum_bit(int num) { int sum2=0; while(num!=0){ sum2+=(num%10)*(num%10); num/=10; } return sum2; } bool isprime(int num) { int x=0; int i=0; for(i=2;i<num;i++){ if(num%i==0){ x=1; break; } } if(x==1){ return false; } else{ return true; } } int main() { int i=0,j=0; int flag=0; int sum=0; int maxin=0; long long int allsum=0; for(i=100;i<=9999;i++){ if(isprime(i)&&isprime(sum_bit(i))&&isprime(multi_bit(i))&&isprime(square_sum_bit(i))){ sum++; allsum+=i; maxin=i; } } printf("%d %lld %d",sum,allsum,maxin); //to do sth } <file_sep>#include <stdio.h> #include<iostream> using namespace std; int i=1; void move(int n,char from,char to) { cout<<from<<"->"<<to<<endl; i++; } void hanoi(int n,char from,char denpend_on,char to) { if (n==1) move(1,from,to); else { hanoi(n-1,from,to,denpend_on); move(n,from,to); hanoi(n-1,denpend_on,from,to); } } int main() { int n; cin>>n; if(n==0){ cout<<"0"<<endl; } else{ char x='A',y='B',z='C'; hanoi(n,x,y,z); cout<<i-1<<endl; } return 0; } <file_sep>#include<stdio.h> #include<math.h> #include<iostream> #include<string.h> using namespace std; long int m[1100],as[1100],pw[1100]; int main() { long int a,n; while(1) { cin>>a>>n; if ( a==0 && n==0) { break; } m[0] = n; m[1] = a; pw[0] = 0; pw[1] = 0; int i=1; while ( m[i] > 1) { pw[i] = m[i-1] / m[i]; m[++i] = m[i-2] % m[i-1]; } i--; as[i] = -pw[i]; as[--i] = 1 - as[i+1] * pw[i]; for ( int j=i-1; j>=1; j--) { as[j] = as[j+2] - as[j+1] * pw[j]; } if ( as[1] < 0) { as[1] += n; } cout<<as[1]<<endl; } return 0; } <file_sep>#ifndef TREE_H #define TREE_H class tree { public: tree(int size,int *proot); ~tree(); int *searchnode(int nodeindex); bool addnode(int nodeindex, int direction, int *pnode); bool deletenode(int nodeindex, int *pnode); void treetraverse(); private: int *m_ptree; int m_isize; }; #endif <file_sep>#include"customer.h" #include<iostream> using namespace std; customer::customer(string name, int age) { m_age = age; m_strname = name; } void customer::printinfo()const { cout << "ÐÕÃû£º" << m_strname << endl; cout << "ÄêÁ䣺" << m_age << endl; cout << endl; } <file_sep>#include<stdio.h> #include<algorithm> #include<iostream> #include<queue> using namespace std; int number[100001]; int number1[100001]; int len1[100001]; int lis(int n) { int len=0; len1[len]=number[0]; for(int i=1;i<n;i++){ if(number[i]>len1[len]){ len1[++len]=number[i]; number1[i]=1; //cout<<len1[len-1]<<" "<<number[i]<<" "; } else{ int m=lower_bound(len1,len1+len,number[i],less<int>() )-len1; //cout<<len1[m]<<" "<<number[i]<<" "; len1[m]=number[i]; } } return len+1; } void printn(int n){ for(int j=0;j<n;j++){ cout<<len1[j]<<" "; } return ; } int main(){ int N=0; int k=0; int M=0; cin>>M; if(M==0){ cout<<"0"; } while(M--){ cin>>N; if(N==0){ cout<<"0"<<endl; } else{ for(int j=0;j<N;j++){ cin>>number[j]; } int q=lis(N); cout<<q<<" "; printn(q); } } return 0; } <file_sep>#include<iostream> #include"timefor.h" time::time(int hour, int min, int sec) { m_hour = hour; m_min = min; m_sec = sec; }<file_sep>#ifndef CUSTOMER_H #define CUSTOMER_H #include<string> using namespace std; class customer { public: customer(string name="", int age=0); void printinfo()const; private: string m_strname; int m_age; }; #endif <file_sep>c和c++的区别概述 C语言主要解决的问题是,不同机器平台上的汇编语言指令,功能相似但写法不一样。 所以, C语言的发明者的想法是,我只要把这些不同的汇编语言的共同点提取出来,用一种相同的表达方式来描述这些共同点,那么程序只需要写一遍,就可以在不同的机器上去编译了。于是C语言大部分的工作是在汇编语言的层面上做抽象。 如果要选最能体现上述思路的 C 语言作品,我选 CURL 和 openssl 。这也是我认为 C语言最适合的应用场合。 C++ 主要想解决的问题是,不同操作系统上的 API 功能相似但是形式不同;这些功能相似的代码很难用同一种形式的 C语言表达出来(所以要有面向对象和模版),硬要用C的话对软件工程组织的挑战太大。 所以, C++发明者的想法是,我只要捏合一些规则,使得基于不同OS的但功能相同的代码能够以同一种形式写出来。于是现在我们用 C++ 的话可以比较容易地(并且看起来是唯一成熟的, Rust 我认为尚未 ready)写出跨平台可编译的用户软件项目。 如果要选一个最能体现上述思路的 C++ 作品,我选 asio,尽管我并不觉得它比 libev 或者 libuv 好,但是最能体现 C++ 的思维方式。超过这种复杂度的工程,用 C++ 来做的话很勉强了。 一:C语言。 C语言诞生得非常早,当时人们普遍还习惯用汇编语言编写软件,而且没有什么统一,通用的操作系统,基本上软件都是从0开始写的。C语言的目标就是比汇编方便易用,同时不要损失汇编的表达能力。所以C语言可以看成是“高级的汇编”语言。C语言的源代码基本上可以非常容易地对应到汇编代码,而且可以不需要什么运行时环境的支持。C的特点,简单容易编译,灵活贴近底层。所以一直到现在,一些需要直接和硬件打交道的软件都还是用C语言写的,比如(但不限于)Linux Kernel和一些嵌入式领域。 二:C++ 语言。 C++早期是基于C的,C++早期的编译方法是将C++的代码编译成C代码然后再调用C的编译器来生成机器码。C++的目标是提高编程人员的生产率,哪怕代价是增加编译器的复杂度。而提高编程人员生产率的方法有如下几种:提高抽象层次,支持模块化编程,模块内紧耦合,模块间松耦合,自动化的代码生成等等,这些在C++中都有体现(“有体现”不是说只有C++能做这些,理论上C++能做的事情C和汇编都能做,“有体现”是指C++里面你可以更直接,更自然地做到这些)。面向对象只是C++的一部分,现代的C++的目标是支持多种编程范型,同时并不会离硬件太远。所以C++是非常适合写一些基础架构级软件的,比如编译器,GUI库等等。 一、C++概述 1、发展历史 1980年,Bjarne Stroustrup博士开始着手创建一种模拟语言,能够具有面向对象的程序设计特色。在当时,面向对象编程还是一个比较新的理念,Stroustrup博士并不是从头开始设计新语言,而是在C语言的基础上进行创建。这就是C++语言。 1985年,C++开始在外面慢慢流行。经过多年的发展,C++已经有了多个版本。为次,ANSI和ISO的联合委员会于1989年着手为C++制定标准。1994年2月,该委员会出版了第一份非正式草案,1998年正式推出了C++的国际标准。 2、C和C++ C++是C的超集,也可以说C是C++的子集,因为C先出现。按常理说,C++编译器能够编译任何C程序,但是C和C++还是有一些小差别。 例如C++增加了C不具有的关键字。这些关键字能作为函数和变量的标识符在C程序中使用,尽管C++包含了所有的C,但显然没有任何C++编译器能编译这样的C程序。 C程序员可以省略函数原型,而C++不可以,一个不带参数的C函数原型必须把void写出来。而C++可以使用空参数列表。 C++中new和delete是对内存分配的运算符,取代了C中的malloc和free。 标准C++中的字符串类取代了C标准C函数库头文件中的字符数组处理函数(C中没有字符串类型)。 C++中用来做控制态输入输出的iostream类库替代了标准C中的stdio函数库。 C++中的try/catch/throw异常处理机制取代了标准C中的setjmp()和longjmp()函数。 二、关键字和变量 C++相对与C增加了一些关键字,如下: typename bool dynamic_cast mutable namespace static_cast using catch explicit new virtual operator false private template volatile const protected this wchar_t const_cast public throw friend true reinterpret_cast try bitor xor_e and_eq compl or_eq not_eq bitand 在C++中还增加了bool型变量和wchar_t型变量: 布尔型变量是有两种逻辑状态的变量,它包含两个值:真和假。如果在表达式中使用了布尔型变量,那么将根据变量值的真假而赋予整型值1或0。要把一个整型变量转换成布尔型变量,如果整型值为0,则其布尔型值为假;反之如果整型值为非0,则其布尔型值为真。布儿型变量在运行时通常用做标志,比如进行逻辑测试以改变程序流程。 [cpp] view plain copy #include iostream.h int main() { bool flag; flag = true; if(flag) cout << true << endl; return 0; } C++中还包括wchar_t数据类型,wchar_t也是字符类型,但是是那些宽度超过8位的数据类型。许多外文字符集所含的数目超过256个,char字符类型无法完全囊括。wchar_t数据类型一般为16位。 标准C++的iostream类库中包括了可以支持宽字符的类和对象。用wout替代cout即可。 [cpp] view plain copy #include iostream.h int main() { wchar_t wc; wc = 'b'; wout << wc; wc = 'y'; wout << wc; wc = 'e'; wout << wc << endl; return 0; } 说明一下:某些编译器无法编译该程序(不支持该数据类型)。 三、强制类型转换 有时候,根据表达式的需要,某个数据需要被当成另外的数据类型来处理,这时,就需要强制编译器把变量或常数由声明时的类型转换成需要的类型。为此,就要使用强制类型转换说明,格式如下: int* iptr=(int*) &table; 表达式的前缀(int*)就是传统C风格的强制类型转换说明(typecast),又可称为强制转换说明(cast)。强制转换说明告诉编译器把表达式转换成指定的类型。有些情况下强制转换是禁用的,例如不能把一个结构类型转换成其他任何类型。数字类型和数字类型、指针和指针之间可以相互转换。当然,数字类型和指针类型也可以相互转换,但通常认为这样做是不安全而且也是没必要的。强制类型转换可以避免编译器的警告。 [cpp] view plain copy long int el = 123; short i = (int) el; float m = 34.56; int i = (int) m; 上面两个都是C风格的强制类型转换,C++还增加了一种转换方式,比较一下上面和下面这个书写方式的不同: [cpp] view plain copy long int el = 123; short i = int (el); float m = 34.56; int i = int (m); 使用强制类型转换的最大好处就是:禁止编译器对你故意去做的事发出警告。但是,利用强制类型转换说明使得编译器的类型检查机制失效,这不是明智的选择。通常,是不提倡进行强制类型转换的。除非不可避免,如要调用malloc()函数时要用的void型指针转换成指定类型指针。 四、标准输入输出流 在C语言中,输入输出是使用语句scanf()和printf()来实现的,而C++中是使用类来实现的。 [cpp] view plain copy #include iostream.h main() //C++中main()函数默认为int型,而C语言中默认为void型。 { int a; cout << input a number: ; cin >> a; /*输入一个数值*/ cout << a << endl; //输出并回车换行 return 0; } cin,cout,endl对象,他们本身并不是C++语言的组成部分。虽然他们已经是ANSI标准C++中被定义,但是他们不是语言的内在组成部分。在C++中不提供内在的输入输出运算符,这与其他语言是不同的。输入和输出是通过C++类来实现的,cin和cout是这些类的实例,他们是在C++语言的外部实现。 在C++语言中,有了一种新的注释方法,就是‘//’,在该行//后的所有说明都被编译器认为是注释,这种注释不能换行。C++中仍然保留了传统C语言的注释风格/*……*/。 C++也可采用格式化输出的方法: [cpp] view plain copy #include iostream.h int main() { int a; cout << input a number: ; cin >> a; cout << dec << a << ' ' //输出十进制数 << oct << a << ' ' //输出八进制数 << hex << a << endl; //输出十六进制数 return 0; } 从上面也可以看出,dec,oct,hex也不可作为变量的标识符在程序中出现。 五、函数参数问题 1、无名的函数形参 声明函数时可以包含一个或多个用不到的形式参数。这种情况多出现在用一个通用的函数指针调用多个函数的场合,其中有些函数不需要函数指针声明中的所有参数。看下面的例子: [cpp] view plain copy int fun(int x,int y) { return x*2; } 尽管这样的用法是正确的,但大多数C和C++的编译器都会给出一个警告,说参数y在程序中没有被用到。为了避免这样的警告,C++允许声明一个无名形参,以告诉编译器存在该参数,且调用者需要为其传递一个实际参数,但是函数不会用到这个参数。下面给出使用了无名参数的C++函数代码: [cpp] view plain copy int fun(int x,int) //注意不同点 { return x*2; } 2、函数的默认参数 C++函数的原型中可以声明一个或多个带有默认值的参数。如果调用函数时,省略了相应的实际参数,那么编译器就会把默认值作为实际参数。可以这样来声明具有默认参数的C++函数原型: [cpp] view plain copy #include iostream.h void show(int = 1,float = 2.3,long = 6); int main() { show(); show(2); show(4,5.6); show(8,12.34,50L); return 0; } void show(int first,float second,long third) { cout << first =<< first << second =<< second << third =<< third << endl; } 上面例子中,第一次调用show()函数时,让编译器自动提供函数原型中指定的所有默认参数,第二次调用提供了第一个参数,而让编译器提供剩下的两个,第三次调用则提供了前面两个参数,编译器只需提供最后一个,最后一个调用则给出了所有三个参数,没有用到默认参数。 六、函数重载 在C++中,允许有相同的函数名,不过它们的参数类型不能完全相同,这样这些函数就可以相互区别开来。而这在C语言中是不允许的。 1、参数个数不同 [cpp] view plain copy #include iostream.h void a(int,int); void a(int); int main() { a(5); a(6,7); return 0; } void a(int i) { cout << i << endl; //输出5 } void a(int i,int j) { cout << i << j << endl; //输出67 } 2.参数格式不同 [cpp] view plain copy #include iostream.h void a(int,int); void a(int,float); int main() { a(5,6); a(6,7.0); return 0; } void a(int i,int j) { cout << i << j <<endl; //输出56 } void a(int i,float j) { cout << i << j << endl; //输出67.0 } 七、变量作用域 C++语言中,允许变量定义语句在程序中的任何地方,只要在是使用它之前就可以;而C语言中,必须要在函数开头部分。而且C++允许重复定义变量,C语言也是做不到这一点的。看下面的程序: [cpp] view plain copy #include iostream.h int a; int main() { cin >> a; for(int i = 1;i <= 10; i++) //C语言中,不允许在这里定义变量 { static int a = 0; //C语言中,同一函数块,不允许有同名变量 a += i; cout<<::a<< <<a<<endl; } return 0; } 八、new和delete运算符 在C++语言中,仍然支持malloc()和free()来分配和释放内存,同时增加了new和delete来管理内存。 1.为固定大小的数组分配内存 [cpp] view plain copy #include iostream.h int main() { int *birthday = new int[3]; birthday[0] = 6; birthday[1] = 24; birthday[2] = 1940; cout << I was born on << birthday[0] << '/' << birthday[1] << '/' << birthday[2] << endl; delete [] birthday; //注意这儿 return 0; } 在删除数组时,delete运算符后要有一对方括号。 2.为动态数组分配内存 [cpp] view plain copy #include iostream.h #include stdlib.h int main() { int size; cin >> size; int *array = new int[size]; for(int i = 0;i < size;i++) array[i] = rand(); for(i = 0;i < size;i++) cout << '\n' << array[i]; delete [] array; return 0; } 九、引用型变量 在C++中,引用是一个经常使用的概念。引用型变量是其他变量的一个别名,我们可以认为他们只是名字不相同,其他都是相同的。 1.引用是一个别名 C++中的引用是其他变量的别名。声明一个引用型变量,需要给他一个初始化值,在变量的生存周期内,该值不会改变。& 运算符定义了一个引用型变量: int a; int& b=a; 先声明一个名为a的变量,它还有一个别名b。我们可以认为是一个人,有一个真名,一个外号,以后不管是喊他a还是b,都是叫他这个人。同样,作为变量,以后对这两个标识符操作都会产生相同的效果。 [cpp] view plain copy #include iostream.h int main() { int a = 123; int& b = a; cout << a << ','<< b << endl; //输出123,123 a++; cout << a << ','<< b << endl; //输出124,124 b++; cout << a<< ',' << b << endl; //输出125,125 return 0; } 2.引用的初始化 和指针不同,引用变量的值不可改变。引用作为真实对象的别名,必须进行初始化,除非满足下列条件之一: (1) 引用变量被声明为外部的,它可以在任何地方初始化 (2) 引用变量作为类的成员,在构造函数里对它进行初始化 (3) 引用变量作为函数声明的形参,在函数调用时,用调用者的实参来进行初始化 3.作为函数形参的引用 引用常常被用作函数的形参。以引用代替拷贝作为形参的优点: 引用避免了传递大型数据结构带来的额外开销 引用无须象指针那样需要使用*和->等运算符 [cpp] view plain copy #include iostream.h void func1(s p); void func2(s& p); struct s { int n; char text[10]; }; int main() { static s str = {123,China}; func1(str); func2(str); return 0; } void func1(s p) { cout << p.n << endl; cout << p.text << endl; } void func2(s& p) { cout << p.n << endl; cout << p.text << endl; } 从表面上看,这两个函数没有明显区别,不过他们所花的时间却有很大差异,func2()函数所用的时间开销会比func2()函数少很多。它们还有一个差别,如果程序递归func1(),随着递归的深入,会因为栈的耗尽而崩溃,但func2()没有这样的担忧。 4.以引用方式调用 当函数把引用作为参数传递给另一个函数时,被调用函数将直接对参数在调用者中的拷贝进行操作,而不是产生一个局部的拷贝(传递变量本身是这样的)。这就称为以引用方式调用。把参数的值传递到被调用函数内部的拷贝中则称为以传值方式调用。 [cpp] view plain copy #include iostream.h void display(const Date&,const char*); void swapper(Date&,Date&); struct Date { int month,day,year; }; int main() { static Date now={2,23,90}; static Date then={9,10,60}; display(now,Now: ); display(then,Then: ); swapper(now,then); display(now,Now: ); display(then,Then: ); return 0; } void swapper(Date& dt1,Date& dt2) { Date save; save=dt1; dt1=dt2; dt2=save; } void display(const Date& dt,const char *s) { cout << s; cout << dt.month << '/' << dt.day << '/'<< dt.year << endl; } 5.以引用作为返回值 [cpp] view plain copy #include iostream.h struct Date { int month,day,year; }; Date birthdays[]= { {12,12,60}; {10,25,85}; {5,20,73}; }; const Date& getdate(int n) { return birthdays[n-1]; } int main() { int dt=1; while(dt!=0) { cout<<Enter date # (1-3,0 to quit)<<endl; cin>>dt; if(dt>0 && dt<4) { const Date& bd = getdate(dt); cout << bd.month << '/' << bd.day << '/'<< bd.year << endl; } } return 0; } C++和C的设计哲学并不一样,两者取舍不同,所以不同的程序员和软件项目会有不同选择,难以一概而论。与C++相比,C具备编译速度快、容易学习、显式描述程序细节、较少更新标准(后两者也可同时视为缺点)等优点。在语言层面上,C++包含绝大部分C语言的功能(例外之一,C++没有C99的变长数组VLA),且提供OOP和GP的特性。但其实用C也可实现OOP思想,亦可利用宏去实现某程度的GP,只不过C++的语法能较简洁、自动地实现OOP/GP。C++的RAII(resource acquisition is initialization,资源获取就是初始化)特性比较独特,C/C#/Java没有相应功能。回顾历史,Stroustrup开发的早期C++编译器Cpre/Cfront是把C++源代码翻译为C,再用C编译器编译的。由此可知,C++编写的程序,都能用等效的C程序代替,但C++在语言层面上提供了OOP/GP语法、更严格的类型检查系统、大量额外的语言特性(如异常、RTTI等),并且C++标准库也较丰富。有时候C++的语法可使程序更简洁,如运算符重载、隐式转换。但另一方面,C语言的API通常比C++简洁,能较容易供其他语言程序调用。因此,一些C++库会提供C的API封装,同时也可供C程序调用。相反,有时候也会把C的API封装成C++形式,以支持RAII和其他C++库整合等。 <file_sep>#include<iostream> #include<stdio.h> #include<math.h> using namespace std; class Prime { public: Prime(int num):mNum(num) {} ~Prime(); bool isPrime(); Prime sumBit(); Prime multiBit(); Prime sqaureSumBit(); private: const int mNum; }; Prime::~Prime(){ return; } Prime Prime::sumBit() { int a = 0; int b = mNum; while(b != 0){ a += b % 10; b /= 10; } Prime p(a); return p; } Prime Prime::multiBit() { int a = 1; int b = mNum; while(b != 0){ a *= b % 10; b /= 10; } Prime p(a); return p; } Prime Prime::sqaureSumBit() { int a = 0; int b = mNum; while(b != 0){ a += b % 10 * b % 10; b /= 10; } Prime p(a); return p; } bool Prime::isPrime() { if(mNum % 2 == 0) return false; for(int i = 3;i * i < mNum;i+=2){ if(mNum % i == 0){ return false; } } return true; } int main() { int count=0; int allsum=0; int maxin=0; for(int i=100;i<9999;i++){ Prime pm(i); Prime sb = pm.sumBit(); Prime mb = pm.multiBit(); Prime ssb = pm.sqaureSumBit(); if(pm.isPrime() && sb.isPrime() && mb.isPrime() && ssb.isPrime()){ allsum+=i; count++; maxin=i; } } cout<<count<<" "<<allsum<<" "<<maxin<<endl; //to do sth return 0; } <file_sep>#include<iostream> #include<string> #include<math.h> #include<stdio.h> using namespace std; class Cell; class Table { public: Table(int i,int j); ~Table(); void show(); int addRow(); void delRow(int n); int addColumn(); void delColumn(int n); private: Cell cells; }; class Cell { public: Cell(char con[]); ~Cell(); void show(); private: string content; }; int main() { Table tb; tb.show(); tb.addRow(); tb.show(); tb.addColumn(); tb.show(); Table tb1(5,5); tb1.show(); tb1.set(1,1,30); tb1.set(2,2,"hello"); tb1.show(); tb1.delRow(1); tb1.show(); tb1.delColumn(1); tb1.show(); return 0; } Table::Table(int i,int j){ } void Table::show(){ } int Table::addRow(){ } void Table::delRow(int n){ } int Table::addColumn(){ } void Table::delColumn(int n){ } Cell::Cell(char con[]){ content = *con; } void Cell::show(){ cout<<content<<endl; } <file_sep>#include<iostream> #include<string> using namespace std; //初始化列表 初始化const常对象成员; //常成员函数 void changex() const;不能修改数据成员的值 //和正常函数互为重载 //const 对象 实例 然后调用函数是常成员函数 // class line { public: line(int x1, int y1, int x2, int y2); ~line(); void setA(int x1, int y1); void setB(int x2, int y2); void printinfo(); private: // const coordinate m_coora; // coordinate m_coorb; }; class coordinate { public: coordinate(int x, int y); int getx(); int gety(); void printinfo() const; private: int m_ix; int m_iy; }; coordinate::coordinate(int x, int y) { m_ix = x; m_iy = y; } int coordinate::getx(){ return m_ix; } int coordinate::gety() { return m_iy; } void coordinate::printinfo()const { cout << m_ix << " " << m_iy << endl; } int main() { coordinate coor1(3, 5); const coordinate &coor2 = coor1;//常成员函数 const coordinate *pcoor = &coor1; coor1.printinfo(); coor2.printinfo();//只能调用常成员函数 pcoor->printinfo(); getchar(); return 0; }<file_sep>#include<iostream> #include<vector> #include<stdio.h> #include<queue> #include<algorithm> #include<map> #include<list> #include<deque> #include<stack> //顺序容器 :vector list deque ; //关联容器 :map set multimap multiset; //容器适配: stack queue priority_queue; using namespace std; int main() { //.....vector.....//导入头文件#include<vector> vector<int> vec_test1;//初始化 空向量 vector<int> vec_test2(vec_test1);//初始化方式 用已有vector初始 vector<int> vec_test3(108);//108个值为0的向量 还可为(108,4)这样初始 //<>内部同样可以是其他数据类型; bool isempty=vec_test1.empty(); int lenth=vec_test1.size(); vec_test1.push_back(1998);//插入1998 lenth=vec_test1.size(); cout<<vec_test1[0]<<" "<<lenth<<" "<<isempty<<endl; vec_test1.push_back(1007);//插入1007 lenth=vec_test1.size(); cout<<vec_test1[0]<<" "<<lenth<<" "<<isempty<<endl; vec_test1.push_back(108);//插入108 lenth=vec_test1.size(); cout<<vec_test1[0]<<" "<<lenth<<" "<<isempty<<endl; vec_test1.pop_back();//删除末尾元素 lenth=vec_test1.size(); cout<<vec_test1[0]<<" "<<lenth<<" "<<isempty<<endl; vec_test1.insert(vec_test1.end(),5,3);//在最后插入5个3; lenth=vec_test1.size(); //迭代器学习日后补充; cout<<vec_test1[0]<<" "<<lenth<<" "<<isempty<<endl; vec_test1.clear(); //没有sort; //遍历方法 通过取长度访问下标或者迭代器遍历 //.....list.....//导入头文件#include<list> list<int> list1; list<int> list2(3);//含有三个元素; list<int> list3(4,2);//含有四个值为二的元素; list<int> list4(list2); // list1.push_back(1); // list1.clear(); list1.pop_back(); int lenth1=list3.size(); cout<<" "<<lenth1<<endl; //remove(int) 相同元素全部删除; //reverse() 同vector 反转 //sort 提供排序操作 //遍历通过迭代器 //.....deque.....//需导入头文件#include<deque> //除了从头插入数据别的与vector类似 //.....priorty_queue....//优先队列 priority_queue<int> big; priority_queue<int,vector<int>,greater<int> > small;//最后要有空格 small.push(4); small.push(34); small.push(2); small.push(32); cout<<small.top()<<endl; small.pop();//弹出顶元素;优先级按照以上big 和small 定义 cout<<small.empty()<<endl; cout<<small.top()<<endl; //不能随机访问任意顺序的值; //自定义优先级 // struct node //{ //int x, y; //friend booloperator< (node a, node b) //{ //return a.x > b.x; //结构体中,x小的优先级高 //} //}; //priority_queue<node>q;//定义方法 //在该结构中,y为值, x为优先级。 //通过自定义operator<操作符来比较元素中的优先级。 //在重载”<”时,最好不要重载”>”,可能会发生编译错误 queue<int> test_queue1; test_queue1.push(1); test_queue1.push(32); // push(x) 将x压入队列的末端 // // pop() 弹出队列的第一个元素(队顶元素),注意此函数并不返回任何值 // // front() 返回第一个元素(队顶元素) // // back() 返回最后被压入的元素(队尾元素) // // empty() 当队列为空时,返回true // // size() 返回队列的长度 cout<<small.size()<<endl; return 0; } <file_sep>#include<iostream> #include<string> #include<algorithm> #include<stdio.h> #include<vector> #include<queue> #include<stack> using namespace std; //学习几大算法以及已有模板使用总结; //插入排序:直接插入和希尔排序; //选择排序:直接选排序和堆排序; //交换排序:冒泡排序和快速排序(递归); //归并排序和基数排序; void print(int a[], int n ,int i){ cout<<i <<":"; for(int j= 0; j<5; j++){ cout<<a[j] <<" "; } cout<<endl; } //....插排....// void InsertSort(int a[], int n)//O(n^2)复杂度 { for(int i= 1; i<n; i++){ if(a[i] < a[i-1]){ //若第i个元素大于i-1元素,直接插入。小于的话,移动有序表后插入 int j= i-1; int x = a[i]; //复制存储待排序元素 a[i] = a[i-1]; //先后移一个元素 while(x < a[j]){ //查找在有序表的插入位置 a[j+1] = a[j]; j--; //元素后移 } a[j+1] = x; //插入到正确位置 } print(a,n,i); //打印每趟排序的结果 } } //....希尔排序....// 缩小增量排序 void ShellInsertSort(int a[], int n, int dk) { for(int i= dk; i<n; ++i){ if(a[i] < a[i-dk]){ //若第i个元素大于i-1元素,直接插入。小于的话,移动有序表后插入 int j = i-dk; int x = a[i]; //复制为存储待排序元素 a[i] = a[i-dk]; //首先后移一个元素 while(x < a[j]){ //查找在有序表的插入位置 a[j+dk] = a[j]; j -= dk; //元素后移 } a[j+dk] = x; //插入到正确位置 } print(a, n,i ); } } /** * 先按增量d(n/2,n为要排序数的个数进行希尔排序 * */ void shellSort(int a[], int n){ int dk = n/2; while( dk >= 1 ){ ShellInsertSort(a, n, dk); dk = dk/2; } } //....选择排序....// void selectsort(int a[],int n){ for(int i=0;i<n;i++){ int max=i; for(int j=i+1;j<n;j++){ if(a[j]>=a[max]){ max=j; } } if(max!=i){ int swap=a[max];a[max]=a[i];a[i]=swap; } } } void SelectSort(int r[],int n) //选排优化 同时记录最大最小值 { int i ,j , min ,max, tmp; for (i=1 ;i <= n/2;i++) { // 做不超过n/2趟选择排序 min = i; max = i ; //分别记录最大和最小关键字记录位置 for (j= i+1; j<= n-i; j++) { if (r[j] > r[max]) { max = j ; continue ; } if (r[j]< r[min]) { min = j ; } } //该交换操作还可分情况讨论以提高效率 tmp = r[i-1]; r[i-1] = r[min]; r[min] = tmp; tmp = r[n-i]; r[n-i] = r[max]; r[max] = tmp; } } //.....冒泡排序.....// //不能再手写错; void bubbleSort(int a[], int n){ for(int i =0 ; i< n-1; ++i) { for(int j = 0; j < n-i-1; ++j) { if(a[j] > a[j+1]) { int tmp = a[j] ; a[j] = a[j+1] ; a[j+1] = tmp; } } } } //可以同过增加指示符来判断时候已经有序 或者标记已经有序的位置; void Bubble_1 ( int r[], int n) { int i= n -1; //初始时,最后位置保持不变 while ( i> 0) { int pos= 0; //每趟开始时,无记录交换 for (int j= 0; j< i; j++) if (r[j]> r[j+1]) { pos= j; //记录交换的位置 int tmp = r[j]; r[j]=r[j+1];r[j+1]=tmp; } i= pos; //为下一趟排序作准备 } } //通过前后冒泡来减少遍历次序; void Bubble_2 ( int r[], int n){ int low = 0; int high= n -1; //设置变量的初始值 int tmp,j; while (low < high) { for (j= low; j< high; ++j) //正向冒泡,找到最大者 if (r[j]> r[j+1]) { tmp = r[j]; r[j]=r[j+1];r[j+1]=tmp; } --high; //修改high值, 前移一位 for ( j=high; j>low; --j) //反向冒泡,找到最小者 if (r[j]<r[j-1]) { tmp = r[j]; r[j]=r[j-1];r[j-1]=tmp; } ++low; //修改low值,后移一位 } } //.....快速排序.....// void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } int partition(int a[], int low, int high) { int privotKey = a[low]; //基准元素 while(low < high){ //从表的两端交替地向中间扫描 while(low < high && a[high] >= privotKey) --high; //从high 所指位置向前搜索,至多到low+1 位置。将比基准元素小的交换到低端 swap(&a[low], &a[high]); while(low < high && a[low] <= privotKey ) ++low; swap(&a[low], &a[high]); } print(a,10,10); return low; } void quickSort(int a[], int low, int high){ if(low < high){ int privotLoc = partition(a, low, high); //将表一分为二 quickSort(a, low, privotLoc -1); //递归对低子表递归排序 quickSort(a, privotLoc + 1, high); //递归对高子表递归排序 } } //......另一种c实现快排........// void quick_Sort(int array[],int left,int right) { if(left>right) return; /*取最左边的值为pivot(基准)*/ int i=left,j=right,pivot=array[left]; while(i<j) { while( (i<j) && (pivot <= array[j]) ) j--; if(i<j) array[i++]=array[j]; while( (i<j) && (array[i] <= pivot) ) i++; if(i<j) array[j--]=array[i]; } array[j]=pivot;/*也可以是 array[i]=piovt。因为此时i=j*/ quick_Sort(array,left,i-1); quick_Sort(array,i+1,right); } //.....qsort.....// //一、对int类型数组排序 // //int num[100]; // //Sample: // //int cmp ( const void *a , const void *b ) //{ //return *(int *)a - *(int *)b; //} // //qsort(num,100,sizeof(num[0]),cmp); // //二、对char类型数组排序(同int类型) // //char word[100]; // //Sample: // //int cmp( const void *a , const void *b ) //{ //return *(char *)a - *(int *)b; //} // //qsort(word,100,sizeof(word[0]),cmp); // //三、对double类型数组排序(特别要注意) // //double in[100]; // //int cmp( const void *a , const void *b ) //{ //return *(double *)a > *(double *)b ? 1 : -1; //} // //qsort(in,100,sizeof(in[0]),cmp); // //四、对结构体一级排序 // //struct In //{ //double data; //int other; //}s[100] // ////按照data的值从小到大将结构体排序,关于结构体内的排序关键数据data的类型可以很多种,参考上面的例子写 // //int cmp( const void *a ,const void *B) //{ //return (*(In *)a)->data > (*(In *)B)->data ? 1 : -1; //} // //qsort(s,100,sizeof(s[0]),cmp); // //五、对结构体二级排序 // //struct In //{ //int x; //int y; //}s[100]; // ////按照x从小到大排序,当x相等时按照y从大到小排序 // //int cmp( const void *a , const void *b ) //{ //struct In *c = (In *)a; //struct In *d = (In *)b; //if(c->x != d->x) return c->x - d->x; //else return d->y - c->y; //} // //qsort(s,100,sizeof(s[0]),cmp); // //六、对字符串进行排序 // //struct In //{ //int data; //char str[100]; //}s[100]; // ////按照结构体中字符串str的字典顺序排序 // //int cmp ( const void *a , const void *b ) //{ //return strcmp( (*(In *)a)->str , (*(In *)B)->str ); //} // //qsort(s,100,sizeof(s[0]),cmp); // //七、计算几何中求凸包的cmp // //int cmp(const void *a,const void *B) //重点cmp函数,把除了1点外的所有点,旋转角度排序 //{ //struct point *c=(point *)a; //struct point *d=(point *)b; //if( calc(*c,*d,p[1]) < 0) return 1; //else if( !calc(*c,*d,p[1]) && dis(c->x,c->y,p[1].x,p[1].y) < dis(d->x,d->y,p[1].x,p[1].y)) //如果在一条直线上,则把远的放在前面 //return 1; //else return -1; //} //: // //c++中加载头文件 "iostream" // //c中qsort函数包含在<stdlib.h>的头文件里,strcmp包含在<string.h>的头文件里 //.....sort.....//需添加头文件#include<algorithm> //int cmp(int a,int b) //{ // return a<b; //升序排列;改为return a>b,则为降序 // //} // //int main() //{ // int a[20],i; // for(i=0;i<20;i++) // cin>>a[i]; // sort(a,a+20,cmp); // for(i=0;i<20;i++) // cout<<a[i]<<endl; // return 0; //} //......不同数据类型的模板排序使用......// //升序:sort(begin,end,less<data-type>()); //降序:sort(begin,end,greater<data-type>()); //....归并排序.....// //将r[i…m]和r[m +1 …n]归并到辅助数组rf[i…n] //void Merge(ElemType *r,ElemType *rf, int i, int m, int n) //{ // int j,k; // for(j=m+1,k=i; i<=m && j <=n ; ++k){ // if(r[j] < r[i]) rf[k] = r[j++]; // else rf[k] = r[i++]; // } // while(i <= m) rf[k++] = r[i++]; // while(j <= n) rf[k++] = r[j++]; // print(rf,n+1); //} // //void MergeSort(ElemType *r, ElemType *rf, int lenght) //{ // int len = 1; // ElemType *q = r ; // ElemType *tmp ; // while(len < lenght) { // int s = len; // len = 2 * s ; // int i = 0; // while(i+ len <lenght){ // Merge(q, rf, i, i+ s-1, i+ len-1 ); //对等长的两个子表合并 // i = i+ len; // } // if(i + s < lenght){ // Merge(q, rf, i, i+ s -1, lenght -1); //对不等长的两个子表合并 // } // tmp = q; q = rf; rf = tmp; //交换q,rf,以保证下一趟归并时,仍从q 归并到rf // } //} // //void MSort(ElemType *r, ElemType *rf,int s, int t) //{ // ElemType *rf2; // if(s==t) r[s] = rf[s]; // else // { // int m=(s+t)/2; /*平分*p 表*/ // MSort(r, rf2, s, m); /*递归地将p[s…m]归并为有序的p2[s…m]*/ // MSort(r, rf2, m+1, t); /*递归地将p[m+1…t]归并为有序的p2[m+1…t]*/ // Merge(rf2, rf, s, m+1,t); /*将p2[s…m]和p2[m+1…t]归并到p1[s…t]*/ // } //} //void MergeSort_recursive(ElemType *r, ElemType *rf, int n) //{ /*对顺序表*p 作归并排序*/ // MSort(r, rf,0, n-1); //} //两路归并 int main(){ int a[5]={4,32,1,6,5}; InsertSort(a, 5);//插入排序 print(a,5,5); int b[5]={5,2,32,52,2}; shellSort(b,5); //希尔插入排序 print(b,5,5); int c[8]={2,45,34,26,63,35,5,4}; selectsort(c,8); //选择排序 print(c,8,8); return 0; } <file_sep>#include<string> #include<iostream> #include<cstdlib> //公有继承public //保护继承protected //私有继承private using namespace std; class person { public: person(); ~person(); void eat(); protected: string m_strname; private: int m_iage; }; class worker :public person { public: worker(); ~worker(); void work(); int m_salary; }; person::person() { cout << "person()" << endl; } person::~person(){ cout << "~person()" << endl; } void person::eat() { m_strname = "jin"; m_iage = 2; cout << "eat()" << endl; cout << m_strname << endl; } worker::worker() { cout << "worker()" << endl; } worker::~worker() { cout << "~worker()" << endl; } void worker::work() { cout << "work()" << endl; } int main() { worker *p = new worker(); delete p; p = NULL; person per; per.eat(); getchar(); return 0; } //隐藏 继承中同名函数访问机制区别 //soldier.play() //soldier.person::play(); //参数不同 只有函数名相同不构成隐藏 //父子类同名函数访问同名数据成员 则在各自区域内访问需要类名::数据成员 //is a 概念 //虚析构函数 virtual 防止内存泄漏 //当父类指针指向堆中子类对象并用父类指针销毁归还内存 //void test1(person p)类在函数传参会初始化临时对象 void test2(person &p) 引用不会产生临时对象 用*p传参也跟引用一样 //class mm:public worker,public person 不写继承方式则默认private //构造函数 mm::mm(parameter):worker(参数),person(参数) <file_sep>#include <iostream> #include <stdio.h> #include<string.h> #include<stdlib.h> using namespace std; #define LEN 1000005 int aaa[LEN], bbb[LEN]; int loc[LEN], n; void calLoc() { int i; for(i = 1; i <= n; i++) loc[bbb[i]] = i; } int LIS() { int i, k, l, r, mid; aaa[1] = bbb[1], k = 1; for(i = 2; i <= n; i++) { if(aaa[k] < bbb[i]) aaa[++k] = bbb[i]; else { l = 1; r = k; while(l <= r) { mid = ( l + r ) / 2; if(aaa[mid] < bbb[i]) l = mid + 1; else r = mid - 1; } aaa[l] = bbb[i]; } } return k; } int main() { int i; scanf("%d", &n); for(i = 1; i <= n; i++) { scanf("%d", &aaa[i]); } for(i = 1; i <= n; i++) { scanf("%d", &bbb[i]); } calLoc(); for(i = 1; i <= n; i++) bbb[i] = loc[aaa[i]]; printf("%d\n", LIS()); return 0; }
98ee469dcf1de54128f778a5418d1f5a0fa37b4c
[ "C", "C++" ]
33
C++
ZFancy/hello-world-1
ce23113b933584ef0f3f7d717f8da285ae46ea69
bfeb1161a27dd9dce04ac1d09f0c99c749bcf585
refs/heads/master
<file_sep>package com.example.huangxinhui.erpapp.Fragment; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.alibaba.fastjson.JSON; import com.example.huangxinhui.erpapp.Adapter.QueryAdapter; import com.example.huangxinhui.erpapp.JavaBean.Machine; import com.example.huangxinhui.erpapp.JavaBean.Query; import com.example.huangxinhui.erpapp.JavaBean.Wear; import com.example.huangxinhui.erpapp.R; import com.example.huangxinhui.erpapp.Util.JsonReader; import com.yatoooon.screenadaptation.ScreenAdapterTools; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; @SuppressLint("ValidFragment") public class QueryFragment extends Fragment { Unbinder unbinder; List<Query.DataBean.Info> data; @BindView(R.id.list_query) RecyclerView listQuery; private Map<String, String> wear; private Map<String, String> status; private Map<String, String> machine; private Map<String, String> bb; private Map<String, String> bc; public static QueryFragment getInstance(ArrayList<Query.DataBean.Info> data) { QueryFragment f = new QueryFragment(); Bundle bundle = new Bundle(); bundle.putSerializable("data", data); f.setArguments(bundle); return f; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); data = (List<Query.DataBean.Info>) getArguments().getSerializable("data"); status = JSON.parseObject(JsonReader.getJson("status.json", getActivity()), Map.class); wear = getWear(JSON.parseArray(JsonReader.getJson("wear.json", getActivity()), Wear.class)); machine = getMachine(JSON.parseArray(JsonReader.getJson("machine.json", getActivity()), Machine.class)); bb = JSON.parseObject(JsonReader.getJson("bb.json", getActivity()), Map.class); bc = JSON.parseObject(JsonReader.getJson("bc.json", getActivity()), Map.class); for (int i=0;i<data.size();i++){ if(data.get(i).getKey().equals("状态")) data.get(i).setValue(status.get(data.get(i).getValue())); if(data.get(i).getKey().equals("库位")) data.get(i).setValue(wear.get(data.get(i).getValue())); if(data.get(i).getKey().equals("去向")) data.get(i).setValue(wear.get(data.get(i).getValue())); if(data.get(i).getKey().equals("连铸机号")) data.get(i).setValue(machine.get(data.get(i).getValue())); if(data.get(i).getKey().equals("班次")) data.get(i).setValue(bc.get(data.get(i).getValue())); if(data.get(i).getKey().equals("班别")) data.get(i).setValue(bb.get(data.get(i).getValue())); } } /** * 将Wear集合转化为Map,便于取值 * * @param wears * @return */ private Map<String, String> getWear(List<Wear> wears) { Map<String, String> result = new HashMap<>(); for (Wear bean : wears) { result.put(bean.getValue(),bean.getKey()); } return result; } /** * 将Machine集合转化为Map,便于取值 * * @param machine * @return */ private Map<String, String> getMachine(List<Machine> machine) { Map<String, String> result = new HashMap<>(); for (Machine bean : machine) { result.put(bean.getValue(),bean.getKey()); } return result; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.layout_fragment_query, container, false); unbinder = ButterKnife.bind(this, view); listQuery.setLayoutManager(new LinearLayoutManager(getActivity())); listQuery.setAdapter(new QueryAdapter(data, getActivity())); ScreenAdapterTools.getInstance().loadView(view); return view; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } } <file_sep>package com.example.huangxinhui.erpapp.Util; import android.support.v4.content.FileProvider; public class MyProvide extends FileProvider { } <file_sep>package com.example.huangxinhui.erpapp.Function; import android.Manifest; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.bigkoo.pickerview.builder.OptionsPickerBuilder; import com.bigkoo.pickerview.listener.OnOptionsSelectListener; import com.bigkoo.pickerview.view.OptionsPickerView; import com.example.huangxinhui.erpapp.Information.ReceiveInformationActivity; import com.example.huangxinhui.erpapp.JavaBean.Machine; import com.example.huangxinhui.erpapp.JavaBean.Receive; import com.example.huangxinhui.erpapp.R; import com.example.huangxinhui.erpapp.Util.IpConfig; import com.example.huangxinhui.erpapp.Util.JsonReader; import com.example.huangxinhui.erpapp.Util.JsonUtil; import com.uuzuche.lib_zxing.activity.CaptureActivity; import com.uuzuche.lib_zxing.activity.CodeUtils; import com.yatoooon.screenadaptation.ScreenAdapterTools; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class ReceiveActivity extends AppCompatActivity { @BindView(R.id.producedDate) TextView producedDate; @BindView(R.id.furnaceCode) EditText furnaceCode; @BindView(R.id.brevityCode) EditText brevityCode; @BindView(R.id.deviceNumber) TextView deviceNumber; @BindView(R.id.qualityBooks) EditText qualityBooks; String date = ""; ProgressDialog dialog; AlertDialog date_dialog; List<Machine> machine; String device_id = ""; @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case -1: dialog.show(); break; case 0: // 处理异常,网络请求失败 Toast.makeText(ReceiveActivity.this, "网络异常,请检查网络是否通畅", Toast.LENGTH_SHORT).show(); if (dialog.isShowing()) dialog.dismiss(); break; case 1: // 处理服务器返回的数据 String data = msg.getData().getString("data"); if (JsonUtil.isJson(data)) {// 判断是否为json Receive result = JSON.parseObject(data, Receive.class); if (result != null && !result.getResult().equals("F")) { Intent intent = new Intent(ReceiveActivity.this, ReceiveInformationActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("data", (Serializable) result.getData().get(0).getInfos()); bundle.putSerializable("cfy", (Serializable) result.getData().get(0).getCfy().getList_info()); intent.putExtras(bundle); startActivity(intent); } else { Toast.makeText(ReceiveActivity.this, "查询失败", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(ReceiveActivity.this, data, Toast.LENGTH_SHORT).show(); } if (dialog.isShowing()) dialog.dismiss(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_receive); ButterKnife.bind(this); ScreenAdapterTools.getInstance().loadView(getWindow().getDecorView()); dialog = new ProgressDialog(this); dialog.setMessage("查询中"); machine = JSON.parseArray(JsonReader.getJson("machine.json", ReceiveActivity.this), Machine.class); } @OnClick({R.id.back, R.id.producedDate, R.id.query, R.id.img_qr, R.id.deviceNumber}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.back: finish(); break; case R.id.producedDate: if (date_dialog == null) { AlertDialog.Builder builder = new AlertDialog.Builder(this); View itemView = LayoutInflater.from(this).inflate(R.layout.item_date, null); final DatePicker picker = itemView.findViewById(R.id.dataPicker); builder.setTitle("请选择查询日期") .setView(itemView) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }).setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { date = new SimpleDateFormat("yyyyMMdd").format(new Date(picker.getYear() - 1900, picker.getMonth(), picker.getDayOfMonth())); producedDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date(picker.getYear() - 1900, picker.getMonth(), picker.getDayOfMonth()))); } } ); date_dialog = builder.create(); } date_dialog.show(); break; case R.id.query: new Thread(new ReceiverThread(furnaceCode.getText().toString().trim(), brevityCode.getText().toString().trim(), device_id, qualityBooks.getText().toString().trim())).start(); break; case R.id.img_qr: if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { //如果应用之前请求过此权限但用户拒绝了请求,此方法将返回 true。 //申请权限,字符串数组内是一个或多个要申请的权限,1是申请权限结果的返回参数,在onRequestPermissionsResult可以得知申请结果 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,}, 1); } else { Intent intent = new Intent(this, CaptureActivity.class); startActivityForResult(intent, 0x666); } break; case R.id.deviceNumber: OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() { @Override public void onOptionsSelect(int options1, int option2, int options3, View v) { deviceNumber.setText(machine.get(options1).getKey()); device_id = machine.get(options1).getValue(); } }).setOutSideCancelable(false) .setContentTextSize(25) .build(); pvOptions.setPicker(machine); pvOptions.setTitleText("请选择连铸机号"); pvOptions.show(); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 0x666) { //处理扫描结果(在界面上显示) if (null != data) { Bundle bundle = data.getExtras(); if (bundle == null) { return; } if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) { String result = bundle.getString(CodeUtils.RESULT_STRING); qualityBooks.setText(result); // Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show(); } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) { Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show(); } } } } class ReceiverThread implements Runnable { private String heatNo; private String heatNoj; private String ccNo; private String chgLocRptNo; public ReceiverThread(String heatNo, String heatNoj, String ccNo, String chgLocRptNo) { this.heatNo = heatNo; this.heatNoj = heatNoj; this.ccNo = ccNo; this.chgLocRptNo = chgLocRptNo; } @Override public void run() { String result = ""; String nameSpace = "http://service.sh.icsc.com"; // 调用的方法名称 String methodName = "run"; // EndPoint //String endPoint = "http://10.10.4.210:9081/erp/sh/Scanning.ws";//测试 String endPoint = "http://" + IpConfig.IP + "/erp/sh/Scanning.ws";//正式 // SOAP Action String soapAction = "http://service.sh.icsc.com/run"; // 指定WebService的命名空间和调用的方法名 SoapObject rpc = new SoapObject(nameSpace, methodName); String data = String.format("%-10s", "GPIS02") + String.format("%-10s", heatNo) + String.format("%-10s", heatNoj) + String.format("%-10s", date) + String.format("%-10s", ccNo) + String.format("%-12s", chgLocRptNo) + "*"; // 设置需调用WebService接口需要传入的参数 Log.i("params", data); rpc.addProperty("date", data); // 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER10); envelope.bodyOut = rpc; // 设置是否调用的是dotNet开发的WebService envelope.dotNet = false; envelope.setOutputSoapObject(rpc); HttpTransportSE transport = new HttpTransportSE(endPoint); mHandler.sendEmptyMessage(-1); try { // 调用WebService transport.call(soapAction, envelope); Object object = (Object) envelope.getResponse(); // 获取返回的结果 result = object.toString(); Log.i("Receiver", result); // 如果有数据返回,通知handler 1 Message msg = mHandler.obtainMessage(); msg.what = 1; Bundle bundle = new Bundle(); bundle.putString("data", result); msg.setData(bundle); msg.sendToTarget(); } catch (Exception e) { // 如果捕获异常,通知handler 0 mHandler.sendEmptyMessage(0); e.printStackTrace(); } } } } <file_sep>apply plugin: 'com.android.application' android { signingConfigs { config { keyAlias 'android_lyy' keyPassword '12348888' storeFile file('/Users/huangxinhui/Desktop/ERPApp/app/android_lyy.jks') storePassword '<PASSWORD>' } } compileSdkVersion 26 defaultConfig { applicationId "com.example.huangxinhui.erpapp" minSdkVersion 21 targetSdkVersion 26 versionCode 4 versionName "4.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" signingConfig signingConfigs.config } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.config } debug { signingConfig signingConfigs.config } } buildToolsVersion '28.0.3' productFlavors { } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') //noinspection GradleCompatible implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support:design:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.1.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' //butterknife implementation 'com.jakewharton:butterknife:8.4.0' annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0' //httpUtil implementation 'io.reactivex:rxandroid:1.2.1' implementation 'io.reactivex:rxjava:1.1.6' implementation 'com.squareup.retrofit2:retrofit:2.1.0' implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0' implementation 'org.ligboy.retrofit2:converter-fastjson-android:2.0.2' //下拉刷新上拉加载 implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.3' implementation 'com.scwang.smartrefresh:SmartRefreshHeader:1.0.3' //ScreenAdaptation屏幕ui适配 implementation 'me.yatoooon:screenadaptation:1.1.1' implementation files('libs/ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar') // 滚轮选择器 implementation 'com.contrarywind:Android-PickerView:4.1.4' // 二维码扫描 implementation 'cn.yipianfengye.android:zxing-library:2.2' } allprojects { repositories { maven { url 'https://jitpack.io' } } } <file_sep>package com.example.huangxinhui.erpapp.Fragment; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.DialogInterface; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.DatePicker; import android.widget.EditText; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.bigkoo.pickerview.builder.OptionsPickerBuilder; import com.bigkoo.pickerview.listener.OnOptionsSelectListener; import com.bigkoo.pickerview.view.OptionsPickerView; import com.example.huangxinhui.erpapp.Adapter.OutAdapter; import com.example.huangxinhui.erpapp.App; import com.example.huangxinhui.erpapp.JavaBean.Banci; import com.example.huangxinhui.erpapp.JavaBean.BusinessType; import com.example.huangxinhui.erpapp.JavaBean.Err; import com.example.huangxinhui.erpapp.JavaBean.LoginResult; import com.example.huangxinhui.erpapp.JavaBean.Query; import com.example.huangxinhui.erpapp.JavaBean.Wear; import com.example.huangxinhui.erpapp.R; import com.example.huangxinhui.erpapp.Util.IpConfig; import com.example.huangxinhui.erpapp.Util.JsonReader; import com.example.huangxinhui.erpapp.Util.JsonUtil; import com.yatoooon.screenadaptation.ScreenAdapterTools; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; public class OutFragment extends Fragment { Unbinder unbinder; List<Query.DataBean.Info> data; Map<String, String> data_map; ProgressDialog dialog; @BindView(R.id.list_query) RecyclerView listOut; private Map<String, String> status; private Map<String, String> wear; private PopupWindow pop; private List<BusinessType> types = new ArrayList<>(); private int select_lb; private AlertDialog dialog_date; private String selected_date; private List<Wear> list_wear; private int selected_wear; private List<Banci> list_banci = new ArrayList<>(); private int selected_banci; private App app; private String code; @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case -1: dialog.show(); break; case 0: // 处理异常,网络请求失败 Toast.makeText(getActivity(), "网络异常,请检查网络是否通畅", Toast.LENGTH_SHORT).show(); if (dialog.isShowing()) dialog.dismiss(); break; case 1: // 处理服务器返回的数据 String data = msg.getData().getString("data"); if (JsonUtil.isJson(data)) {// 判断是否为json LoginResult result = JSON.parseObject(data, LoginResult.class); if (result != null && !result.getResult().equals("F")) { Toast.makeText(getActivity(), "出库成功", Toast.LENGTH_SHORT).show(); getActivity().finish(); } else { Err errResult = JSON.parseObject(data, Err.class); Toast.makeText(getActivity(), errResult.getMsg(), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), "出库失败", Toast.LENGTH_SHORT).show(); } if (dialog.isShowing()) dialog.dismiss(); break; } } }; public static OutFragment getInstance(ArrayList<Query.DataBean.Info> data,String code) { OutFragment qf = new OutFragment(); Bundle bundle = new Bundle(); bundle.putSerializable("data", data); bundle.putString("code",code); qf.setArguments(bundle); return qf; } /** * 初始化pop */ private void initPop() { View view = LayoutInflater.from(getActivity()).inflate(R.layout.pop_out, null); final TextView lb = view.findViewById(R.id.lb); final TextView outWarehouseNo = view.findViewById(R.id.outWarehouseNo); final TextView chgLocDate = view.findViewById(R.id.chgLocDate); final EditText carNo = view.findViewById(R.id.carNo); final TextView operateShift = view.findViewById(R.id.operateShift); TextView operateCrew = view.findViewById(R.id.operateCrew); final EditText driver = view.findViewById(R.id.driver); final TextView inWarehouseNo = view.findViewById(R.id.inWarehouseNo); final EditText qty = view.findViewById(R.id.qty); final EditText bz = view.findViewById(R.id.bz); qty.setText(data_map.get("块数")); lb.setText(types.get(select_lb).getName()); lb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pop.dismiss(); OptionsPickerView pvOptions = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() { @Override public void onOptionsSelect(int options1, int option2, int options3, View v) { select_lb = options1; lb.setText(types.get(select_lb).getName()); showPop(); } }).setOutSideCancelable(false) .setContentTextSize(25) .build(); pvOptions.setPicker(types); pvOptions.setSelectOptions(select_lb); pvOptions.setTitleText("请选择班组"); pvOptions.show(); } }); outWarehouseNo.setText(wear.get(data_map.get("当前库"))); selected_date = new SimpleDateFormat("yyyyMMdd").format(new Date()); chgLocDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date())); chgLocDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (pop.isShowing()) pop.dismiss(); if (dialog_date == null) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.item_date, null); final DatePicker picker = itemView.findViewById(R.id.dataPicker); builder.setTitle("请选择查询日期") .setView(itemView) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { showPop(); } }).setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { selected_date = new SimpleDateFormat("yyyyMMdd").format(new Date(picker.getYear() - 1900, picker.getMonth(), picker.getDayOfMonth())); chgLocDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date(picker.getYear() - 1900, picker.getMonth(), picker.getDayOfMonth()))); showPop(); } }); dialog_date = builder.create(); } dialog_date.show(); } }); inWarehouseNo.setText(list_wear.get(selected_wear).getKey()); inWarehouseNo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pop.dismiss(); OptionsPickerView pvOptions = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() { @Override public void onOptionsSelect(int options1, int option2, int options3, View v) { selected_wear = options1; inWarehouseNo.setText(list_wear.get(selected_wear).getKey()); showPop(); } }).setOutSideCancelable(false) .setContentTextSize(25) .build(); pvOptions.setPicker(list_wear); pvOptions.setSelectOptions(selected_wear); pvOptions.setTitleText("请选择接收库别"); pvOptions.show(); } }); operateShift.setText(list_banci.get(selected_banci).getDesc()); operateShift.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pop.dismiss(); OptionsPickerView pvOptions = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() { @Override public void onOptionsSelect(int options1, int option2, int options3, View v) { selected_banci = options1; operateShift.setText(list_banci.get(selected_banci).getDesc()); showPop(); } }).setOutSideCancelable(false) .setContentTextSize(25) .build(); pvOptions.setPicker(list_banci); pvOptions.setSelectOptions(selected_banci); pvOptions.setTitleText("请选择班次"); pvOptions.show(); } }); operateCrew.setText(app.getGroup().getName()); view.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!qty.getText().toString().equals("")) { new Thread(new OutConfirmThread( types.get(select_lb).getValue(), data_map.get("当前库"), selected_date, carNo.getText().toString(), list_banci.get(selected_banci).getCode(), app.getGroup().getId(), driver.getText().toString(), list_wear.get(selected_wear).getValue(), bz.getText().toString(), data_map.get("炉号"), data_map.get("长度"), data_map.get("重量"), data_map.get("钢种"), data_map.get("钢坯状态"), //data_map.get("块数"),// 后面改 qty.getText().toString(), data_map.get("当前库"), data_map.get("当前跨"), data_map.get("当前储序"), code )).start(); } else { Toast.makeText(app, "块数不能为空", Toast.LENGTH_SHORT).show(); } } }); pop = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); pop.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFFFF"))); pop.setFocusable(true); pop.setOutsideTouchable(true); pop.update(); pop.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes(); lp.alpha = 1f; //0.0-1.0 getActivity().getWindow().setAttributes(lp); } }); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); status = JSON.parseObject(JsonReader.getJson("status.json", getActivity()), Map.class); wear = getWear(JSON.parseArray(JsonReader.getJson("wear.json", getActivity()), Wear.class)); data = (List<Query.DataBean.Info>) getArguments().getSerializable("data"); code = getArguments().getString("code"); list_wear = JSON.parseArray(JsonReader.getJson("wear.json", getActivity()), Wear.class); data_map = exchange(data); types.add(new BusinessType("热送", "A")); types.add(new BusinessType("冷发", "B")); list_banci.add(new Banci("1", "夜")); list_banci.add(new Banci("2", "白")); list_banci.add(new Banci("3", "中")); for (int i = 0; i < data.size(); i++) { if (data.get(i).getKey().equals("钢坯状态")) data.get(i).setValue(status.get(data.get(i).getValue())); if (data.get(i).getKey().equals("当前库")) data.get(i).setValue(wear.get(data.get(i).getValue())); } } /** * 将List转化为Map */ private Map<String, String> exchange(List<Query.DataBean.Info> data) { Map<String, String> result = new HashMap<>(); for (Query.DataBean.Info bean : data) { result.put(bean.getKey(), bean.getValue()); } return result; } /** * 将Wear集合转化为Map,便于取值 * * @param wears * @return */ private Map<String, String> getWear(List<Wear> wears) { Map<String, String> result = new HashMap<>(); for (Wear bean : wears) { result.put(bean.getValue(), bean.getKey()); } return result; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.layout_fragment_query, container, false); ScreenAdapterTools.getInstance().loadView(view); unbinder = ButterKnife.bind(this, view); app = (App) getActivity().getApplication(); dialog = new ProgressDialog(getActivity()); dialog.setMessage("出库中"); initPop(); listOut.setLayoutManager(new LinearLayoutManager(getActivity())); OutAdapter adapter = new OutAdapter(data, getActivity()); adapter.setOnButtonClickListener(new OutAdapter.OnButtonClickListener() { @Override public void onCLick(View view, int position) { showPop(); } }); listOut.setAdapter(adapter); return view; } private void showPop() { if (!pop.isShowing()) { pop.showAtLocation(listOut, Gravity.CENTER, 0, 0); WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes(); lp.alpha = 0.5f; //0.0-1.0 getActivity().getWindow().setAttributes(lp); } } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } class OutConfirmThread implements Runnable { private String lb; private String outWarehouseNo; private String chgLocDate; private String carNo; private String operateShift; private String operateCrew; private String driver; private String inWarehouseNo; private String bz; private String heatNo; private String length; private String weight; private String spec; private String status; private String qty; private String warehouseNo; private String areaNo; private String rowNo; private String code; public OutConfirmThread(String lb, String outWarehouseNo, String chgLocDate, String carNo, String operateShift, String operateCrew, String driver, String inWarehouseNo, String bz, String heatNo, String length, String weight, String spec, String status, String qty, String warehouseNo, String areaNo, String rowNo, String code ) { this.lb = lb; this.outWarehouseNo = outWarehouseNo; this.chgLocDate = chgLocDate; this.carNo = carNo; this.operateShift = operateShift; this.operateCrew = operateCrew; this.driver = driver; this.inWarehouseNo = inWarehouseNo; this.bz = bz; this.heatNo = heatNo; this.length = length; this.weight = weight; this.spec = spec; this.status = status; this.qty = qty; this.warehouseNo = warehouseNo; this.areaNo = areaNo; this.rowNo = rowNo; this.code = code; } @Override public void run() { String result = ""; String nameSpace = "http://service.sh.icsc.com"; // 调用的方法名称 String methodName = "run"; // EndPoint //String endPoint = "http://10.10.4.210:9081/erp/sh/Scanning.ws";//测试 String endPoint = "http://" + IpConfig.IP + "/erp/sh/Scanning.ws";//正式 // SOAP Action String soapAction = "http://service.sh.icsc.com/run"; // 指定WebService的命名空间和调用的方法名 SoapObject rpc = new SoapObject(nameSpace, methodName); String data = String.format("%-10s", "GPIS08") + String.format("%-10s", lb) + String.format("%-10s", outWarehouseNo) + String.format("%-8s", chgLocDate) + String.format("%-15s", carNo) + String.format("%-5s", operateShift) + String.format("%-5s", operateCrew) + String.format("%-10s", driver) + String.format("%-10s", inWarehouseNo) + String.format("%-50s", bz) + String.format("%-10s", heatNo) + String.format("%-10s", length) + String.format("%-10s", weight) + String.format("%-20s", spec) + String.format("%-5s", status) + String.format("%-3s", qty) + String.format("%-10s", warehouseNo) + String.format("%-10s", areaNo) + String.format("%-10s", rowNo) + String.format("%-10s", code) + "*"; // 设置需调用WebService接口需要传入的参数 Log.i("params", data); rpc.addProperty("date", data); // 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER10); envelope.bodyOut = rpc; // 设置是否调用的是dotNet开发的WebService envelope.dotNet = false; envelope.setOutputSoapObject(rpc); HttpTransportSE transport = new HttpTransportSE(endPoint); mHandler.sendEmptyMessage(-1); try { // 调用WebService transport.call(soapAction, envelope); Object object = (Object) envelope.getResponse(); // 获取返回的结果 result = object.toString(); Log.i("login", result); // 如果有数据返回,通知handler 1 Message msg = mHandler.obtainMessage(); msg.what = 1; Bundle bundle = new Bundle(); bundle.putString("data", result); msg.setData(bundle); msg.sendToTarget(); } catch (Exception e) { // 如果捕获异常,通知handler 0 mHandler.sendEmptyMessage(0); e.printStackTrace(); } } } } <file_sep>package com.example.huangxinhui.erpapp.Adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.example.huangxinhui.erpapp.JavaBean.Receive; import com.example.huangxinhui.erpapp.R; import java.util.List; public class ReceiverAdapter extends RecyclerView.Adapter<ReceiverAdapter.ViewHolder> { private static final int TYPE_LAYOUT = 1; private static final int TYPE_WATCH = 2; private static final int TYPE_BUTTON = 3; private OnButtonClickListener onButtonClickListener; private OnButtonClickListener onWatchClickListener; private List<Receive.DataBean.InfosBean.TabsBean.ListInfoBeanX> data; private LayoutInflater inflater; public ReceiverAdapter(List<Receive.DataBean.InfosBean.TabsBean.ListInfoBeanX> data, Context context) { this.data = data; this.inflater = LayoutInflater.from(context); } public void setOnButtonClickListener(OnButtonClickListener onButtonClickListener) { this.onButtonClickListener = onButtonClickListener; } public void setOnWatchClickListener(OnButtonClickListener onWatchClickListener) { this.onWatchClickListener = onWatchClickListener; } @Override public int getItemViewType(int position) { if (position == data.size()+1) { return TYPE_BUTTON; }else if(position == data.size()){ return TYPE_WATCH; } else { return TYPE_LAYOUT; } } @NonNull @Override public ReceiverAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int type) { if (type == TYPE_BUTTON) { Log.i("onCreateViewHolder", "TYPE_BUTTON"); return new ViewHolder(inflater.inflate(R.layout.list_button, viewGroup, false)); }else if(type == TYPE_WATCH){ return new ViewHolder(inflater.inflate(R.layout.list_watch, viewGroup, false)); } else { return new ViewHolder(inflater.inflate(R.layout.list_information, viewGroup, false)); } } @Override public void onBindViewHolder(@NonNull ReceiverAdapter.ViewHolder holder, final int i) { switch (getItemViewType(i)) { case TYPE_LAYOUT: holder.name.setText(data.get(i).getKey()); holder.num.setText(data.get(i).getValue()); break; case TYPE_WATCH: if(onWatchClickListener != null){ holder.watch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onWatchClickListener.onCLick(view,i); } }); } break; case TYPE_BUTTON: holder.button.setText("点击入库"); if (onButtonClickListener != null) { holder.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onButtonClickListener.onCLick(view, i); } }); } break; } } @Override public int getItemCount() { return data.size() + 2; } static class ViewHolder extends RecyclerView.ViewHolder { TextView name; TextView num; Button button; LinearLayout watch; ViewHolder(View view) { super(view); name = view.findViewById(R.id.name); num = view.findViewById(R.id.num); button = view.findViewById(R.id.button); watch = view.findViewById(R.id.watch); } } /** * 按钮的点击事件 */ public interface OnButtonClickListener { void onCLick(View view, int position); } } <file_sep>package com.example.huangxinhui.erpapp.Information; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.example.huangxinhui.erpapp.JavaBean.Query; import com.example.huangxinhui.erpapp.JavaBean.Receive; import com.example.huangxinhui.erpapp.R; import com.example.huangxinhui.erpapp.Util.JsonReader; import com.yatoooon.screenadaptation.ScreenAdapterTools; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import butterknife.BindView; import butterknife.ButterKnife; public class WarrantyActivity extends AppCompatActivity { @BindView(R.id.list_warranty) RecyclerView listWarranty; List<Receive.DataBean.InfosBean.ZbsBean.ListInfoBeanXX> list_zbs; List<Receive.DataBean.CfyBean.ListInfoBean> list_cfy; WarrantyAdapter adapter; private Map<String, String> bb; private Map<String, String> bc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_warranty); ButterKnife.bind(this); ScreenAdapterTools.getInstance().loadView(getWindow().getDecorView()); list_zbs = (List<Receive.DataBean.InfosBean.ZbsBean.ListInfoBeanXX>) getIntent().getExtras().getSerializable("zbs"); list_cfy = (List<Receive.DataBean.CfyBean.ListInfoBean>) getIntent().getExtras().getSerializable("cfy"); bb = JSON.parseObject(JsonReader.getJson("bb.json", this), Map.class); if (list_zbs == null || list_cfy == null) { Toast.makeText(this, "数据有误,请联系管理员", Toast.LENGTH_SHORT).show(); } else { listWarranty.setLayoutManager(new LinearLayoutManager(this)); // adapter = new WarrantyAdapter(list_data.get(1).getList_info(), list_data.get(2).getList_info(), getBookCode(list_data.get(0).getList_info()), this); adapter = new WarrantyAdapter( list_zbs, list_cfy, list_zbs.get(0).getValue(), this ); listWarranty.setAdapter(adapter); } } private String getBookCode(List<Query.DataBean.Info> info) { for (Query.DataBean.Info i : info) { if (i.getKey().equals("质保书编号")) { return i.getValue(); } } return ""; } class WarrantyAdapter extends RecyclerView.Adapter<WarrantyAdapter.ViewHolder> { private final int TYPE_HEAD = 0; private final int TYPE_LAYOUT = 1; private final int TYPE_GRID = 2; List<Receive.DataBean.InfosBean.ZbsBean.ListInfoBeanXX> data; List<Receive.DataBean.CfyBean.ListInfoBean> cell; LayoutInflater inflater; String book_code; public WarrantyAdapter(List<Receive.DataBean.InfosBean.ZbsBean.ListInfoBeanXX> data, List<Receive.DataBean.CfyBean.ListInfoBean> cell, String book_code, Context context) { this.data = data; this.cell = cell; this.book_code = book_code; inflater = LayoutInflater.from(context); } @Override public int getItemViewType(int position) { if (position == 0) { return TYPE_HEAD; } else if (position == data.size() + 1) { return TYPE_GRID; } else { return TYPE_LAYOUT; } } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int type) { switch (type) { case TYPE_HEAD: return new ViewHolder(inflater.inflate(R.layout.item_head, viewGroup, false)); case TYPE_LAYOUT: return new ViewHolder(inflater.inflate(R.layout.list_information, viewGroup, false)); case TYPE_GRID: return new ViewHolder(inflater.inflate(R.layout.item_grid, viewGroup, false)); } return null; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { switch (getItemViewType(position)) { case TYPE_HEAD: holder.finish.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); holder.book_code.setText(book_code); break; case TYPE_LAYOUT: holder.name.setText(data.get(position - 1).getKey()); holder.num.setText(data.get(position - 1).getValue()); break; case TYPE_GRID: holder.list_grid.setLayoutManager(new GridLayoutManager(WarrantyActivity.this, 4)); holder.list_grid.setAdapter(new CellAdapter(cell, inflater)); break; } } @Override public int getItemCount() { return data.size() + 2; } class ViewHolder extends RecyclerView.ViewHolder { @Nullable @BindView(R.id.finish) ImageView finish; @Nullable @BindView(R.id.book_code) TextView book_code; @Nullable @BindView(R.id.name) TextView name; @Nullable @BindView(R.id.num) TextView num; @Nullable @BindView(R.id.list_grid) RecyclerView list_grid; ViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } } class CellAdapter extends RecyclerView.Adapter<CellAdapter.ViewHolder> { List<Receive.DataBean.CfyBean.ListInfoBean> data; LayoutInflater inflater; public CellAdapter(List<Receive.DataBean.CfyBean.ListInfoBean> data, LayoutInflater inflater) { this.data = data; this.inflater = inflater; } @NonNull @Override public CellAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = inflater.inflate(R.layout.item_cell, viewGroup, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull CellAdapter.ViewHolder holder, int position) { if(Pattern.compile("(?i)[A-z]").matcher(data.get(position).getValue()).find()){ holder.key.setTextColor(Color.parseColor("#FF0000")); holder.value.setTextColor(Color.parseColor("#FF0000")); holder.key.setText(data.get(position).getKey()); holder.value.setText(data.get(position).getValue().substring(0,data.get(position).getValue().length()-2)); }else { holder.key.setText(data.get(position).getKey()); holder.value.setText(data.get(position).getValue()); } } @Override public int getItemCount() { return data.size(); } class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.key) TextView key; @BindView(R.id.value) TextView value; ViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } } } <file_sep>package com.example.huangxinhui.erpapp.Adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.huangxinhui.erpapp.JavaBean.Query; import com.example.huangxinhui.erpapp.R; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class QueryAdapter extends RecyclerView.Adapter<QueryAdapter.ViewHolder> { private List<Query.DataBean.Info> data; private LayoutInflater inflater; public QueryAdapter(List<Query.DataBean.Info> data, Context context) { this.data = data; this.inflater = LayoutInflater.from(context); } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { ViewHolder holder = new ViewHolder(inflater.inflate(R.layout.list_information, viewGroup, false)); return holder; } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { viewHolder.name.setText(data.get(i).getKey()); viewHolder.num.setText(data.get(i).getValue()); } @Override public long getItemId(int position) { return position; } @Override public int getItemCount() { return data==null?0:data.size(); } static class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.name) TextView name; @BindView(R.id.num) TextView num; ViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } } <file_sep>package com.example.huangxinhui.erpapp; import android.app.Application; import android.content.res.Configuration; import com.example.huangxinhui.erpapp.JavaBean.GroupBean; import com.uuzuche.lib_zxing.activity.ZXingLibrary; import com.yatoooon.screenadaptation.ScreenAdapterTools; public class App extends Application { private GroupBean group;// 登录时选择的班别 public GroupBean getGroup() { return group; } public void setGroup(GroupBean group) { this.group = group; } @Override public void onCreate() { super.onCreate(); ScreenAdapterTools.init(this); ZXingLibrary.initDisplayOpinion(this); } //旋转适配,如果应用屏幕固定了某个方向不旋转的话(比如qq和微信),下面可不写. @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); ScreenAdapterTools.getInstance().reset(this); } } <file_sep>package com.example.huangxinhui.erpapp.Util; import android.content.Context; import android.os.Environment; import android.util.DisplayMetrics; import android.view.WindowManager; import java.io.File; public class MyUtils { public static final String APP_NAME = "erpapp.apk";//名字 public static final String PACKAGE_NAME = "com.example.huangxinhui.erpapp"; /** * 获得存储文件 * * @param * @param * @return */ public static File getCacheFile(String name, Context context) { return new File(Environment.getExternalStorageDirectory() + "/" + MyUtils.PACKAGE_NAME + "/" + MyUtils.APP_NAME); } /** * 获取手机大小,px * * @param context * @return */ public static DisplayMetrics getPhoneMetrics(Context context) {// 获取手机分辨率 DisplayMetrics dm = new DisplayMetrics(); WindowManager manager = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); manager.getDefaultDisplay().getMetrics(dm); return dm; } } <file_sep>package com.example.huangxinhui.erpapp; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.KeyEvent; import android.view.View; import com.example.huangxinhui.erpapp.Function.IntoActivity; import com.example.huangxinhui.erpapp.Function.MoveActivity; import com.example.huangxinhui.erpapp.Function.OutActivity; import com.example.huangxinhui.erpapp.Function.QueryActivity; import com.example.huangxinhui.erpapp.Function.ReceiveActivity; import com.yatoooon.screenadaptation.ScreenAdapterTools; import butterknife.ButterKnife; import butterknife.OnClick; public class HomeActivity extends AppCompatActivity { //A180700002 18B606163 private String code = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ButterKnife.bind(this); ScreenAdapterTools.getInstance().loadView(getWindow().getDecorView()); code = getIntent().getExtras().getString("code"); } @OnClick({R.id.query, R.id.receive, R.id.out, R.id.into, R.id.move}) public void onViewClicked(View view) { Intent intent = null; switch (view.getId()) { case R.id.query: intent = new Intent(this, QueryActivity.class); break; case R.id.receive: intent = new Intent(this, ReceiveActivity.class); break; case R.id.out: Bundle bundle = new Bundle(); bundle.putString("code", code); intent = new Intent(this, OutActivity.class); intent.putExtras(bundle); break; case R.id.into: intent = new Intent(this, IntoActivity.class); break; case R.id.move: intent = new Intent(this, MoveActivity.class); break; } if (intent != null) startActivity(intent); } // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // if (keyCode == KeyEvent.KEYCODE_BACK) { // moveTaskToBack(true); // return true; // } // return super.onKeyDown(keyCode, event); // } } <file_sep>package com.example.huangxinhui.erpapp.Information; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.alibaba.fastjson.JSON; import com.example.huangxinhui.erpapp.Fragment.QueryFragment; import com.example.huangxinhui.erpapp.JavaBean.Machine; import com.example.huangxinhui.erpapp.JavaBean.Query; import com.example.huangxinhui.erpapp.JavaBean.Wear; import com.example.huangxinhui.erpapp.R; import com.example.huangxinhui.erpapp.Util.JsonReader; import com.yatoooon.screenadaptation.ScreenAdapterTools; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class QueryInformationActivity extends AppCompatActivity { @BindView(R.id.titleName) TextView titleName; @BindView(R.id.tl_tab) TabLayout tlTab; @BindView(R.id.pager) ViewPager pager; QueryFragment[] fragments; String[] titles; private Map<String, String> wear; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_query_information); ButterKnife.bind(this); ScreenAdapterTools.getInstance().loadView(getWindow().getDecorView()); ArrayList<Query.DataBean> list_data = (ArrayList<Query.DataBean>) getIntent().getExtras().getSerializable("data"); wear = getWear(JSON.parseArray(JsonReader.getJson("wear.json", this), Wear.class)); titleName.setText(getIntent().getExtras().getString("title") == null ? "" : getIntent().getExtras().getString("title")); fragments = new QueryFragment[list_data.size()]; titles = new String[list_data.size()]; for (int i = 0; i < list_data.size(); i++) { fragments[i] = QueryFragment.getInstance(list_data.get(i).getList_info()); list_data.get(i).setName(wear.get(list_data.get(i).getName())); titles[i] = list_data.get(i).getName(); } pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager())); tlTab.setTabMode(TabLayout.MODE_SCROLLABLE); tlTab.setTabTextColors(Color.parseColor("#000000"), Color.parseColor("#40a9ff")); tlTab.setupWithViewPager(pager); } /** * 将Wear集合转化为Map,便于取值 * * @param wears * @return */ private Map<String, String> getWear(List<Wear> wears) { Map<String, String> result = new HashMap<>(); for (Wear bean : wears) { result.put(bean.getValue(),bean.getKey()); } return result; } class MyPagerAdapter extends FragmentPagerAdapter { public MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { return fragments[i]; } @Override public int getCount() { return fragments.length; } @Nullable @Override public CharSequence getPageTitle(int position) { return titles[position]; } } @OnClick(R.id.back) public void onViewClicked() { finish(); } }
6452c5eaaed914426be3cc99ba088a832f7a37d0
[ "Java", "Gradle" ]
12
Java
H-494/ERPApp
4033fa6fcaf17646ea87206034b74b23454eef50
133b2084ead33b79498121d80fd855fb8429ad73
refs/heads/master
<repo_name>bugger-caihao/ch<file_sep>/src/main/resources/static/asset/js/shop.js /*获取登陆信息*/ $(function getUserType(){ $.ajax({ type : "GET", url : "getLoginInfo", data : {}, dataType : "json", async : false, cache:false, success : function(result) { if(result.status=="000"){ if(result.data.userType==2){//如果是主账号,去掉去购物车和加入购物车功能。 $("#gouwuche").remove(); $("#openShop").remove(); } }else{ window.top.location.href="login"; } } }); }); /*点击变色*/ $(".wtbz_title").click(function(){ $(".wtbz_title").removeClass("click") $(this).addClass("click"); }); //显示详情 function displayDetails(id) { $(".bigg_box").css('display','none'); $(".dgwc").css('display','none'); $("#shopDiv").css('display','none'); $("#comboDiv").css('display','none'); $(".big-boxx").css('display','block'); $.ajax({ type : "get", url : "../manageShow/list", data : {id:id}, dataType : "json", async : false, success : function(data) { if (data.status=='000'){ addDetails(data.rows[0]); }else{ $.alert("系统故障,请联系管理员!"); } } }); } /*购物车页面*/ function openShop(){ $(".bigg_box").css('display','none'); $(".dgwc").css('display','none'); $("#tdgl_right").css('display','none'); $("#shopDiv").css('display','block'); $(".big-boxx").css('display','none'); $("#comboDiv").css('display','none'); loadtable(); } /*套餐页面*/ function openCombo(){ $(".bigg_box").css('display','block'); $(".dgwc").css('display','block'); $("#tdgl_right").css('display','none'); $("#shopDiv").css('display','none'); $(".big-boxx").css('display','none'); $("#comboDiv").css('display','block'); comboTable(); } //谈单管理 $("#wtbz").click();//采用点击事件触发舞台布置列表 //manageList(1); function manageList(type) { $(".bigg_box").css('display','block'); $(".dgwc").css('display','block'); $("#tdgl_right").css('display','block'); $("#comboDiv").css('display','none'); $(".big-boxx").css('display','none'); $("#shopDiv").css('display','none'); $.ajax({ type : "GET", url : "manageShow/list", data : {manageType:type,status:1}, async : false, success : function(data) { if(data.rows.length>0){ addManage(data.rows); }else{ $.alert("请上传相关图片信息!"); } }, error : function(){ $.alert("系统故障,请联系管理员!"); } }); } //平铺谈单管理 function addManage(data) { var divAdd=""; for(var i=0,len=data.length;i<len;i++){ var imgArr = []; $.each(data[i].files,function(i,file){ if(file.fileType==0){ imgArr = file.fileAliyunUrl.split(","); } }); divAdd += '<div class="jstplb"><div class="jstplb_img"><img style="cursor:pointer" src="' + imgArr[0] + '" onclick="displayDetails(' + data[i].id + ')"></div><div class="wzxqjs">' + '<div class="xqjss">详情:</div><div class="xqwzms">' + data[i].description + '</div>' + '<div class="jgsz">价格:<span>¥' + data[i].price + '</span></div>' + '<a><div class="jrgwcan" onclick="updateStatus(' + data[i].id + ')"><div class="gwc_img"><img src="asset/img/navigation/gwc.png"></div><div class="jrgwc">加入购物车</div></div></a></div>' + '<div class="clearfix"></div></div>'; } $("#tdgl_right").html(divAdd); } //平铺详情显示 function addDetails(data) { $("#vedioUrl").empty(); $("#imgDiv").empty(); var imgDiv = ""; var imgArr = []; var vedioFlag = false; $.each(data.files,function(i,file){ if(file.fileType==0){ imgArr = file.fileAliyunUrl.split(","); } else if(file.fileType==1){ vedioFlag = true; $("#spbf").css('display','block'); var sourceDom = $("<source src=\""+ file.fileAliyunUrl +"\">"); $("#vedioUrl").append(sourceDom); } }); if(vedioFlag==false){ $("#spbf").css("display","none"); } $.each(imgArr,function(i,img){ imgDiv += '<div style="text-align: center">' + '<a href="'+img+'" target="_blank">' + '<img class="shopImg" src="'+ img +'">' + '</a>' + '</div>'; }); $("#description_p").html(data.description); $("#price_p").html("¥"+data.price); $("#imgDiv").append(imgDiv); $("#gouwuche").attr("onclick","updateStatus("+data.id+")"); } //加入购物车 function updateStatus(id){ $.ajax({ type : "post", url : "../manageShow/addShopManage", data : {id:id,type:0,customerId:JSON.parse(window.localStorage.customer).id}, dataType : "json", async : false, success : function(data) { if (data.status=='000'){ $.alert("加入成功!"); }else{ $.alert("加入失败!"); } } }); } function comboAddShop(id){ $.confirm({ title: '加入购物车!', content: '是否加入购物车?', buttons: { '确定': function () { $.ajax({ type : "post", url : "../manageShow/addShopManage", data : {id:id,type:1,customerId:JSON.parse(window.localStorage.customer).id}, dataType : "json", async : false, success : function(data) { if (data.status=='000'){ $.alert("加入成功!"); }else{ $.alert("加入失败!"); } } }); }, '取消': function () { } } }); } $("#btn_exit").on("click", function() { var storage = window.localStorage; storage.clear();//清楚当前顾客信息。 window.location.href = "initPage"; }); $("#btn_delete").on("click", function() { $.confirm({ title: '清空购物车!', content: '是否清空购物车?', buttons: { '确定': function () { deleteShop(); }, '取消': function () { } } }); }); $("#btn_edit").on("click", function() { var selectRows=$table.bootstrapTable('getAllSelections'); if(selectRows==null||selectRows.length==0){ $.alert("请勾选一条数据!"); }else if(selectRows.length>1){ $.alert("只能勾选一条数据!"); }else{ $.ajax({ type : "post", url : "../manageShow/deleteShop", data : {customerId:JSON.parse(window.localStorage.customer).id,manageId:selectRows[0].manageId}, dataType : "json", async : false, success : function(data) { if (data.status=='000'){ $.alert("取消成功!"); $table.bootstrapTable('refresh'); }else{ $.alert("取消失败!"); } } }); } }); $("#btn_read").on("click", function() { var selectRows=$table.bootstrapTable('getAllSelections'); if(selectRows==null||selectRows.length==0) { $.alert("请勾选要计算总价的订单!"); return; } var prices = 0; var i=0; while(i<selectRows.length){ prices += Number(selectRows[i].price); i++; } $("#prices").html("总价为"+prices); }); function deleteShop(){ $.ajax({ type : "post", url : "../manageShow/deleteShop", data : {customerId:JSON.parse(window.localStorage.customer).id}, dataType : "json", async : false, success : function(data) { if (data.status=='000'){ window.localStorage.removeItem("customer");//清楚当前顾客信息。 $.alert("清空成功!"); $table.bootstrapTable('refresh'); }else{ $.alert("清空失败!"); } } }); } /*加载表格*/ var $table = $("#shopTable"); function loadtable(){ $table.bootstrapTable('destroy'); $table.bootstrapTable({ columns : [ { field : 'state', checkbox : true, align : 'center', valign : 'middle' },{ title: '序号',//标题 可不加 align : 'center', valign : 'middle', formatter: function (value, row, index) { return index + 1; } }, { title : '信息', field : 'fileType', align : 'center', valign : 'middle', formatter:function(value){ if(value==3){ return "套餐"; }else { return "信息"; } } }, { title : '信息类型', field : 'typeString', align : 'center', valign : 'middle', }, { title : '描述', field : 'description', align : 'center', valign : 'middle' }, { title : '价格', field : 'price', align : 'center', valign : 'middle' }, { title : '操作', field : 'status', align : 'center', valign : 'middle', events: shopEvents,//给按钮注册事件 formatter:function(value, row){ if (row.fileType==3){ return '<button type="button" class="btn btn-info" id="shopDetails" >查看详情</button>'; } else { return '<button type="button" class="btn btn-info" id="lookDetail" >查看详情</button>'; } } }], url : '../manageShow/shop', sidePagination : 'server', idField : "id", contentType:"application/x-www-form-urlencoded; charset=UTF-8", toolbar: '#toolbar', //工具按钮用哪个容器 striped: true, //是否显示行间隔色 cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: false, //是否显示分页(*) sortable: false, //是否启用排序 clickToSelect: true, //点击行选中 method: 'GET', //height: 550, pageNumber : 1, pageSize : 10, pageList : [10,20,50,100], showFooter : false, queryParamsType:'',/* queryParamsType的默认值为 'limit',在默认情况下传给服务端的参数为:offset,limit,sort设置为 '' 在这种情况下传给服务器的参数为:pageSize,pageNumber */ queryParams : function(params) { var storage = window.localStorage; var map = { pageNumber: params.pageNumber,//当前页码 pageSize: params.pageSize,//页面大小 customerId:JSON.parse(storage.customer).id }; $(".manage input,.manage select").each(function(){ if($(this).val()!=""){ map[""+$(this).attr('name')] = $(this).val(); } }); return map; }, }); } window.shopEvents = { "click #lookDetail" : function (e,value,row,index) { displayDetails(row.manageId); }, "click #shopDetails" : function (e,value,row,index) { $("#manageTable .del").remove(); $.ajax({ type : "get", url : "../combo/getComboById", data : {id:row.manageId}, async : false, success : function(data) { if (data.status=='000'){ $.each(data.data.manageShowList,function(i,manage){ addManage1(manage); }); }else{ $.alert("打开失败,请联系管理员!"); } } }); $("#manageModal").modal('show'); } } /*加载表格*/ var $comboTable = $("#comboTable"); function comboTable(){ $comboTable.bootstrapTable('destroy'); $comboTable.bootstrapTable({ columns : [ { title: '序号',//标题 可不加 align : 'center', valign : 'middle', formatter: function (value, row, index) { return index + 1; } }, { title : '标题', field : 'name', align : 'center', valign : 'middle', }, { title : '套餐描述', field : 'description', align : 'center', valign : 'middle' }, { title : '套餐价格', field : 'price', align : 'center', valign : 'middle' }, { title : '操作', field : 'status', align : 'center', valign : 'middle', events: operateEvents,//给按钮注册事件 formatter: addFunctionAlty,//表格中添加按钮 }], url : '../combo/list?enable=1', sidePagination : 'server', idField : "id", contentType:"application/x-www-form-urlencoded; charset=UTF-8", toolbar: '#toolbar', //工具按钮用哪个容器 striped: true, //是否显示行间隔色 cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: false, //是否显示分页(*) sortable: false, //是否启用排序 clickToSelect: true, //点击行选中 method: 'GET', //height: 550, pageNumber : 1, pageSize : 10, pageList : [10,20,50,100], showFooter : false, queryParamsType:'',/* queryParamsType的默认值为 'limit',在默认情况下传给服务端的参数为:offset,limit,sort设置为 '' 在这种情况下传给服务器的参数为:pageSize,pageNumber */ queryParams : function(params) { var map = { pageNumber: params.pageNumber,//当前页码 pageSize: params.pageSize,//页面大小 }; return map; }, }); } window.operateEvents = { "click #comboAddShop" : function (e,value,row,index) { comboAddShop(row.id); }, "click #lookDetails" : function (e,value,row,index) { $("#manageModal").modal('show'); $("#manageTable .del").remove(); $.each(row.manageShowList,function(i,manage){ addManage1(manage); }); } } function addManage1(row) { var strVar = '<tr class="del"><td>' + row.typeString + '</td><td>' + row.description + '</td><td>' + row.price + '</td>' + '<td><button type="button" class="btn btn-danger btn-block" onclick="delatils(' + row.id + ')">查看详情</button></td></tr>'; $("#manageTable").append(strVar); } function delatils(id) { $("#manageModal").modal('hide'); displayDetails(id); } function addFunctionAlty(value, row){ return '<button type="button" class="btn btn-info" id="comboAddShop" >加入购物车</button>' + '<button type="button" class="btn btn-info" id="lookDetails" >查看详情</button>'; }<file_sep>/src/main/java/com/ch/entity/Menu.java package com.ch.entity; import java.util.Date; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableField; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * * </p> * * @author caihao * @since 2019-08-06 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @ApiModel(value="Menu对象", description="") public class Menu implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "主键") @TableId("id") private Integer id; @ApiModelProperty(value = "父级菜单编号") @TableField("parent_number") private Integer parentNumber; @ApiModelProperty(value = "父级菜单名称") @TableField("parent_name") private String parentName; @ApiModelProperty(value = "子级菜单编号(顺序)") @TableField("son_order") private Integer sonOrder; @ApiModelProperty(value = "子级菜单名称") @TableField("son_name") private String sonName; @ApiModelProperty(value = "子级菜单链接") @TableField("son_rel") private String sonRel; @ApiModelProperty(value = "菜单图标") @TableField("menu_icon") private String menuIcon; @ApiModelProperty(value = "是否可用(0:不可用;1:可用)") @TableField("enable") private Integer enable; @ApiModelProperty(value = "创建时间") @TableField("create_time") private Date createTime; @ApiModelProperty(value = "创建人id") @TableField("create_id") private Integer createId; @ApiModelProperty(value = "修改时间") @TableField("update_time") private Date updateTime; @ApiModelProperty(value = "修改人id") @TableField("update_id") private Integer updateId; } <file_sep>/src/main/java/com/ch/entity/StudentInfo.java package com.ch.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import java.time.LocalDateTime; import com.baomidou.mybatisplus.annotation.TableField; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * * </p> * * @author caihao * @since 2019-07-10 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class StudentInfo implements Serializable { private static final long serialVersionUID = 1L; /** * 学号 */ @TableId(value = "student_id", type = IdType.AUTO) private Long studentId; /** * 学生姓名 */ @TableField("student_name") private String studentName; /** * 学生性别:0:男 、1:女 */ @TableField("student_sex") private Integer studentSex; /** * 学生家庭住址 */ @TableField("student_address") private String studentAddress; /** * 学生年龄 */ @TableField("student_age") private Integer studentAge; /** * 创建时间 */ @TableField("create_time") private LocalDateTime createTime; /** * 创建人 */ @TableField("create_user") private String createUser; } <file_sep>/src/main/java/com/ch/entity/Student.java package com.ch.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableField; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * * </p> * * @author caihao * @since 2019-08-05 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @AllArgsConstructor @ApiModel(value="Student对象", description="") public class Student implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "主键") @TableId("student_id") private Integer studentId; @ApiModelProperty(value = "学生姓名") @TableField("student_name") private String studentName; @ApiModelProperty(value = "和teacher表关联的条件") @TableField("p_id") private Integer relId; } <file_sep>/src/main/java/com/ch/test/strategy/Sub.java package com.ch.test.strategy; /** * @ClassName: Sub * @Description: 具体策略角色 ConcreteStrategy ,两个数做减法 * @Author: caihao * @Date: 2019/9/6 15:26 */ public class Sub implements MathStrategy{ @Override public int math(int a, int b) { return a - b; } } <file_sep>/src/test/java/com/ch/thread/MyContainer.java package com.ch.thread; import java.util.LinkedList; /** * @ClassName: MyContainer * @Description: wait 和 notify、notifyAll来写一个生产者消费值模型 * @Author: caihao * @Date: 2019/9/21 14:28 */ public class MyContainer { final private LinkedList list = new LinkedList(); final private int MAX = 10; private int count = 0; public synchronized void put(Object o){ while(list.size() == MAX){ try { this.wait();// 容器满了,生产者线程等待 } catch (InterruptedException e) { e.printStackTrace(); } } list.add(o); System.out.println(Thread.currentThread().getName()+"生产了一个产品"); count++; this.notifyAll();// 通知消费者消费 } public synchronized Object get(){ while (list.size() == 0){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Object o = list.removeFirst(); count --; this.notifyAll(); return o; } public static void main(String[] args) { MyContainer c = new MyContainer(); for(int i=0; i<10; i++){ new Thread(() -> System.out.println(c.get()), "c-"+i).start(); } for(int j=0; j<2; j++){ new Thread(() -> c.put(new Object()), "p-"+j).start(); } } } <file_sep>/src/main/java/com/ch/controller/UserInfoController.java package com.ch.controller; import com.ch.entity.UserInfo; import com.ch.enumTool.ErrorCodeAndMessage; import com.ch.exception.StudentException; import com.ch.service.IUserInfoService; import com.ch.utils.JsonResult; import com.ch.utils.MD5Utils; import com.ch.utils.ResultUtil; import com.ch.utils.ToolUtil; import com.google.gson.Gson; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; /** * <p> * 前端控制器 * </p> * value是不会在文档中显示的,没有什么意义,一般不用指定 * @author caihao * @since 2019-07-12 */ @Controller @Slf4j @Api(tags = {"用户操作接口"}) public class UserInfoController { @Autowired private IUserInfoService iUserInfoService; /** * 欢迎页 */ @ApiOperation(value = "欢迎请求controller", notes = "项目访问路径:http://localhost:8080/") @GetMapping("/") public String login(){ return "login"; } @GetMapping("/index") public String index(){ // 走后端跳转的目的在与走拦截器,验证session中有没有用户信息 return "main"; } /** *注册请求,跳转到注册页面 */ @GetMapping("/register") public String register(){ // 要排除拦截器拦截注册请求 return "register"; } /** * @Description 登陆请求 * @Author caihao * @Date 2019/7/16 14:53 * @Param [user] * @Return com.ch.utils.JsonResult * @ApiImplicitParam(paramType = "body", name = "user", value = "用户信息对象", required = true, dataType = "UserInfo") */ @PostMapping("/doLogin") @ResponseBody @ApiOperation(value = "根据用户输入的账号密码来判断是否正确,并成功跳转", notes = "备注信息...") @ApiResponses({ @ApiResponse(code=400,message="请求参数没填好"), @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对") }) public JsonResult<UserInfo> doLogin(@RequestBody @ApiParam(name = "userInfo", value = "user对象", required = true) UserInfo user){ JsonResult<UserInfo> jsonResult = new JsonResult<>(); String userPassword = user.getUserPassword(); if (userPassword != null) { user.setUserPassword(MD5Utils.MD5Encode(userPassword)); UserInfo userInfo = iUserInfoService.login(user); if(userInfo != null){ // 将用户信息添加到session中 ToolUtil.setLoginUser(userInfo); jsonResult.setRows(userInfo); } }else { throw new StudentException(ErrorCodeAndMessage.User_password_is_empty); } return jsonResult; } /** * @Description 修改密码 * @Author caihao * @Date 2019/7/17 15:03 * @Param [map] * @Return com.ch.utils.JsonResult */ @PostMapping("/modifyPw") @ResponseBody public JsonResult<UserInfo> modifyPw(@RequestParam Map map){ // 从session中获取用户信息 UserInfo loginUser = ToolUtil.getLoginUser(); if(null != map.get("oldPassword")){ loginUser.setUserPassword(MD5Utils.MD5Encode(map.get("oldPassword").toString())); UserInfo login = iUserInfoService.login(loginUser); if(login != null){ // 原密码和账号匹配,更新密码 loginUser.setUserPassword(MD5Utils.MD5Encode(map.get("newPassword").toString())); iUserInfoService.updateById(loginUser); // 修改密码后使session过期 ToolUtil.setLoginUser(null); }else { // 原密码和账号不匹配 throw new StudentException(ErrorCodeAndMessage.User_password_not_match); } }else { // 传进来的原密码为空 throw new StudentException(ErrorCodeAndMessage.User_password_is_empty); } // 根据用户名和原密码去查询 JsonResult jsonResult = new JsonResult(); return jsonResult; } /** * @Description 注册账号的后台请求 * @Author caihao * @Date 2019/7/17 17:37 * @Param [user] * @Return com.ch.utils.JsonResult */ @PostMapping("/doRegister") @ResponseBody public JsonResult<UserInfo> doRegister(UserInfo user){ // 查看注册的账号是否已经存在 List<UserInfo> list = iUserInfoService.selectAccount(user); if(list.size() > 0){ // 注册的账号已经存在 throw new StudentException(ErrorCodeAndMessage.User_account_is_exist); }else { // 将注册信息插入到用户表中 iUserInfoService.insert(user); } return ResultUtil.success(); } @GetMapping("/logout") @ResponseBody public JsonResult<UserInfo> logout(){ String account = ToolUtil.getLoginUser().getUserName(); ToolUtil.setLoginUser(null); log.info("账户:"+ account + "已退出登陆"); return ResultUtil.success(); } @GetMapping(value = "/hello/{id}/{flag}") @ResponseBody public String hello(@PathVariable("id") String id, @PathVariable("flag") String flag){ System.out.println("参数:flag=" + flag); System.out.println("参数:id=" + id); return "这是用 restTemplate 发送的第一个 get 请求"; } @PostMapping("/hello") @ResponseBody public JsonResult postHello(@RequestBody UserInfo user){ JsonResult jsonResult = ResultUtil.success(); Gson gson = new Gson(); String json = gson.toJson(user); System.out.println(json); return jsonResult; } } <file_sep>/src/main/java/com/ch/mapper/StudentInfoMapper.java package com.ch.mapper; import com.ch.entity.StudentInfo; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * <p> * Mapper 接口 * </p> * * @author caihao * @since 2019-07-10 */ public interface StudentInfoMapper extends BaseMapper<StudentInfo> { } <file_sep>/src/main/java/com/ch/test/strategy/Mulpi.java package com.ch.test.strategy; /** * @ClassName: Mulpi * @Description: 具体策略角色 ConcreteStrategy ,两个数做乘法运算 * @Author: caihao * @Date: 2019/9/6 15:27 */ public class Mulpi implements MathStrategy { @Override public int math(int a, int b) { return a * b; } } <file_sep>/src/test/java/com/ch/RedisTest.java package com.ch; import com.fasterxml.jackson.core.JsonProcessingException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.test.context.junit4.SpringRunner; /** * @ClassName: RedisTest * @Description: redis的测试类 * @Author: caihao * @Date: 2019/7/27 20:37 */ @RunWith(SpringRunner.class) @SpringBootTest public class RedisTest { // <Object, Object> 键值都为对象类型 @Autowired RedisTemplate redisTemplate; // <String, String> 键值都为String类型的 @Autowired StringRedisTemplate stringRedisTemplate; /** * @Description 测试 StringRedisTemplate 操作 * @Author caihao * @Date 2019/7/27 21:13 * @Param [] * @Return void */ @Test public void test01(){ //stringRedisTemplate.opsForValue().set("redis", "hello"); stringRedisTemplate.opsForValue().append("redis", " world!"); //stringRedisTemplate.delete("redis");//删除key } /** * @Description 测试 redisTemplate 操作 * @Author caihao * @Date 2019/7/30 14:16 * @Param [] * @Return void */ @Test public void test02() throws JsonProcessingException { //UserInfo user = new UserInfo(5l,"蔡浩", MD5Utils.MD5Encode("0926"), "2019-7-30", null); /*user.setUserId(5L); user.setUserName("蔡浩"); user.setUserPassword("<PASSWORD>"); user.setCreateTime("2019-7-30");*/ //redisTemplate.opsForValue().set("user", user); Object user = redisTemplate.opsForValue().get("user"); System.out.println(user); } } <file_sep>/src/main/java/com/ch/service/impl/StudentInfoServiceImpl.java package com.ch.service.impl; import com.ch.entity.StudentInfo; import com.ch.mapper.StudentInfoMapper; import com.ch.service.IStudentInfoService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author caihao * @since 2019-07-10 */ @Service public class StudentInfoServiceImpl extends ServiceImpl<StudentInfoMapper, StudentInfo> implements IStudentInfoService { @Autowired private StudentInfoMapper mapper; @Override public StudentInfo selectById(StudentInfo studentInfo) { return mapper.selectById(studentInfo.getStudentId()); } } <file_sep>/src/test/java/com/ch/thread/ThreadTest3.java package com.ch.thread; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * @ClassName: ThreadTest3 * @Description: * @Author: caihao * @Date: 2019/9/20 11:34 */ public class ThreadTest3 { /*volatile*/ List lists = new ArrayList(); public void add(Object object){ lists.add(object); } public int size(){ return lists.size(); } public static void main(String[] args) { ThreadTest3 test3 = new ThreadTest3(); final Object o = new Object(); new Thread(() -> { synchronized (o){ System.out.println("thread-2 启动"); if(test3.size() != 5){ try { o.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("thread-2 结束"); o.notify(); } }, "thread-2").start(); new Thread(() -> { System.out.println("thread-1 启动"); synchronized (o){ for(int i=0; i<10; i++){ test3.add(new Object()); System.out.println("add:"+i); if(test3.size() == 5){ o.notify(); try { o.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }, "thread-1").start(); } } <file_sep>/src/main/java/com/ch/test/strategy/Calculator.java package com.ch.test.strategy; /** * @Description 策略枚举 * @Author caihao * @Date 2019/9/6 15:44 * @Param * @Return */ public enum Calculator { ADD("+"){ @Override public int math(int a, int b) { return a + b; } }, SUB("-"){ @Override public int math(int a, int b) { return a - b; } }, MULTI("×"){ @Override public int math(int a, int b) { return a * b; } }, DEVISED("÷"){ @Override public int math(int a, int b) { return a / b; } }; private String symbol; Calculator(String symbol) { this.symbol = symbol; } public String getSymbol() { return symbol; } public abstract int math(int a, int b); } <file_sep>/src/main/java/com/ch/entity/UserInfo.java package com.ch.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableField; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.*; import lombok.experimental.Accessors; /** * <p> * * </p> * * @author caihao * @since 2019-07-12 */ @Data //@AllArgsConstructor // 带全部参数的有参构造方法(不判断参数的值是为为null) //@RequiredArgsConstructor @ApiModel("用户信息类") public class UserInfo implements Serializable { private static final long serialVersionUID = 1L; /** * 主键(mybatis插入数据的时候,会根据字段类型的长度来产生一个值,我刚开始设置的是50长度,就产生了一个long类型的值,导致用integer接收不了报错) */ @ApiModelProperty("用户主键") @TableId("user_id") private Long userId; /** * 登录名 */ @ApiModelProperty("用户姓名") @TableField("user_name") private String userName; /** * 用户密码 */ @ApiModelProperty("用户密码") @TableField("user_password") private String userPassword; /** * 创建时间 */ @ApiModelProperty("创建时间") @TableField("create_time") private String createTime; /** * 修改时间 */ @ApiModelProperty("修改时间") @TableField("modify_time") private String modifyTime; } <file_sep>/src/main/java/com/ch/test/proxy/ClothFactory.java package com.ch.test.proxy; /** * @ClassName: ClothFactory * @Description: * @Author: caihao * @Date: 2019/9/3 16:31 */ public interface ClothFactory { /** * 生产衣服方法 */ void produceCloth(); } <file_sep>/src/main/java/com/ch/config/RedisConfig.java package com.ch.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.time.Duration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @ClassName: RedisConfig * @Description: redis配置类 * @Author: caihao * @Date: 2019/7/27 20:56 */ @Configuration //@EnableCaching 这里的@EnableCaching项目的主启动类中已经配置了,所以这里不用这个注解可以开启缓存 public class RedisConfig { // 默认的缓存过期时间 @Value("${cache.default.expire-time}") private int defaultExpireTime; // cacheName为“test”的缓存过期时间 @Value("${cache.test.expire-time}") private int testExpireTime; @Value("${cache.test.name}") private String testCacheName; // cacheName为“user”的缓存过期时间 @Value("${cache.user.expire-time}") private int userExpireTime; @Value("${cache.user.name}") private String userCacheName; //缓存管理器 @Bean public CacheManager cacheManager(RedisConnectionFactory lettuceConnectionFactory) { RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig(); // 设置缓存管理器管理的缓存的默认过期时间 defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(defaultExpireTime)) // 设置 key为string序列化 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 设置value为json序列化 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) // 不缓存空值 .disableCachingNullValues(); Set<String> cacheNames = new HashSet<>(); cacheNames.add(testCacheName); cacheNames.add(userCacheName); // 对每个缓存空间应用不同的配置 Map<String, RedisCacheConfiguration> configMap = new HashMap<>(); // 设置缓存管理器管理的缓存的默认过期时间(这里单指的是项目中已经配置的cacheName为“test”和“user”的缓存) configMap.put(testCacheName, defaultCacheConfig.entryTtl(Duration.ofSeconds(testExpireTime))); configMap.put(userCacheName,defaultCacheConfig.entryTtl(Duration.ofSeconds(userExpireTime))); RedisCacheManager cacheManager = RedisCacheManager.builder(lettuceConnectionFactory) .cacheDefaults(defaultCacheConfig) .initialCacheNames(cacheNames) .withInitialCacheConfigurations(configMap) .build(); return cacheManager; } } <file_sep>/src/main/java/com/ch/mapper/StudentMapper.java package com.ch.mapper; import com.ch.entity.Student; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author caihao * @since 2019-08-05 */ public interface StudentMapper extends BaseMapper<Student> { } <file_sep>/src/main/java/com/ch/controller/StudentInfoController.java package com.ch.controller; import com.ch.entity.StudentInfo; import com.ch.enumTool.ErrorCodeAndMessage; import com.ch.exception.StudentException; import com.ch.service.IStudentInfoService; import com.ch.utils.JsonResult; import lombok.extern.slf4j.Slf4j; 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.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; /** * <p> * 前端控制器 * </p> * * @author caihao * @since 2019-07-10 */ @RestController @RequestMapping("/student-info") @Slf4j public class StudentInfoController { @Autowired private IStudentInfoService iStudentInfoService; /** * @Description 保存学生信息 * @Author caihao * @Date 2019/7/10 16:38 * @Param [studentInfo] * @Return void */ @PostMapping("/save") public void save(StudentInfo studentInfo){ iStudentInfoService.save(studentInfo); } @PostMapping("selectById") public JsonResult<StudentInfo> selectById(StudentInfo studentInfo){ try { log.info("get student information by id:{}", studentInfo.getStudentId()); if(null == studentInfo.getStudentId()){ throw new StudentException(ErrorCodeAndMessage.Student_id_is_empty); } if(8 != studentInfo.getStudentId().toString().length()){ throw new StudentException(ErrorCodeAndMessage.student_id_insufficient); } StudentInfo student = iStudentInfoService.selectById(studentInfo); if(null == student){ throw new StudentException(ErrorCodeAndMessage.Student_id_not_exist); } return new JsonResult<>(student); } catch (StudentException e) { if(e instanceof StudentException){ throw e; }else { log.error("select by id error:{}", e); throw new StudentException(ErrorCodeAndMessage.Network_error); } } } @GetMapping("/test") public String test(HttpServletRequest request){ return "123"; } } <file_sep>/src/main/java/com/ch/exception/ExceptionHandler.java package com.ch.exception; import com.ch.enumTool.ErrorCodeAndMessage; import com.ch.utils.JsonResult; import com.ch.utils.ResultUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.BindException; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; /** * @ClassName: ExceptionHandler * @Description: 统一异常处理类 * @Author: caihao * @Date: 2019/7/10 15:58 */ @ControllerAdvice @Slf4j public class ExceptionHandler { @org.springframework.web.bind.annotation.ExceptionHandler(value = {StudentException.class}) @ResponseBody public JsonResult handleStudentException(HttpServletRequest request, StudentException ex){ JsonResult jsonResult; log.error("StudentException code:{}, msg{}", ex.getErrorCodeAndMessage().getCode(), ex.getErrorCodeAndMessage().getMsg()); jsonResult = new JsonResult(ex.getErrorCodeAndMessage().getCode(), ex.getErrorCodeAndMessage().getMsg()); return jsonResult; } @org.springframework.web.bind.annotation.ExceptionHandler(value = {Exception.class}) @ResponseBody public JsonResult handleException(HttpServletRequest request, Exception ex){ JsonResult jsonResult = null; log.error("Exception error:{}", ex); if(ex instanceof BindException){ List errList = new ArrayList(); BindException bindException = (BindException)ex; List<ObjectError> errors = bindException.getAllErrors(); for (ObjectError error : errors) { errList.add(error.getDefaultMessage()); } jsonResult = ResultUtil.error(errList); jsonResult.setCode("0007"); jsonResult.setMsg("实体参数校验不通过"); }else { jsonResult = new JsonResult(ErrorCodeAndMessage.Network_error.getCode(), ErrorCodeAndMessage.Network_error.getMsg()); } return jsonResult; } } <file_sep>/src/main/java/com/ch/service/StudentService.java package com.ch.service; import com.ch.entity.Student; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 服务类 * </p> * * @author caihao * @since 2019-08-05 */ public interface StudentService extends IService<Student> { } <file_sep>/src/test/java/com/ch/ChApplicationTests.java package com.ch; import com.ch.entity.UserInfo; import com.ch.utils.JsonResult; import com.google.gson.Gson; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; @RunWith(SpringRunner.class) @SpringBootTest public class ChApplicationTests { @Test public void contextLoads() { int[] intArray = {1, 2, 3}; List<int[]> ints = Arrays.asList(intArray); //ints.add("hello"); // java.lang.UnsupportedOperationException //ints.remove(2); // java.lang.UnsupportedOperationException //ints.clear(); // java.lang.UnsupportedOperationException } @Test public void test(){ int[] intArray = {1, 2, 3}; List list = new ArrayList(Arrays.asList(intArray)); // 不报错 list.add(4); list.remove(1); list.clear(); } @Test public void test1(){ Integer[] intArray = {1, 2, 3}; List list = Arrays.stream(intArray).collect(Collectors.toList()); // 不报错 list.add(4); list.remove(1); list.clear(); } @Test public void test2(){ String a = new String("123"); String b = new String("123"); System.out.println(a == b); System.out.println(a.equals(b)); String c = "123"; String d = "123"; System.out.println(c == d); System.out.println(c.equals(d)); } @Test public void test3(){ String str1 = "aaa"; String str2 = "bbb"; String str3 = "aaabbb"; String str4 = str1 + str2; String str5 = "aaa" + "bbb"; System.out.println(str3 == str4); // false System.out.println(str3 == str4.intern()); // true System.out.println(str3 == str5);// true } @Test public void getHttp() throws UnsupportedEncodingException { // 获取rest客户端对象 RestTemplate restTemplate = new RestTemplate(); // 解决(响应数据中可能出现的)中文乱码问题 List<HttpMessageConverter<?>> convertersList = restTemplate.getMessageConverters(); // 移出原来的转化器 convertersList.remove(1); // 设置字符编码为UTF-8 HttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8); // 添加新的转换器(convert顺序错误会导致失败) convertersList.add(1, converter); restTemplate.setMessageConverters(convertersList); // 请求头信息 // HttpHeaders实现了MultiValueMap接口 HttpHeaders headers = new HttpHeaders(); // 给请求header中添加一些数据 headers.add("ch", "哈哈哈"); // 注:GET请求 创建HttpEntity时,请求体传入null即可 // 请求体的类型任选即可;只要保证 请求体 的类型与HttpEntity类的泛型保持一致即可 String httpBody = null; HttpEntity<String> httpEntity = new HttpEntity<String>(httpBody, headers); // 设置 URI 地址 StringBuffer paramURI = new StringBuffer("http://127.0.0.1:8080/hello"); // 字符数据最好encoding一下;这样一来,某些特殊字符才能传过去(如:flag的参数值就是“&”,不encoding的话,传不过去) paramURI.append("/" + URLEncoder.encode("哈哈哈", "utf-8")); paramURI.append("/" + URLEncoder.encode("是", "utf-8")); URI uri = URI.create(paramURI.toString()); // 执行请求并返回响应的结果 // 此处的泛型对应响应体数据类型;即:这里指定响应体的数据装配为String ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class); // 状态码 System.out.println(response.getStatusCode()); System.out.println(response.getHeaders()); System.out.println(response.getBody()); System.out.println("========================================"); Gson gson = new Gson(); String s = gson.toJson(response.getHeaders()); String s1 = gson.toJson(response.getBody()); System.out.println("响应头: "+s); System.out.println("响应体: "+s1); } @Test public void postHttp() throws UnsupportedEncodingException { // 获取rest客户端对象 RestTemplate restTemplate = new RestTemplate(); // 解决(响应数据中可能出现的)中文乱码问题 List<HttpMessageConverter<?>> convertersList = restTemplate.getMessageConverters(); // 移出原来的转化器 convertersList.remove(1); // 设置字符编码为UTF-8 HttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8); // 添加新的转换器(convert顺序错误会导致失败) convertersList.add(1, converter); restTemplate.setMessageConverters(convertersList); // 请求头信息 // HttpHeaders实现了MultiValueMap接口 HttpHeaders headers = new HttpHeaders(); // 给请求header中添加一些数据 headers.add("ch", "哈哈哈"); // post请求:请求体的类型任选即可,只要保证请求体的类型与HttpEntity类的泛型保持一致即可 Gson gson = new Gson(); UserInfo userInfo = new UserInfo(); userInfo.setUserId(10l); userInfo.setUserName("哈哈"); userInfo.setUserPassword("<PASSWORD>"); HttpEntity<UserInfo> httpEntity = new HttpEntity<UserInfo>(userInfo, headers); // 设置 URI 地址 StringBuffer paramURI = new StringBuffer("http://127.0.0.1:8080/hello"); // 字符数据最好encoding一下;这样一来,某些特殊字符才能传过去(如:flag的参数值就是“&”,不encoding的话,传不过去) /*String json = gson.toJson(userInfo); paramURI.append("/"+URLEncoder.encode(json, "utf-8"));*/ URI uri = URI.create(paramURI.toString()); // 执行请求并返回响应的结果 // 此处的泛型对应响应体数据类型;即:这里指定响应体的数据装配为String ResponseEntity<JsonResult> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, JsonResult.class); // 状态码 System.out.println(response.getStatusCode()); System.out.println(response.getHeaders()); System.out.println(response.getBody()); System.out.println("========================================"); String s = gson.toJson(response.getHeaders()); String s1 = gson.toJson(response.getBody()); System.out.println("响应头: "+s); System.out.println("响应体: "+s1); } @Test public void test05(){ List<String> list = new ArrayList<>(); list.add("张三"); list.add("李四"); list.add("王五"); list.add("赵六"); String reomveName = "赵六"; /*for (String s : list) { if(reomveName.equals(s)){ // for循环在编译的时候,会被默认的编译成遍历器,这里调用的是list的remove()方法,源码中会验证checkForComodification(); list.remove(s); } }*/ Iterator<String> it = list.iterator(); while (it.hasNext()){ String next = it.next(); if(reomveName.equals(next)){ it.remove(); } } System.out.println(list); } } <file_sep>/src/main/java/com/ch/test/builder/BuilderTest.java package com.ch.test.builder; import lombok.Data; /** * @ClassName: BuilderTest * @Description: 构建者模式测试类 * @Author: caihao * @Date: 2019/9/4 11:02 */ public class BuilderTest { public static void main(String[] args) { BuilderInterface builder = new ComputerBuilder(); Director director = new Director(); director.construct(builder); Computer computer = builder.getComputer(); System.out.println(computer); } } /** * Builder 构建者接口 */ interface BuilderInterface{ /** * 组装cpu */ void buildCpu(); /** * 组装主板 */ void buildMainBoard(); /** * 组装内存 */ void buildMemory(); /** * 组装硬盘 */ void buildDesk(); /** * 组装电源 */ void buildPower(); /** * @Description 获取Computer成品 * @Author caihao * @Date 2019/9/4 11:16 * @Param [] * @Return com.ch.test.builder.Computer */ Computer getComputer(); } /** * 具体构建者类 */ class ComputerBuilder implements BuilderInterface{ private Computer computer = new Computer(); @Override public void buildCpu() { computer.setCpu("组装 inter 酷睿 i7 处理器"); } @Override public void buildMainBoard() { computer.setMainBoard("组装大型主板"); } @Override public void buildMemory() { computer.setMemory("组装16G内存"); } @Override public void buildDesk() { computer.setDesk("组装 1T 固态硬盘"); } @Override public void buildPower() { computer.setPower("组装三星电源"); } @Override public Computer getComputer() { return computer; } } /** * 成品类 */ @Data class Computer{ public String cpu; public String mainBoard; public String memory; public String desk; public String power; } /** * 组装类 */ class Director{ public void construct(BuilderInterface bulider){ bulider.buildCpu(); bulider.buildMainBoard(); bulider.buildMemory(); bulider.buildDesk(); bulider.buildPower(); } } <file_sep>/src/test/java/com/ch/lambda/StrategyInterface.java package com.ch.lambda; import com.ch.entity.Student; /** * @Description 策略接口 * @FunctionalInterface 用来验证该接口是否是函数式接口(只有一个方法的接口) * @Author caihao * @Date 2019/9/6 8:48 * @Param * @Return */ @FunctionalInterface public interface StrategyInterface { /** * 按照策略来过滤 */ boolean strategy(Student student); } <file_sep>/src/main/resources/static/asset/js/companyInfo.js //初始化fileinput var ImgInput = function () { var oFile = new Object(); //初始化fileinput控件(第一次初始化) oFile.Init = function(ctrlName) { var control = $('#' + ctrlName); //初始化上传控件的样式 control.fileinput({ language: 'zh', //设置语言 uploadUrl: "", //上传的地址。如果设置了,附件框也会出现上传标记。 allowedFileExtensions: ['jpg', 'png','bmp'],//接收的文件后缀 showUpload: false, //是否显示上传按钮 showRemove: true,//是否显示移除按钮 showCaption: true,//是否文字表述 browseClass: "btn btn-primary", //按钮样式 dropZoneEnabled: false,//是否显示拖拽区域 uploadAsync: false,//同步上传 maxFileCount:1, //表示允许同时上传的最大文件个数 enctype: 'multipart/form-data', validateInitialCount:true, previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!", overwriteInitial: true,//覆盖已存在的图片 initialPreviewAsData: true, initialPreview: imgArr, initialPreviewConfig: [ {caption: "",width: "120px", url: "company/deletePicture"} ], layoutTemplates:{ actionUpload:'', //设置为空可去掉上传按钮 actionDelete:'' //设置为空可去掉删除按钮 } }).on('filepredelete', function(event, key, jqXHR, data) { //点击删除触发事件。 }); }; return oFile; }; <file_sep>/src/test/java/com/ch/LambdaTest.java package com.ch; import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer; import com.ch.entity.Student; import com.ch.entity.StudentInfo; import org.junit.Test; import java.io.PrintStream; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.function.*; /** * @ClassName: LambdaTest * @Description: 四大内置核心函数接口 * @Author: caihao * @Date: 2019/9/6 22:09 */ public class LambdaTest { /** * 消费型接口 * Consumer<T>{ * void accept(T t); * } * * 供给型接口 * Supplier<T>{ * T get(); * } * * 函数型接口 * Function<T, R>{ * R apply(T t); * } * * 断言型接口 * Predicate<T>{ * boolean test(T t); * } * */ @Test public void test1(){ // 测试消费型接口 Consumer<T> useMoney(1000d, (m) -> System.out.println("周末出门花费了"+m+"元")); } public void useMoney(double money, Consumer<Double> con){ con.accept(money); } @Test public void test2(){ // 测试供给型接口 Supplier<T> // 产生指定个数的整数,并放入集合中 List<Integer> list = getNumList(10, () -> (int)(Math.random() * 100)); list.forEach(System.out::println); } public List<Integer> getNumList(int a, Supplier<Integer> sup){ List<Integer> list = new ArrayList<>(); for (int i = 0; i < a; i++){ list.add(sup.get()); } return list; } @Test public void test3(){ // 测试函数型接口 Function<T, R> // 需求:操作字符串,去除首尾或者截取 String s1 = strOperate(" hahha 去除首尾空格 ", (s) -> s.trim()); System.out.println(s1); String s2 = strOperate(" hahha 去除首尾空格 ", (s) -> s.toUpperCase()); System.out.println(s2); } public String strOperate(String str, Function<String, String> fun){ return fun.apply(str); } @Test public void test4(){ // 测试断言型接口 Predicate<T> // 需求:满足条件的字符串放入到集合中去 List<String> list = Arrays.asList("哈哈", "嘻嘻嘻", "则啧啧啧", "啊啊啊啊啊", "abcde"); List<String> list1 = filterStr(list, (s) -> s.length() > 3); list1.forEach(System.out::println); System.out.println("---------------------------------"); List<String> list2 = filterStr(list, (s) -> s.contains("abc")); list2.forEach(System.out::println); /*LocalDateTime localDateTime = LocalDateTime.of(2019, 12, 21, 19, 30, 59); System.out.println(localDateTime); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm:ss"); String format = localDateTime.format(dateTimeFormatter); System.out.println(format);*/ } public List<String> filterStr(List<String> list, Predicate<String> pre){ List<String> valueList = new ArrayList<>(); for (String s : list) { if(pre.test(s)){ valueList.add(s); } } return valueList; } /** * 方法的引用 * 1.对象::实例方法 * 2.类::静态方法 * 3.类::实例方法 */ @Test public void test5(){ // 对象::实例方法 // Lambda 表达式 Consumer<String> con1 = (x) -> System.out.println(x); con1.accept("hello Lambda!"); System.out.println("======================="); // Lambda 方法引用 PrintStream ps = System.out; Consumer<String> con2 = ps::println; con2.accept("hello Lambda 方法引用"); System.out.println("======================="); // 更加简化一步 Consumer<String> con3 = System.out::println; con3.accept("这是简化后最终的 Lambda 方法引用"); System.out.println("======================="); // 普通的 Lambda 表达式 StudentInfo student = new StudentInfo(); student.setStudentAge(18); student.setStudentName("蔡浩"); Supplier<Integer> sup = () -> student.getStudentAge(); System.out.println(sup.get()); System.out.println("======================="); // 对象::实例方法 Supplier<Integer> sup1 = student::getStudentAge; System.out.println(sup1.get()); Supplier<String> sup2 = student::getStudentName; System.out.println(sup2.get()); } @Test public void test6(){ // 普通 Lambda 表达式 Comparator<Integer> com = (x, y) -> Integer.compare(x, y); int result = com.compare(1, 2); System.out.println(result); System.out.println("======================="); // 类::静态方法 Comparator<Integer> com1 = Integer::compare; int result1 = com1.compare(100, 10); System.out.println(result1); } /** * 构造方法的引用 * 类名::new * */ @Test public void test7(){ // 普通的 Lambda 表达式 Supplier<StudentInfo> sup = () -> new StudentInfo(); StudentInfo studentInfo = sup.get(); System.out.println(studentInfo); System.out.println("======================="); // 类名::new Supplier<StudentInfo> sup1 = StudentInfo::new; StudentInfo studentInfo1 = sup1.get(); System.out.println(studentInfo1); } } <file_sep>/src/main/java/com/ch/test/proxy/StaticProxy.java package com.ch.test.proxy; /** * @ClassName: StaticProxy * @Description: 代理类(静态代理) * @Author: caihao * @Date: 2019/9/3 15:34 */ public class StaticProxy implements ClothFactory{ private ClothFactory clothFactory; public StaticProxy(ClothFactory clothFactory){ this.clothFactory = clothFactory; } @Override public void produceCloth() { System.out.println("代理类开始收取代理费用1000$"); clothFactory.produceCloth(); } } <file_sep>/src/main/java/com/ch/utils/ResultUtil.java package com.ch.utils; import com.ch.enumTool.ErrorCodeAndMessage; import java.util.List; /** * @ClassName: ResultUtil * @Description: 封装返回值的操作方法 * @Author: caihao * @Date: 2019/7/16 16:43 */ public class ResultUtil { /** * @Description 返回数据用对象封装 * @Author caihao * @Date 2019/7/16 17:23 * @Param [object] * @Return com.ch.utils.JsonResult */ public static JsonResult success(Object object){ JsonResult jsonResult = new JsonResult(); jsonResult.setRows(object); return jsonResult; } public static JsonResult success(){ return success(null); } /** * @Description 返回数据用list封装 * @Author caihao * @Date 2019/7/16 17:24 * @Param [list, total] * @Return com.ch.utils.JsonResult */ public static JsonResult successList(List list, long total){ JsonResult jsonResult = new JsonResult(); jsonResult.setRows(list); jsonResult.setTotal(total); return jsonResult; } public static JsonResult successList(){ return successList(null, 0L); } public static JsonResult error(List error){ return new JsonResult(error); } } <file_sep>/src/main/java/com/ch/test/strategy/Division.java package com.ch.test.strategy; /** * @ClassName: Division * @Description: 具体策略角色 ConcreteStrategy ,两个数做除法运算 * @Author: caihao * @Date: 2019/9/6 15:29 */ public class Division implements MathStrategy{ @Override public int math(int a, int b) { return a / b; } } <file_sep>/src/main/java/com/ch/mapper/UserInfoMapper.java package com.ch.mapper; import com.ch.entity.UserInfo; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import java.util.List; /** * <p> * Mapper 接口 * </p> * * @author caihao * @since 2019-07-12 */ public interface UserInfoMapper extends BaseMapper<UserInfo> { UserInfo login(UserInfo user); List<UserInfo> selectAccount(UserInfo map); void insertAccount(UserInfo user); } <file_sep>/src/main/java/com/ch/test/strategy/StrategyTest.java package com.ch.test.strategy; /** * @ClassName: StrategyTest * @Description: 策略模式测试类(客户端) * @Author: caihao * @Date: 2019/9/6 15:37 */ public class StrategyTest { public static void main(String[] args) { // 选择一个具体策略 // 客户端与具体策略类耦合了,而上下文环境在这里其的作用只是负责调度执行, // 获取结果,并没有完全起到隔离客户端与策略类的作用。 // 一般可以通过简单工厂模式将具体策略的创建与客户端进行隔离,或者是通过 策略枚举 将上下文环境与具体策略类融合在一起,简化代码。 // 当具体策略相对稳定时,推荐使用 策略枚举 简化代码 MathStrategy mathStrategy = new Add(); // 创建一个上下文 Context context = new Context(mathStrategy); // 调用 Context 中的方法 int value = context.math(1, 2); System.out.println(value); // 使用策略枚举来接触客户端和具体策略类的耦合 int sub = Calculator.SUB.math(1, 2); System.out.println(sub); int devised = Calculator.DEVISED.math(1, 2); System.out.println(devised); // 一个类型转换的问题 int a = 1; int b = 2; // double c = a / b; // int c = a / b; // 存在一个类型转换问题,两个int类型的值运算后结果为int类型,计算后0.5,int类型转换成double类型取整数部分0,小数部分丢掉,所以追中结果为0 double c = (double) a / b; System.out.println(c); } } <file_sep>/src/main/java/com/ch/config/MyConfig.java package com.ch.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @ClassName: MyConfig * @Description: 配置类 * @Author: caihao * @Date: 2019/6/25 18:46 */ @Configuration public class MyConfig implements WebMvcConfigurer { } <file_sep>/src/main/java/com/ch/config/JsrValidAspect.java package com.ch.config; import com.ch.utils.JsonResult; import com.ch.utils.ResultUtil; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @ClassName: JsrValidAspect * @Description: JSR303 校验实体类抛出异常的切面 * @Author: caihao * @Date: 2019/8/8 14:24 */ //@Aspect //@Component public class JsrValidAspect { /** * @Description 指定切点 * @Author caihao * @Date 2019/8/8 14:51 * @Param [bindingResult] * @Return com.ch.utils.JsonResult */ @Pointcut("execution(public * com.ch.controller.*.*(..))") public void pointCut(){ } @Around(value = "pointCut()") public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint){ Object obj = null; try { obj = proceedingJoinPoint.proceed(); //可以加参数 Object[] args = proceedingJoinPoint.getArgs(); for (Object arg : args) { if(arg instanceof BindingResult){ if(((BindingResult) arg).hasErrors()){ List<ObjectError> errorList = ((BindingResult) arg).getAllErrors(); List<String> mesList = new ArrayList<String>(); for (int i = 0; i < errorList.size(); i++) { mesList.add(errorList.get(i).getDefaultMessage()); } obj = ResultUtil.error(mesList); } } } } catch (Throwable throwable) { throwable.printStackTrace(); } return obj; } } <file_sep>/src/main/java/com/ch/test/Test01.java package com.ch.test; /** * @ClassName: Test * @Description: * @Author: caihao * @Date: 2019/7/1 19:21 */ public class Test01 { public static void main(String[] args) { // switch中表达式的值可以为整型,字节类型,字符串类型,但是为字符串类型的时候不可以为空 // 同样的case中的值也不可以为null String a = "12"; switch (a){ case "12": System.out.println("匹配到值12"); break; case "34": System.out.println("匹配到值34"); break; /* case null: System.out.println("匹配到值null"); break;*/ } } }
52510204f03dbf8541a460f5f69c9e0806505345
[ "JavaScript", "Java" ]
33
JavaScript
bugger-caihao/ch
bd6668b1de30d3000cf16affa1fbf88fbd255859
e6cc662dccedf421cd752fe58a83a46542cd90cc
refs/heads/master
<repo_name>SavKS/liquor-tree<file_sep>/webpack.config.js const { VueLoaderPlugin } = require('vue-loader'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const base = mode => ({ mode, devtool: mode === 'development' ? 'source-map' : false, entry: { main: { import: './src/main.js', filename: `main.${ mode === 'production' ? 'prod' : 'dev' }.js` } }, output: { libraryTarget: 'umd' }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { js: [ { loader: 'babel-loader', exclude: [ /node_modules/ ] } ] } } }, { test: /\.js$/, loader: 'babel-loader', exclude: [ /node_modules/ ] }, { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, 'css-loader' ] } ] }, plugins: [ new VueLoaderPlugin(), new MiniCssExtractPlugin({ filename: `main.${ mode === 'development' ? 'dev' : 'prod' }.css` }) ], externals: { 'vue': { commonjs: 'vue', commonjs2: 'vue' } }, resolve: { extensions: [ '.js', '.ts', '.vue' ] } }); module.exports = [ base('production'), base('development') ];
267114b8995354da97897c57fbd88302598c16c5
[ "JavaScript" ]
1
JavaScript
SavKS/liquor-tree
012eb6cd74a4707cb44e48f09391b707c0aaedd8
a780c17f83d256c3d75b3889722688989c74bfb0
refs/heads/master
<repo_name>jnelson1010/py-fun<file_sep>/.ipynb_checkpoints/Beginner Excercises-checkpoint.py { "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# practice python beginner excercises" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Jason, You will be 100 in the year 2081. \n", "Jason, You will be 100 in the year 2081. \n", "Jason, You will be 100 in the year 2081. \n", "Jason, You will be 100 in the year 2081. \n" ] } ], "source": [ "# Excercise #1\n", "name = input('What is your name? ')\n", "age = int(input('What is your age? '))\n", "answer = (100 - age + 2018)\n", "message = int(input('How many times would you like to see this message? '))\n", "print(('\\n' '' + name + ', You will be 100 in the year ' + str(answer) + '. ')* message)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }
ef2f4f72cd5a0c169a1d4a180907702dc4004941
[ "Python" ]
1
Python
jnelson1010/py-fun
24e4654b8199b41b4460a3ce74c4241bb49cbb75
43b94c9f358463d5e0b5eedf69957085ea56d6fd
refs/heads/master
<repo_name>likeaboy/snaptoy<file_sep>/src/main/java/com/rocky/snaptoy/multithread/pcm/Model.java package com.rocky.snaptoy.multithread.pcm; import java.util.Random; public class Model { private int id; private String name; private String desc; private Random random = new Random(); private String[] names = {"John","Haaf","Peter","Jim","Tom"}; private String[] secrets = {"mmksdfkfd","adbbbbbkbkk","ppppppppppp"}; public Model(){ build(); } private void build(){ this.id = Math.abs(random.nextInt()%1000); this.name = names[id%5] + id%2; this.desc = secrets[id%3] + id%3; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } @Override public String toString() { return "[id=" + this.id + "name=" + this.name + "desc=" + this.desc + "]"; } } <file_sep>/src/main/java/com/rocky/snaptoy/multithread/abc/Main.java package com.rocky.snaptoy.multithread.abc; public class Main { public static void main(String[] args) { Thread a = new Thread(new ABCThread(1)); a.setName("ThreadA"); a.start(); Thread b = new Thread(new ABCThread(2)); b.setName("ThreadB"); b.start(); Thread c = new Thread(new ABCThread(3)); c.setName("ThreadC"); c.start(); } } class ABCThread implements Runnable{ private int type = 0; private int count = 10; public ABCThread(int type){ this.type = type; } public void run() { while(count > 0){ switch(type){ case 1: System.out.print("A"); break; case 2: System.out.print("B"); break; case 3: System.out.print("C"); break; } count --; } } } <file_sep>/README.md # test sdfsdfs ssdfsdfdsf
7292aea61a0b9f2cef3e7b3515fe6158ea0d33b1
[ "Markdown", "Java" ]
3
Java
likeaboy/snaptoy
86998bcfbd5311522a5f245ae55590803a1cbe78
5f25ea683f4c0916536ac91ecc9bf56f7a0d1a38
refs/heads/master
<repo_name>wanmaoor/sign_up<file_sep>/src/com/jeelearning/Login.java package com.jeelearning; import java.io.IOException; import java.util.ArrayList; import java.util.List; 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; /** * Servlet implementation class Login */ @WebServlet("/sign.do") public class Login extends HttpServlet { private static final long serialVersionUID = 1L; //创建Bean类类型的数组 private List<Bean> list=new ArrayList<Bean>(); /** * @see HttpServlet#HttpServlet() */ public Login() { 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 } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); String username=request.getParameter("username"); String email=request.getParameter("email"); String userpwd=request.getParameter("userpwd"); Bean bean=new Bean(username,email,userpwd); list.add(bean);//添加存储信息 //创建会话对象 HttpSession s=request.getSession(); //设置会话属性 s.setAttribute("list", list); //页面重定向 response.sendRedirect("play.jsp"); } }
7b1b5439a82df0ee9b707128cae5d95ce5c3960f
[ "Java" ]
1
Java
wanmaoor/sign_up
2cbc11bc06f88e3793150e9dbacfe8cdf18cd450
4292cb2594fd7454ea1decc5a1f0255bf9e7a2e4
refs/heads/master
<file_sep>class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int,int> nummap; for (int i = 0; i< (int)nums.size(); i++) { if (nummap.count(target-nums[i])!=0) { vector<int> ans = {nummap[target-nums[i]],i}; return ans; } else { nummap[nums[i]]=i; } } return vector<int>(); } };<file_sep>class Solution { public: int numTrees(int n) { vector<int> results={1,1,2}; for (int i=3;i<=n;i++) { int ans=0; for (int j=0;j<=i-1;j++) { ans+=results[j]*results[i-j-1]; } results.push_back(ans); } return results[n]; } };<file_sep># Smashing-Leet-Code<file_sep>/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root==p || root==q) { return root; } else if (root==nullptr) { return nullptr; } else { TreeNode* leftans=lowestCommonAncestor(root->left,p,q); TreeNode* rightans=lowestCommonAncestor(root->right,p,q); if(leftans!=nullptr && rightans!=nullptr) { return root; } else if (leftans==nullptr) { return rightans; } else { return leftans; } } } }; <file_sep>class Solution { public: vector<int> grayCode(int n) { if (n==0) { vector<int> tmp={0}; return tmp; } if (n==1) { vector<int> tmp={0,1}; return tmp; } vector<int> former=grayCode(n-1); for (int i=former.size()-1;i>=0;i--) { former.push_back(pow(2,n-1)+former[i]); } return former; } };
9bde3ee493b84a387a544f99fe878eedda99200a
[ "Markdown", "C++" ]
5
C++
yodahuang/Smashing-Leet-Code
c9481f95a3ff29062dd44d6e07fb66916d317cd3
963d3efa60d0728e311aa6dc71c5c85a290daad9
refs/heads/master
<repo_name>xdu/cmdline-podcasts-downloader<file_sep>/README.md # cmdline-podcasts-downloader<file_sep>/config.js import os from 'os' import path from 'path' import fs from 'fs' const filename = "feeds.json" export default function getConfig() { console.log("__dirname : " + __dirname) console.log("os.homedir() : " + os.homedir()) let fpath = getConfigFile() if (! fpath) { console.error("Configuration file " + filename + " is not found.") process.exit() } let file = fs.readFileSync(fpath) let config = JSON.parse(file) return config.feeds } function getConfigFile() { let fpath = path.join(__dirname, filename) if (fs.existsSync(fpath)) { return fpath } fpath = path.join(os.homedir(), filename) if (fs.existsSync(fpath)) { return fpath } return null }<file_sep>/index.js import Feed from './Feed' import getConfig from './config' function main() { let feeds = getConfig() for (let i = 0; i < feeds.length; i ++) { const{ url, directory } = feeds[i] //console.log(url, directory) const feed = new Feed(url, directory) feed.download() } } main() <file_sep>/FeedConfig.js import fs from 'fs' import path from 'path' const CONFIG = 'content.json' class FeedConfig { constructor(folder) { this.path = folder this._downloaded = [] this.filename = path.join(this.path, CONFIG) if (fs.existsSync(this.filename)) { let data = fs.readFileSync(this.filename) this._downloaded = JSON.parse(data) } } isDownloaded(id) { for (let i = 0; i < this._downloaded.length; i++) { if (this._downloaded[i].guid === id) { return true } } return false } add(record) { this._downloaded.push(record) } save() { //console.log("save " + JSON.stringify(this._downloaded)) fs.writeFileSync(this.filename, JSON.stringify(this._downloaded)) } } //const instance = new FeedHitory() //Object.freeze(instance) export default FeedConfig <file_sep>/episode.js import request from 'request' import sanitize from 'sanitize-filename' import path from 'path' import fs from 'fs' import moment from 'moment' export function getNewEpisodes(podcastXML, index) { var rv = [] for (var i = 0; i < podcastXML.episodes.length; i++) { var epis = podcastXML.episodes[i] if (!(epis.guid in index)) { rv.push({ ...epis }) } } return rv } export function buildPath(episode, folder) { let dt = moment(episode.published.getTime()).format('YYYY-MM-DD') return dt + ' ' + sanitize(episode.title) + '.mp3' } export function downloadEpisode(url) { return new Promise((resolve, reject) => { request({ url, encoding: null }, (err, res, data) => { err ? reject(err) : resolve(data) }) }) } export function saveFile(data, path) { return new Promise((resolve, reject) => { fs.writeFile(path, data, (err) => { err ? reject(err) : resolve(path) }) }) } export function updateConfig(config, episode, filename) { let obj = { ...episode, filename } config[episode.guid] = obj console.log(config) }<file_sep>/request.js import request from 'request' import parser from 'node-podcast-parser' export default function podcastXML(url) { return new Promise((resolve, reject) => { request(url, (err, res, data) => { if (err) { reject("Network error"); } parser(data, (err, podcast) => { if (err) { reject('Parsing error') } //console.log(podcast) resolve(podcast) }) }) }) }
df8142f114018bb7b5ad1831477cf8122f3cd3c7
[ "Markdown", "JavaScript" ]
6
Markdown
xdu/cmdline-podcasts-downloader
3494feff2ca74fac15f7515648039024bd1838c7
4f266c29263b50f80750653a2de1dd6de7a578fe
refs/heads/master
<repo_name>nicholasblack-g/alwayslearn<file_sep>/c-programing-from-tsu.c //eg.1.1 # include <stdio.h> #include <math.h> int main() { //section 1 hello world printf("Hello World!\n"); //section 2 basic calculations double x, y; x = sin(0.19199); y = cos(0.19199); printf("%f^2 + %f^2 = %f\n", x, y, x * x + y * y);//x^2 + y^2 = 1 return 0; } //Error console says that ^ must calculate with integers both sides. //How exactlly the expressions of formulas work very in a function like printf? ////////////////////////////////////////////////////////// //eg.1.2 embled # include <stdio.h> int main() { //section 1 a + b int a, b, sum; int add (int, int); //identify "add" function with its parameters' types a = 123; b = 456; sum = add(a, b); //sum = a + b; //alter printf("The sum of %d and %d is %d.\n", a, b, sum); //section 2 compare x, y, z with maxinum and decsended sequence scanf("%d%d%d", &a, &b, &sum); int max3(int, int, int); printf("Maxinum of %d, %d and %d is %d.\n", a, b, sum, max3(a, b, sum)); void decsend(int, int, int); printf("Decsending order is "); decsend(a,b,sum); printf("\n"); return 0; } int add(int x, int y) { int z = x + y; return z; }//sec 1 int max3(int x, int y, int z) { if(x<y) x=y; else if(x<z) x=z; return x; }//sec 2.1 void exchange(int x, int y){int t; t = x; x = y; y = t;} void decsend(int x,int y, int z) { while(x < y || y < z) { exchange(x,y); exchange(x,z); exchange(y,z); } printf("%d, %d, %d.", x, y, z); }//sec 2.2 //todo: //////////////////////////////////////////////////////////<file_sep>/README.md # alwayslearn This is a sync repo from Visual Studio, with a few notes of other learnings.
02704a56798a84e7ab5c58d50e182db14fb31347
[ "Markdown", "C" ]
2
C
nicholasblack-g/alwayslearn
c7ffc188e7ab5259b2ae0923f9e793b325f5671e
bdc021576ccb8a2cf3453b045152d21acfe4386a
refs/heads/master
<repo_name>Saphiresurf/sidescroller<file_sep>/src/hardoncollider.lua local HC = require "libraries/HC" collider = HC.new(32) return collider <file_sep>/src/entities/player.lua local collider = require "src/hardoncollider" require "src/entityinteraction/controls" Player = Object:extend() function Player:new(x, y) -- Sprite self.player_idle = love.graphics.newImage("/assets/img/img_player_idle.png") -- Characters coordinates in the level self.x = x self.y = y -- Direction of movement as dictated by controls self.xaxis = 0 self.yaxis = 0 -- Speed of Player self.speed = 85 -- Shape of the players collision box self.width = 12 self.height = 11 -- Players collision box self.collisionShape = collider:rectangle(self.x, self.y, self.width, self.height) self.collisionShape.id = "player" end function Player:update(dt) -- Moves the Player according to controls set in controls.lua self:move(dt) -- Check player collisions, handle them accordingly as defined self:checkCollisions(dt) end function Player:draw() -- Draw collision box for testing purposes -- love.graphics.setColor(255, 255, 255, 255) -- local x1, y1, x2, y2 = self.collisionShape:bbox() -- love.graphics.rectangle('line', x1, y1, x2 - x1, y2 - y1) love.graphics.draw(self.player_idle, self.x, self.y) end -- General purpose functions -- Moves the Player according to controls set in controls.lua function Player:move(dt) self.xaxis, self.yaxis = updateControls() self.x = self.x + (self.xaxis * self.speed) * dt self.y = self.y + (self.yaxis * self.speed) * dt self.collisionShape:moveTo(self.x + (self.width / 2), self.y + (self.height / 2)) end -- Check collisions and act accordingly function Player:checkCollisions(dt) -- Checks a list of collisions with the player object for shape, collisionVector in pairs(collider:collisions(self.collisionShape)) do -- How to handle collisions with the level (platforms.. stuff like that) if shape["id"] == "platform" then -- FOR SOME REASON THE PLAYER VIBRATES WHEN THEY'RE TOUCHING MORE THAN ONE PLATFORM AT A TIME WHY -- comin back to this later -- it's not delta time either tho self.x, self.y = self.x + collisionVector.x , self.y + collisionVector.y end end end <file_sep>/[Non-Code] TILED PROJECT FILES/platformer_tiled/previous/tiled_lua.lua return { version = "1.1", luaversion = "5.1", tiledversion = "0.18.2", orientation = "orthogonal", renderorder = "right-down", width = 32, height = 32, tilewidth = 16, tileheight = 16, nextobjectid = 76, properties = {}, tilesets = {}, layers = { { type = "objectgroup", name = "Entities", visible = true, opacity = 1, offsetx = 0, offsety = 0, draworder = "topdown", properties = {}, objects = { { id = 2, name = "Platform", type = "", shape = "rectangle", x = 224, y = 240, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 3, name = "Platform", type = "", shape = "rectangle", x = 240, y = 240, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 4, name = "Platform", type = "", shape = "rectangle", x = 256, y = 240, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 5, name = "Platform", type = "", shape = "rectangle", x = 272, y = 240, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 6, name = "Platform", type = "", shape = "rectangle", x = 288, y = 240, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 7, name = "Platform", type = "", shape = "rectangle", x = 304, y = 240, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 9, name = "Platform", type = "", shape = "rectangle", x = 208, y = 240, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 10, name = "Platform", type = "", shape = "rectangle", x = 336, y = 304, width = 144, height = 48, rotation = 0, visible = true, properties = {} }, { id = 11, name = "Platform", type = "", shape = "rectangle", x = 416, y = 272, width = 64, height = 32, rotation = 0, visible = true, properties = {} }, { id = 12, name = "Platform", type = "", shape = "rectangle", x = 400, y = 288, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 13, name = "Platform", type = "", shape = "rectangle", x = 304, y = 304, width = 32, height = 48, rotation = 0, visible = true, properties = {} }, { id = 14, name = "Platform", type = "", shape = "rectangle", x = 240, y = 192, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 15, name = "Platform", type = "", shape = "rectangle", x = 256, y = 192, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 17, name = "Platform", type = "", shape = "rectangle", x = 80, y = 304, width = 128, height = 16, rotation = 0, visible = true, properties = {} }, { id = 18, name = "Platform", type = "", shape = "rectangle", x = 80, y = 320, width = 128, height = 16, rotation = 0, visible = true, properties = {} }, { id = 19, name = "Platform", type = "", shape = "rectangle", x = 80, y = 336, width = 128, height = 16, rotation = 0, visible = true, properties = {} }, { id = 20, name = "Platform", type = "", shape = "rectangle", x = 64, y = 288, width = 48, height = 16, rotation = 0, visible = true, properties = {} }, { id = 21, name = "Platform", type = "", shape = "rectangle", x = 32, y = 272, width = 48, height = 16, rotation = 0, visible = true, properties = {} }, { id = 22, name = "Platform", type = "", shape = "rectangle", x = 64, y = 240, width = 48, height = 16, rotation = 0, visible = true, properties = {} }, { id = 23, name = "Platform", type = "", shape = "rectangle", x = 96, y = 208, width = 48, height = 16, rotation = 0, visible = true, properties = {} }, { id = 32, name = "Platform", type = "", shape = "rectangle", x = 464, y = 192, width = 16, height = 80, rotation = 0, visible = true, properties = {} }, { id = 34, name = "Platform", type = "", shape = "rectangle", x = 304, y = 144, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 35, name = "Platform", type = "", shape = "rectangle", x = 320, y = 144, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 36, name = "Platform", type = "", shape = "rectangle", x = 336, y = 144, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 37, name = "Platform", type = "", shape = "rectangle", x = 352, y = 144, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 38, name = "Platform", type = "", shape = "rectangle", x = 368, y = 144, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 39, name = "Platform", type = "", shape = "rectangle", x = 368, y = 128, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 40, name = "Platform", type = "", shape = "rectangle", x = 368, y = 112, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 41, name = "Platform", type = "", shape = "rectangle", x = 368, y = 96, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 42, name = "Platform", type = "", shape = "rectangle", x = 368, y = 80, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 48, name = "Platform", type = "", shape = "rectangle", x = 336, y = 112, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 49, name = "Platform", type = "", shape = "rectangle", x = 320, y = 96, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 50, name = "Platform", type = "", shape = "rectangle", x = 32, y = 256, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 51, name = "Platform", type = "", shape = "rectangle", x = 32, y = 240, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 52, name = "Platform", type = "", shape = "rectangle", x = 32, y = 224, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 53, name = "Platform", type = "", shape = "rectangle", x = 32, y = 208, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 54, name = "Platform", type = "", shape = "rectangle", x = 32, y = 192, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 55, name = "Platform", type = "", shape = "rectangle", x = 32, y = 176, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 56, name = "Platform", type = "", shape = "rectangle", x = 32, y = 160, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 57, name = "Platform", type = "", shape = "rectangle", x = 32, y = 144, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 58, name = "Platform", type = "", shape = "rectangle", x = 208, y = 304, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 59, name = "Platform", type = "", shape = "rectangle", x = 224, y = 304, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 60, name = "Platform", type = "", shape = "rectangle", x = 240, y = 304, width = 0, height = 16, rotation = 0, visible = true, properties = {} }, { id = 63, name = "Platform", type = "", shape = "rectangle", x = 272, y = 304, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 64, name = "Platform", type = "", shape = "rectangle", x = 288, y = 304, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 66, name = "Platform", type = "", shape = "rectangle", x = 192, y = 224, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 67, name = "Platform", type = "", shape = "rectangle", x = 176, y = 208, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 68, name = "Platform", type = "", shape = "rectangle", x = 320, y = 224, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 69, name = "Platform", type = "", shape = "rectangle", x = 336, y = 208, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 70, name = "Platform", type = "", shape = "rectangle", x = 288, y = 160, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 71, name = "Platform", type = "", shape = "rectangle", x = 272, y = 176, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 72, name = "Player", type = "", shape = "rectangle", x = 240, y = 160, width = 16, height = 16, rotation = 0, visible = true, properties = {} } } } } } <file_sep>/src/parselevel.lua -- TILED STANDARDS FOR THIS SETUPER -- DEFINING COLLISIONS -- Layer: "Collisions" -- Objects: "platform" --Make sure to add more here to make your Tiled maps --a little more personalized -- DEFINING ENTITIES -- Layer: "entitySpawns" -- Player Object Name: "Player" function parseLevel(levelPath) -- Grabbing the level file local level = sti(levelPath) tileSetup(level) entitySetup(level) return level end -- Creates collision boxes in accordance to the collisions layer function tileSetup(level) -- ADDING TILE COLLISIONS TO A NEW CUSTOM LAYER -- -- Create a custom layer to store our tile collison boxes in tiles = level:addCustomLayer("tiles", 8) -- Create a table to store those collisionShapes in tiles.collisionShape = {} -- Creating level collisions (platforms) for x, object in pairs(level.layers.Collisions.objects) do if object.name == "platform" then tiles.collisionShape[x] = collider:rectangle(object.x, object.y, object.width, object.height) tiles.collisionShape[x] = tiles.collisionShape[x]:rotate(object.rotation) tiles.collisionShape[x].id = "platform" end end end -- Sets up entities in accordance to the entitySpawns layer function entitySetup(level) -- ADDING ENTITES TO A NEW CUSTOM LAYER & DEFINING UPDATE AND DRAW FUNCTIONS-- -- Create new custom layer called "Sprites" as the 8th layer local entities = level:addCustomLayer("entities", 9) -- Create entity objects (player, enemeis, etc) in entities custom layer -- x, y coordinate fetched from object layer "entitySpawns" in level for k, object in pairs(level.layers.entitySpawns.objects) do if object.name == "Player" then entities.player = Player(object.x, object.y) break end end -- Override the function to update entities entities.update = function(self, dt) self.player:update(dt) end -- Override the function to draw the entities entities.draw = function(self) self.player:draw() end -- Remove uneeded object layer level:removeLayer("entitySpawns") end <file_sep>/src/world.lua World = Object:extend() -- Files with functions to include require "src/parselevel" -- Shared objects to include local collider = require "src/hardoncollider" function World:new(levelPath) --Set's up the level and creates an independent variable for our entity layer self.level = parseLevel(levelPath) -- New camera that follows the player self.playercam = gamera.new(0, 0, self.level.width * self.level.tilewidth, self.level.height * self.level.tileheight) self.playercam:setScale(3.0) -- Sets the amount of screen that can be used to display gramphics self.playercam:setWindow(0, 0, self.level.width * self.level.tilewidth, self.level.height * self.level.tileheight) -- Sets the window to the same size of the window love.window.setMode(self.level.width * self.level.tilewidth, self.level.height * self.level.tileheight) end function World:update(dt) -- Update every layer in the map level self.level:update(dt) self.playercam:setPosition(self.level.layers.entities.player.x, self.level.layers.entities.player.y) end function World:draw() self.playercam:draw(function() self.level:draw(self.level.layers.entities.player.x, self.level.layers.entities.player.y) end) end <file_sep>/main.lua -- main.lua -- -- Load the necessary libraries Object = require "libraries/classic" -- OOP Support for Lua HC = require "libraries/HC" -- Collision Detection sti = require "libraries/sti" -- Support for Tiled Maps Gamestate = require "libraries/hump/hump_gamestate" gamera = require "libraries/gamera" Camera = require "libraries/hump/hump_camera" -- Pass in an instance of hardon collider (HC) shared between files collider = require ("src/hardoncollider") -- Other project files included here require "src/entities/player" -- Player class require "src/world" -- World builder/management -- Set default image filter to nearest neighbor love.graphics.setDefaultFilter('nearest', 'nearest') -- Initialize world level1 = World("levels/test_level.lua") function love.update(dt) level1:update(dt) end function love.draw() level1:draw() end <file_sep>/src/entityinteraction/controls.lua function updateControls() --Sets the xaxis and yaxis to 0 so that if no key is pressed it will remain at 0 (no movement) xaxis = 0 yaxis = 0 -- If the right key is pressed then the xaxis will be set to 1 (they'll be moving along the positive x-axis) if (love.keyboard.isDown("right")) then xaxis = 1 end -- If the left key is pressed then the xaxis will be set to -1 (they'll be moving along the negative x-axis) if (love.keyboard.isDown("left")) then xaxis = -1 end -- If the up key is pressed then the yaxis will be set to -1 (they'll mvoe along the negative y-axis, this is technically up in LOVE) if (love.keyboard.isDown("up")) then yaxis = -1 end if (love.keyboard.isDown("down")) then yaxis = 1 end return xaxis, yaxis end
ce550efb956f387d8c215af96e0f750c077e5f21
[ "Lua" ]
7
Lua
Saphiresurf/sidescroller
55c238f736d2647553520570f0a00230d4275c46
7144e9f15da414d7279d2ea795fb85c256ee9be2
refs/heads/master
<repo_name>RestOpenGov/RestOpenGov<file_sep>/crawler/RELEASES.md ## RestOpenGov Crawler ### Releases #### 0.1.4 (16/09/2012) * Major refactor/rewrite. CKAN part is now decoupled from the indexer * Now it's possible to index a single file from a given URL (CSV or zipped CSVs) * Updated the Elasticsearch version to 0.19.9 * Bugfixes #### 0.1.3 (11/05/2012) * Fixed issues in all demos #### 0.1.2 (10/05/2012) * Added filter to the openbafici demo #### 0.1.1 (10/05/2012) * Added ReadMe to playdemo * Minor fixes in playdemo #### 0.1 (05/05/2012) * First release, which includes: Crawler, RestBA and RestOpenGov.js <file_sep>/elastic-search-openshift-cartridge/info/bin/mongodb_dump.sh #!/bin/bash # Import Environment Variables for f in ~/.env/* do . $f done source /etc/stickshift/stickshift-node.conf CART_INFO_DIR=${CARTRIDGE_BASE_PATH}/embedded/mongodb-2.0/info source ${CART_INFO_DIR}/lib/util function die() { exitcode=${1:-0} tag=${2:-"WARNING"} msg=${3:-"Could not dump MongoDB databases! Continuing anyway ..."} echo 1>&2 echo "!$tag! $msg" 1>&2 echo 1>&2 exit $exitcode } # End of function die. function create_mongodb_snapshot() { # Work in a temporary directory (create and cd to it). mkdir -p /tmp/mongodump.$$ pushd /tmp/mongodump.$$ > /dev/null # Take a "dump". creds="-u $OPENSHIFT_NOSQL_DB_USERNAME -p \"$OPENSHIFT_NOSQL_DB_PASSWORD\"" if mongodump -h $OPENSHIFT_NOSQL_DB_HOST $creds --directoryperdb > /dev/null 2>&1; then # Dump ok - now create a gzipped tarball. if tar -zcf $OPENSHIFT_DATA_DIR/mongodb_dump_snapshot.tar.gz . ; then # Created dump snapshot - restore previous dir and remove temp dir. popd > /dev/null /bin/rm -rf /tmp/mongodump.$$ return 0 else err_details="- snapshot failed" fi else err_details="- mongodump failed" fi # Failed to dump/gzip - log error and exit. popd > /dev/null /bin/rm -rf /tmp/mongodump.$$ /bin/rm -f $OPENSHIFT_DATA_DIR/mongodb_dump_snapshot.tar.gz die 0 "WARNING" "Could not dump MongoDB databases ${err_details}!" } # End of function create_mongodb_snapshot. start_mongodb_as_user create_mongodb_snapshot exit 0 <file_sep>/RestBA/src/main/java/ar/com/restba/exception/RestBAException.java package ar.com.restba.exception; public class RestBAException extends RuntimeException { private static final long serialVersionUID = 7979999937975490005L; public RestBAException(String message, Throwable t) { super(message, t); } public RestBAException(String message) { super(message); } } <file_sep>/openBafici/deploy.sh rm -fr ../../RestOpenGov.openshift/openbafici/* cp -r * ../../RestOpenGov.openshift/openbafici pushd ../../RestOpenGov.openshift/openbafici ./.openshift_deploy popd<file_sep>/PlayBafici/README.md PlayBafici ========== Play Bafici Live site: [here](http://playbafici.com.ar/) (images are broken) <file_sep>/crawler/src/main/java/com/nardoz/restopengov/ckan/utils/CSVDatasetReader.java package com.nardoz.restopengov.ckan.utils; import com.nardoz.restopengov.ckan.models.MetadataResource; import com.nardoz.restopengov.utils.CSVFetcher; import com.nardoz.restopengov.utils.ICSVFetcherResult; import com.nardoz.restopengov.utils.IFormatReader; public class CSVDatasetReader extends CSVFetcher implements IFormatReader, IResourceFormatReader { private MetadataResource resource; public CSVDatasetReader(MetadataResource resource) { this(resource, new DatasetReaderResult()); } public CSVDatasetReader(MetadataResource resource, ICSVFetcherResult callback) { this.resource = resource; this.callback = callback; } public ICSVFetcherResult readFromResourceURL() throws Exception { return readFromURL(resource.url.replace("https", "http")); } }<file_sep>/crawler/src/main/java/com/nardoz/restopengov/ckan/models/Metadata.java package com.nardoz.restopengov.ckan.models; import java.io.Serializable; import java.util.List; import java.util.Map; public class Metadata implements Serializable { public String mantainer; public String id; public String metadata_created; public List<String> relationships; public String license; public String metadata_modified; public String author; public String author_email; public String download_url; public String state; public String version; public String licence_id; public List<MetadataResource> resources; public List<String> tags; public List<String> groups; public String name; public String isopen; public String notes_rendered; public String url; public String ckan_url; public String notes; public String title; public String ratings_average; public Map<String, String> extras; public String ratings_count; public String revision_id; } <file_sep>/crawler/src/main/java/com/nardoz/restopengov/Crawler.java package com.nardoz.restopengov; import akka.actor.ActorSystem; import com.nardoz.restopengov.ckan.CkanActorHandler; import com.nardoz.restopengov.standalone.StandaloneActorHandler; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.apache.log4j.Logger; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.transport.InetSocketTransportAddress; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; public class Crawler { public static Logger logger = Logger.getLogger("restopengov"); public static void main(String[] args) { if(args.length == 0) { System.out.println("USAGE: crawler [command] <args>"); System.out.println("Available commands:\n"); System.out.println("Standalone commands:"); System.out.println("standalone fetch-url <url> Fetches a single file\n"); System.out.println("CKAN commands:"); System.out.println("ckan list Lists all datasets"); System.out.println("ckan fetch-all Fetches all datasets"); System.out.println("ckan fetch <ds1 ds2 ds3> Fetches all specified datasets (space separated)"); return; } Config config = ConfigFactory.load(); ActorSystem system = ActorSystem.create("crawler", config); system.registerOnTermination(new Runnable() { public void run() { nodeBuilder().client(true).node().close(); } }); final Client client = new TransportClient() .addTransportAddress(new InetSocketTransportAddress( config.getString("restopengov.elasticsearch-host"), config.getInt("restopengov.elasticsearch-port"))); if(args[0].equals("ckan")) { CkanActorHandler ckanHandler = new CkanActorHandler(system, client); ckanHandler.handle(args); } else if(args[0].equals("standalone")) { StandaloneActorHandler standaloneHandler = new StandaloneActorHandler(system, client); standaloneHandler.handle(args); } else { System.out.println("Command not found"); system.shutdown(); } } } <file_sep>/crawler/src/main/java/com/nardoz/restopengov/utils/ICSVFetcherResult.java package com.nardoz.restopengov.utils; public interface ICSVFetcherResult { public void onStart(); public void add(String id, String json); public void onEnd(); } <file_sep>/PlayBafici/query.sh curl -X post 'http://elastic.restopengov.org/gcba/bafici/_search?pretty=1' -d ' { "query": { "custom_score": { "script" : "random()*20", "query" : { "query_string": { "query" : "_id:bafici12-films-*" } } } }, "sort": { "_score": { "order":"desc" } } } ' <file_sep>/elastic-search-openshift-cartridge/info/hooks/status #!/bin/bash # Gets status of instance # Exit on any errors set -e function print_help { echo "Usage: $0 app-name namespace uuid" echo "Get application status" echo "$0 $@" | logger -p local0.notice -t stickshift_mongodb_status exit 1 } while getopts 'd' OPTION do case $OPTION in d) set -x ;; ?) print_help ;; esac done [ $# -eq 3 ] || print_help source "/etc/stickshift/stickshift-node.conf" source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util setup_basic_hook "$1" $2 $3 MONGODB_DIR="$APP_HOME/mongodb-2.0/" mongodbctl="$MONGODB_DIR/${application}_mongodb_ctl.sh" # # Get the status of the application # if output=$(runuser --shell /bin/sh "$uuid" "$mongodbctl" status 2>&1) then status_client_result "$output" else client_result "MongoDB is either stopped or inaccessible" fi<file_sep>/RestBA/src/main/java/ar/com/restba/connectors/con/RestBAIterator.java package ar.com.restba.connectors.con; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; class RestBAIterator<T> implements Iterator<List<T>> { private RestBAConnection<T> connection; private boolean initialPage = true; /** * Creates a new iterator over the given {@code connection}. * * @param connection * The connection over which to iterate. */ protected RestBAIterator(RestBAConnection<T> connection) { this.connection = connection; } /** * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return connection.hasNext(); } /** * @see java.util.Iterator#next() */ public List<T> next() { // Special case: initial page will always have data, return it // immediately. if (initialPage) { initialPage = false; return connection.getData(); } if (!connection.hasNext()) throw new NoSuchElementException("There are no more pages in the connection."); connection = connection.fetchNextPage(); return connection.getData(); } /** * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(RestBAIterator.class.getSimpleName() + " doesn't support the remove() operation."); } }<file_sep>/crawler/README.md ## RestOpenGov Crawler El Crawler es el encargado de acceder periódicamente a los diversos endpoints publicados por los gobiernos, extraer la información que allí publican, procesarla y almacenarla en un servidor elasticsearch para su posterior consulta. ### Tecnologías El procesamiento de los datasets es realizado utilizando la API Java de Akka (www.akka.io), un framework de procesamiento distribuído basado en Actores. Para la búsqueda e indexación de la información, utilizamos Elasticsearch (www.elasticsearch.org). ### Setup 1. Bajar las fuentes: ``` git clone <EMAIL>:Nardoz/RestOpenGov.git cd RestOpenGov/crawler ``` 2. Compilar y bajar dependencias: ``` mvn compile ``` Para crear el proyecto para Eclipse ejecutar ```mvn eclipse:eclipse``` o ```mvn idea:idea``` para IntelliJ. 3. Correr Elasticsearch: ``` ../tools/elasticsearch-0.19.9/bin/elasticsearch ``` 4. Ejecutar el crawler: ``` mvn exec:java -Dexec.args="ckan fetch-all" ``` 5. Verlo en acción: Abrir un explorador y navegar a ```http://localhost:9200/_plugin/head/```. El crawler tiene dos modos de ejecución por CLI. Uno es para trabajar con CKAN y otro como standalone: CKAN: ``` ckan list ckan fetch-all ckan fetch <dataset1 dataset2 dataset3 ...> ``` Standalone: ``` standalone fetch-url <url> ``` ### Configuración Es posible configurar tanto Akka como el crawler desde el mismo archivo de configuración: ``` src/main/java/resources/application.conf ``` En lo que respecta al crawler, podemos definir el entrypoint (actualmente sólo soporta uno) de la API REST de metadatos de CKAN (la que contiene el listado de datasets disponibles). También se puede configurar cantidad máxima de elementos a indexar enviados en un sólo bulk. ``` restopengov { ckan-rest-api = "http://data.buenosaires.gob.ar/api/rest/dataset/" index = "gcba" max-per-bulk = 500 } ``` Por otro lado, se puede setear el nombre del índice que va a utilizar el crawler (en este ejemplo gcba), si bien actualmente el servicio no se encargará de crearlo automáticamente. La manera más fácil de hacerlo es siguiendo esta guía: http://www.elasticsearch.org/guide/reference/api/admin-indices-create-index.html ``` $ curl -XPUT 'http://localhost:9200/gcba/' $ curl -XPUT 'http://localhost:9200/gcba/' -d ' index : number_of_shards : 3 number_of_replicas : 2 ' ``` Más detalles de cómo configurar Akka aquí: http://doc.akka.io/docs/akka/2.0.1/general/configuration.html ### Formatos soportados Hasta el momento, el crawler sólo soporta datasets en CSV (separados por coma, punto y coma o tabs) o varios CSVs comprimidos en un ZIP. ## Actores ![Actors](http://f.cl.ly/items/042M1m1b320I1f2f0S3v/Image%202012.04.22%2011:10:38%20PM.png) ## Licencia Este software es distribuído bajo la licencia Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0<file_sep>/elastic-search-openshift-cartridge/README.md elastic-search-openshift-cartridge ================================== elastic-search-openshift-cartridge<file_sep>/crawler/src/main/java/com/nardoz/restopengov/standalone/StandaloneActorHandler.java package com.nardoz.restopengov.standalone; import akka.actor.*; import akka.routing.FromConfig; import com.nardoz.restopengov.standalone.actors.FileFetcher; import com.nardoz.restopengov.standalone.actors.ZipFileFetcher; import com.nardoz.restopengov.standalone.models.RemoteFile; import org.elasticsearch.client.Client; public class StandaloneActorHandler { private ActorSystem system; public ActorRef fileFetcher; public ActorRef zipFileFetcher; public StandaloneActorHandler(ActorSystem system, final Client client) { this.system = system; fileFetcher = system.actorOf(new Props(new UntypedActorFactory() { public UntypedActor create() { return new FileFetcher(client); } }).withRouter(new FromConfig()), "standaloneFileFetcher"); zipFileFetcher = system.actorOf(new Props(new UntypedActorFactory() { public UntypedActor create() { return new ZipFileFetcher(client); } }).withRouter(new FromConfig()), "standaloneZipFileFetcher"); } public void handle(String[] args) { if(args[1].equals("fetch-url") && args.length > 2) { RemoteFile file = new RemoteFile(args[2]); if(file.format.toLowerCase().equals("zip")) { zipFileFetcher.tell(file); } else { fileFetcher.tell(file); } } else { System.out.println("Command not found"); system.shutdown(); } } } <file_sep>/RestOpenGov.js/demos/browser/browser.js var opengov = new RestOpenGov(); $(function() { $('#form').submit(function(e) { e.preventDefault(); $('#submit').val("Buscando...").attr("disabled", "disabled"); opengov.search({ dataset: $("#dataset").val(), query: $("#query").val() }, showResults); }); }); var showResults = function(obj) { $('#submit').val("Buscar").removeAttr("disabled"); var html = "<h3>Resultados:</h3>"; for(i in obj) { html += "<h4><a target=\"_blank\" href=\"" + obj[i].resourceURL + "\">Resultado #" + (parseInt(i) + 1) + "</a></h4>"; html += "<table class=\"table\">"; for(key in obj[i]._source) { html += "<tr><th>" + key + "</th><td>"; if(typeof obj[i]._source[key] == "object") { for(j in obj[i]._source[key]) { if(typeof obj[i]._source[key][j] == "object") { html += "<table class=\"table\">"; for(k in obj[i]._source[key][j]) { html += "<tr><th>" + k + "</th><td>" + obj[i]._source[key][j][k] + "</td></tr>"; } html += "</table>"; } else { html += obj[i]._source[key][j] + ", "; } } } else { html += obj[i]._source[key]; } html += "</td></tr>"; } html += "</table>"; } $('#results').html(html); }; <file_sep>/openBafici/README.md # openBafici - Toda la información del Festival de Cine de Buenos Aires en tu celular [openBafici](https://openbafici-rog.rhcloud.com/) te permite consultar la lista de películas exhibidas en el [Festival Internacional de Cine Indepenciente de Cine de Buenos Aires](http://www.bafici.gov.ar/home/web/en/index.html) (baFici) desde tu celular. Puedes acceder a la misma en [https://openbafici-rog.rhcloud.com/](https://openbafici-rog.rhcloud.com/) Es una aplicación web que utiliza los servicios de [restOpenGov](https://restopengov.org/) y está desarrollada con como Play Framework 2.0, Scala y alojada en [Openshift](https://openshift.redhat.com), la plataforma de cloud computing libre (y gratuita) de Red Hat. Si querés saber cómo podés hacer para comenzar ya mismo a desarrollar aplicaciones que accedan a la información de restOpenGov seguí [este tutorial](https://github.com/Nardoz/RestOpenGov/blob/develop/playdemo/README.md) que te explica cómo hacerlo.<file_sep>/crawler/src/main/java/com/nardoz/restopengov/ckan/actors/ResourceFetcher.java package com.nardoz.restopengov.ckan.actors; import akka.actor.UntypedActor; import com.nardoz.restopengov.Crawler; import com.nardoz.restopengov.ckan.models.MetadataResource; import com.nardoz.restopengov.ckan.utils.DatasetReader; import com.nardoz.restopengov.ckan.utils.ElasticDatasetReaderResult; import com.nardoz.restopengov.ckan.utils.IResourceFormatReader; import com.typesafe.config.ConfigFactory; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.client.Client; public class ResourceFetcher extends UntypedActor { private Client client; public ResourceFetcher(Client client) { this.client = client; } public void onReceive(Object message) { if (message instanceof MetadataResource) { final MetadataResource resource = (MetadataResource) message; String index = ConfigFactory.load().getString("restopengov.index"); GetResponse response = client.prepareGet(index, resource.metadata_name, resource.id).execute().actionGet(); if(response.getSource() != null) { String hash = (String) response.getSource().get("hash"); if(resource.hash == hash) { Crawler.logger.info(resource.name + " didn't change, not crawling"); return; } } ElasticDatasetReaderResult callback = new ElasticDatasetReaderResult(resource, client); try { IResourceFormatReader datasetReader = DatasetReader.read(resource, callback); if(datasetReader != null) { datasetReader.readFromResourceURL(); } } catch (Exception e) { Crawler.logger.error(e.getMessage()); e.printStackTrace(); } } else { unhandled(message); } } } <file_sep>/crawler/src/main/java/com/nardoz/restopengov/standalone/models/RemoteFile.java package com.nardoz.restopengov.standalone.models; import java.net.MalformedURLException; import java.net.URL; public class RemoteFile { public URL url = null; public String type; public String id; public String format; public RemoteFile(String url) { try { this.url = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } String[] tmp = url.split("\\."); format = tmp[tmp.length - 1]; id = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.')); if(url.contains("file://")) { type = id; } else { type = this.url.getHost().replaceAll("\\.", "-"); } } } <file_sep>/RestOpenGov.js/demos/datagrid/js/demo.js var opengov = new RestOpenGov(); var currentFrom = 0; var rows = []; $(function() { $('#form').submit(function(e) { e.preventDefault(); $('#submit').val("Buscando...").attr("disabled", "disabled"); opengov.search({ dataset: $("#dataset").val(), from: currentFrom, query: $("#query").val() }, buildGrid); }); }); var buildGrid = function(obj) { currentFrom = obj.length; $('#submit').val("Buscar").removeAttr("disabled"); $('#results').html('<table id="grid" />'); $('#grid').flexigrid({ height: obj.length * 40, dataType: 'json', colModel: getColumns(obj) }).flexAddData(getData(obj)).flexReload(); }; var getColumns = function(obj) { var list = []; for(var key in obj[0]._source) { list.push({ display: key, name: key, align: 'center', width: 200 }); } return list; }; var getData = function(obj) { for(var i in obj) { var row = {}; for(var j in obj[i]._source) { row[j] = ''; if(typeof obj[i]._source[j] != 'object') { row[j] = obj[i]._source[j].replace('\<p\>', '').replace('\<\/p\>', ''); } } rows.push({ cell: row }); } return { total: obj.length, page: 1, rows: rows }; } var showResults = function(obj) { $('#submit').val("Buscar").removeAttr("disabled"); var html = "<h3>Resultados:</h3>"; for(var i in obj) { html += "<h4><a target=\"_blank\" href=\"" + obj[i].resourceURL + "\">Resultado #" + (parseInt(i) + 1) + "</a></h4>"; html += "<table class=\"table\">"; for(var key in obj[i]._source) { html += "<tr><th>" + key + "</th><td>"; if(typeof obj[i]._source[key] == "object") { for(var j in obj[i]._source[key]) { if(typeof obj[i]._source[key][j] == "object") { html += "<table class=\"table\">"; for(k in obj[i]._source[key][j]) { html += "<tr><th>" + k + "</th><td>" + obj[i]._source[key][j][k] + "</td></tr>"; } html += "</table>"; } else { html += obj[i]._source[key][j] + ", "; } } } else { html += obj[i]._source[key]; } html += "</td></tr>"; } html += "</table>"; } $('#results').html(html); }; <file_sep>/crawler/src/main/java/com/nardoz/restopengov/standalone/actors/FileFetcher.java package com.nardoz.restopengov.standalone.actors; import akka.actor.UntypedActor; import com.nardoz.restopengov.Crawler; import com.nardoz.restopengov.standalone.models.RemoteFile; import com.nardoz.restopengov.standalone.utils.FileReader; import com.nardoz.restopengov.utils.ElasticIndexer; import com.nardoz.restopengov.utils.ICSVFetcherResult; import com.nardoz.restopengov.utils.IFormatReader; import org.elasticsearch.client.Client; public class FileFetcher extends UntypedActor { private Client client; public FileFetcher(Client client) { this.client = client; } public void onReceive(Object message) { if(message instanceof RemoteFile) { RemoteFile file = (RemoteFile) message; ICSVFetcherResult callback = new ElasticIndexer(client, file.type, file.id); try { IFormatReader fileReader = FileReader.read(file, callback); if(fileReader != null) { fileReader.readFromURL(file.url.toString()); } } catch (Exception e) { Crawler.logger.error(e.getMessage()); e.printStackTrace(); } getContext().system().shutdown(); } else { unhandled(message); } } } <file_sep>/crawler/src/main/java/com/nardoz/restopengov/ckan/actors/ZipResourceFetcher.java package com.nardoz.restopengov.ckan.actors; import akka.actor.ActorRef; import akka.actor.UntypedActor; import com.nardoz.restopengov.Crawler; import com.nardoz.restopengov.ckan.models.MetadataResource; import com.nardoz.restopengov.ckan.utils.DatasetReader; import com.nardoz.restopengov.ckan.utils.ElasticDatasetReaderResult; import com.nardoz.restopengov.ckan.utils.IResourceFormatReader; import com.typesafe.config.ConfigFactory; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.client.Client; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ZipResourceFetcher extends UntypedActor { private Client client; private ActorRef resourceFetcher; public ZipResourceFetcher(Client client) { this.client = client; } public void onReceive(Object message) { if(message instanceof MetadataResource) { final MetadataResource resource = (MetadataResource) message; String index = ConfigFactory.load().getString("restopengov.index"); GetResponse response = client.prepareGet(index, resource.metadata_name, resource.id).execute().actionGet(); if(response.getSource() != null) { String hash = (String) response.getSource().get("hash"); if(resource.hash == hash) { Crawler.logger.info(resource.name + " didn't change, not crawling"); return; } } try { URL url = new URL(resource.url.replace("https", "http")); InputStream stream = url.openStream(); byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry entry; zipinputstream = new ZipInputStream(stream); Integer id = 0; while((entry = zipinputstream.getNextEntry()) != null) { id++; Crawler.logger.info("Extracting: " + entry); resource.id = resource.id + "-" + id; resource.format = entry.getName().substring(entry.getName().lastIndexOf('.') + 1); if(!DatasetReader.handles(resource.format)) { continue; } FileOutputStream fos = new FileOutputStream("tmp/" + entry.getName()); int data; while (0 < (data = zipinputstream.read(buf))){ fos.write(buf, 0, data); } fos.close(); zipinputstream.closeEntry(); Crawler.logger.info("Completed extraction for: " + entry); ElasticDatasetReaderResult callback = new ElasticDatasetReaderResult(resource, client); IResourceFormatReader datasetReader = DatasetReader.read(resource, callback); if(datasetReader != null) { datasetReader.readFromFile("tmp/" + entry.getName()); } } zipinputstream.close(); } catch(Exception e) { e.printStackTrace(); } } else { unhandled(message); } } } <file_sep>/elastic-search-openshift-cartridge/info/hooks/configure #!/bin/bash # Creates a mongodb instance # Exit on any errors set -e function print_help { echo "Usage: $0 app-name namespace uuid" echo "$0 $@" | logger -p local0.notice -t stickshift_mongodb_configure exit 1 } while getopts 'd' OPTION do case $OPTION in d) set -x ;; ?) print_help ;; esac done [ $# -eq 3 ] || print_help source "/etc/stickshift/stickshift-node.conf" source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util CART_INFO_DIR=${CARTRIDGE_BASE_PATH}/embedded/elasticsearch-0.19.4/info app_type="elasticsearch-0.19.4" setup_embedded_configure "$1" $2 $3 source ${CART_INFO_DIR}/lib/util ELASTICSEARCH_DIR="$APP_HOME/elasticsearch-0.19.4/" # # Detect IP . $APP_HOME/.env/OPENSHIFT_INTERNAL_IP IP=$OPENSHIFT_INTERNAL_IP # # Create the core of the application # client_result "nico - r = $ELASTICSEARCH_DIR " if [ -d "$ELASTICSEARCH_DIR" ] then client_error "Embedded elastic search 0.19.4 is already attached to $application" exit 132 fi mkdir -p "$ELASTICSEARCH_DIR" pushd "$ELASTICSEARCH_DIR" > /dev/null mkdir -p logs work data conf pid sed "s,ELASTICSEARCH_CONF_PATH,$ELASTICSEARCH_DIR/conf," $CART_ETC_DIR/elasticsearch.yml > $ELASTICSEARCH_DIR/conf/elasticsearch.yml sed -i "s,ELASTICSEARCH_DATA_PATH,$ELASTICSEARCH_DIR/data," $ELASTICSEARCH_DIR/conf/elasticsearch.yml sed -i "s,ELASTICSEARCH_WORK_PATH,$ELASTICSEARCH_DIR/work," $ELASTICSEARCH_DIR/conf/elasticsearch.yml sed -i "s,ELASTICSEARCH_LOGS_PATH,$ELASTICSEARCH_DIR/logs," $ELASTICSEARCH_DIR/conf/elasticsearch.yml popd > /dev/null # # Create simple mongodb start / stop script # ln -s $CART_INFO_DIR/bin/elasticsearch_ctl.sh $ELASTICSEARCH_DIR/${application}_elasticsearch_ctl.sh # # Setup Permissions # chmod +x "$ELASTICSEARCH_DIR/"*.sh || error "Failed to chmod new application scripts" 122 chown $user_id.$group_id -R $ELASTICSEARCH_DIR/ || error "Failed to chown new application space. Please contact support" 123 # Secure script and root dir (so they can't chown the script" chown root.root "$ELASTICSEARCH_DIR" "$ELASTICSEARCH_DIR"/*.sh observe_setup_var_lib_dir "$ELASTICSEARCH_DIR" client_result "Trying to start elastic search" start_elasticsearch # Generate a password with no o's O's or 0's password=$(generate_password) # # Setup Environment Variables # #echo "export OPENSHIFT_NOSQL_DB_MONGODB_20_EMBEDDED_TYPE='mongodb-2.0'" > $APP_HOME/.env/OPENSHIFT_NOSQL_DB_MONGODB_20_EMBEDDED_TYPE client_result "" client_result "Elastic Search added. Please make note of these credentials:" <file_sep>/RestBA/README.md RestBA ========================== **RestBA en una libreria java pensada para acceder a los datos de la ciudad de buenos aires de una manera simple y flexible.** *Tiene Licencia Apache, versión 2.0 , por lo que esta libreria se puede utilizar para cualquier actividad comercial* Este blog post tiene información interesante sobre el uso de RestBA: http://blog.melendez.com.ar/gobierno-abierto-accediendo-a-los-datos-de-la-ciudad-de-buenos-aires-usando-java/ Quick start ========================== Para bajarse la libreria y sus dependencias (pocas) usando <a href="http://maven.apache.org/">maven</a> se debe agregar adentro del < dependecies > del pom.xml <dependency> <groupId>ar.com.restba</groupId> <artifactId>restba</artifactId> <version>1.0.4</version> </dependency> y luego debemos agregar el repositorio público de RestOpenGov, adentro del tag < repositories > poner: <repository> <id>RestOpenGov</id> <url>http://maven.melendez.com.ar:8081/nexus/content/repositories/RestOpenGov</url> </repository> <b>Si no queres usar maven</b> tambien te podes descargar la libreria con sus dependencias de github en la carpeta <a href="https://github.com/Nardoz/RestOpenGov/tree/develop/RestBA/download">download</a> *Ahora tu proyecto puede acceder a los datos de la ciudad de Buenos Aires y ser feliz como una lombriz :)* Ejemplo 1 : Lista Obras Registradas con Mapping de json a objeto java. ========================================================================= *Ejemplo que lista la dirección de todas las obras registradas. Busca todas la obras registradas en la ciudad de Buenos Aires. Obras en construcción, Obras en demolición, etc con sus respectivos datos como dirección de la obra, nombre del responsable, etc.* public static void main(String[] args) { RestBAClient dataBairesClient = new DefaultRestBAClient(); String query = "gcba/obras-registradas/_search?"; RestBAConnection<ObraRegistrada> fetchConnectionRestBA = dataBairesClient .fetchConnectionRestBA(query, ObraRegistrada.class); for (List<ObraRegistrada> page : fetchConnectionRestBA) { for (ObraRegistrada obraRegistrada : page) { System.out.println(obraRegistrada.getDireccion()); } } } Ejemplo 2 : Lista los metadatos pidiendo solamente json, sin mappear. ========================================================================= *Imprime los autor, título de todos los datasets de la ciudad de buenos aires* public static void main(String[] args) { RestBAClient dataBairesClient = new DefaultRestBAClient(); String query = "gcba/metadata/_search?"; RestBAConnection<JsonObject> fetchConnectionRestBA = dataBairesClient .fetchConnectionRestBA(query, JsonObject.class); for (List<JsonObject> page : fetchConnectionRestBA) { for (JsonObject metadato : page) { System.out.println("Author: " + metadato.getString("author") + " Title: " + metadato.getString("title") + " _id: " + metadato.getString("_id")); } } } Ejemplo 3 : Pedido simple a elastic search y devuelve un json normal ========================================================================= public static void main(String[] args) { RestBAClient dataBairesClient = new DefaultRestBAClient(); String query = "gcba/metadata/_search?&from=0"; JsonObject q = dataBairesClient.executeQuery(query, JsonObject.class); System.out.println("JSON object: " + q.toString()); } <file_sep>/RestBA/src/main/java/ar/com/restba/examples/SimpleQuery.java package ar.com.restba.examples; import ar.com.restba.DefaultRestBAClient; import ar.com.restba.RestBAClient; import ar.com.restba.json.JsonObject; /** * Muestra como hacer una query de elastic search * */ public class SimpleQuery { public static void main(String[] args) { RestBAClient dataBairesClient = new DefaultRestBAClient(); String query = "gcba/metadata/_search?&from=0"; JsonObject q = dataBairesClient.executeQuery(query, JsonObject.class); System.out.println("JSON object: " + q.toString()); } } <file_sep>/demos/visualizaciones/presupuesto/js/data.js function Data() { } Data.prototype = (function() { var _anio, _marca, _restOpenGov, _resultado; var _reset = function() { //_anio = ''; _marca = ''; _restOpenGov = new RestOpenGov({ dataSource:'test' }); _instance = {}; }; var _queryElastic = function(){ consulta = { anio: _anio, marca: _marca }; _restOpenGov.search({ dataset: 'autos-'+_anio, query: '' }, _orderResults); }; var _orderResults = function(res) { var field = (_marca == '') ? 'TOTAL' : _marca; res = res.sort(function(a, b) { return b._source[field]-a._source[field] }); _processResults(res); }; var _processResults = function(res) { var procesado = { label: [], values: [] }; var obj; $.each(res, function(i,e) { if (procesado.label.length == 0) { procesado.label = (_marca == '') ? _getMarcasNames(e._source) : [_marca]; } if (e._source.PROVINCIA!='TOTAL') { obj = { 'label': _getShortProvName(e._source.PROVINCIA), 'values': _getMarcasValues(e._source) }; procesado.values.push(obj); }; }); _resultado = procesado; _dispatchEvent(); }; var _getMarcasValues = function(marcas){ var resp = []; if(_marca==''){ $.each(marcas,function(i,e) { if (i != 'PROVINCIA' && i != 'TOTAL') { resp.push(e); } }); } else { resp.push(marcas[_marca]); } return resp; }; var _getMarcasNames = function(marcas){ var resp = []; $.each(marcas,function(i,e){ if (i != 'PROVINCIA' && i != 'TOTAL') { resp.push(i); } }); return resp; }; var _getShortProvName = function(prov){ switch (prov) { case'TIERRA DEL FUEGO': prov = 'T. DEL FUEGO'; break; case'<NAME>': prov = 'B. AIRES'; break; case'SANTIAGO DEL ESTERO': prov = 'SGO. DEL ESTERO'; break; case'CAPITAL FEDERAL': prov = 'CAP. FED.'; break; } return prov; }; var _dispatchEvent = function() { var event = jQuery.Event("retrieveInfoComplete"); event.results = _resultado; $(_instance).trigger(event); }; return { constructor: Data, retrieveInfo: function(anio, marca) { _reset(); _marca = marca; _anio = anio; _instance = this; _queryElastic(); } }; })(); <file_sep>/demos/visualizaciones/presupuesto/js/PresupuestoVizRing.js var PresupuestoViz = function(options) { this.conn = new PresupuestoData(options) this.retrieveByAnio = function(anio) { this.conn.search({'anio':anio,'graph':'ring'}, function(data){ this._dispatchEvent(data, 'retrieveByAnioComplete'); }, this); } this._dispatchEvent = function(data, event) { var e = jQuery.Event(event); e.results = data; $(this).trigger(e); }; };<file_sep>/elastic-search-openshift-cartridge/info/hooks/move #!/bin/bash # Move to a new ip # Exit on any errors set -e source "/etc/stickshift/stickshift-node.conf" source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/apache source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/network while getopts 'd' OPTION do case $OPTION in d) set -x ;; ?) print_help ;; esac done [ $# -eq 3 ] || print_help namespace=`basename $2` application="$1" uuid=$3 setup_basic_vars CART_INFO_DIR=${CARTRIDGE_BASE_PATH}/embedded/mongodb-2.0/info source ${CART_INFO_DIR}/lib/util MONGODB_DIR="$APP_HOME/mongodb-2.0/" observe_setup_var_lib_dir "$MONGODB_DIR" . $APP_HOME/.env/OPENSHIFT_NOSQL_DB_HOST ORIG_DB_HOST=$OPENSHIFT_NOSQL_DB_HOST . $APP_HOME/.env/OPENSHIFT_INTERNAL_IP IP=$OPENSHIFT_INTERNAL_IP if [ "$ORIG_DB_HOST" != "$IP" ] then . $APP_HOME/.env/OPENSHIFT_NOSQL_DB_PASSWORD . $APP_HOME/.env/OPENSHIFT_NOSQL_DB_USERNAME echo "export OPENSHIFT_NOSQL_DB_HOST='$IP'" > $APP_HOME/.env/OPENSHIFT_NOSQL_DB_HOST echo "export OPENSHIFT_NOSQL_DB_URL='mongodb://$OPENSHIFT_NOSQL_DB_USERNAME:$OPENSHIFT_NOSQL_DB_PASSWORD@$IP:27017/'" > $APP_HOME/.env/OPENSHIFT_NOSQL_DB_URL sed -i "s,$ORIG_DB_HOST,$IP," $MONGODB_DIR/etc/mongodb.conf fi set_app_info "Connection URL: mongodb://$IP:27017/"<file_sep>/RestBA/buildLib.sh echo "Starting Building libs" rm -rf download/lib rm -rf download/lib-sources mvn dependency:copy-dependencies -DoutputDirectory=download/lib mvn dependency:copy-dependencies -Dclassifier=sources -DoutputDirectory=download/lib-sources -Dmdep.failOnMissingClassifierArtifact=false mvn jar:jar cp -f target/restba-1.0.jar download/lib mvn source:jar cp -f target/restba-1.0-sources.jar download/lib-sources echo "End..." <file_sep>/demos/visualizaciones/presupuesto/js/PresupuestoViz.js var PresupuestoViz = function(options) { this.conn = new PresupuestoData(options) this.retrieveByAnio = function() { this.conn.search({}, function(data){ this._dispatchEvent(this._dataByAnio(data), 'retrieveByAnioComplete'); }, this); } this._dataByAnio = function(presupuesto) { // los nombres de las cuentas var label = this.conn.getCuentas(presupuesto); var values = []; _.each(presupuesto.detalle, function(anioData, anioLabel) { var value = { label: anioLabel, values: anioData.valores } values.push(value); }, this); return { label: label, values: values } } this._dispatchEvent = function(data, event) { var e = jQuery.Event(event); e.results = data; $(this).trigger(e); }; };<file_sep>/README.md Atención: El proyecto se encuentra deprecado. Consultas al slack de #nardoz http://www.nardoz.com/ RestOpenGov =========== El proyecto RestOpenGov surge inicialmente para proveer acceso programático a la información que el Gobierno de la Ciudad de Buenos Aires expone a través de http://data.buenosaires.gob.ar/. Luego de una primera iteración el objetivo de RestOpenGov se ha vuelto más general, y se propone proveer una API pública de tipo REST, que permita acceder de una manera estándar a información que los gobiernos de diversos países y ciudades expongan a partir de fuentes heterogéneas de datos. Por lo tanto, RestOpenGov estará compuesto por una serie de proyectos que interactuarán para lograr este fin. ## Proyectos #### [RestOpenGov Crawler](https://github.com/RestOpenGov/RestOpenGov/tree/master/crawler) Es el encargado de acceder periódicamente a los diversos endpoints publicados por los gobiernos, extraer la información que allí publican, procesarla, indexarla y almacenarla en un servidor elasticsearch para su posterior consulta. #### [RestBA](https://github.com/RestOpenGov/RestOpenGov/tree/master/RestBA) API java que brinda acceso programático a la información expuesta por el Gobierno de la Ciudad de Buenos, accediendo a RestOpenGov. Permite a los desarrolladores acceder de manera simple y type-safe a la información expuesta. ## Aplicaciones de ejemplo #### [RestOpenGov.js](https://github.com/RestOpenGov/RestOpenGov/tree/master/RestOpenGov.js) Es un simple cliente de RestOpenGov escrito en Javascript. Permite explorar los datos y realizar búsquedas. #### [openBafici](https://openbafici-rog.rhcloud.com/) Una aplicación web mobile, desarrollada con restOpenGov, Play Framework 2.0 y Scala, desplegada en Openshift, para que puedas consultar toda la información del BAFICI desde tu celular. (fork me at [github](https://github.com/RestOpenGov/RestOpenGov/tree/master/openBafici)) #### [playDemo](https://playdemo-rog.rhcloud.com/) Tutorial paso a paso que que muestra cómo utilizar el servicio de restOpenGov, creando una aplicación Play 2.0 desde cero y poniéndola en línea en Openshift. Consultá el [tutorial](https://github.com/RestOpenGov/RestOpenGov/blob/master/playdemo/README.md) ## Primeros pasos Para comenzar a utilizar una instalación de RestOpenGov hemos preparado [este tutorial](https://github.com/RestOpenGov/RestOpenGov/wiki/Primeros-pasos). ## Comunidad * [Wiki](https://github.com/RestOpenGov/RestOpenGov/wiki) * [Mailing List](http://groups.google.com/group/restopengov) * [Issue Tracking](https://github.com/RestOpenGov/RestOpenGov/issues) * [Seguinos en twitter](https://twitter.com/#!/RestOpenGov) ## Autores * <NAME> ([@nfmelendez](http://twitter.com/nfmelendez)) * <NAME> ([@alan_reid](http://twitter.com/alan_reid)) * <NAME> ([@develsas](http://twitter.com/develsas)) * <NAME> ([@mdellapittima](http://twitter.com/mdellapittima)) * <NAME> ([@palamago](http://twitter.com/palamago)) * <NAME> ([@wfranck](http://twitter.com/wfranck)) ## Licencia Este software es distribuído bajo la licencia Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0 <file_sep>/demos/showCase/deploy.sh rm -fr ../../../RestOpenGov.openshift/demos/showCase/* # resolve symlinks cp -rL * ../../../RestOpenGov.openshift/demos/showCase/ pushd ../../../RestOpenGov.openshift/demos/showCase ./.openshift_deploy popd <file_sep>/elastic-search-openshift-cartridge/info/bin/mongodb_restore.sh #!/bin/bash # Import Environment Variables for f in ~/.env/* do . $f done source /etc/stickshift/stickshift-node.conf CART_INFO_DIR=${CARTRIDGE_BASE_PATH}/embedded/mongodb-2.0/info source ${CART_INFO_DIR}/lib/util function die() { exitcode=${1:-0} tag=${2:-"ERROR"} msg=${3:-"Could not dump restore databases from dump"} echo 1>&2 echo "!$tag! $msg" 1>&2 echo 1>&2 exit $exitcode } # End of function die. function restore_from_mongodb_snapshot() { # Work in a temporary directory (create and cd to it). mkdir -p /tmp/mongodump.$$ pushd /tmp/mongodump.$$ > /dev/null # Extract dump from the snapshot. if ! tar -zxf $OPENSHIFT_DATA_DIR/mongodb_dump_snapshot.tar.gz ; then popd > /dev/null /bin/rm -rf /tmp/mongodump.$$ die 0 "WARNING" "Could not restore MongoDB databases - extract failed!" fi # Restore from the "dump". creds="-u $OPENSHIFT_NOSQL_DB_USERNAME -p \"$OPENSHIFT_NOSQL_DB_PASSWORD\"" if ! mongorestore -h $OPENSHIFT_NOSQL_DB_HOST $creds --directoryperdb --drop; then popd > /dev/null /bin/rm -rf /tmp/mongodump.$$ die 0 "WARNING" "Could not restore MongoDB databases - mongorestore failed!" fi # Restore previous dir and clean up temporary dir. popd > /dev/null /bin/rm -rf /tmp/mongodump.$$ return 0 } # End of function restore_from_mongodb_snapshot. if [ ! -f $OPENSHIFT_DATA_DIR/mongodb_dump_snapshot.tar.gz ]; then echo "MongoDB restore attempted but no dump was found!" 1>&2 die 0 "ERROR" "$OPENSHIFT_DATA_DIR/mongodb_dump_snapshot.tar.gz does not exist" else start_mongodb_as_user restore_from_mongodb_snapshot fi exit 0 #<file_sep>/playdemo/deploy.sh rm -fr ../../RestOpenGov.openshift/playdemo/* cp -r * ../../RestOpenGov.openshift/playdemo pushd ../../RestOpenGov.openshift/playdemo ./.openshift_deploy popd<file_sep>/PlayBafici/public/javascripts/intro.js var opengov = new RestOpenGov(); $(document).ready(function() { if(typeof sessionStorage.getItem("imagesHtml") == 'undefined' || sessionStorage.getItem("imagesHtml") == null) { opengov.search({ dataset: 'bafici', query: '_id:bafici11-films-* AND filepic1:* AND id_film:*', limit: 50 }, function(obj) { var html = ''; var x = 0, y = 0, counter=0; for(var i in obj) { counter++; html += '<div style="position:absolute;top:'+y+'px;left:'+x+'px"><img id="'+i+'" height="150" src="http://www.bafici.gov.ar/home11/photobase/films/' + obj[i]._source.filepic1 + '" /></div>'; x += 150; if(counter % 10 == 0){ y += 150; x = 0; } } sessionStorage.setItem("imagesHtml", html); fx(html); }); } else { fx(sessionStorage.getItem("imagesHtml")); } }); function fx(html) { $('#container').html(html); $('#screen').show(); $('#title').show(); setInterval(function() { $($('#container img').get(Math.floor(Math.random() * $('#container img').length))) .animate({ opacity: 1 }, { duration: 200 }) .animate({ opacity: 0.7 }, { duration: 100 }); }, 70); }<file_sep>/elastic-search-openshift-cartridge/info/bin/mongodb_ctl.sh #!/bin/bash if ! [ $# -eq 1 ] then echo "Usage: $0 [start|restart|stop|status]" exit 1 fi # Import Environment Variables for f in ~/.env/* do . $f done export STOPTIMEOUT=10 if whoami | grep -q root then echo 1>&2 echo "Please don't run script as root, try:" 1>&2 echo "runuser --shell /bin/sh $OPENSHIFT_GEAR_UUID $MONGODB_DIR/${OPENSHIFT_GEAR_NAME}_mongodb_ctl.sh" 1>&2 echo 2>&1 exit 15 fi MONGODB_DIR="$OPENSHIFT_HOMEDIR/mongodb-2.0/" isrunning() { if [ -f $MONGODB_DIR/pid/mongodb.pid ]; then mongodb_pid=`cat $MONGODB_DIR/pid/mongodb.pid 2> /dev/null` myid=`id -u` if `ps --pid $mongodb_pid 2>&1 | grep mongod > /dev/null 2>&1` || `pgrep -x mongod -u $myid > /dev/null 2>&1` then return 0 fi fi return 1 } repair() { if ! isrunning ; then echo "Attempting to repair MongoDB ..." 1>&2 tmp_config="/tmp/mongodb.repair.conf" grep -ve "fork\s*=\s*true" $MONGODB_DIR/etc/mongodb.conf > $tmp_config /usr/bin/mongod --auth --nojournal --smallfiles -f $tmp_config --repair echo "MongoDB repair status = $?" 1>&2 rm -f $tmp_config else echo "MongoDB already running - not running repair" 1>&2 fi } start() { if ! isrunning then /usr/bin/mongod --auth --nojournal --smallfiles --quiet -f $MONGODB_DIR/etc/mongodb.conf run >/dev/null 2>&1 & else echo "MongoDB already running" 1>&2 fi } stop() { if [ -f $MONGODB_DIR/pid/mongodb.pid ]; then pid=$( /bin/cat $MONGODB_DIR/pid/mongodb.pid ) fi if [ -n "$pid" ]; then /bin/kill $pid ret=$? if [ $ret -eq 0 ]; then TIMEOUT="$STOPTIMEOUT" while [ $TIMEOUT -gt 0 ] && [ -f "$MONGODB_DIR/pid/mongodb.pid" ]; do /bin/kill -0 "$pid" >/dev/null 2>&1 || break sleep 1 let TIMEOUT=${TIMEOUT}-1 done fi else if `pgrep -x mongod > /dev/null 2>&1` then echo "Warning: MongoDB process exists without a pid file. Use force-stop to kill." 1>&2 else echo "MongoDB already stopped" 1>&2 fi fi } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; repair) repair start ;; status) if isrunning then echo "MongoDB is running" 1>&2 else echo "MongoDB is stopped" 1>&2 fi exit 0 ;; esac <file_sep>/demos/showCase/public/restopengov.js ../../../RestOpenGov.js<file_sep>/elastic-search-openshift-cartridge/info/lib/util #!/bin/bash # que hace esto? #[ ! -z "$MONGODB_LIB_UTIL" ] && return 0 #MONGODB_LIB_UTIL=true function start_elasticsearch { super_run_as_user "$ELASTICSEARCH_DIR/${application}_elasticsearch_ctl.sh start" #wait_to_start } function restart_mongodb { super_run_as_user "$ELASTICSEARCH_DIR/${application}_mongodb_ctl.sh restart" wait_to_start } function wait_to_start { i=0 while (( ! echo "exit" | mongo $IP > /dev/null 2>&1) || \ [ ! -f ${ELASTICSEARCH_DIR}/pid/mongodb.pid ]) && [ $i -lt 10 ] do sleep 1 i=$(($i + 1)) done } function stop_mongodb { super_run_as_user "$ELASTICSEARCH_DIR/${application}_mongodb_ctl.sh stop" } function repair_mongodb { super_run_as_user "$ELASTICSEARCH_DIR/${application}_mongodb_ctl.sh repair" } function start_mongodb_as_user { ${OPENSHIFT_NOSQL_DB_CTL_SCRIPT} start wait_to_start } function stop_mongodb_as_user { ${OPENSHIFT_NOSQL_DB_CTL_SCRIPT} stop sleep 1 } <file_sep>/playdemo/README.md # Desarrollando una aplicación mobile con restOpenGov usando Play Framework 2.0 y Scala Para mostrarles cómo pueden utilizar la API de restOpenGov, haremos un ejemplo completo, paso a paso, en el cual desarrollaremos una aplicación mobile usando [Play Framework 2.0](http://www.playframework.org/) y Scala, para luego desplegarla en Openshift, la plataforma cloud-computing libre (y gratuita) de Red Hat. Pueden ver y probar la aplicación en [https://playdemo-rog.rhcloud.com/](https://playdemo-rog.rhcloud.com/) ## Instalación de Play Framework Para ello deben tener instalado un [jdk de Java](http://www.oracle.com/technetwork/java/javase/downloads/index.html). Luego descarguen [Play Framework](http://www.playframework.org/) de su sitio web, [aquí](http://download.playframework.org/releases/play-2.0.1.zip) tienen un link. O desde la línea de comandos pueden hacer: wget http://download.playframework.org/releases/play-2.0.1.zip unzip play-2.0.1.zip Para mayor comodidad agréguen el directorio play-2.0.1 al path. ## Creando la aplicación Luego escriban ``` play new playdemo ``` Como nombre de aplicación ingresen 'playdemo' y elijan crear una aplicación simple con scala. Luego deben iniciar la aplicación: ``` cd playdemo play ``` Con esa orden ingresarán a la consola de play. ``` play! 2.0.1, http://www.playframework.org > Type "help play" or "license" for more information. > Type "exit" or use Ctrl+D to leave this console. [playdemo] $ ``` Para iniciar la aplicación, desde la consola de play, escribimos "~ run" ``` [playdemo] $ ~ run [info] Updating {file:/home/sas/dev/apps/tmp/playdemo/}playdemo... --- (Running the application from SBT, auto-reloading is enabled) --- [info] play - Listening for HTTP on port 9000... (Server started, use Ctrl+D to stop and go back to the console...) ``` Abran un explorador en [http://localhost:9000/](http://localhost:9000/) y verán la página de bienvenida de Play Framework. En esta página nos dan una brevísima introducción al funcionamiento del framework, explicando cómo interactúan el archivo de rutas, los controladores y las vistas para mostrarnos la página de bienvenida. Desde cualquier editor de texto, abran el archivo 'app/views/index.scala.html' y cambien `@play20.welcome(message)` por algo como '¡Hola desde restOpenGov!'. Vuelvan al explorador y refrequen la página. > Play recompila automáticamente nuestra aplicación cada vez que detecta un cambio en los archivos. Esto nos permite trabajar con un simple editor de texto, modificar los archivos y ver los cambios reflejados en nuestro explorador. Ya sabemos, si están acostumbrados a trabajar con php, ruby, python o similares, todo esto les parecerá algo natural, pero en el mundo Java esto es bastante novedoso. Si desean [configurar un IDE](https://github.com/opensas/Play20Es/wiki/IDE), tan sólo tienen que frenar el servidor con ctrl-d, ejecutar el comando 'eclipsify' o 'idea' para generar el proyecto para eclipse o IntelliJ respectivamente, volver a iniciar el servidor con '~ run', e importar el proyecto desde el IDE. ##Accediendo a restOpenGov Nuestra aplicación de ejemplo simplemente nos mostrará una lista con el título y el resumen de las películas del festival de Buenos Aires (bafici) y nos permitirá filtrar por texto buscando en el resumen de la película. Nuestro controlador recibirá una parámetro 'q' a través del querystring con los términos a utilizar para filtrar. Usaremos el valor de este parámetro para armar la consultar para acceder al web service de restOpenGov. En nuestro archivo de rutas, especificaremos el parámetro que llegará a nuestro controlador y le asignaremos un string vacío como valor por defecto: /conf/routes ``` # Home page GET / controllers.Application.index(q: String ?= "") ``` Para acceder a la informacion precisaremos armar un url como el siguiente: [http://elastic.restopengov.org/gcba/bafici/_search?fields=title_es,synopsis_es&q=id_film:*+AND+title_es:*](http://elastic.restopengov.org/gcba/bafici/_search?fields=title_es,synopsis_es&q=id_film:*+AND+title_es:*) Podés probarlo con cualquier navegador (agregale un parámetro 'pretty=1' para más comodidad) o desde la línea de comandos: ``` curl http://elastic.restopengov.org/gcba/bafici/_search?pretty=1&fields=title_es,synopsis_es&q=id_film:*+AND+title_es:* ``` Y obtendrás el siguiente mensaje [json](http://json.org/): ``` { "took" : 102, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 1011, "max_score" : 1.4142135, "hits" : [ { "_index" : "gcba", "_type" : "bafici", "_id" : "bafici11-films-4", "_score" : 1.4142135, "fields" : { "title_es" : "Cerdo hormiguero", "synopsis_es" : "La opera prima de Kitao Sakurai[...]" } }, { "_index" : "gcba", "_type" : "bafici", "_id" : "bafici11-films-9", "_score" : 1.4142135, "fields" : { "title_es" : "Pink Saris", "synopsis_es" : "La camara de Kim Longinotto[...]" } [... más películas ...] } ] } } ``` ## El modelo Ahora lo que tendremos que hacer es definir un objeto Film para almacenar esta información, al final del controlador agregamos la siguiente línea: /app/controllers/Application.scala ``` case class Film(id: String, titulo: String, resumen: String) ``` Con esto ya hemos definido una clase, con sus getters y setter, su constructor por defecto y métodos 'Hash' y 'Equals' ## Controladores: Todo bajo control Luego accederemos al web service, para ello tendremos que generar la consulta al web service. Básicamente queremos traer todos los films, que en su título o resumen contengan la frase especificada. Nuestra consulta debería tener la siguiente forma: 'id_film:* AND title_es:* AND (title_es:'termino' OR synopsis_es:'termino') ``` import java.net.URLEncoder object Application extends Controller { def index(q: String = "") = Action { val elasticQuery = "http://elastic.restopengov.org/gcba/bafici/_search?" + "fields=title_es,synopsis_es&" + "q=" + formatQuery("cerdo") Ok(views.html.index("Hola desde restOpenGov")) } private def formatQuery(q:String = ""):String = { val query = if (q=="") { "id_film:* AND title_es:*" } else { "id_film:* AND (title_es:%s OR synopsis_es:%s)".format(q, q) } URLEncoder.encode(query, "UTF-8") } } case class Film(id: String, titulo: String, resumen: String) ``` y parsearemos su resultado como un json ``` // accedemos al web service y parseamos su resultado como un json val json: JsValue = WS.url(elasticQuery).get().await.get.json ``` Ahora lo que debemos hacer es acceder al array de hits, instanciar un film por cada elemento del array de hits, y pasar esta información a nuestra vista. Así es como quedaría nuestro controlador completo app/controllers/Application.scala ``` package controllers import play.api._ import play.api.mvc._ import play.api.libs.ws.WS import play.api.libs.json.JsValue import java.net.URLEncoder import play.Logger object Application extends Controller { def index(q: String = "") = Action { val elasticQuery = "http://elastic.restopengov.org/gcba/bafici/_search?" + "fields=title_es,synopsis_es&" + "q=" + formatQuery(q) Logger.info("[info] about to fetch %s".format(elasticQuery) ) // accedemos al web service y parseamos su resultado como un json val json: JsValue = WS.url(elasticQuery).get().await.get.json // get the hits array val hits = (json \ "hits" \ "hits").as[Seq[JsValue]] // convert json hits to Seq[Film] val films: Seq[Film] = hits.map { hit => Film( (hit \ "_id").as[String], (hit \ "fields" \ "title_es").as[String], (hit \ "fields" \ "synopsis_es").as[String] ) } Ok(views.html.index(q, films, elasticQuery)) } private def formatQuery(q:String = ""):String = { val query = if (q=="") { "id_film:* AND title_es:*" } else { "id_film:* AND (title_es:%s OR synopsis_es:%s)".format(q, q) } URLEncoder.encode(query, "UTF-8") } } case class Film(id: String, titulo: String, resumen: String) ``` ## La Vista Ahora bien, si vuelven al explorador y refrescan la página se encontrarán con el siguiente error: ``` too many arguments for method apply: (message: String)play.api.templates.Html in object index ``` Play nos avisa que tenemos que actualizar nuestro template y agregar los parámetros necesarios. Todas estas validaciones son realizadas por Play en tiempo de compilación. En la vista lo único que haremos será crear un form para que ingresen el término a buscar, y luego iterar la lista de films para mostrarlos en pantalla. También crearemos links a la consulta de nuestro web service para que lo puedan ver en acción. app/views/index.scala.html ``` @(q: String, films: Seq[Film], elasticQuery: String) @main("Welcome to Play 2.0") { <h1>Play Framework 2.0 simple demo for restOpenGov</h1><hr /> <form method="get" action="@routes.Application.index()"> <label for="query">Buscar:</label> <input type="text" name="q" value="@q" /> <input type="submit" id="submit"value="Buscar" /> </form> <h3><a target="_blank" href="@elasticQuery">Filmes</a></h3> <table class="table"> @for(film <- films) { <tr> <th><a target="_blank" href="http://elastic.restopengov.org/gcba/bafici/@film.id?pretty=1">@film.titulo</a></th> <td>@film.resumen</td> </tr> } </table> } ``` Pueden ir al explorador y refrescar la página. Ingresen un término de búsqueda y todo debería funcionar bien. Como último paso, aplicaremos twitter bootstrap a nuestra aplicación para mejorar su apariencia. Agreguen el estilo de twitter bootstrap y encierren en @content en un "container" div app/views/main.scala.html ``` @(title: String)(content: Html) <!DOCTYPE html> <html> <head> <title>@title</title> <link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet"> <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")"> <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")"> <script src="@routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <div class="container"> @content </div> </body> </html> ``` Y luego agreguemos algo de estilo a nustra página: app/views/indes.scala.html ``` @(q: String, films: Seq[Film], elasticQuery: String) @main("Welcome to Play 2.0") { <h1>Play Framework 2.0 simple demo for restOpenGov</h1><hr /> <form method="get" action="@routes.Application.index()" id="form" class="form-inline" > <p> <label for="query">Buscar:</label> <input type="text" name="q" value="@q" /> <input type="submit" id="submit" class="btn btn-primary" value="Buscar" /> </form> <h3><a target="_blank" href="@elasticQuery">Filmes</a></h3> <table class="table"> @for(film <- films) { <tr> <th><a target="_blank" href="http://elastic.restopengov.org/gcba/bafici/@film.id?pretty=1">@film.titulo</a></th> <td>@film.resumen</td> </tr> } </table> } ``` ## ¡A la nube! Ahora vamos a poner esta aplicación en producción en [Openshift](https://openshift.redhat.com/) la nube de Red Hat. Para ellos vamos a utilizar el siguiente [quickstart](https://github.com/opensas/play2-openshift-quickstart). Tambien tenés un [screen cast](http://playlatam.wordpress.com/2012/05/01/desplegando-aplicaciones-de-play-framework-2-con-java-y-scala-en-openshift/) en el que mostramos paso a paso como desarrollar una aplicación con Play, usando Java y Scala, para luego deplegarla en Openshift. Antes que nada tendrás que sacar una cuenta en Openshift, instalar git y el el cliente de línea de comando de Openshift, registrar tu clave pública ssh y generar un dominio. Tan sólo sigan los pasos 3 al 5 de [este artículo](http://playlatam.wordpress.com/2012/02/09/play-framework-on-the-cloud-made-easy-openshift-module/) Estando en el directorio de tu aplicación, ejecuta los siguientes comandos para crear un repositorio git: ``` git init ``` Luego deberás ejecutar este comando para crear una nueva aplicación en openshift: ``` rhc app create -a playdemo -t diy-0.1 --nogit -l <EMAIL> -p yoursecretpass Creating application: playdemo Now your new domain name is being propagated worldwide (this might take a minute)... !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! IMPORTANT: Since the -n flag was specified, no local repo has been created. This means you can't make changes to your published application until after you clone the repo yourself. See the git url below for more information. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Confirming application 'playdemo' is available: Success! playdemo published: http://playdemo-yourlogin.rhcloud.com/ git url: ssh://2e2d7a222f7c44d9a529f940363bdb7f@playdemo-yourlogin.rhcloud.com/~/git/playdemo.git/ Disclaimer: This is an experimental cartridge that provides a way to try unsupported languages, frameworks, and middleware on Openshift. ``` Copia la dirección del repositorio recién creado para agregarlo como un repositorio remoto y traerte el contenido: ``` git remote add origin ssh://2e2d7a222f7c44d9a529f940363bdb7f@playdemo-yourlogin.rhcloud.com/~/git/playdemo.git/ git pull -s recursive -X theirs origin master git add . git commit -m "initial deploy" ``` Ahora traeremos el contenido del quickstart a nuestro repositorio local ``` git remote add quickstart -m master git://github.com/opensas/play2-openshift-quickstart.git git pull -s recursive -X theirs quickstart master ``` Ahora tan sólo tendremos que compilar nuestra aplicación de play y luego agregar los cambios y enviarlos a nuestro repositorio remoto en openshift: ``` play clean compile stage git add . git commit -m "mi primer deploy" git push origin ``` Opcionalmente puedes ejecutar un script que agregramos para facilitar esta tarea: ``` openshift_deploy ``` Tu aplicación estará lista en playdemo-yourlogin.rhcloud.com Y eso es todo. La primera vez tardará unos cuantos minutos porque hay que enviar todas las librerías de Play (aproximadamente 30 MB) pero luego tan śolo se enviarán las diferencias. Puedes ir monitoreando los logs de tu aplicación con el siguiente comando: ``` rhc app tail -a playdemo -l <EMAIL> -p yoursecretpass ``` Para más información pueden consultar [este artículo](http://playlatam.wordpress.com/2012/05/01/soporte-nativo-para-play-framework-en-openshift-con-el-nuevo-tipo-de-aplicacion-diy/). Saludo y happy hacking sas <file_sep>/RestOpenGov.js/demos/datagrid/js/preload.js var opengov = new RestOpenGov(); $(function() { opengov.search({ dataset: 'bafici', query: '', limit: 100 }, function(obj) { var html = ''; for(var i in obj) { if(typeof obj[i]._source.filepic1 != "undefined" && obj[i]._source.filepic1.length > 0) { html += '<span><img src="http://www.bafici.gov.ar/home11/photobase/films/' + obj[i]._source.filepic1 + '" /></span>'; } } $('#container').html(html); $('#screen, #title').show(); setInterval(function() { $($('#container img').get(Math.floor(Math.random() * $('#container img').length))) .animate({ opacity: 1 }, { duration: 200 }) .animate({ opacity: 0.7 }, { duration: 100 }); }, 70); }); }); <file_sep>/tools/elasticsearch-0.19.9/plugins/head/_site/lib/es/core.js (function() { var es = window.es = {}; /* notes on elasticsearch terminology used in this project indices[index] contains one or more types[type] contains one or more documents contain one or more paths[path] each path contains one element of data each path maps to one field eg PUT, "/twitter/tweet/1" { user: "mobz", date: "2011-01-01", message: "You know, for browsing elasticsearch", name: { first: "Ben", last: "Birch" } } creates 1 index: twitter this is the collection of index data 1 type: tweet this is the type of document (kind of like a table in sql) 1 document: /twitter/tweet/1 this is an actual document in the index ( kind of like a row in sql) 5 paths: [ ["user"], ["date"], ["message"], ["name","first"], ["name","last"] ] since documents can be heirarchical this maps a path from a document root to a piece of data 5 fields: [ "user", "date", "message", "first", "last" ] this is an indexed 'column' of data. fields are not heirarchical the relationship between a path and a field is called a mapping. mappings also contain a wealth of information about how es indexes the field notes 1) a path is stored as an array, the dpath is <index> . <type> . path.join("."), which can be considered the canonical reference for a mapping 2) confusingly, es uses the term index for both the collection of indexed data, and the individually indexed fields so the term index_name is the same as field_name in this sense. */ es.storage = (function() { var storage = {}; return { get: function(k) { try { return JSON.parse(localStorage[k] || storage[k]); } catch(e) { return null } }, set: function(k, v) { v = JSON.stringify(v); localStorage[k] = v; storage[k] = v; } }; })(); var coretype_map = { "string" : "string", "long" : "number", "integer" : "number", "float" : "number", "double" : "number", "ip" : "number", "date" : "date", "boolean" : "boolean", "binary" : "binary" }; var default_property_map = { "string" : { "store" : "no", "index" : "analysed" }, "number" : { "store" : "no", "precision_steps" : 4 }, "date" : { "store" : "no", "format" : "dateOptionalTime", "index": "yes", "precision_steps": 4 }, "boolean" : { "store" : "no", "index": "yes" }, "binary" : { } }; es.Cluster = acx.Class.extend({ defaults: { base_uri: "http://localhost:9200/" }, request: function(params) { return $.ajax(acx.extend({ url: this.config.base_uri + params.path, dataType: "json", error: function(xhr, type, message) { if("console" in window) { console.log({ "XHR Error": type, "message": message }); } } }, params)); }, "get": function(path, success) { return this.request( { type: "GET", path: path, success: success } ); }, "post": function(path, data, success) { return this.request( { type: "POST", path: path, data: data, success: success } ); }, "put": function(path, data, success) { return this.request( { type: "PUT", path: path, data: data, success: success } ); }, "delete": function(path, data, success) { return this.request( { type: "DELETE", path: path, data: data, success: success } ); } }); // parses metatdata from a cluster, into a bunch of useful data structures es.MetaData = acx.ux.Observable.extend({ defaults: { state: null // (required) response from a /_cluster/state request }, init: function() { this._super(); this.refresh(this.config.state); }, getIndices: function(alias) { return alias ? this.aliases[alias] : this.indicesList; }, // returns an array of strings containing all types that are in all of the indices passed in, or all types getTypes: function(indices) { var indices = indices || [], types = []; this.typesList.forEach(function(type) { for(var i = 0; i < indices.length; i++) { if(! this.indices[indices[i]].types.contains(type)) return; } types.push(type); }, this); return types; }, refresh: function(state) { // currently metadata expects all like named fields to have the same type, even when from different types and indices var aliases = this.aliases = {}; var indices = this.indices = {}; var types = this.types = {}; var fields = this.fields = {}; var paths = this.paths = {}; function createField(mapping, index, type, path, name) { var dpath = [index, type ].concat(path).join("."); var field_name = mapping.index_name || name; var field = paths[dpath] = fields[field_name] = fields[field_name] || acx.extend({ field_name: field_name, core_type: coretype_map[mapping.type], dpaths: [] }, default_property_map[coretype_map[mapping.type]], mapping); field.dpaths.push(dpath); return field; } function getFields(properties, type, index, listeners) { (function(prop, path) { for(var n in prop) { if("properties" in prop[n]) { arguments.callee(prop[n].properties, path.concat(n)); } else { var field = createField(prop[n], index, type, path.concat(n), n); listeners.forEach(function(obj) { obj[field.field_name] = field; }); } } })(properties, []); } for(var index in state.metadata.indices) { indices[index] = { types: [], fields: {}, paths: {} }; indices[index].aliases = state.metadata.indices[index].aliases; indices[index].aliases.forEach(function(alias) { ( aliases[alias] || (aliases[alias] = [ ])).push(index); }); var mapping = state.metadata.indices[index].mappings; for(var type in mapping) { indices[index].types.push(type); if( type in types ) { types[type].indices.push( index ); } else { types[type] = { indices: [ index ], fields: {} }; } getFields(mapping[type].properties, type, index, [ fields, types[type].fields, indices[index].fields ]); } } this.aliasesList = Object.keys(aliases); this.indicesList = Object.keys(indices); this.typesList = Object.keys(types); this.fieldsList = Object.keys(fields); } }); es.MetaDataFactory = acx.ux.Observable.extend({ defaults: { cluster: null // (required) an es.Cluster }, init: function() { this._super(); this.config.cluster.get("_cluster/state", function(data) { this.metaData = new es.MetaData({state: data}); this.fire("ready", this.metaData, { originalData: data }); // TODO originalData needed for legacy es.FilterBrowser }.bind(this)); } }); es.Query = acx.ux.Observable.extend({ defaults: { cluster: null, // (required) instanceof es.Cluster size: 50 // size of pages to return }, init: function() { this._super(); this.cluster = this.config.cluster; this.refuid = 0; this.refmap = {}; this.indices = []; this.types = []; this.search = { query: { bool: { must: [], must_not: [], should: [] } }, from: 0, size: this.config.size, sort: [], facets: {}, version: true }; this.defaultClause = this.addClause(); this.history = [ this.getState() ]; }, clone: function() { var q = new es.Query( { cluster: this.cluster } ); q.restoreState(this.getState()); for(var uqid in q.refmap) { q.removeClause(uqid); } return q; }, getState: function() { return acx.extend(true, {}, { search: this.search, indices: this.indices, types: this.types }); }, restoreState: function(state) { state = acx.extend(true, {}, state || this.history[this.history.length - 1]); this.indices = state.indices; this.types = state.types; this.search = state.search; }, getData: function() { return JSON.stringify(this.search); }, query: function() { var state = this.getState(); this.cluster.post( (this.indices.join(",") || "_all") + "/" + ( this.types.length ? this.types.join(",") + "/" : "") + "_search", this.getData(), function(results) { if(results === null) { alert("Query Failed. Undoing last changes"); this.restoreState(); return; } this.history.push(state); this.fire("results", this, results); }.bind(this)); }, setPage: function(page) { this.search.from = this.config.size * (page - 1); }, setSort: function(index, desc) { var sortd = {}; sortd[index] = { reverse: !!desc }; this.search.sort.unshift( sortd ); for(var i = 1; i < this.search.sort.length; i++) { if(Object.keys(this.search.sort[i])[0] === index) { this.search.sort.splice(i, 1); break; } } }, setIndex: function(index, add) { if(add) { if(! this.indices.contains(index)) this.indices.push(index); } else { this.indices.remove(index); } this.fire("setIndex", this, { index: index, add: !!add }); }, setType: function(type, add) { if(add) { if(! this.types.contains(type)) this.types.push(type); } else { this.types.remove(type); } this.fire("setType", this, { type: type, add: !!add }); }, addClause: function(value, field, op, bool) { bool = bool || "should"; op = op || "match_all"; field = field || "_all"; var clause = this._setClause(value, field, op, bool); var uqid = "q-" + this.refuid++; this.refmap[uqid] = { clause: clause, value: value, field: field, op: op, bool: bool }; if(this.search.query.bool.must.length + this.search.query.bool.should.length > 1) { this.removeClause(this.defaultClause); } this.fire("queryChanged", this, { uqid: uqid, search: this.search} ); return uqid; // returns reference to inner query object to allow fast updating }, removeClause: function(uqid) { var ref = this.refmap[uqid], bool = this.search.query.bool[ref.bool]; bool.remove(ref.clause); if(this.search.query.bool.must.length + this.search.query.bool.should.length === 0) { this.defaultClause = this.addClause(); } }, addFacet: function(facet) { var facetId = "f-" + this.refuid++; this.search.facets[facetId] = facet; this.refmap[facetId] = { facetId: facetId, facet: facet }; return facetId; }, removeFacet: function(facetId) { delete this.search.facets[facetId]; delete this.refmap[facetId]; }, _setClause: function(value, field, op, bool) { var clause = {}, query = {}; if(op === "match_all") { } else if(op === "query_string") { query["default_field"] = field; query["query"] = value; } else { query[field] = value; } clause[op] = query; this.search.query.bool[bool].push(clause); return clause; } }); es.AbstractDataSourceInterface = acx.data.DataSourceInterface.extend({ _getSummary: function(res) { this.summary = acx.text("TableResults.Summary", res._shards.successful, res._shards.total, res.hits.total, (res.took / 1000).toFixed(3)); }, _getMeta: function(res) { this.meta = { total: res.hits.total, shards: res._shards, tool: res.took }; } }); es.ResultDataSourceInterface = es.AbstractDataSourceInterface.extend({ results: function(res) { this._getSummary(res); this._getMeta(res); this._getData(res); this.sort = {}; this.fire("data", this); }, _getData: function(res) { var columns = this.columns = []; this.data = res.hits.hits.map(function(hit) { var row = (function(path, spec, row) { for(var prop in spec) { if(acx.isObject(spec[prop])) { arguments.callee(path.concat(prop), spec[prop], row); } else if(acx.isArray(spec[prop])) { if(spec[prop].length) { arguments.callee(path.concat(prop), spec[prop][0], row) } } else { var dpath = path.concat(prop).join("."); if(! columns.contains(dpath)) { columns.push(dpath); } row[dpath] = (spec[prop] || "null").toString(); } } return row; })([ hit._type ], hit, {}); row._source = hit; return row; }, this); } }); es.QueryDataSourceInterface = es.AbstractDataSourceInterface.extend({ defaults: { metadata: null, // (required) instanceof es.MetaData, the cluster metadata query: null // (required) instanceof es.Query the data source }, init: function() { this._super(); this.config.query.on("results", this._results_handler.bind(this)); }, _results_handler: function(query, res) { this._getSummary(res); this._getMeta(res); var sort = query.search.sort[0] || { "_score": { reverse: false }}; var sortField = Object.keys(sort)[0]; this.sort = { column: sortField, dir: (sort[sortField].reverse ? "asc" : "desc") }; this._getData(res, this.config.metadata); this.fire("data", this); }, _getData: function(res, metadata) { var metaColumns = ["_index", "_type", "_id", "_score"]; var columns = this.columns = [].concat(metaColumns); this.data = res.hits.hits.map(function(hit) { var row = (function(path, spec, row) { for(var prop in spec) { if(acx.isObject(spec[prop])) { arguments.callee(path.concat(prop), spec[prop], row); } else if(acx.isArray(spec[prop])) { if(spec[prop].length) { arguments.callee(path.concat(prop), spec[prop][0], row) } } else{ var dpath = path.concat(prop).join("."); if(metadata.paths[dpath]) { var field_name = metadata.paths[dpath].field_name; if(! columns.contains(field_name)) { columns.push(field_name); } row[field_name] = (spec[prop] === null ? "null" : spec[prop] ).toString(); } else { // TODO: field not in metadata index } } } return row; })([ hit._index, hit._type ], hit._source, {}); metaColumns.forEach(function(n) { row[n] = hit[n]; }); row._source = hit; return row; }, this); } }); })(); <file_sep>/crawler/src/main/java/com/nardoz/restopengov/ckan/utils/DatasetReaderResult.java package com.nardoz.restopengov.ckan.utils; import com.nardoz.restopengov.utils.ICSVFetcherResult; import java.util.ArrayList; import java.util.List; public class DatasetReaderResult implements ICSVFetcherResult { private List<String> jsonList = new ArrayList<String>(); public List<String> getJsonList() { return jsonList; } public void onStart() { } public void add(String id, String json) { jsonList.add(json); } public void onEnd() { } } <file_sep>/elastic-search-openshift-cartridge/info/hooks/pre-install #!/bin/bash # Confirms all required php bits are in place or fails set -e source "/etc/stickshift/stickshift-node.conf" source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util CARTRIDGE_DIR=${CARTRIDGE_DIR:=${CARTRIDGE_BASE_PATH}/embedded/mongodb-2.0/} function print_help { echo "Usage: customername" exit 1 } function quit { echo -e "$1" 1>&2 exit 5 } while getopts 'd' OPTION do case $OPTION in d) set -x ;; ?) print_help ;; esac done [ $# -eq 1 ] || print_help customer=$1 rpm -q libmongodb mongodb-server mongodb-devel mongodb > /dev/null || quit "Missing packages" [ -d "$CARTRIDGE_DIR" ] || quit "Missing cartridge dir: $CARTRIDGE_DIR"<file_sep>/PlayBafici/deploy.sh rm -fr ../../RestOpenGov.openshift/PlayBafici/* cp -r * ../../RestOpenGov.openshift/PlayBafici pushd ../../RestOpenGov.openshift/PlayBafici ./.openshift_deploy popd<file_sep>/elastic-search-openshift-cartridge/info/hooks/deconfigure #!/bin/bash # Destroys mongodb instance function print_help { echo "Usage: $0 app-name namespace uuid" echo "$0 $@" | logger -p local0.notice -t stickshift_mongodb_deconfigure exit 1 } while getopts 'd' OPTION do case $OPTION in d) set -x ;; ?) print_help ;; esac done [ $# -eq 3 ] || print_help source "/etc/stickshift/stickshift-node.conf" source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util CART_INFO_DIR=${CARTRIDGE_BASE_PATH}/embedded/mongodb-2.0/info app_type="mongodb-2.0" setup_embedded_deconfigure "$1" $2 $3 source ${CART_INFO_DIR}/lib/util MONGODB_DIR="$APP_HOME/mongodb-2.0/" # # Teardown port proxy (ignore failures or missing hook) # ( ${CART_INFO_DIR}/hooks/conceal-port "$1" $2 $3 ) &>/dev/null || : # # Remove environment variables # /bin/rm -f $APP_HOME/.env/OPENSHIFT_NOSQL_DB_USERNAME $APP_HOME/.env/OPENSHIFT_NOSQL_DB_PASSWORD $APP_HOME/.env/OPENSHIFT_NOSQL_DB_TYPE $APP_HOME/.env/OPENSHIFT_NOSQL_DB_HOST $APP_HOME/.env/OPENSHIFT_NOSQL_DB_PORT $APP_HOME/.env/OPENSHIFT_NOSQL_DB_SOCKET $APP_HOME/.env/OPENSHIFT_NOSQL_DB_URL $APP_HOME/.env/OPENSHIFT_NOSQL_DB_CTL_SCRIPT $APP_HOME/.env/OPENSHIFT_NOSQL_DB_MONGODB_20_DUMP $APP_HOME/.env/OPENSHIFT_NOSQL_DB_MONGODB_20_DUMP_CLEANUP $APP_HOME/.env/OPENSHIFT_NOSQL_DB_MONGODB_20_RESTORE $APP_HOME/.env/OPENSHIFT_NOSQL_DB_MONGODB_20_EMBEDDED_TYPE stop_mongodb confirm_pid_gone "${MONGODB_DIR}/pid/mongodb.pid" runcon -l s0-s0:c0.c1023 rm -rf "$MONGODB_DIR" "$MONGODB_DIR/${application}_mongodb_ctl.sh"<file_sep>/demos/visualizaciones/presupuesto/js/PresupuestoData.js var PresupuestoData = function(options) { var defaultConfig = { entryPointURL: "http://elastic.restopengov.org/", dataSource: "apn", dataset: "presupuesto", }; this.config = $.extend(defaultConfig, options); this.restOpenGov = new RestOpenGov(this.config); this.COLORS = { '1 - ADMINISTRACION GUBERNAMENTAL' : '#e60042', '2 - SERVICIOS DE DEFENSA Y SEGURIDAD':'#ff7600', '3 - SERVICIOS SOCIALES':'#62e200', '4 - SERVICIOS ECONOMICOS':'#7309aa', '5 - DEUDA PUBLICA':'#ffddee' }; this.search = function(options, callback, context) { var defaultOptions = { dataset: this.config.dataset, query: '*:*', limit: 300, from: 0, anio: undefined, cuenta: undefined, subcuenta: undefined }; var searchParams = $.extend(defaultOptions, options); var query = ''; if (searchParams.anio != undefined) query += ' AND anio:' + searchParams.anio; if (searchParams.cuenta != undefined) query += ' AND cuenta:' + searchParams.cuenta; if (searchParams.subcuenta != undefined) query += ' AND subcuenta:' + searchParams.subcuenta; // remove first ' AND ' if (query!='') searchParams.query = query.substring(5); this.restOpenGov.search(searchParams, function(rawData) { var data; switch(searchParams.graph){ case 'ring': data = this.processDataRing(rawData); break; default: data = this.processData(rawData); break; } if (context) { callback.call(context, data); } else { callback(data); } }, this); }; this.processDataRing = function(data) { var temp = {},temp2 = [],json={}; var anio; var instance = this; $(data).each(function(i,e){ //cuenta if(!temp[e._source.cuenta]){ anio = e._source.anio; temp[e._source.cuenta] = { id:e._source.cuenta, name:e._source.cuenta, data:{ "$color": instance.COLORS[e._source.cuenta], "$angularWidth": 0, "size": 0.0 }, children : [] } } temp[e._source.cuenta].data.size += parseFloat(e._source.valor.replace(".","").replace(",",".")); temp[e._source.cuenta].data['$angularWidth'] += parseFloat(e._source.valor.replace(".","").replace(",",".")); var c = { id:e._source.subcuenta, name:e._source.subcuenta, data:{ "$color": temp[e._source.cuenta].data['$color'], "$angularWidth": e._source.valor.replace(".","").replace(",",""), "size": parseFloat(e._source.valor.replace(".","").replace(",",".")) } }; temp[e._source.cuenta].children.push(c); }); $.each(temp, function(key, value) { temp2.push(value); }); json = { id:anio, name:anio, children : temp2 }; return json; } // procesa la informacion "cruda" de RestOpenGov // y retorna la informacion del presupuesto segun la siguiente estructura: // presupuesto: { // label: presupuesto 2007-2011 // total: xxx.xx // detalle: { // 2007: { // label: presupuesto 2007 // total: xxx.xx // porcentaje: xx.xx // detalle: { // 1 - ADMINISTRACION GUBERNAMENTAL: { // label: 1 - ADMINISTRACION GUBERNAMENTAL // total: xxx.xx // porcentaje: xx.xx // detalle: { // 11-Legislativa: { // label: 11-Legislativa // total: xxx.xx // porcentaje: xx.xx // }, [...] // } // } // } // }, [...] // } // // } this.processData = function(data) { // remove _source and all the rest of the elastic search info data = _.map(data, function(row) { return row._source }); var presupuesto = {}; var byAnio = _.groupBy(data, 'anio'); // Presupuesto var anios = this._properties(byAnio); var anioFrom = _.min(anios); var anioTo = _.max(anios); presupuesto.label = 'Presupuesto ' + (anios.length == 1 ? anioFrom : anioFrom + '-' + anioTo); presupuesto.anios = anios.length; presupuesto.total = undefined; presupuesto.detalle = {}; _.each(byAnio, function(anioRows, anioLabel) { // Anio var anio = {}; anio.label = anioLabel; anio.detalle = {}; var byCuenta = _.groupBy(anioRows, 'cuenta'); _.each(byCuenta, function(cuentaRows, cuentaLabel) { // Cuenta var cuenta = {}; cuenta.label = cuentaLabel; cuenta.detalle = {}; _.each(cuentaRows, function(subcuentaRow) { // Subcuenta var subcuenta = {}; subcuenta.label = subcuentaRow.subcuenta; subcuenta.total = this._strToNum(subcuentaRow.valor); cuenta.detalle[subcuenta.label] = subcuenta; }, this); cuenta.total = this._calculateTotal(cuenta.detalle); cuenta.valores = this._detalleAsArray(cuenta.detalle, 'total'); cuenta.porcentajes = this._detalleAsArray(cuenta.detalle, 'porcentaje'); anio.detalle[cuenta.label] = cuenta; }, this); anio.total = this._calculateTotal(anio.detalle); anio.valores = this._detalleAsArray(anio.detalle, 'total'); anio.porcentajes = this._detalleAsArray(anio.detalle, 'porcentaje'); presupuesto.detalle[anio.label] = anio; }, this); presupuesto.total = this._calculateTotal(presupuesto.detalle); presupuesto.valores = this._detalleAsArray(presupuesto.detalle, 'total'); presupuesto.porcentajes = this._detalleAsArray(presupuesto.detalle, 'porcentaje'); return presupuesto; } this._properties = function(obj) { var properties = []; for (prop in obj) { properties.push(prop); } return properties; } this._strToNum = function(value) { return this._formatNum(value.replace('.', '').replace(',', '.')); } this._formatNum = function(num) { return parseFloat(parseFloat(num).toFixed(2)); } // retorna la suma total de los items, y actualiza el porcentaje de cada item this._calculateTotal = function(items) { var total = _.reduce(items, function(memo, item) { return memo + item.total }, 0); _.each(items, function(item) { item.porcentaje = this._formatNum(item.total * 100 / total); }, this); return this._formatNum(total); }, // helper functions to get anios, cuentas, subcuentas this.getAnios = function(presupuestoData) { return this._properties(presupuestoData.detalle); }, this.getCuentas = function(presupuestoData) { var cuentas = []; _.each(presupuestoData.detalle, function(anio, anioLabel) { var current = this._properties(anio.detalle); $.merge(cuentas, current); }, this); return _.uniq(cuentas); } this._detalleAsArray = function(items, campo) { return _.map(items, campo); } };<file_sep>/RestOpenGov.js/README.md ## RestOpenGov.js RestOpenGov.js es un simple cliente en Javascript para correr consultas client-side. ### Demos En la carpeta de demos se encuentran ejemplos de uso del cliente. Notar que sólo son para fines demostrativos y no pretenden ser aplicaciones para un usuario final. ### Instalación Incluír jQuery y el RestOpenGov.js: ``` <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script> <script type="text/javascript" src="RestOpenGov.js"></script> ``` ### Ejecutar una búsqueda ``` <script type="text/javascript"> RestOpenGov.search({ dataset: 'bafici', query: 'terror' }, function(results) { console.log(results); }); </script> ``` ### Configuración Para configurar otro endpoint u otro index, hay que instanciar RestOpenGov y pasarle esos datos al constructor: ``` <script type="text/javascript"> var opengov = new RestOpenGov({ entryPointURL: 'http://urlpropia.com/', dataSource: 'miIndice' }); opengov.search({ dataset: 'bafici', query: 'terror' }, function(results) { console.log(results); }); </script> ``` Para paginar los resultados, no hay más que pasar el comienzo y la cantidad de resultados: ``` <script type="text/javascript"> var opengov = new RestOpenGov({ endpoint: 'http://urlpropia.com/', dataSource: 'miIndice' }); opengov.search({ dataset: 'bafici', query: 'terror', from: 400, limit: 200 }, function(results) { console.log(results); }); </script> ``` ## Licencia Este software es distribuído bajo la licencia Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0
f1290e3d23b6a93bd27e2012ccf6f6c67ee3b224
[ "Markdown", "Java", "JavaScript", "Shell" ]
47
Markdown
RestOpenGov/RestOpenGov
e2da2b966ec1a7c5b8ada518697cda65887dd237
d52661ffb496ed7956d217bcb9f786430a60453c
refs/heads/master
<repo_name>machiapply/svelte-webpack<file_sep>/src/router.js import Navigo from 'navigo'; const base = process.env.SITE_PUBLIC_PATH; const useHash = true; //Defaults to false const hash = '#!'; //Defaults to '#' // const router = new Navigo(base, useHash, hash); const router = new Navigo(base); export default router;
b4505d004e357d549fc928a90a4a17bb8a7fbd10
[ "JavaScript" ]
1
JavaScript
machiapply/svelte-webpack
504fac6c676f40b8c0b65c8d4a5a6d9fd9891d08
486fb580f4e1659dd979eddef2afe44a90687eec
refs/heads/master
<file_sep>import { useState, useEffect } from "react"; import { motion, AnimateSharedLayout } from "framer-motion"; import router from "next/router"; import { AiOutlineArrowRight } from "react-icons/ai"; import { Button, Rate } from "antd"; import { LeftOutlined, StarFilled } from "@ant-design/icons"; function numberWithCommas(x) { return x?.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } function ExpandCard({ product, setIsOpen }) { console.log(product); const [open, setOpen] = useState(false); useEffect(() => { setIsOpen(open); }, [open]); const imageMotion = { rest: { scale: 1, transition: { duration: 0.5, zIndex: 1000, ease: "easeInOut" }, }, hover: { scale: 1.1, transition: { duration: 0.5, zIndex: 1000, ease: "easeInOut" }, }, }; const containerMotion = { rest: { scale: 1, transition: { duration: 0.5, zIndex: 1000, ease: "easeInOut" }, }, hover: { scale: 1.05, transition: { duration: 0.5, zIndex: 1000, ease: "easeInOut" }, }, }; return ( <AnimateSharedLayout type="switch"> {open ? ( <motion.div className="expanded-card" layoutId="expandable-card"> <motion.img className="expanded-card-image" layoutId={product.id} src={product.image} alt="" /> <motion.h1 className="expanded-card-price" layoutId="expandable-card-price" > {numberWithCommas(product.price)} {product.currency} <motion.div layoutId="expandable-card-stars" className="rating-container-expand" > <Rate style={{ color: "#fff" }} character={(e) => <StarFilled className="single-star" />} className="stars" disabled value={product.rating} /> </motion.div> </motion.h1> <motion.div className="container"> <Button onClick={() => setOpen(false)} className="close-btn" icon={<LeftOutlined style={{ fontSize: "1em" }} />} type="primary" /> <div className="expanded-card-content"> <div className="name-price"> <motion.h1 className="expanded-card-h" layoutId="expandable-card-h" > {product.name} </motion.h1> </div> <p className="description">{product.description}</p> <Button size="large" type="primary" className="button"> Add To Cart </Button> </div> </motion.div> </motion.div> ) : ( <motion.div initial="rest" whileHover="hover" animate="rest" variants={containerMotion} onClick={() => setOpen(true)} className="normal-card" layoutId="expandable-card" > <motion.img variants={imageMotion} className="normal-card-image" layoutId={product.id} src={product.image} alt="" /> <motion.div className="normal-card-type"> <motion.p layoutId="expandable-card-h" className="h1"> {product.name} </motion.p> <motion.div layoutId="expandable-card-stars" className="rating-container" > <Rate style={{ color: "#fc9803" }} character={(e) => <StarFilled className="single-star" />} className="stars" disabled value={product.rating} /> <motion.p>({product.rating})</motion.p> </motion.div> <motion.span className="card-price-wrapper"> <motion.p className="card-price" layoutId="expandable-card-price"> {numberWithCommas(product.price)} </motion.p> <motion.p className={"card-currency"}> {product.currency} </motion.p> </motion.span> </motion.div> </motion.div> )} </AnimateSharedLayout> ); } export default ExpandCard; <file_sep>import { FaHamburger } from "react-icons/fa"; import { Button, Avatar, Popover, button } from "antd"; import Link from "next/link"; import Cookies from "js-cookie"; import { useState, useEffect } from "react"; import { Pagination } from "antd"; const MainLayout = ({ children, hidden, filled, paginationCount, onChangePagination, }) => { const [user, setUser] = useState(); useEffect(() => { getAndSet(); }, []); const getAndSet = async () => { const user = await Cookies.get("client"); if (user) setUser(JSON.parse(user)); }; const logout = async () => { await Cookies.remove("token"); await Cookies.remove("client"); setUser(null); }; const content = ( <div> <Button danger type="primary" onClick={logout}> Logout </Button> </div> ); return ( <> {hidden ? null : ( <nav style={{ backgroundColor: filled ? "#fff" : "transparent" }}> <div className="container"> <Link href="/"> <div className="logo"> <FaHamburger className="logo-icon" /> <h1>FikraFood</h1> </div> </Link> {user ? ( <Popover trigger="click" content={content}> <div className="user"> <h2>{user.name}</h2> <Avatar style={{ backgroundColor: "orange", verticalAlign: "middle", }} size="large" gap="4" > {user.name[0].toUpperCase()} </Avatar> </div> </Popover> ) : ( <div className="menu"> <Link href="/login"> <Button className="login-btn">LOGIN</Button> </Link> <Link href="/signup"> <Button className="signup-btn" type="primary"> SIGN UP </Button> </Link> </div> )} </div> </nav> )} <div>{children}</div> {paginationCount && ( <div className="pagination-wrapper"> <Pagination pageSize={10} defaultCurrent={1} total={paginationCount} onChange={onChangePagination} /> </div> )} </> ); }; export default MainLayout; <file_sep>import Head from "next/head"; import Image from "next/image"; import styles from "../styles/Home.module.css"; import MainLayout from "../components/MainLayout"; import { Carousel } from "react-responsive-carousel"; import { useEffect, useState } from "react"; import { config } from "../config"; import { Button } from "antd"; import { ImSpoonKnife } from "react-icons/im"; import Router from "next/router"; export default function Home() { const [data, setData] = useState(); function onChange(a, b, c) { console.log(a, b, c); } useEffect(() => { // getData(); }, []); const getData = async () => { fetch(`${config.URL}/productAll`, { method: "GET", redirect: "follow", }) .then((response) => response.json()) .then((result) => { if (result.status) setData(result.data); }) .catch((error) => console.log("error", error)); }; const goToProducts = () => { Router.push("/products"); }; return ( <div className="index"> <img src={"/images/bg.svg"} className="hero-image" /> <MainLayout> <div className="container" animate={{ scale: 1 }}> <div className="home"> <div className="left"> <div className="types"> <h1 className="hero-type">Welcome to</h1>{" "} <div className="color"> <h1 className="hero-type-main-color">FikraFood</h1> <h1>!</h1> </div> <p className="hero-type-p"> Start ordering meals weekly for only $5.99/week per dish! </p> </div> <Button onClick={goToProducts} size={"large"} className="cta" type="primary" > Browse Meals <ImSpoonKnife className="cta-icon" /> </Button> </div> <div className="right"> {/* <img src={"/images/blob.svg"} className="blob" /> */} {/* <Carousel showThumbs={false} showIndicators={false} autoplay={true} interval={2000} showStatus={false} infiniteLoop dots={true} effect="fade" afterChange={onChange} > {data && data.map((item) => { return ( <div className="slider"> <img className="carusel-image" src={item.image} /> </div> ); })} </Carousel> */} </div> </div> </div> </MainLayout> </div> ); } <file_sep>import "../styles/result.css"; import "react-responsive-carousel/lib/styles/carousel.min.css"; import "../styles/globals.scss"; import Router from "next/router"; import ProgressBar from "@badrap/bar-of-progress"; import { AnimateSharedLayout } from "framer-motion"; const progress = new ProgressBar({ size: 3, color: "#fc9803", className: "bar-of-progress", delay: 100, }); Router.events.on("routeChangeStart", progress.start); Router.events.on("routeChangeComplete", progress.finish); Router.events.on("routeChangeError", progress.finish); function MyApp({ Component, pageProps }) { return ( <> <AnimateSharedLayout> <Component {...pageProps} /> </AnimateSharedLayout> </> ); } export default MyApp; <file_sep>import { Button } from "antd"; import { LeftOutlined } from "@ant-design/icons"; import router from "next/router"; const BackBtn = () => { const goBack = () => router.back(); return ( <Button onClick={goBack} className="back-btn" icon={<LeftOutlined style={{ fontSize: "1em" }} />} type="primary" /> ); }; export default BackBtn; <file_sep>import MainLayout from "../../components/MainLayout"; import { config } from "../../config"; import { useState, useEffect, useRef } from "react"; import Card from "../../components/Card"; import SkeletonCard from "../../components/SkeletonCard"; import ExpandCard from "../../components/ExpadnCard"; import Masonry, { ResponsiveMasonry } from "react-responsive-masonry"; import { message, Input, Button, Spin } from "antd"; import { BsChevronDoubleDown } from "react-icons/bs"; const { Search } = Input; import { useDebounce } from "use-debounce"; export default function Products() { const [data, setData] = useState([]); const [loading, setLoading] = useState(false); const [isOpen, setIsOpen] = useState(false); const [hasMore, setHasMore] = useState(true); const [page, setPage] = useState(1); const [query, setQuery] = useState(""); const [searchQuery] = useDebounce(query, 1000); const getData = async (page = 1, q = "") => { if (hasMore || !!q.length) { setLoading(true); setPage(page); const res = await fetch( `${config.URL}/productAll?p=${page}&s=10${!!q.length ? "&q=" + q : ""}` ); const data = await res.json(); if (data) { setLoading(false); if (!!q?.length) { return setData(data.data.products); } setData((e) => [...e, ...data.data.products]); if (data.data.products?.length < 10) { setHasMore(false); } else { setHasMore(true); } } } }; const handleScroll = (e) => { const bottom = e.target.scrollHeight - e.target.scrollTop <= e.target.clientHeight; if (bottom) { console.log("bottom"); loadNextPage(); } }; const loadNextPage = () => { if (hasMore) getData(page + 1); }; useEffect(() => { if (searchQuery.length > 0) { setData([]); getData(1, searchQuery); } else { setData([]); getData(1); } }, [searchQuery]); return ( <div className="scroll-conteol" onScroll={handleScroll}> <MainLayout hidden={isOpen} filled> <div className="container"> <div className="search-wrapper"> <Search value={query} onChange={(e) => { setQuery(e.target.value); }} size="large" placeholder="search dishes" enterButton /> </div> {!!data.length ? ( <> <ResponsiveMasonry columnsCountBreakPoints={{ 350: 2, 750: 2, 900: 3, 1000: 5 }} > <Masonry gutter={10} className="masonry"> {data.map((product, index) => { return ( <ExpandCard setIsOpen={setIsOpen} key={index} product={product} /> ); })} </Masonry> </ResponsiveMasonry> {hasMore && !!!searchQuery ? ( loading ? ( <div className="spin" onClick={loadNextPage}> <Spin /> </div> ) : ( <div className="arrowDown" onClick={loadNextPage}> <p>More</p> <BsChevronDoubleDown /> </div> ) ) : !!searchQuery ? null : ( <div className="arrowDown nomore" onClick={loadNextPage}> <p>No more dishes to show</p> </div> )} </> ) : ( <ResponsiveMasonry columnsCountBreakPoints={{ 350: 2, 750: 2, 900: 3, 1000: 5 }} > <Masonry gutter={10} className="masonry paddingTop"> {[...Array(20).keys()] .map((i) => i) .map((product, index) => { return <SkeletonCard />; })} </Masonry> </ResponsiveMasonry> )} </div> </MainLayout> </div> ); } // export const getServerSideProps = async () => { // const res = await fetch("https://prisma-shop.herokuapp.com/v1/productAll"); // const data = await res.json(); // return { props: { data: data.data } }; // }; <file_sep>import { AnimateSharedLayout, motion } from "framer-motion"; export default function SkeletonCard({ product }) { const heights = [250, 300, 350, 400]; return ( <> <div className="normal-card" layoutId="expandable-card" style={{ height: heights[Math.floor(Math.random() * heights.length)] }} > <div className="normal-card-image" style={{ backgroundColor: "#eee", height: "50%" }} /> <div className="normal-card-type" style={{ width: "100%", display: "flex", flexDirection: "column", alignItems: "center", }} > <p layoutId="expandable-card-h" className="h1" style={{ backgroundColor: "#eee", width: "80%", height: "30px", borderRadius: "10px", margin: "20px auto", }} ></p> <span className="card-price-wrapper" style={{ backgroundColor: "#eee", width: "90%", height: "50px", marginTop: "20px", borderRadius: "10px", }} ></span> </div> </div> </> ); }
2113b775cf576d5ae9db617520524fb56c132f03
[ "JavaScript" ]
7
JavaScript
AtheerAPeter/fikraFood
ca5506e19e76644a9af1d7e967a9392b11d7b7ba
049e58d3cb3dc3d1daed7acc93c246d6385c3240
refs/heads/master
<file_sep>// JavaScript Document $(document).ready(function(e) { // document.addEventListener("deviceready",function(){ $('#btndatos') .on ('click', function () { //alert ('hola'); $ ('body').pagecontainer ("change", "#datos", {transition: "flip"}); });// alerta de java $('#btnresultado') .on ('click', function () { $ ('body').pagecontainer ("change", "#resultado", {transition: "flip"}); var imc; var peso = $('#txtpeso').val (); var talla = $('#txttalla').val (); imc =(peso/(talla * talla)); $('#imc').text ('Nombre ' + $('#txtnombre').val () + ' imc= ' + imc); });// alerta de java //}); });
d702b3d083462b1eba71cd750423258147ea84fc
[ "JavaScript" ]
1
JavaScript
AL17F13/aplicacion05
c2871e88c2a43f2157435e5ea977df5cf816850c
ebc012d7b14b25af1c627c8c086a9368c650f70d
refs/heads/master
<file_sep> jQuery(document).ready(function() { var p = $.ajax({ type:"GET", url: "text", cache:false //context: document.body }); p.done(function(text) { $("div.texto").html(text); }); $("button").click(function(){ $.ajax({ type:"GET", url:"text2", cache:false }).done(function(text2){ $("div.texto2").html(text2); }); }); });
fc21f4b79d8a79e729a9f5c564cbe0d7e5c052e6
[ "JavaScript" ]
1
JavaScript
asu88/X-NAV-JQ-Ajax
3ad6f614d4d2d2ffbd3b5cdc2c306ba5724d4667
8b07733c250c61f3b998583289deb7e0745872f5
refs/heads/master
<repo_name>Hanan712/js-data-structures-objects-lab-re-coded_sanaa_web001<file_sep>/index.js // Write your solution in this file! const driver = {} function updateDriverWithKeyAndValue(driver, key, value){ const newdri = Object.assign( {},driver) newdri[key] =value return newdri } function destructivelyUpdateDriverWithKeyAndValue(driver, key, value){ driver[key]=value return driver } function deleteFromDriverByKey(driver,key){ const newdri = Object.assign({},driver) delete newdri[key]; return newdri } function destructivelyDeleteFromDriverByKey(driver,key){ delete driver[key]; return driver }
290bc2db75ac07f42649c686ef062013cefb2570
[ "JavaScript" ]
1
JavaScript
Hanan712/js-data-structures-objects-lab-re-coded_sanaa_web001
54b9594550e5b7092f153190a7eb0dd6a62fb6e0
5db70019c15b58d95a251ff1b27092a77751ffac
refs/heads/master
<repo_name>AhmadAlkurdy/The-Ascending-Order-<file_sep>/README.md # The-Ascending-Order- the ascending order of three numbers <file_sep>/assignment3.cpp // <NAME> // Assignment 3 // the ascending order of three numbers #include <iostream> using namespace std; int main () { // Declaire variebals int num1 = 0; int num2 = 0; int num3 = 0; // entring the numbers cout << "Enter the first number " << endl; cin >> num1; cout << "Enter the second number " << endl; cin >> num2; cout << "Enter the third number " << endl; cin >> num3; // If statment to get the ascending order if ( num1 >= num2 && num2 >= num3 ) cout << "The ascending order is " << num3 << ", " << num2 << ", " << num1 << "." << endl; else if ( num1 <= num2 && num2 <= num3 ) cout << "The ascending order is " << num1 << ", " << num2 << ", " << num3 << "." << endl; else if (( num1 >= num2 && num2 <= num3) && (num1 >= num3)) cout << "The ascending order is " << num2 << ", " << num3 << ", " << num1 << "." << endl; else if (( num1 >= num2 && num2 <= num3 ) && ( num1 <= num3 )) cout << "The ascending order is " << num2 << ", " << num1 << ", " << num3 << "." << endl; else if (( num1 <= num2 && num2 >= num3 ) && ( num1 >= num3)) cout << "The ascending order is " << num3 << ", " << num1 << ", " << num2 << "." << endl; else if (( num1 <= num2 && num2 >= num3) && ( num1 <= num3)) cout << "The ascending order is " << num1 << ", " << num3 << ", " << num2 << "." << endl; system ("pause"); return 0; }
5bce8530a34bc6d998b23d02a053e3edf80c4cfd
[ "Markdown", "C++" ]
2
Markdown
AhmadAlkurdy/The-Ascending-Order-
4d2766bfacc411269998bf153b17e5cdd3f91706
8efa8a7a90425c0a5d9947e43660995ee4debcb2
refs/heads/master
<file_sep># essentiavitis.vin <file_sep>jQuery(function ($) { $(document).ready(function() { /* SIDE MENU */ $(function () { $(".toggle-side-menu").click(function(e) { $("#side-nav").toggleClass('push-left'); $("#main-container").toggleClass('push-left'); e.stopPropagation(); }); $("#main-container").click(function(e) { reset(); }); $(document).keyup(function(e) { if (e.keyCode === 27) { reset(); } }); function reset() { $("#main-container").removeClass('push-left'); $("#side-nav").removeClass('push-left'); } }); /* BS TOOLTIP */ $(function () { $('[data-toggle="tooltip"]').tooltip(); }); /* ENABLE PARALAX ON NON TOUCH DEVICES */ $(function () { if(!Modernizr.touch){ $.stellar({ horizontalScrolling: false, responsive: true, verticalOffset: 100 }); } }); /* SWIPER + ANIMATE.CSS */ $(function () { function doAnimations( elems ) { var animEndEv = 'webkitAnimationEnd animationend'; elems.each(function () { var $this = $(this), $animationType = $this.data('animation'); $this.addClass($animationType).one(animEndEv, function () { $this.removeClass($animationType); }); }); } var swiper1 = new Swiper ('#swiper-1.swiper-container', { effect: 'coverflow', grabCursor: true, loop: true, speed: 1000, pagination: '.swiper-pagination', nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', onSlideChangeStart: function (swiper) { var $animatingElems = $(".swiper-slide-active").find("[data-animation ^= 'animated']"); doAnimations($animatingElems); }, ontouchStart: function (swiper) { var $animatingElems = $(".swiper-slide-next, .swiper-slide-prev").find("[data-animation ^= 'animated']"); doAnimations($animatingElems); }, coverflow: { rotate: 50, stretch: 0, depth: 100, modifier: 1, slideShadows : true } }); var galleryTop = new Swiper('.gallery-top', { nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', spaceBetween: 10, }); var galleryThumbs = new Swiper('.gallery-thumbs', { spaceBetween: 0, centeredSlides: true, slidesPerView: 'auto', touchRatio: 0.2, slideToClickedSlide: true }); galleryTop.params.control = galleryThumbs; galleryThumbs.params.control = galleryTop; var swiperDemo = new Swiper('#swiper-demo', { grabCursor: true, loop: true, speed: 1000, pagination: '.swiper-pagination', nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev' }); }); /* EFFECTS ON IN VIEW */ $(function () { function onScrollInit( items, trigger ) { items.each( function() { var osElement = $(this), osAnimationClass = osElement.attr('data-os-animation'), osAnimationDelay = osElement.attr('data-os-animation-delay'); osElement.css({ '-webkit-animation-delay': osAnimationDelay, '-moz-animation-delay': osAnimationDelay, 'animation-delay': osAnimationDelay, '-webkit-transition-delay': osAnimationDelay, '-moz-transition-delay': osAnimationDelay, 'transition-delay': osAnimationDelay }); var osTrigger = ( trigger ) ? trigger : osElement; osTrigger.waypoint(function() { osElement.addClass('animated').addClass(osAnimationClass); },{ triggerOnce: true, offset: '90%' }); }); } onScrollInit( $('.os-animation') ); onScrollInit( $('.staggered-animation'), $('.staggered-animation-container') ); }); /* STORE VIEW OPTIONS */ $(function () { $("#view-option button").click( function () { $("#view-option button").removeClass("active"); $(this).addClass("active"); var view = $(this).data("view"); var elms = $("#product-gallery .shop-item"); elms.removeClass(); elms.addClass("shop-item"); elms.addClass(view); } ); }); /* SCROLL TO SECTION + SCROLL SPY */ $(function () { $("#secondary-nav li a").click(function () { if (location.pathname.replace(/^\//, "") === this.pathname.replace(/^\//, "") && location.hostname === this.hostname) { var target = $(this.hash); target = target.length ? target : $("[name=" + this.hash.slice(1) + "]"); if (target.length) { $("html,body").animate({ scrollTop: (target.offset().top - $("#section-nav").height()+1) }, 700, 'swing'); return false; } } }); $('body').scrollspy({ target: '#secondary-nav-bar' }); }); }); /* END DOCUMENT READY */ $(window).load( function() { /* STICKY NAV */ $(function () { if ($("#secondary-nav-bar").length) { var sticky = new Waypoint.Sticky({ element: $('#secondary-nav-bar')[0], offset: 0 }); } }); }); /* END WINDOW LOAD */ }); <file_sep><!DOCTYPE html> <html lang="en"> <head> <title>Chateau</title> <!-- meta --> <meta charset="utf-8"> <meta content="" name="description"> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"> <!-- css --> <link href="bootstrap/css/bootstrap.css" rel="stylesheet"> <link href="src/css/font-awesome.css" rel="stylesheet"> <link href="src/css/animate.css" rel="stylesheet"> <link href="src/css/swipebox.css" rel="stylesheet"> <link href="src/css/swiper.min.css" rel="stylesheet"> <link href="src/css/chateau-theme.css" rel="stylesheet"> <!-- google fonts --> <link href="http://fonts.googleapis.com/css?family=Raleway:100,200,300,400,500,600,700,800,900" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Merriweather:300,400,700,900,900italic,700italic,400italic,300italic" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Cookie" rel="stylesheet" type="text/css"> <!-- head js --> <script src="src/js/modernizr-2.6.2.min.js"></script> </head> <body> <aside id="side-nav"> <div> <form class="form-inline"> <div class="form-group has-feedback"> <label for="search-field">Search site</label> <input id="search-field" type="text" class="form-control" placeholder="Search..."> <button id="search-btn" type="submit" class="btn"><span class="fa fa-search"></span></button> </div> </form> <ul class="list-group"> <li class="list-group-item style-1 list-group-label">About</li> <li class="list-group-item style-1"><a href="register.html">Register</a></li> <li class="list-group-item style-1"><a href="login.html">Login</a></li> <li class="list-group-item style-1"><a href="contact.html">Contact</a></li> <li class="list-group-item style-1"><a href="faq.html">FAQ</a></li> </ul> <ul class="list-group"> <li class="list-group-item style-1 list-group-label">Social</li> <li class="list-group-item style-1"><a href="#"><span class="fa fa-facebook-square"></span> Facebook</a></li> <li class="list-group-item style-1"><a href="#"><span class="fa fa-twitter-square"></span> Twitter</a></li> <li class="list-group-item style-1"><a href="#"><span class="fa fa-google-plus-square"></span> Google Plus</a></li> <li class="list-group-item style-1"><a href="#"><span class="fa fa-pinterest-square"></span> Pinterest</a></li> </ul> </div> </aside><!-- /#side-nav --> <div class="container-fluid" id="main-container"> <div class="row" id="main-row"> <header> <nav id="main-nav-bar" class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand hidden-xs hidden-sm" href="homepage.html"><img alt="" src="images/logo-1x.png" srcset="images/logo-1x.png 1x, images/logo-2x.png 2x"></a> <a class="navbar-brand hidden-lg hidden-md" href="homepage.html"><img alt="" src="images/logo-mobile-1x.png" srcset="images/logo-mobile-1x.png 1x, images/logo-mobile-2x.png 2x"></a> <button class="toggle-side-menu navbar-toggle" type="button"><span class="fa fa-ellipsis-v"></span></button> <button class="navbar-toggle collapsed" data-target="#navigation" data-toggle="collapse" type="button"><span class="fa fa-navicon"></span></button> <button class="navbar-toggle" type="button"><span class="fa fa-shopping-cart"></span></button> </div> <!-- navbar-header --> <div class="collapse navbar-collapse navbar-right" id="navigation"> <ul id="main-nav" class="nav navbar-nav"> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Products <span class="fa fa-angle-down"></span></a> <ul class="dropdown-menu"> <li><a href="products.html#filter=*">All Products</a></li> <li><a href="products.html#filter=.red-wines">Red Wines</a></li> <li><a href="products.html#filter=.white-wines">White Wines</a></li> <li><a href="products.html#filter=.rose-wines">Rosé Wines</a></li> <li><a href="products.html#filter=.food-specialties">Food Specialties</a></li> </ul> </li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">About <span class="fa fa-angle-down"></span></a> <ul class="dropdown-menu"> <li><a href="who-we-are.html">Who we are</a></li> <li><a href="our-history.html">Our History</a></li> <li><a href="the-vineyard.html">The Vineyard</a></li> <li><a href="gallery.html">Gallery</a></li> </ul> </li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Blog <span class="fa fa-angle-down"></span></a> <ul class="dropdown-menu"> <li><a href="blog-standard.html">Blog Standard</a></li> <li><a href="blog-masonry.html">Blog Masonry</a></li> <li><a href="blog-entry.html">Blog Entry 1</a></li> <li><a href="blog-entry-alternative.html">Blog Entry 2</a></li> </ul> </li> <li class="active"><a href="elements.html">Elements</a></li> <li><a href="buy-online.html">Buy Online <span class="badge">New</span></a></li> </ul> <ul id="tool-nav" class="nav navbar-nav hidden-xs hidden-sm"> <li><a href="cart.html"><span class="fa fa-shopping-cart"></span></a></li> <li><a href="#" class="toggle-side-menu"><span class="fa fa-ellipsis-v"></span></a></li> </ul> </div> <!-- /.navbar-collapse --> <!-- /.container --> </div> <!-- /.container-fluid --> </nav> </header> <!-- .page-header --> <div class="page-header" style="background-image:url(http://placehold.it/1500x750)" data-stellar-background-ratio="0.2"> <div class="container"> <div class="row"> <div class="col-sm-12"> <ol class="breadcrumb"> <li><a href="homepage.html">Home</a></li> <li class="active">Elements</li> </ol> <h1>Html Elements</h1> </div> </div> </div> </div> <!-- /.page-header --> <!-- #secondary-nav-bar --> <nav id="secondary-nav-bar" class="navbar navbar-default"> <div class="container"> <ul id="secondary-nav" class="nav navbar-nav"> <li><a href="#sec-typo">Typography</a></li> <li><a href="#sec-buttons">Buttons</a></li> <li><a href="#sec-tabs">Tabs & Accordions</a></li> <li><a href="#sec-sliders">Sliders & Swipers</a></li> <li><a href="#sec-lightbox">Lightboxes</a></li> <li><a href="#sec-form">Form elments</a></li> <li><a href="#sec-icons">Icons</a></li> </ul> </div> </nav> <!-- /#secondary-nav-bar --> <div id="html-elements"> <section id="sec-typo"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h2>Typography</h2> <h1>h1. heading</h1> <h2>h2. heading</h2> <h3>h3. heading</h3> <h4>h4. heading</h4> <h5>h5. heading</h5> <h6>h6. heading</h6> <p> Anim pariatur cliche <strong>strong text</strong>, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod <em>emphasized text</em>. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </p> <blockquote> Blockquote brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. </blockquote> </div> </div> </div> </section> <section id="sec-buttons" class="section-bg-light-gray"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h2>Buttons</h2> <div style="margin-top:25px;"> <!-- Standard button --> <button type="button" class="btn btn-xs btn-default">Default Button</button> <!-- Provides extra visual weight and identifies the primary action in a set of buttons --> <button type="button" class="btn btn-xs btn-primary">Primary Button</button> <!-- Indicates a successful or positive action --> <button type="button" class="btn btn-xs btn-success">Success Button</button> <!-- Contextual button for informational alert messages --> <button type="button" class="btn btn-xs btn-info">Info Button</button> <!-- Indicates caution should be taken with this action --> <button type="button" class="btn btn-xs btn-warning">Warning Button</button> <!-- Indicates a dangerous or potentially negative action --> <button type="button" class="btn btn-xs btn-danger">Danger Button</button> <!-- Deemphasize a button by making it look like a link while maintaining button behavior --> <button type="button" class="btn btn-xs btn-link">Link Button</button> </div> <div style="margin-top:25px;"> <!-- Standard button --> <button type="button" class="btn btn-default">Default Button</button> <!-- Provides extra visual weight and identifies the primary action in a set of buttons --> <button type="button" class="btn btn-primary">Primary Button</button> <!-- Indicates a successful or positive action --> <button type="button" class="btn btn-success">Success Button</button> <!-- Contextual button for informational alert messages --> <button type="button" class="btn btn-info">Info Button</button> <!-- Indicates caution should be taken with this action --> <button type="button" class="btn btn-warning">Warning Button</button> <!-- Indicates a dangerous or potentially negative action --> <button type="button" class="btn btn-danger">Danger Button</button> <!-- Deemphasize a button by making it look like a link while maintaining button behavior --> <button type="button" class="btn btn-link">Link Button</button> </div> <div style="margin-top:25px;"> <!-- Standard button --> <button type="button" class="btn btn-lg btn-style-1 btn-default">Default Button</button> <!-- Provides extra visual weight and identifies the primary action in a set of buttons --> <button type="button" class="btn btn-lg btn-style-1 btn-primary">Primary Button</button> <!-- Indicates a successful or positive action --> <button type="button" class="btn btn-lg btn-style-1 btn-success">Success Button</button> <!-- Contextual button for informational alert messages --> <button type="button" class="btn btn-lg btn-style-1 btn-info">Info Button</button> <!-- Indicates caution should be taken with this action --> <button type="button" class="btn btn-lg btn-style-1 btn-warning">Warning Button</button> <!-- Indicates a dangerous or potentially negative action --> <button type="button" class="btn btn-lg btn-style-1 btn-danger">Danger Button</button> <!-- Deemphasize a button by making it look like a link while maintaining button behavior --> <button type="button" class="btn btn-lg btn-link">Link Button</button> </div> <div style="margin-top:25px;"> <button class="btn btn-primary btn-lg btn-animated btn-style-1" type="submit"> <span class="btn-label">Animated icon</span> <span class="btn-icon fa fa-user"></span> </button> </div> </div> </div> </div> </section> <section id="sec-tabs"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h2>Tabs & Accordions</h2> <div style="margin-top:25px;"> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#tab1" aria-controls="tab1" role="tab" data-toggle="tab">Tab 1</a></li> <li role="presentation"><a href="#tab2" aria-controls="tab2" role="tab" data-toggle="tab">Tab 2</a></li> <li role="presentation"><a href="#tab3" aria-controls="tab3" role="tab" data-toggle="tab">Tab 3</a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="tab1"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam semper lorem urna, vitae sodales nisl pretium nec. Ut sed lacus sagittis, commodo tortor eu, sodales erat. Nullam non est porttitor, posuere lacus sed, mattis leo. Morbi malesuada orci est. Duis vel fringilla sem. Morbi pharetra tellus arcu, nec vestibulum elit ultricies eget. Proin accumsan bibendum nibh quis posuere. Maecenas vitae magna egestas, sollicitudin magna non, imperdiet dolor. Phasellus condimentum ex a ullamcorper finibus.</p> </div> <div role="tabpanel" class="tab-pane" id="tab2"> <p>Nullam non est porttitor, posuere lacus sed, mattis leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam semper lorem urna, vitae sodales nisl pretium nec. Ut sed lacus sagittis, commodo tortor eu, sodales erat. Morbi malesuada orci est. Duis vel fringilla sem. Morbi pharetra tellus arcu, nec vestibulum elit ultricies eget. Proin accumsan bibendum nibh quis posuere. Maecenas vitae magna egestas, sollicitudin magna non, imperdiet dolor. Phasellus condimentum ex a ullamcorper finibus.</p> </div> <div role="tabpanel" class="tab-pane" id="tab3"> <p>Ut sed lacus sagittis, commodo tortor eu, sodales erat. Nullam semper lorem urna, vitae sodales nisl pretium nec. Nullam non est porttitor, posuere lacus sed, mattis leo. Morbi malesuada orci est. Duis vel fringilla sem. Morbi pharetra tellus arcu, nec vestibulum elit ultricies eget. Proin accumsan bibendum nibh quis posuere. Maecenas vitae magna egestas, sollicitudin magna non, imperdiet dolor. Phasellus condimentum ex a ullamcorper finibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> </div> </div> </div> <div> <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingOne"> <h4 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="false" aria-controls="collapseOne"> <span class="fa fa-arrow-right"></span>Panel 1 </a> </h4> </div> <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne"> <p class="panel-body"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </p> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingTwo"> <h4 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> <span class="fa fa-arrow-right"></span>Panel 2 </a> </h4> </div> <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo"> <p class="panel-body"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </p> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingThree"> <h4 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree"> <span class="fa fa-arrow-right"></span>Panel 3 </a> </h4> </div> <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree"> <p class="panel-body"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </p> </div> </div> </div> </div> </div> </div> </div> </section> <section id="sec-sliders" class="section-bg-light-gray"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h2>Sliders & Swipers</h2> <div id="swiper-demo" class="swiper-container" style="margin-top:25px;"> <div class="swiper-wrapper"> <div class="swiper-slide" id="slide-1"> <img alt="" class="img-responsive" src="http://placehold.it/1200x600" width="1200" height="600"/> </div> <div class="swiper-slide" id="slide-2"> <img alt="" class="img-responsive" src="http://placehold.it/1200x600" width="1200" height="600"/> </div> <div class="swiper-slide" id="slide-3"> <img alt="" class="img-responsive" src="http://placehold.it/1200x600" width="1200" height="600"/> </div> <div class="swiper-slide" id="slide-4"> <img alt="" class="img-responsive" src="http://placehold.it/1200x600" width="1200" height="600"/> </div> <div class="swiper-slide" id="slide-5"> <img alt="" class="img-responsive" src="http://placehold.it/1200x600" width="1200" height="600"/> </div> <div class="swiper-slide" id="slide-6"> <img alt="" class="img-responsive" src="http://placehold.it/1200x600" width="1200" height="600"/> </div> </div> <div class="swiper-pagination"></div> <div class="swiper-button-prev"></div> <div class="swiper-button-next"></div> </div> </div> </div> </div> </section> <section id="sec-lightbox"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h2>Lightboxes</h2> </div> <div class="col-sm-4 mar-v"> <a class="swipebox" href="http://placehold.it/800x800"><img class="img-responsive" alt="" src="http://placehold.it/400x400" /></a> </div> <div class="col-sm-4 mar-v"> <a class="swipebox" href="http://placehold.it/800x800"><img class="img-responsive" alt="" src="http://placehold.it/400x400" /></a> </div> <div class="col-sm-4 mar-v"> <a class="swipebox" href="http://placehold.it/800x800"><img class="img-responsive" alt="" src="http://placehold.it/400x400" /></a> </div> </div> </div> </section> <section id="sec-form" class="section-bg-light-gray"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h2>Form elements</h2> <form> <div class="form-group"> <label for="InputEmail">Email</label> <input type="email" class="form-control" id="InputEmail" placeholder="Email"> </div> <div class="form-group"> <label for="InputPassword1">Password</label> <input type="<PASSWORD>" class="form-control" id="InputPassword1" placeholder="<PASSWORD>"> </div> <div class="form-group"> <label for="InputText">Text</label> <input type="password" class="form-control" id="InputText" placeholder="Text"> </div> <div class="form-group"> <label for="InputFile">File input</label> <input type="file" id="InputFile"> <p class="help-block">Block-level help text.</p> </div> <div class="form-group"> <label for="InputFile">Textarea</label> <textarea class="form-control" rows="10"></textarea> <p class="help-block">Block-level help text.</p> </div> <div class="checkbox"> <label> <input type="checkbox"> Check 1 </label> </div> <div class="checkbox"> <label> <input type="checkbox"> Check 2 </label> </div> <div class="checkbox"> <label> <input type="checkbox"> Check 3 </label> </div> <button class="btn pull-right btn-primary btn-lg btn-animated btn-style-1" type="submit"> <span class="btn-label">Submit</span> <span class="btn-icon fa fa-arrow-circle-right"></span> </button> </form> </div> </div> </div> </section> <section id="sec-icons"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h2>Font Awesome Icons</h2> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-adjust </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-adn </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-align-center </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-align-justify </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-align-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-align-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-ambulance </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-anchor </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-android </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-angellist </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-angle-double-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-angle-double-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-angle-double-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-angle-double-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-angle-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-angle-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-angle-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-angle-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-apple </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-archive </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-area-chart </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrow-circle-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrow-circle-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrow-circle-o-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrow-circle-o-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrow-circle-o-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrow-circle-o-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrow-circle-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrow-circle-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrow-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrow-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrow-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrow-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrows </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrows-alt </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrows-h </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-arrows-v </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-asterisk </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-at </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-automobile <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-backward </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-ban </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bank <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bar-chart </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bar-chart-o <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-barcode </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bars </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bed </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-beer </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-behance </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-behance-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bell </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bell-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bell-slash </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bell-slash-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bicycle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-binoculars </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-birthday-cake </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bitbucket </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bitbucket-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bitcoin <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bold </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bolt </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bomb </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-book </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bookmark </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bookmark-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-briefcase </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-btc </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bug </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-building </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-building-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bullhorn </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bullseye </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-bus </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-buysellads </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cab <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-calculator </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-calendar </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-calendar-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-camera </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-camera-retro </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-car </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-caret-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-caret-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-caret-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-caret-square-o-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-caret-square-o-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-caret-square-o-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-caret-square-o-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-caret-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cart-arrow-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cart-plus </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cc </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cc-amex </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cc-discover </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cc-mastercard </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cc-paypal </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cc-stripe </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cc-visa </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-certificate </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-chain <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-chain-broken </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-check </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-check-circle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-check-circle-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-check-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-check-square-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-chevron-circle-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-chevron-circle-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-chevron-circle-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-chevron-circle-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-chevron-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-chevron-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-chevron-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-chevron-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-child </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-circle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-circle-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-circle-o-notch </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-circle-thin </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-clipboard </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-clock-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-close <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cloud </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cloud-download </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cloud-upload </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cny <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-code </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-code-fork </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-codepen </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-coffee </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cog </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cogs </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-columns </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-comment </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-comment-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-comments </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-comments-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-compass </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-compress </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-connectdevelop </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-copy <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-copyright </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-credit-card </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-crop </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-crosshairs </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-css3 </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cube </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cubes </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cut <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-cutlery </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-dashboard <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-dashcube </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-database </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-dedent <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-delicious </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-desktop </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-deviantart </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-diamond </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-digg </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-dollar <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-dot-circle-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-download </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-dribbble </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-dropbox </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-drupal </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-edit <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-eject </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-ellipsis-h </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-ellipsis-v </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-empire </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-envelope </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-envelope-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-envelope-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-eraser </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-eur </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-euro <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-exchange </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-exclamation </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-exclamation-circle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-exclamation-triangle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-expand </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-external-link </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-external-link-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-eye </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-eye-slash </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-eyedropper </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-facebook </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-facebook-f <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-facebook-official </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-facebook-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-fast-backward </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-fast-forward </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-fax </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-female </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-fighter-jet </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-archive-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-audio-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-code-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-excel-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-image-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-movie-o <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-pdf-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-photo-o <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-picture-o <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-powerpoint-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-sound-o <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-text </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-text-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-video-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-word-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-file-zip-o <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-files-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-film </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-filter </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-fire </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-fire-extinguisher </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-flag </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-flag-checkered </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-flag-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-flash <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-flask </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-flickr </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-floppy-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-folder </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-folder-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-folder-open </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-folder-open-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-font </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-forumbee </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-forward </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-foursquare </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-frown-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-futbol-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-gamepad </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-gavel </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-gbp </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-ge <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-gear <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-gears <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-genderless <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-gift </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-git </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-git-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-github </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-github-alt </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-github-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-gittip <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-glass </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-globe </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-google </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-google-plus </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-google-plus-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-google-wallet </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-graduation-cap </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-gratipay </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-group <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-h-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-hacker-news </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-hand-o-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-hand-o-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-hand-o-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-hand-o-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-hdd-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-header </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-headphones </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-heart </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-heart-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-heartbeat </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-history </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-home </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-hospital-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-hotel <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-html5 </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-ils </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-image <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-inbox </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-indent </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-info </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-info-circle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-inr </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-instagram </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-institution <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-ioxhost </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-italic </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-joomla </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-jpy </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-jsfiddle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-key </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-keyboard-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-krw </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-language </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-laptop </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-lastfm </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-lastfm-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-leaf </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-leanpub </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-legal <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-lemon-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-level-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-level-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-life-bouy <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-life-buoy <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-life-ring </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-life-saver <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-lightbulb-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-line-chart </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-link </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-linkedin </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-linkedin-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-linux </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-list </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-list-alt </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-list-ol </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-list-ul </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-location-arrow </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-lock </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-long-arrow-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-long-arrow-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-long-arrow-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-long-arrow-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-magic </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-magnet </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-mail-forward <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-mail-reply <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-mail-reply-all <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-male </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-map-marker </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-mars </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-mars-double </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-mars-stroke </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-mars-stroke-h </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-mars-stroke-v </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-maxcdn </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-meanpath </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-medium </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-medkit </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-meh-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-mercury </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-microphone </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-microphone-slash </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-minus </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-minus-circle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-minus-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-minus-square-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-mobile </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-mobile-phone <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-money </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-moon-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-mortar-board <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-motorcycle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-music </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-navicon <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-neuter </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-newspaper-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-openid </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-outdent </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-pagelines </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-paint-brush </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-paper-plane </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-paper-plane-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-paperclip </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-paragraph </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-paste <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-pause </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-paw </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-paypal </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-pencil </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-pencil-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-pencil-square-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-phone </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-phone-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-photo <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-picture-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-pie-chart </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-pied-piper </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-pied-piper-alt </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-pinterest </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-pinterest-p </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-pinterest-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-plane </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-play </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-play-circle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-play-circle-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-plug </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-plus </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-plus-circle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-plus-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-plus-square-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-power-off </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-print </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-puzzle-piece </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-qq </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-qrcode </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-question </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-question-circle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-quote-left </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-quote-right </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-ra <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-random </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-rebel </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-recycle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-reddit </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-reddit-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-refresh </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-remove <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-renren </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-reorder <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-repeat </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-reply </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-reply-all </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-retweet </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-rmb <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-road </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-rocket </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-rotate-left <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-rotate-right <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-rouble <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-rss </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-rss-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-rub </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-ruble <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-rupee <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-save <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-scissors </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-search </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-search-minus </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-search-plus </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sellsy </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-send <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-send-o <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-server </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-share </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-share-alt </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-share-alt-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-share-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-share-square-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-shekel <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sheqel <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-shield </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-ship </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-shirtsinbulk </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-shopping-cart </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sign-in </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sign-out </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-signal </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-simplybuilt </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sitemap </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-skyatlas </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-skype </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-slack </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sliders </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-slideshare </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-smile-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-soccer-ball-o <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sort </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sort-alpha-asc </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sort-alpha-desc </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sort-amount-asc </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sort-amount-desc </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sort-asc </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sort-desc </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sort-down <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sort-numeric-asc </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sort-numeric-desc </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sort-up <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-soundcloud </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-space-shuttle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-spinner </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-spoon </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-spotify </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-square-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-stack-exchange </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-stack-overflow </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-star </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-star-half </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-star-half-empty <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-star-half-full <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-star-half-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-star-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-steam </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-steam-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-step-backward </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-step-forward </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-stethoscope </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-stop </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-street-view </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-strikethrough </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-stumbleupon </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-stumbleupon-circle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-subscript </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-subway </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-suitcase </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-sun-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-superscript </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-support <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-table </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-tablet </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-tachometer </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-tag </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-tags </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-tasks </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-taxi </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-tencent-weibo </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-terminal </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-text-height </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-text-width </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-th </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-th-large </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-th-list </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-thumb-tack </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-thumbs-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-thumbs-o-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-thumbs-o-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-thumbs-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-ticket </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-times </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-times-circle </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-times-circle-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-tint </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-toggle-down <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-toggle-left <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-toggle-off </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-toggle-on </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-toggle-right <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-toggle-up <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-train </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-transgender </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-transgender-alt </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-trash </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-trash-o </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-tree </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-trello </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-trophy </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-truck </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-try </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-tty </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-tumblr </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-tumblr-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-turkish-lira <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-twitch </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-twitter </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-twitter-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-umbrella </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-underline </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-undo </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-university </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-unlink <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-unlock </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-unlock-alt </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-unsorted <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-upload </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-usd </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-user </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-user-md </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-user-plus </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-user-secret </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-user-times </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-users </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-venus </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-venus-double </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-venus-mars </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-viacoin </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-video-camera </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-vimeo-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-vine </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-vk </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-volume-down </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-volume-off </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-volume-up </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-warning <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-wechat <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-weibo </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-weixin </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-whatsapp </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-wheelchair </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-wifi </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-windows </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-won <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-wordpress </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-wrench </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-xing </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-xing-square </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-yahoo </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-yelp </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-yen <span class="text-muted">(alias)</span> </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-youtube </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-youtube-play </div> <div class="col-md-4 col-sm-6 col-lg-3"> <i class="fa fa-fw"></i> fa-youtube-square </div> </div> </div> </section> </div> <footer> <div class="container"> <div class="row"> <div class="col-sm-3"> <ul class="list-group"> <li class="list-group-item style-1 list-group-label">Products</li> <li class="list-group-item style-1"><a href="products.html#filter=*">All Products</a></li> <li class="list-group-item style-1"><a href="products.html#filter=.red-wines">Red Wines</a></li> <li class="list-group-item style-1"><a href="products.html#filter=.white-wines">White Wines</a></li> <li class="list-group-item style-1"><a href="products.html#filter=.rose-wines">Rosé Wines</a></li> <li class="list-group-item style-1"><a href="products.html#filter=.food-specialties">Food Specialties</a></li> </ul> </div> <div class="col-sm-3"> <ul class="list-group"> <li class="list-group-item style-1 list-group-label">About</li> <li class="list-group-item style-1"><a href="who-we-are.html">Who we are</a></li> <li class="list-group-item style-1"><a href="our-history.html">Our History</a></li> <li class="list-group-item style-1"><a href="the-vineyard.html">The Vineyard</a></li> <li class="list-group-item style-1"><a href="gallery.html">Gallery</a></li> </ul> </div> <div class="col-sm-3"> <ul class="list-group"> <li class="list-group-item style-1 list-group-label">Clients</li> <li class="list-group-item style-1"><a href="register.html">Register</a></li> <li class="list-group-item style-1"><a href="login.html">Login</a></li> <li class="list-group-item style-1"><a href="contact.html">Contact</a></li> <li class="list-group-item style-1"><a href="faq.html">FAQ</a></li> </ul> </div> <div class="col-sm-3"> <ul class="list-group"> <li class="list-group-item style-1 list-group-label">Services</li> <li class="list-group-item style-1"><a href="buy-online.html">Buy Online <span class="badge">New!</span></a></li> <li class="list-group-item style-1"><a href="#">Blog</a></li> </ul> </div> </div> <div class="row"> <div class="col-sm-4 col-sm-offset-4 pad-v text-center"> <img alt="" src="images/logo-1x.png" class="img-responsive" srcset="images/logo-1x.png 1x, images/logo-2x.png 2x"> </div> </div> </div> </footer> <footer class="credits"> <div class="container"> <div class="row"> <div class="col-sm-6"> Chateau Theme Design by <a href="http://www.directdesign.it/">Direct Design</a> / <a href="http://www.andreapilutti.com/"><NAME></a> </div> <div class="col-sm-6 text-right social"> <a href="#"><span class="fa fa-facebook-square"></span></a> <a href="#"><span class="fa fa-twitter-square"></span></a> <a href="#"><span class="fa fa-google-plus-square"></span></a> <a href="#"><span class="fa fa-pinterest-square"></span></a> </div> </div> </div> </footer> </div> <!-- /#main-row --> </div> <!-- /#main-container --> <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script type="text/javascript">if (!window.jQuery) { document.write('<script src="src/js/jquery-1.11.3.min.js"><\/script>'); }</script> <script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript" src="src/js/jquery.swipebox.min.js"></script> <script type="text/javascript" src="src/js/jquery.stellar.js"></script> <script type="text/javascript" src="src/js/swiper.jquery.min.js"></script> <script type="text/javascript" src="src/js/jquery.waypoints.min.js"></script> <script type="text/javascript" src="src/js/sticky.js"></script> <script type="text/javascript" src="src/js/isotope.pkgd.min.js"></script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> <script type="text/javascript" src="src/js/chateau-script.js"></script> <script type="text/javascript"> ;( function( $ ) { $( '.swipebox' ).swipebox(); } )( jQuery ); </script> </body> </html>
57f763252571cdd95f5dcc6565c9097e7e923adb
[ "Markdown", "JavaScript", "HTML" ]
3
Markdown
essentiavitis/essentiavitis.vin
af40575c3a109a32edb8d6fc643d665c89544220
0f743d3e27d65c82b1d6721f0d24d5259bef1956
refs/heads/master
<file_sep> dependencies { // https://mvnrepository.com/artifact/commons-net/commons-net compile group: 'commons-net', name: 'commons-net', version: '2.2' }<file_sep>package com.moduscreate.plugin; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONException; import android.content.Context; import android.widget.Toast; import java.io.IOException; import java.net.InetAddress; import java.net.SocketException; import org.apache.commons.net.ntp.NTPUDPClient; import org.apache.commons.net.ntp.TimeInfo; public class ModusEcho extends CordovaPlugin { @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if ("echo".equals(action)) { echo(args.getString(0), callbackContext); return true; } if ("ntp".equals(action)) { final CallbackContext cb = callbackContext; cordova.getThreadPool().execute(new Runnable() { public void run() { NTPUDPClient client = new NTPUDPClient(); client.setDefaultTimeout(10000); try { client.open(); } catch (final SocketException se) { se.printStackTrace(); cb.error("socket exception " + se.toString()); } try { TimeInfo info = client.getTime(InetAddress.getByName("time.bora.net")); // TimeInfo info = client.getTime(InetAddress.getByName("192.168.3.11")); info.computeDetails(); Long offsetValue = info.getOffset(); int receiverTimeDelta = (offsetValue == null) ? 0 : offsetValue.intValue(); cb.success(receiverTimeDelta); } catch (final IOException ioe) { ioe.printStackTrace(); cb.error("io exception " + ioe.toString()); } client.close(); } }); return true; } return false; } private void echo(String msg, CallbackContext callbackContext) { if (msg == null || msg.length() == 0) { callbackContext.error("Empty message!"); } else { Toast.makeText(webView.getContext(), msg, Toast.LENGTH_LONG).show(); callbackContext.success(msg); } } // https://www.programcreek.com/java-api-examples/index.php?source_dir=TKSmartKitchen-master/android/src/de/tud/kitchen/android/NTPTimeReceiver.java private void ntp(CallbackContext cb) { NTPUDPClient client = new NTPUDPClient(); client.setDefaultTimeout(10000); try { client.open(); } catch (final SocketException se) { se.printStackTrace(); cb.error("socket exception " + se.toString()); } try { // TimeInfo info = client.getTime(InetAddress.getByName("time.bora.net")); TimeInfo info = client.getTime(InetAddress.getByName("192.168.3.11")); info.computeDetails(); Long offsetValue = info.getOffset(); int receiverTimeDelta = (offsetValue == null) ? 0 : offsetValue.intValue(); cb.success(receiverTimeDelta); } catch (final IOException ioe) { ioe.printStackTrace(); cb.error("io exception " + ioe.toString()); } client.close(); } } <file_sep>var argscheck = require('cordova/argscheck'); var utils = require('cordova/utils'); var exec = require('cordova/exec'); var cordova = require('cordova'); exports.echo = function (arg0, success, error) { exec(success, error, "ModusEcho", "echo", [arg0]); }; exports.echojs = function (arg0, success, error) { if (arg0 && typeof (arg0) === 'string' && arg0.length > 0) { success(arg0); } else { error('Empty message!'); } }; exports.ntp = function(success, error) { exec(success, error, "ModusEcho", "ntp"); }
f8a511fb40aa887c4fc00c5bd54cfd105370f547
[ "JavaScript", "Java", "Gradle" ]
3
Gradle
swcho/ex_cordova_plugin
e02fe782ffce4321c044099d2f0b83ce05848262
64e8e72f1d49bc38e3375f8991bba6fdf3da4bbb
refs/heads/master
<repo_name>faizana/WeblogChallenge<file_sep>/web_log_challenge.py # coding: utf-8 # In[2]: # As written in instructions all libraries are allowed except SparkSQL therefore I will be using PySpark and Pandas for my # data wrangling. import pandas as pd import re import time import datetime import numpy as np from pyspark import SparkContext from pyspark.sql import HiveContext sc = SparkContext() hiveContext = HiveContext(sc) # In[3]: def read_and_extract_fields(path): input_file = sc.textFile(path) return input_file def get_log_stats(line): #Function for extracting timestamp client_ip and destination_ip. The destination_ip is used to represent distinct URL's try: timestamp = re.search('\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}:\d{2}',line).group().replace('T',' ') # yyyy/mm/dd HH:MM:SS ips = re.findall('\d+\.\d+\.\d+\.\d+',line) #Regex for extracting ip addresses visitor_ip = ips[0] url_ip = ips[1] return [timestamp,visitor_ip,url_ip] except: #Returning Gateway Timeouts as in the url column return [timestamp,visitor_ip,'504'] # In[4]: #Optional_method:To find out list of ips which got 504s ,appending .count() will give us the total count def get_504_response_entries(df): return df[df.destination_ip == '504'] # In[5]: def filter_504_and_cast_to_unix_ts(df): logs_pd_sorted_cleaned = df.drop(df[df.destination_ip == '504'].index) #Sorting by visitor_ip inplace to bring all individual user hits together logs_pd_sorted_cleaned.sort(columns = ['visitor_ip'],axis = 0,inplace = True) #Converting date string to unix timestamp for convenience in sessionizing logs_pd_sorted_cleaned['timestamp'] = logs_pd_sorted_cleaned.timestamp.map(lambda x: time.mktime(datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S").timetuple())) return logs_pd_sorted_cleaned # In[13]: def generate_sessions_sequence(df): # Grouping by visitor_ip logs_pd_sorted_cleaned_g = df.groupby('visitor_ip') #Creating session numbers for each individual user based on a session length of 15 min= 900seconds on basis on timestamp df['session_number'] = logs_pd_sorted_cleaned_g['timestamp'].apply(lambda s: (s - s.shift(1) > 900).fillna(0).cumsum(skipna=False)) return df # In[7]: def get_overall_average_session_time(df): avg = df.groupby(['visitor_ip','session_number'])['timestamp'].apply(lambda x: max(x)-min(x)).reset_index() avg.columns = ['visitor_ip','session_number','average_time_per_session_per_user'] #Calculating overall average session time (Comes out to be 1481 seconds ~ 25 mins) overall_average_session_time = avg.groupby('visitor_ip') \ .agg({'average_time_per_session_per_user' : np.mean})['average_time_per_session_per_user'].mean() return overall_average_session_time,avg # In[16]: def get_most_engaged_users(df): #Finding ip's of most engaged users by finding longest mean session times, #this is done by sorting in descending after averaging copy_df = df.groupby('visitor_ip').agg({'average_time_per_session_per_user' : np.mean})['average_time_per_session_per_user'] most_engaged_users = copy_df.reset_index().sort('average_time_per_session_per_user',ascending = False) return most_engaged_users # In[8]: def get_unique_urls_per_session(df): #unique url session numbers: 1. Apply groupby to get unique destination_ip per user per session # 2. Perform a count and again groupby to get count of unique urls visited per session unique_urls_per_session = df.groupby(['visitor_ip','session_number','destination_ip']).count() \ .reset_index().groupby(['visitor_ip','session_number']) \ .count('destination_ip').reset_index() #Renaming and dropping extra columns unique_urls_per_session.columns = ['visitor_ip','session_number','unique_url','timestamp'] unique_urls_per_session = unique_urls_per_session.drop('timestamp',axis=1) return unique_urls_per_session #Result is Number of unqiue url hits per session per user #IP Address does not guarantee distinct user therefore if we had user_id embedded withing the url then #further distinctive analysis could have been done # In[18]: def df_to_csv(df,name): df.to_csv(name, sep=',', encoding='utf-8',headers = True) # In[ ]: if __name__ == '__main__': input_file = read_and_extract_fields('2015_07_22_mktplace_shop_web_log_sample.log') splitted_input = input_file.map(get_log_stats) logs_pd = splitted_input.toDF().toPandas() #Converting to Pandas dataframe, takes 30 seconds approx for whole file. logs_pd.columns = ['timestamp','visitor_ip','destination_ip'] #Renaming columns of DF # gateway_timeout_response_entries = get_504_response_entries(logs_pd) filtered_df = filter_504_and_cast_to_unix_ts(logs_pd) sessions_sequence_df = generate_sessions_sequence(filtered_df) ovearall_mean,aggregated_df = get_overall_average_session_time(filtered_df) most_engaged_users = get_most_engaged_users(aggregated_df) unique_urls_per_session = get_unique_urls_per_session(sessions_sequence_df) df_to_csv(unique_urls_per_session,'unique_urls_per_session.csv') df_to_csv(most_engaged_users,'most_engaged_users.csv') print "Overall Average session time:",ovearall_mean, "seconds" print "Check directory for result csv's on most_engaged_users and unique_urls_per_session" # In[ ]:
241592a9e194b8f23f8f8baf161303e254b3b34a
[ "Python" ]
1
Python
faizana/WeblogChallenge
bf2048fa14ea136f69d1919dc942d9fca27648c8
64687a17bb3285ae0e0047bcd840efc1f48f30c4
refs/heads/master
<repo_name>key-amb/fireap<file_sep>/spec/fireap/data/event_spec.rb require 'fireap' require 'fireap/data/event' require 'base64' require 'json' payload = {'name' => 'foo', 'version' => 'v1'} describe 'Transform to Model::Event' do describe 'Valid Event data' do evt = { 'ID' => '5bce61f8-eaad-ff09-b5a3-89818cdb6b7b', 'Name' => Fireap::EVENT_NAME, 'Payload' => Base64.encode64(payload.to_json), } data = Fireap::Data::Event.new(evt) event = data.to_model it 'event is a Fireap::Model::Event' do expect(event).to be_an_instance_of(Fireap::Model::Event) end it 'event.payload is decoded' do expect(event.payload).to eq payload end end describe 'Valid Event data' do evt = { 'ID' => '5bce61f8-eaad-ff09-b5a3-89818cdb6b7b', 'Name' => Fireap::EVENT_NAME, 'Payload' => nil, } data = Fireap::Data::Event.new(evt) event = data.to_model it 'event is a Fireap::Model::Event' do expect(event).to be_an_instance_of(Fireap::Model::Event) end it 'event.payload is undefined' do expect(event.payload).to be nil end end end <file_sep>/spec/fireap/util/string_spec.rb require 'fireap/util/string' describe 'to_snakecase - string converter' do { 'ID' => 'id', 'Key' => 'key', 'camelCase' => 'camel_case', 'FooBar' => 'foo_bar', 'ServiceID' => 'service_id', }.each_pair do |k,v| it "#{k} => #{v}" do expect(k.to_snakecase).to eq(v) end end end <file_sep>/lib/fireap/data/node.rb require 'diplomat' require 'fireap' require 'fireap/model/node' require 'fireap/util/string' module Fireap::Data class Node def initialize(stash) @me = stash end def self.find(name) raw = Diplomat::Node.get(name) new(raw['Node']) end def get_val(key) @me ? @me[key] : nil end def to_model stash = {} @me.each_pair do |key, val| if key == 'Node' stash['name'] = val else stash[key.to_s.to_snakecase] = val end end Fireap::Model::Node.spawn(stash) end end end <file_sep>/lib/fireap/util/string.rb # Extends class String class String def to_snakecase str = self if /^([A-Z]+)/.match(str) str = $&.downcase + $' end while /[A-Z]+/.match(str) str = [$`, '_', $&.downcase, $'].join end str end end <file_sep>/lib/fireap/view_model/application_node.rb module Fireap::ViewModel ## # A view object which has info of a particular Application and a Node. class ApplicationNode attr :appname, :nodename, :version, :semaphore, :updated_at, :remote_node # @param app [Fireap::Model::Application] # @param node [Fireap::Model::Node] def initialize(app, node) @app = app @node = node @appname = app.name @nodename = node.name @version = app.version ? app.version.value : '-' @semaphore = app.semaphore ? app.semaphore.value : '-' @updated_at = app.update_info ? app.update_info.updated_at : '-' @remote_node = app.update_info ? app.update_info.remote_node : '-' end # @note For sorting in view def <=>(other) ret = other.version <=> self.version return ret if ret == 0 self.nodename <=> other.nodename end end end <file_sep>/spec/fireap/config_spec.rb require 'fireap/config' require 'lib/test_config' require 'tempfile' require 'toml' class Fireap::Config def test_me @me end end describe 'Fireap::Config#validate' do context 'with wrong key' do tester = TestConfig.new(<<"EOS") uri = "http://localhost:8500" enable_debug = "true" #{TestConfig.minimum_body} max_semaphore = 5 EOS it 'raise Fireap::Config::Error' do expect { tester.config.validate }.to raise_error( Fireap::Config::Error, /\["uri", "enable_debug", "task.max_semaphore"\] extra/ ) end end context 'type miss match' do ['url = 5', "[log]\nlevel = {}"].each do |text| context "given #{text}" do tester = TestConfig.new(<<"EOS") #{text} #{TestConfig.minimum_body} EOS it 'raise Fireap::Config::Error' do expect { tester.config.validate }.to \ raise_error(Fireap::Config::Error, /type mismatch/) end end end end end describe 'Fireap::Config features' do context 'with minimum config' do tester = TestConfig.minimum it 'is valid config' do expect(tester.config.validate).to be true end end context 'with global configured params' do tester = TestConfig.basic it 'match with TOML' do expect(tester.config.test_me).to match tester.parsed end it 'is valid config' do expect(tester.config.validate).to be true end describe 'Top level keys are readable accessors' do tester.parsed.each_pair do |key, value| it "{key: '#{key}', value: '#{value.to_s}'}" do expect( tester.config.send(key) ).to match value end end end describe 'When undefined key specified, Returns nil' do it "no such a key" do expect( tester.config.no_such_a_key ).to be_nil end end end context 'with some app task settings' do tester = TestConfig.tasks it 'is valid config' do expect(tester.config.validate).to be true end describe 'Not configured App' do it 'return nil' do expect( tester.config.app_config('baz') ).to be nil end end describe 'App = "foo"' do parsed = tester.parsed['task'] appc = tester.config.app_config('foo') %w[ max_semaphores on_command_failure ].each do |key| it "#{key} is overridden" do expect( appc.send(key) ).to eq parsed['apps']['foo'][key] end end it %q[ failure is ignored ] do expect(appc.is_failure_ignored?).to be_truthy end commands = [] [ parsed['before_commands'], parsed['apps']['foo']['exec_commands'], parsed['apps']['foo']['after_commands'] ].each do |a| commands.concat(a) end it 'commands are partially overridden' do expect(appc.commands).to match_array(commands) end it 'service_regexp is ignored because service is specified' do expect(appc.service_filter).to eq '^foo$' end it 'tag_regexp is ignored because tag is specified' do expect(appc.tag_filter).to eq '^v1$' end end describe 'App = "bar"' do parsed = tester.parsed['task'] appc = tester.config.app_config('bar') %w[ max_semaphores wait_after_fire watch_timeout on_command_failure ].each do |key| it "#{key} - common setting is chosen" do expect( appc.send(key) ).to eq parsed[key] end end it %q[ failure isn't ignored ] do expect(appc.is_failure_ignored?).to be_falsy end commands = [] [ parsed['before_commands'], parsed['exec_commands'], parsed['after_commands'] ].each do |a| commands.concat(a) end it 'commands all come from common setting' do expect(appc.commands).to match_array(commands) end it 'service_regexp is taken as filter because service is omitted' do expect(appc.service_filter).to eq '^[bB]ar$' end it 'tag_regexp is taken as filter because tag is omitted' do expect(appc.tag_filter).to eq '^(master|slave)$' end end end end <file_sep>/spec/fireap/util/validator_spec.rb require 'fireap/util/validator' require 'data/validator' include Fireap::Util::Validator describe 'Fireap::Util::Validator::BOOL_FAMILY' do before(:example) do @rule = Data::Validator.new(bool: { isa: BOOL_FAMILY }) end [ [ true, :is ], [ false, :is ], [ nil, :is ], [ 0, :is_not ] ].each do |sbj| it "#{sbj[0].to_s} #{sbj[1]} boolean" do case sbj[1] when :is expect( @rule.validate(bool: sbj[0]) ).to be_truthy when :is_not expect { @rule.validate(bool: sbj[0]) }.to raise_error(Data::Validator::Error) else raise "Unknown test case! #{sbj.inspect}" end end end end <file_sep>/lib/fireap.rb module Fireap VERSION = '0.4.0' NAME = 'fireap' EVENT_NAME = 'FIREAP:TASK' module Kv PREFIX = Fireap::NAME + '/' end class Error < StandardError end end <file_sep>/lib/fireap/cli.rb require 'thor' require 'fireap/config' require 'fireap/context' require 'fireap/controller/fire' require 'fireap/controller/monitor' require 'fireap/controller/reap' require 'fireap/controller/task' module Fireap class CLI < Thor @ctx package_name "Fireap::CLI" class_option 'config', :type => :string, :aliases => 'c' class_option 'debug', :type => :boolean, :aliases => 'd' desc 'fire', 'Fire an update Event for target Application' option 'app', :type => :string, :required => true, :aliases => 'a' option 'version', :type => :string, :aliases => 'v' option 'node-name', :type => :string, :aliases => 'n' #option 'node-regexp', :type => :string, :aliases => 'nr' def fire load_context(options) Fireap::Controller::Fire.new(options, @ctx).fire(options) end desc 'reap', 'Watch and Reap a fired event' option 'dry-run', :type => :boolean, :aliases => 'n' def reap load_context(options) Fireap::Controller::Reap.new(options, @ctx).reap end desc 'clear', 'Clear Fire Lock for target Application' option 'app', :type => :string, :required => true, :aliases => 'a' def clear load_context(options) Fireap::Controller::Fire.new(options, @ctx).release_lock puts "Successfully cleared lock for app=#{options['app']}." end desc 'monitor', 'Monitor update propagation of target Application' option 'app', :type => :string, :required => true, :aliases => 'a' option 'interval', :type => :numeric, :aliases => 'i' option 'one-shot', :type => :boolean, :aliases => 'o' def monitor opts = options.dup opts['suppress-log'] = true unless options['one-shot'] load_context(opts) monitor = Fireap::Monitor.new(options, @ctx) return monitor.oneshot(options) if options['one-shot'] monitor.monitor(options) end desc 'task', 'List configured tasks' option 'width', :type => :numeric, :aliases => 'w' def task load_context(options) Fireap::Controller::Task.new.show(options, @ctx) end private def load_context(options) @ctx ||= proc { opt = { config_path: options['config'], dry_run: options['dry-run'], suppress_log: options['suppress-log'], develop_mode: options['debug'], } Fireap::Context.new(opt) }.call @ctx.config.validate if ! @ctx.develop_mode? and options['debug'] @ctx.log.warn %q[You specified DEBUG option. But DEBUG mode is disabled by configuration. Please set `enable_debugging = "ON"` in your config file.] end end end end <file_sep>/lib/fireap/controller/fire.rb require 'socket' require 'fireap' require 'fireap/data_access/kv' require 'fireap/manager/node' require 'fireap/manager/node_factory' require 'fireap/model/application' require 'fireap/model/event' module Fireap::Controller class Fire @@default_semaphore = 2 @@wait_interval = 2 # @param ctx [Fireap::Context] def initialize(options, ctx) @appname = options['app'] @version = options['version'] || nil @node_filter = options['node-name'] @ctx = ctx @appconf = ctx.config.app_config(@appname) end def fire(options) payload = prepare_event(options) return unless payload params = { payload: payload, node_filter: @node_filter ? "^#{@node_filter}$" : nil, service_filter: @appconf.service_filter, tag_filter: @appconf.tag_filter, } Fireap::Model::Event.new(params).fire @ctx.log.info "Event Fired! Params = #{params.inspect}" if @appconf.wait_after_fire.to_i > 0 unless wait_propagation @ctx.log.warn <<"EOS" Task #{@appname} propagation is unfinished. If you want to check the propagation, do following: % #{Fireap::NAME} monitor -a #{@appname} Or check the logs. EOS end end self.release_lock end def get_lock @lock_key ||= "#{@appname}/lock" if Fireap::DataAccess::Kv.get(@lock_key, :return).length > 0 @ctx.log.warn(<<"EOS") Task #{@appname} is already locked! Maybe update is ongoing. Please Check! If you want to clear the lock, do following: % #{Fireap::NAME} clear -a #{@appname} EOS return false end unless Fireap::DataAccess::Kv.put(@lock_key, Socket.gethostname) @ctx.die("Failed to put kv! key=#{@appname}") end @ctx.log.debug "Succeed to get lock for app=#{@appname}" return true end def release_lock @lock_key ||= "#{@appname}/lock" unless Fireap::DataAccess::Kv.delete(@lock_key) @ctx.die("Failed to delete kv! key=#{@appname}") end end private def prepare_event(options) unless @ctx.config.app_config(@appname) @ctx.die("Not configured app! #{@appname}") end return unless self.get_lock app = Fireap::Model::Application.find_or_new(@appname, @ctx.mynode) @version ||= app.version.next_version app.semaphore.update(@appconf.max_semaphores) app.version.update(@version) payload = { app: @appname, version: @version } end def wait_propagation wait_s = @appconf.wait_after_fire time_s = Time.now.to_i @app = Fireap::Model::Application.new(@appname) nodes = target_nodes() node_num = nodes.size interval = (@@wait_interval > wait_s) ? sec : @@wait_interval interrupt = 0 Signal.trap(:INT) { interrupt = 1 } try = 1 finished = false while interrupt == 0 @ctx.log.info "Waiting for propagation ... trial: #{try}" sleep interval ntbl = Fireap::Manager::Node.instance ntbl.collect_app_info(@app, ctx: @ctx) updated = ntbl.select_updated(@app, @version, ctx: @ctx) updated_num = compare_nodes_and_updated(nodes, updated) @ctx.log.info '%d/%d nodes updated.' % [updated_num, node_num] if updated_num == node_num @ctx.log.info 'Complete!' finished = true break end break if (Time.now.to_i - time_s) >= wait_s end finished end def target_nodes if @node_filter [ Fireap::Model::Node.find(@node_filter) ] elsif @appconf.service_filter Fireap::Manager::NodeFactory.catalog_service_by_filter( @appconf.service_filter, tag_filter: @appconf.tag_filter) else Fireap::Manager::Node.instance.nodes end end # @return [Fixnum] Updated node number def compare_nodes_and_updated(nodes, updated) if nodes.class == Hash and nodes.size >= updated.size updated.size else # nodes is from NodeFactory match = updated.select do |key, val| nodes.find_index do |nd| nd.address == val.address end end match.size end end end end <file_sep>/lib/fireap/view_controller/terminal.rb require 'curses' module Fireap::ViewController class Terminal def clear Curses.clear Curses.setpos(0, 0) end def draw(str) Curses.addstr(str) Curses.refresh end def finalize Curses.clear Curses.close_screen end end end <file_sep>/spec/lib/test_config.rb require 'tempfile' require 'toml' require 'fireap/config' class TestConfig attr :parsed, :config def initialize(toml) @parsed = TOML.parse(toml) tmp = Tempfile.open('tmp') do |fp| fp.puts toml fp end ENV['FIREAP_CONFIG_PATH'] = tmp.path @config = Fireap::Config.new end def self.minimum_body <<"EOS" [task] apps = {} EOS end def self.minimum new(minimum_body()) end def self.basic new(<<"EOS") url = "http://localhost:8500" enable_debugging = "" [log] level = "INFO" file = "tmp/fireap.log" #{minimum_body()} EOS end def self.tasks new(<<"EOS") ## Common Task Settings [task] max_semaphores = 5 wait_after_fire = 10 watch_timeout = 120 on_command_failure = "abort" before_commands = [ "common before" ] exec_commands = [ "common exec" ] after_commands = [ "common after" ] [task.apps.foo] max_semaphores = 3 on_command_failure = "ignore" exec_commands = [ "foo exec1", "foo exec2" ] after_commands = [ "foo after" ] service = "foo" service_regexp = "^fooo*$" tag = "v1" tag_regexp = "^v.$" [task.apps.bar] service_regexp = "^[bB]ar$" tag_regexp = "^(master|slave)$" EOS end end <file_sep>/spec/fireap/model/application_spec.rb require 'fireap/model/application' ver2next = { '1' => '2', 'v1' => 'v2', 'v0.3.1' => 'v0.3.2', 'p208-1' => 'p208-2', 'foo' => 'foo-1', } describe 'Fireap::Model::Application' do ver = Fireap::Model::Application::Version.new(value: 'v1') sem = Fireap::Model::Application::Semaphore.new(value: '5') nod = Fireap::Model::Node.new('test1', '127.0.0.1') describe 'New' do it 'with all params' do app = Fireap::Model::Application.new('foo', version: ver, semaphore: sem, node: nod) expect(app.name).to eq 'foo' expect(app.version).to be ver expect(app.semaphore).to be sem expect(app.node).to be nod expect(app.update_info).to be nil end it 'with least params' do app = Fireap::Model::Application.new('bar') expect(app.name).to eq 'bar' expect(app.version).to be nil expect(app.semaphore).to be nil expect(app.node).to be nil expect(app.update_info).to be nil end end end describe 'Fireap::Model::Application::Version' do describe 'Automatically determine next version' do ver2next.each_pair do |pre,nxt| it "#{pre} => #{nxt}" do ver = Fireap::Model::Application::Version.new(value: pre) expect(ver.next_version).to eq nxt end end end end <file_sep>/lib/fireap/validator.rb require 'data/validator' require 'fireap' module Fireap class Validator Error = Class.new(StandardError) def initialize(rules) @rules = rules @validator = ::Data::Validator.new(rules) end def validate(args) errors = [] begin result = @validator.validate(args) rescue => e errors << e end extra = find_extra(args, @rules) if extra.length > 0 errors << Error.new("#{extra.inspect} extra") end if errors.length > 0 raise Error, errors.join("\n") end true end private def find_extra(given, rules, prefix='') extra = [] given.each_pair do |key, val| if ! rules.has_key?(key) extra << prefix + key elsif rules[key].has_key?(:rule) extra.concat( find_extra(val, rules[key][:rule], prefix + "#{key}.") ) end end extra end end end <file_sep>/lib/fireap/model/kv.rb require 'diplomat' require 'fireap' require 'fireap/data_access/kv' require 'fireap/util/string' module Fireap::Model class Kv @@accessors = [ :key, :value, :create_index, :modify_index, :lock_index, :flags, :session, :is_dirty ] @@accessors.each do |key| attr key end def initialize(params) params.each do |key, val| instance_variable_set("@#{key}", val) end @is_dirty = false end def self.get(path) Fireap::DataAccess::Kv.get_data(path) || new({ key: Fireap::Kv::PREFIX + path, }) end def to_hash stash = {} @@accessors.each do |key| stash[key] = instance_variable_get("@#{key}") end stash end # Query Kv and return the new instance def refetch Fireap::DataAccess::Kv.get_data(self.key, with_prefix: true) end def update(value, cas: false) before = @value updated = proc { @value = value.to_s save(cas: cas) }.call if updated # Set dirty flag because @modiry_index is unreliable now. @is_dirty = true true else @value = before false end end def save(cas: false) args = [self.key, self.value] args.push({ cas: self.modify_index }) if cas if Diplomat::Kv.put(*args) return true end false end end end <file_sep>/lib/fireap/util/validator.rb require 'fireap' module Fireap::Util module Validator BOOL_FAMILY = [TrueClass, FalseClass, NilClass] end end <file_sep>/lib/fireap/logger.rb require 'logger' module Fireap # Logger Factory class to controll logging class Logger # @param outs [Array] Log outputs. Given to Logger.new as logdev # @param rotate [Fixnum, String] shift_age param in Logger.new # @param level Log level defined as constants in Logger class # @param header [String] Custom header for each log line def initialize(outs, rotate: 0, level: nil, header: '') @loggers = [] @header = header.length > 0 ? header : nil level ||= 'INFO' outs.each do |out| logger = ::Logger.new(out, rotate) logger.level = Object.const_get("Logger::#{level}") logger.progname = [$0, ARGV].join(%q[ ]) logger.formatter = proc do |level, date, prog, msg| "#{date} [#{level}] #{msg} -- #{prog}\n" end @loggers.push(logger) end end def log(level=::Logger::INFO, message) @loggers.each do |logger| logger.log(level, custom_message(message)) end end # Supposed to receive logging methods like :info, :warn or others which # is given to Logger instances in @loggers. def method_missing(method, *args) @loggers.each do |logger| msg = custom_message(args[0]) new_args = args[1 .. args.size-1] logger.send(method, msg, *new_args) end end private def custom_message(message) customized = [message, 'at', caller(4, 1).to_s].join(%q[ ]) @header ? "#{@header} #{customized}" : customized end end end <file_sep>/lib/fireap/context.rb require 'data/validator' require 'fireap/logger' require 'fireap/util/validator' module Fireap class Context include Fireap::Util::Validator attr :config, :log @node = nil # Fireap::Model::Node of running host @mode = 'production' def initialize(*args) params = ::Data::Validator.new( config_path: { isa: [String, NilClass], default: nil }, dry_run: { isa: BOOL_FAMILY, default: nil }, suppress_log: { isa: BOOL_FAMILY, default: nil }, develop_mode: { isa: BOOL_FAMILY, default: nil }, ).validate(*args) cfg = {} cfg[:path] = params[:config_path] if params[:config_path] @config = Fireap::Config.new(cfg) @dry_run = params[:dry_run] @mode = 'develop' if params[:develop_mode] @log = logger(@config.log, params[:suppress_log]) end def die(message, level=::Logger::ERROR, err=Fireap::Error) @log.log(level, [message, 'at', caller(1).to_s].join(%q{ })) raise err, message unless self.develop_mode? end def mynode @node ||= Fireap::Model::Node.query_agent_self end def dry_run? @dry_run end def develop_mode? if is_develop_mode? @log.warn 'IN DEVELOP MODE. Called from ' + caller(1..2).to_s if @log true else false end end private def logger(config, suppress) config ||= {} outs = [] unless suppress outs.push(STDOUT) if STDOUT.tty? outs.push(config['file']) if config['file'] end headers = [] headers.push('## DEVELOP MODE ##') if is_develop_mode? headers.push('[Dry-run]') if dry_run? Fireap::Logger.new( outs, rotate: config['rotate'], level: config['level'], header: headers.join(%q[ ]) ) end def is_develop_mode? @mode == 'develop' \ and flg = @config.enable_debugging \ and flg != 0 and flg.length > 0 end end end <file_sep>/spec/fireap/manager/node_factory_spec.rb require 'fireap/manager/node_factory' require 'diplomat' include Fireap::Manager describe 'Fireap::Manager::NodeFactory#catalog_service' do data = [ { 'Name' => 'test1', 'Address' => '192.168.101.1', 'ServiceID' => 'web', }, { 'Name' => 'test2', 'Address' => '192.168.101.2', 'ServiceID' => 'web', }, ] context 'when Diplomat::Service#get return Node data' do before(:example) do allow(Diplomat::Service).to receive_message_chain(:get).and_return(data) end it 'returned data number matches' do nodes = NodeFactory.catalog_service('web') expect(nodes.size).to eq data.size end end end describe 'Fireap::Manager::NodeFactory#catalog_service_by_filter' do catalog = { 'foo' => %w(v1 v2), 'bar' => [], } data = [{ 'Name' => 'test1', 'Address' => '192.168.101.1', 'ServiceID' => 'web', }] context "Service Catalog: #{catalog.inspect}" do before do allow(Diplomat::Service).to receive_message_chain(:get).and_return(data) allow(Diplomat::Service).to receive_message_chain(:get_all).and_return(catalog) end context 'with service_filter: ^(foo|bar)$, tag_filter: nil' do it 'matches 3 times' do nodes = NodeFactory.catalog_service_by_filter('^(foo|bar)$') expect(nodes.size).to eq 3 end end context 'with service_filter: ^(foo|bar).*$, tag_filter: ^v[12]$' do it 'matches 2 times' do nodes = NodeFactory.catalog_service_by_filter('^(foo|bar).*$', tag_filter: '^v[12]$') expect(nodes.size).to eq 2 end end context 'with service_filter: ^bar, tag_filter: v3' do it 'matches 0 times' do nodes = NodeFactory.catalog_service_by_filter('^bar', tag_filter: 'v3') expect(nodes.size).to eq 0 end end end end <file_sep>/lib/fireap/data_access/service.rb require 'diplomat' require 'fireap' module Fireap::DataAccess class Service class << self def catalog_all Diplomat::Service.get_all end end end end <file_sep>/lib/fireap/model/application.rb require 'data/validator' require 'json' require 'fireap' require 'fireap/data_access/kv' require 'fireap/model/kv' require 'fireap/model/node' module Fireap::Model # A data container of an Application and related information. # @todo Ideally it should belong to a Node object. So this object should not # include @node # If you want to treat Application and Node, use Fireap::Mode::ApplicationNode # @see Fireap::Model::ApplicationNode class Application attr :name, :version, :semaphore, :node, :update_info def initialize(name, *option) args = { name: name } args.merge!(*option) if ! option.empty? params = Data::Validator.new( name: { isa: String }, version: { isa: Version, default: nil }, semaphore: { isa: Semaphore, default: nil }, node: { isa: Fireap::Model::Node, default: nil }, ).validate(args) params.each_pair do |key, val| instance_variable_set("@#{key}", val) end @update_info = nil end # @todo Move this to Fireap::Model::ApplicationNode def self.find_or_new(name, node, ctx: nil) app = new(name, node: node) path = "#{name}/nodes/#{node.name}/" kv_data = Fireap::DataAccess::Kv.get_recurse(path) if kv_data.length > 0 kv_data.each do |kv| if kv.key =~ %r|#{name}/nodes/#{node.name}/([\w]+)| app.set_kv_prop($1, kv) else ctx.log.error "Got key doesn't match! Got=#{kv.key}, Expected Node=#{node.name}" end end end %w[version semaphore update_info].each do |key| unless app.instance_variable_get("@#{key}") app.set_kv_prop(key, Fireap::Model::Kv.new({ key: Fireap::Kv::PREFIX + [path, key].join('/'), })) end end app end def to_hash { name: @name, version: @version ? @version.value : '0', semaphore: @semaphore ? @semaphore.value : '0', update_at: @update_info ? @update_info.updated_at : nil, remote_node: @update_info ? @update_info.remote_node : nil, } end def set_kv_prop(key, kv_data) case key when 'version' @version = Version.new(kv_data.to_hash) when 'semaphore' @semaphore = Semaphore.new(kv_data.to_hash) when 'update_info' @update_info = UpdateInfo.new(kv_data.to_hash) else raise "Unkwon kv_prop! key=#{key}, data=#{kv_data.to_s}" end end def update_properties(version: nil, semaphore: nil, cas: nil, remote_node: nil) updated = 0 if version and @version.update(version) updated += 1 end if semaphore and @semaphore.update(semaphore, cas: cas) updated += 1 end if remote_node ret = @update_info.update({ updated_at: Time.now.to_s, remote_node: remote_node }.to_json) updated += 1 if ret end updated end class Version < Fireap::Model::Kv def initialize(params) super(params) @value ||= '0' end def next_version if %r{(.*\D)?(\d+)(\D*)?}.match(@value.to_s) [$1, $2.to_i + 1, $3].join else @value + '-1' end end end class Semaphore < Fireap::Model::Kv def consume(cas: false) if @value.to_i <= 0 raise "No more semaphore! val=#{@value}" end self.update(@value.to_i - 1, cas: cas) end def restore(cas: false) self.update(@value.to_i + 1, cas: cas) end def refetch self.class.new(super.to_hash) end end class UpdateInfo < Fireap::Model::Kv attr :updated_at, :remote_node def initialize(params) super(params) return unless @value JSON.parse(@value).tap do |v| @updated_at = v['updated_at'] @remote_node = v['remote_node'] end end end end end <file_sep>/lib/fireap/controller/monitor.rb require 'fireap/view_controller/terminal' require 'fireap/view_model/application' module Fireap class Monitor # @param ctx [Fireap::Context] def initialize(options, ctx) @appname = options['app'] @appdata = Fireap::ViewModel::Application.new(options['app'], ctx) @interval = options['interval'].to_i || 2 @ctx = ctx end def monitor(options) @screen = Fireap::ViewController::Terminal.new int = 0 Signal.trap(:INT) { int = 1 } @appdata.refresh while int == 0 @screen.clear @screen.draw( @appdata.render_text ) sleep @interval @appdata.refresh end @screen.finalize puts "End." end def oneshot(options) @appdata.refresh puts @appdata.render_text end end end <file_sep>/README.md # fireap [![Build Status](https://travis-ci.org/progrhyme/fireap.svg?branch=master)](https://travis-ci.org/progrhyme/fireap) Consul-based rapid propagative task runner for large systems. ### Table of Contents * [Overview](#overview) * [What's this?](#whats-this) * [Benchmark](#benchmark) * [About Consul](#about-consul) * [Take a look at how it works](#take-a-look-at-how-it-works) * [Task Propagation Procedure](#task-propagation-procedure) * [Publisher and Subscribers](#publisher-and-subscribers) * [Procedure](#procedure) * [Consul Kv](#consul-kv) * [How to get started?](#how-to-get-started) # Overview ## What's this? This program triggers to execute configured tasks on nodes in **_Consul Cluster_**. And tasks will be executed in propagative way. Task propagation time takes _O(log N)_ in theory; as _N_ means node number in cluster. So this tool can shorten the time of tasks which take _O(N)_ time in system of large number of nodes. Typical usecase is software deployment. The name **fireap** comes from _"fire"_ and _"reap"_. ## Benchmark Here is a benchmark result comparing **fireap** against [GNU Parallel](http://www.gnu.org/software/parallel/). | | GNU Parallel | fireap | | ---- | ------------:|----------:| | real | 0m46.906s | 0m18.992s | | user | 0m40.407s | 0m00.527s | | sys | 0m04.241s | 0m00.046s | The job executed here is a directory sync operation by `rsync` command which contains a thousand of files up to total 12MB size, through 100 t2.micro instances on AWS EC2. Concurrency numbers of both _GNU Parallel_ and _fireap_ is 5 in this benchmark. In _fireap_, the word _"concurrency"_ means the maximum concurrent number that one node can be "pulled" by other nodes. You will grasp the concept by going under part of this document. ## About Consul [Consul](https://www.consul.io/) is a tool for service discovery and infrastructure automation developed and produced by [HashiCorp](https://www.hashicorp.com/). ## Take a look at how it works Below is a demo of **fireap** task propagation at a 10-node Consul cluster. ![Fireap Demo](https://raw.githubusercontent.com/progrhyme/fireap/resource/image/fireap-demo.gif) On the top of the screen, `fireap monitor` command is executed. This continuously shows the application version and updated information of nodes those are stored in _Consul Kv_. On the bottom of the screen, `fireap fire` command is executed which fires _Consul Event_. The triggered event is broadcasted to cluster members at once. And it leads cluster members to execute `fireap reap` command by _Consul Watch_ mechanism. Eventually, configured tasks are executed on nodes in the cluster. ## Task Propagation Procedure The image below illustrates task propagation procedure by **fireap** in Consul cluster. ![Fireap Task Propagation Illustration](https://raw.githubusercontent.com/progrhyme/fireap/resource/image/fireap-propagation.png) ### Publisher and Subscribers One _publisher_ node fires Consul events whose `Name` is `FIREAP:TASK`. And it is assumed to be the 1st node in the cluster which finishes the task. All other nodes are _subscribers_ who receive events and execute tasks. Concept of _publisher_ and _subscriber_ is not related to role of _server_ and _client_ in Consul. _Server_ or _client_ in Consul cluster can be either _publisher_ or _subscriber_. ### Procedure 1. _Publisher_ fires a Consul event. 2. The event is broadcasted for appropriate _subscribers_ at once. 3. _Subscribers_ execute the task in propagative way: 1. All _subscribers_ search for a finished node in the cluster to "pull" update information or contents from the node. In first stage, there is only _publisher_ who finished the task. So they all tries to "pull" from _publisher_, but maximum number of who can "pull" from a particular node is limited by configuration. Then, only several _subscribers_ succeed to "pull" and execute the task. 2. In second stage, _publisher_ and several _subscribers_ now finished the task. Their update will be "pulled" by other _subscribers_. 3. Stage goes on until all _subscribers_ finish the task. This propagation way looks like tree branching. But it is rather robust because even if a _subscriber_ happens to fail the task, the failure does not affect others. ### Consul Kv _Publisher_ and _subscribers_ store information in _Consul Kv_ about task completion and so on. All keys of data related to this program begin with prefix `fireap/`. # How to get started? You can start **fireap** with the guide in [Documentation](http://progrhyme.github.io/fireap-doc/). # LICENSE The MIT License (MIT) Copyright (c) 2016-2017 <NAME> <file_sep>/spec/fireap/data/kv_spec.rb require 'fireap/data/kv' require 'base64' describe 'Transform to Model::Kv' do describe 'Valid Kv kv_m' do kv = { 'Key' => 'version', 'Value' => Base64.encode64('v0.1.0'), } data = Fireap::Data::Kv.new(kv) kv_m = data.to_model it 'kv_m is a Fireap::Model::Kv' do expect(kv_m).to be_an_instance_of(Fireap::Model::Kv) end it 'kv_m.value is decoded' do expect(kv_m.value).to eq 'v0.1.0' end end describe 'Value is undefined' do kv = { 'Key' => 'version', 'Value' => nil, } data = Fireap::Data::Kv.new(kv) kv_m = data.to_model it 'kv_m is a Fireap::Model::Kv' do expect(kv_m).to be_an_instance_of(Fireap::Model::Kv) end it 'kv_m.value is nil' do expect(kv_m.value).to be nil end end end <file_sep>/spec/base_spec.rb require 'rspec' describe 'Require All *.rb files' do Dir[ File.join(File.dirname(__FILE__), '..', 'lib', '**/*.rb') ].each do |f| it "require #{f}" do ret = require f expect(ret).to_not be_nil end end end <file_sep>/spec/fireap/controller/task_spec.rb require 'fireap/controller/task' require 'fireap/context' require 'lib/test_config' class TestContext attr :ctx def initialize config = TestConfig.tasks # will be ctx.config @ctx = Fireap::Context.new end end describe 'Fireap::Controller::Task#show' do ctx = TestContext.new.ctx config = ctx.config apps = config.task['apps'] context 'when config is valid' do it 'print output' do $stdout = StringIO.new Fireap::Controller::Task.new.show({'width' => 80}, ctx) output = $stdout.string expect(output.length > 0).to be true $stdout = STDOUT end end end <file_sep>/Gemfile source "https://rubygems.org" gem 'rake', '~> 10.4' gem 'curses', '~> 1.0' gem 'data-validator', '~> 1.0' gem 'diplomat', '~> 0.15.0' gem 'terminal-table', '~> 1.5' gem 'thor', '~> 0.19' gem 'toml-rb', '~> 0.3.10' group :development do gem 'rspec', '~> 3.4' end <file_sep>/lib/fireap/controller/task.rb require 'fireap' require 'fireap/view_model/config' module Fireap::Controller class Task # @param ctx [Fireap::Context] def show(options, ctx) renderer = Fireap::ViewModel::Config.new(width: options['width']) list = ctx.config.app_list puts '== Configured Tasks ==' puts renderer.render_applist(list) end end end <file_sep>/lib/fireap/data_access/kv.rb require 'fireap' require 'fireap/model/kv' require 'fireap/data/kv' module Fireap::DataAccess class Kv < Diplomat::Kv @@prefix = Fireap::Kv::PREFIX @access_methods = [ :get, :put, :delete, :get_data, :get_recurse ] def get(key, not_found=:reject, options=nil, found=:return) # Notice: change args order to be less coding super(@@prefix + key, options, not_found, found) end # Diplomat::Kv#get returns only string def get_data(key, with_prefix: nil) path = with_prefix ? '/kv/' + key : "/kv/#{@@prefix}" + key unless resp = Fireap::DataAccess::Rest.get(path) return false end Fireap::Data::Kv.new(resp.shift).to_model end # Diplomat::Kv#get with option (:recurse => 1) doesn't work. # This is a work around. def get_recurse(key) unless resp = Fireap::DataAccess::Rest.get("/kv/#{@@prefix}" + key, params: ['recurse=1']) return [] end resp.map { |kv| Fireap::Data::Kv.new(kv).to_model } end def put(key, value, options=nil) super(@@prefix + key, value, options) end def delete(key, options=nil) super(@@prefix + key, options) end end end <file_sep>/spec/fireap/model/event_spec.rb require 'fireap' require 'fireap/data/event' require 'base64' require 'json' require 'tempfile' def test_event_data_match(event, data) describe "Test event data match. ID=#{event.id}" do it 'event is a Fireap::Model::Event' do expect(event).to be_an_instance_of(Fireap::Model::Event) end it 'check id/payload match' do expect(event.id).to eq data['ID'] expect(event.payload).to eq JSON.parse( Base64.decode64(data['Payload']) ) end it 'name is set default when data is undefined' do if data['Name'] expect(event.name).to eq data['Name'] else expect(event.name).to eq Fireap::EVENT_NAME end end end end describe 'Fireap::Model::Event' do payloads = [ {'name' => 'foo', 'version' => 'v1'}, {'name' => 'bar', 'version' => 'v2'}, ] data = [ { 'ID' => '5bce61f8-eaad-ff09-b5a3-89818cdb6baa', 'Name' => 'test-event', 'Payload' => Base64.encode64(payloads[0].to_json), }, { 'ID' => '1bce61f8-eaad-ff09-b5a3-89818cdb6aaa', 'Payload' => Base64.encode64(payloads[1].to_json), } ] describe 'Class method "convert_from_streams"' do describe 'returns all parsed event objects' do events = Fireap::Model::Event.convert_from_streams(data.to_json) it 'all given data are parsed' do expect(data.size).to eq events.size end events.each_with_index do |event, i| test_event_data_match(event, data[i]) end end end describe 'Class method "fetch_from_stdin"' do describe 'case no input' do $stdin = StringIO.new(data.to_json) it 'return nothing' do end end describe 'case data are set' do $stdin = StringIO.new(data.to_json) event = Fireap::Model::Event.fetch_from_stdin describe 'returns last event' do test_event_data_match(event, data[1]) end end end end <file_sep>/spec/fireap/model/kv_spec.rb require 'fireap/model/kv' kv1 = Fireap::Model::Kv.new( key: 'version', value: 'v0.1', modify_index: '1', is_dirty: false, ) kv2 = kv1.clone describe 'Update Kv data' do describe 'Case - Diplomat::Kv#put succeeds' do before do allow(Diplomat::Kv).to receive_message_chain(:put).and_return(true) end it 'update succeeds' do ret = kv1.update('v0.2') expect(ret).to be true expect(kv1.value).to eq 'v0.2' expect(kv1.is_dirty).to be true end end describe 'Case - Diplomat::Kv#put fails' do before do allow(Diplomat::Kv).to receive_message_chain(:put).and_return(false) end it 'update fails' do ret = kv2.update('v0.2') expect(ret).to be false expect(kv2.value).to eq 'v0.1' expect(kv2.is_dirty).to be false end end end <file_sep>/lib/fireap/view_model/config.rb require 'terminal-table' module Fireap::ViewModel class Config def initialize(width: nil) @cmdwidth = width || 90 end # @param list [Array] of Fireap::Config::App objects def render_applist(list) text = "[Summary]\n" text << render_applist_summary(list) text << "\n" text << render_applist_commands(list) end private # @param list [Array] of Fireap::Config::App objects def render_applist_summary(list) tt = Terminal::Table.new tt.headings = %w[ App MaxSem Timeout OnCmdFail Service Tag WaitAfterFire ] list.each do |conf| app = conf.to_view tt.add_row [ app.name, app.max_semaphores, '%d sec' % [app.watch_timeout], app.is_failure_ignored ? 'IGNORE' : 'ABORT', app.service_filter, app.tag_filter, '%d sec' % [app.wait_after_fire], ] end tt.to_s end # @param list [Array] of Fireap::Config::App objects def render_applist_commands(list) text = '' list.each do |conf| app = conf.to_view text << %Q|[App "#{app.name}" - Commands]\n| text << render_app_commands(conf) text << "\n" end text end def render_app_commands(app) tt = Terminal::Table.new tt.headings = %w[ # Command ] app.commands.each_with_index do |cmd, i| cmds = cmd.scan(/.{1,#{@cmdwidth}}/) tt.add_row [ i+1, cmds.join("\n") ] end tt.to_s end # ViewModel of Fireap::Config::App class App def initialize(stash) @me = stash end def method_missing(method) if @me.has_key?(method.to_s) @me[method.to_s] end end end end end <file_sep>/lib/fireap/model/job.rb require 'fireap/model/command' module Fireap::Model # A Job is defined by set of Commands. # @see Fireap::Model::Command # @todo Currently this class suppose that Fireap::Context object is given. # It should be more isolative from context. class Job attr :ctx def initialize(ctx: nil) @ctx = ctx end def run_commands(app: nil, remote: nil) app_cfg = @ctx.config.app_config(app.name) formats = app_cfg.commands \ or "No command configured! app=#{app.name}" @results = [] formats.each do |fmt| command = Fireap::Model::Command.new( app: app.name, format: fmt, remote: remote, config: app_cfg, ctx: @ctx, ) result = command.run @results.push(result) if result.is_failed? if app_cfg.is_failure_ignored? @ctx.log.warn "[#{app}] Failure IGNORE is ON. Going on." result.mark_ignored next else @ctx.log.error "[#{app}] ABORT because Failed!" break unless @ctx.develop_mode? end end end @results end end end <file_sep>/lib/fireap/view_model/application.rb require 'terminal-table' require 'fireap/view_model/application_node' module Fireap::ViewModel class Application def initialize(name, ctx) @name = name @data = Fireap::Model::Application.new(name) @appnodes = [] # List of ApplicationNode @ctx = ctx end def refresh ntbl = Fireap::Manager::Node.instance ntbl.collect_app_info(@data, ctx: @ctx) @appnodes = [] ntbl.nodes.values.each do |node| app = node.apps[@name] appnode = Fireap::ViewModel::ApplicationNode.new(app, node) @appnodes.push(appnode) end end def render_text text = header_text() text << body_text() end private def header_text <<"EOH" ---- Time: #{Time.now} App: "#{@name}" ---- EOH end def body_text tt = Terminal::Table.new tt.headings = %w[ Name Version Sem Date From ] @appnodes.sort.each do |an| tt.add_row [ an.nodename, an.version, an.semaphore, an.updated_at, an.remote_node, ] end @body = tt.to_s end end end <file_sep>/lib/fireap/manager/node_factory.rb require 'diplomat' require 'fireap' require 'fireap/data/node' require 'fireap/data_access/service' module Fireap::Manager class NodeFactory class << self def catalog_service_by_filter(service_filter, tag_filter: nil) nodes = [] svc_regexp = Regexp.new(service_filter) tag_regexp = tag_filter ? Regexp.new(tag_filter) : nil service_catalog = Fireap::DataAccess::Service.catalog_all service_catalog.each_pair do |svc, tags| next unless svc_regexp.match(svc) if tags.length > 0 tags.each do |t| next if tag_regexp && ! tag_regexp.match(t) nodes.concat( catalog_service(svc, tag: t) ) end elsif ! tag_regexp nodes.concat( catalog_service(svc) ) else # tag_filter specified, but no tag found next end end nodes end def catalog_service(service, tag: nil) opt = { tag: tag } data = Diplomat::Service.get(service, :all, opt) return nil unless data data.map { |d| Fireap::Data::Node.new(d).to_model } end end end end <file_sep>/lib/fireap/model/application_node.rb module Fireap::Model ## # A data model which has info of a particular Application and a Node. class ApplicationNode attr :app, :node, :appname, :nodename # @param app [Fireap::Model::Application] # @param node [Fireap::Model::Node] # @param ctx [Fireap::Context] def initialize(app, node, ctx: nil) @app = app @node = node @ctx = ctx @appname = app.name @nodename = node.name end # @return [Array(Fireap::Model::ApplicationNode)] def find_updated_nodes(version) ntable = Fireap::Manager::Node.instance ntable.collect_app_info(@app, ctx: @ctx) found = [] nodes = ntable.select_updated(@app, version, ctx: @ctx) nodes.each_pair do |host, node| if @nodename == host @ctx.log.info "Candidate node is myself. #{host} Skip." next unless @ctx.develop_mode? end found.push( self.class.new(node.apps[@appname], node, ctx: @ctx) ) end found end end end <file_sep>/lib/fireap/data_access/rest.rb module Fireap::DataAccess class Rest < Diplomat::RestClient @access_methods = [:get] def get(path, params: []) begin @raw = @conn.get do |req| req.url concat_url [ '/v1' + path, params ] req.options.timeout = 10 end rescue => e logger = Fireap::Context.new.log logger.info "REST failed. Data not found. path=#{path}" logger.debug e return nil end parse_body end end end <file_sep>/config/sample.toml ## General Settings # url = "http://localhost:8500" # enable_debugging = "true" # For development Only [log] level = "INFO" # from Ruby Logger::LEVEL rotate = "daily" # from Ruby Logger shift_age # file = path/to/logfile ## Common Task Settings # Can be overridden by each app settings [task] max_semaphores = 5 # Max concurrency when one node can be "pulled" by others wait_after_fire = 15 # seconds. Don't wait if not defined watch_timeout = 120 # seconds on_command_failure = "abort" # or "ignore". Default is "abort" # You can define common task commands for all apps here. # Available variables for command formats: # - @app ... Target App's Name # - @remote.name ... Node Name in Consul Cluster # - @remote.address ... Node's Ipaddress in Consul Cluster # - ENV ... Given Environment Vars for Watch Command before_commands = [ "echo Task <%= @app %> Started.", ] # exec_commands = [] # Probably different for each apps. after_commands = [ "echo Task <%= @app %> Ended.", ] # Belows are not implemented yet: # command_timeout = 60 ## Settings for each Task target Application [task.apps.foo] # max_semaphores = 3 # before_commands = [] exec_commands = [ #"scp -rp <%= @remote.name %>:<%= ENV['HOME'] %>/<%= @app %> <%= ENV['HOME'] %>/" "scp -rp <%= @remote.address %>:<%= ENV['HOME'] %>/<%= @app %> <%= ENV['HOME'] %>/" ] # You can specify Consul service and tag to filter the task propagation targets. # It can be normal string or regexp; if you want to specify regexp, use the keys # "service_regexp" or "tag_regexp". # If you miss "service" or "service_regexp" filter, "tag" and "tag_regexp" won't # be evaluated. service = "foo" tag = "v1" # service_regexp = "^foo(:[a-z]+)?$" # tag_regexp = "^v[0-9]$" [task.apps.bar] on_command_failure = "ignore" before_commands = [] exec_commands = [ "date '+%FT%T' > /tmp/bar.updated_at.txt", "rsync -az --delete --exclude='.git*' <%= @remote.address %>:<%= ENV['HOME'] %>/<%= @app %> <%= ENV['HOME'] %>/", ] after_commands = [] <file_sep>/spec/fireap/controller/fire_spec.rb require 'fireap/controller/fire' require 'fireap/context' require 'lib/test_config' class TestContext attr :ctx def initialize config = TestConfig.tasks # will be ctx.config @ctx = Fireap::Context.new end end describe 'Fireap::Controller::Fire#new' do ctx = TestContext.new.ctx config = ctx.config apps = config.task['apps'] context 'given valid arguments' do it 'can new' do firer = Fireap::Controller::Fire.new({'app' => apps.keys[0]}, ctx) expect(firer).to be_an_instance_of(Fireap::Controller::Fire) end end end <file_sep>/lib/fireap/controller/reap.rb require 'base64' require 'timeout' require 'fireap/model/application' require 'fireap/model/application_node' require 'fireap/controller/fire' require 'fireap/model/event' require 'fireap/model/job' require 'fireap/model/node' require 'fireap/manager/node' module Fireap::Controller class Reap @@default_timeout = 600 # seconds @@loop_interval = 5 @@restore_interval = 3 @@restore_retry = 3 # @param ctx [Fireap::Context] def initialize(options, ctx) @ctx = ctx @config = ctx.config @event = nil @appconf = nil @myapp = nil @myappnode = nil end def reap unless evt = Fireap::Model::Event.fetch_from_stdin @ctx.log.info 'Event not happend yet. Do nothing.' return end @ctx.log.debug evt.to_s @event = evt.payload return unless prepare_reap() watch_sec = @appconf.watch_timeout || @@default_timeout result = nil Timeout.timeout(watch_sec) do |t| result = update_myapp() end if result @ctx.log.info "Update is successful. app=#{@myapp.name}, version=#{@event['version']}" else @ctx.log.error "Update failed! app=#{@myapp.name}, version=#{@event['version']}" end end private def prepare_reap unless @appconf = @config.app_config(@event['app']) @ctx.die("Not configured app! #{@event['app']}") end @myapp = Fireap::Model::Application.find_or_new( @event['app'], @ctx.mynode, ctx: @ctx ) @myappnode = Fireap::Model::ApplicationNode.new(@myapp, @ctx.mynode, ctx: @ctx) if @myapp.version.value == @event['version'] @ctx.log.info( "App #{@event['app']} already updated. version=#{@event['version']} Nothing to do.") return unless @ctx.develop_mode? end return true end def update_myapp appname = @myapp.name version = @event['version'] mynode = @ctx.mynode updated = false while !updated candidates = @myappnode.find_updated_nodes(version) if candidates.empty? @ctx.log.warn "Can't fetch updated app from any node! app=#{appname}, version=#{version}" sleep @@loop_interval next end candidates.shuffle.each do |appnode| unless appnode.app.semaphore.consume(cas: true) @ctx.log.debug "Can't get semaphore from #{appnode.node.name}; app=#{appname}" next end begin pull_update(appnode.node) updated = true return updated ensure unless restore_semaphore(appnode.app.semaphore) @ctx.die("Failed to restore semaphore! app=#{appname}, node=#{host}") end end end sleep @@loop_interval end updated end def pull_update(node) appname = @myapp.name new_version = @event['version'] @ctx.log.debug "Start pulling update #{appname} from #{node.name} toward #{new_version}." job = Fireap::Model::Job.new(ctx: @ctx) @results = job.run_commands(app: @myapp, remote: node) failed = @results.select { |r| r.is_failed? } ignored = failed.select { |r| r.is_ignored? } if failed.length > 0 if failed.length > ignored.length @ctx.die "[#{appname}] Update FAILED! cnt=#{failed.length}, ignored=#{ignored.length}. ABORT!" else @ctx.log.warn \ "[#{appname}] Some commands failed. cnt=#{failed.length}, ignored=#{ignored.length}. CONTINUE ..." end else @ctx.log.info "[#{appname}] All commands Succeeded." end # Update succeeded. So set node's version and semaphore cnt = @myapp.update_properties( version: new_version, semaphore: @appconf.max_semaphores, remote_node: node.name, ) unless cnt == 3 @ctx.log.error "Update some properties Failed! updated count = #{cnt}. Should be 3." end @ctx.log.info "[#{@ctx.mynode.name}] Updated app #{appname} to version #{new_version} ." end def restore_semaphore(semaphore) (1..@@restore_retry).each do |i| semaphore = semaphore.refetch @ctx.log.debug "Restore semaphore (#{i}). key=#{semaphore.key}, current=#{semaphore.value}" return true if semaphore.restore sleep @@restore_interval end false end end end <file_sep>/lib/fireap/data/kv.rb require 'base64' require 'fireap/model/kv' require 'fireap/util/string' module Fireap::Data class Kv def initialize(kv) @me = kv end def to_model data = {} @me.each do |key, val| if key == 'Value' && val data[key.to_snakecase] = Base64.decode64(val) else data[key.to_snakecase] = val end end Fireap::Model::Kv.new(data) end end end <file_sep>/lib/fireap/model/command.rb require 'erb' require 'open3' module Fireap::Model class Command attr :format, :app, :remote, :config, :ctx def initialize(args) args.each do |key, val| instance_variable_set("@#{key}", val) end end def run @script = ERB.new(@format).result(binding) prefix = @ctx.dry_run? ? '' : 'EXEC ' @ctx.log.info "#{prefix}#{@script}" if ! @ctx.dry_run? @result = Result.new(@script, Open3.capture3(@script) ) if @result.is_failed? @ctx.log.error %Q|Command FAILED! #{@result.to_s}| else @ctx.log.info %Q|Command Succeeded. #{@result.to_s}| end else @result = Result.fake(@script, success: true) @ctx.log.debug %Q|Assume Success. #{@result.to_s}| end @result end class Result attr :command, :stdout, :stderr, :status, :exit def initialize(command, captured) @command = command @stdout, @stderr, @status = captured @exit = @status.exitstatus end def self.fake(command, success: true) status = OpenStruct.new({ pid: '<#dummy>', exitstatus: success ? 0 : 1, }) new(command, ['<stdout>', '<stderr>', status]) end def to_s %q|EXIT=%d, PID = %s, STDOUT = [%s], STDERR = [%s]|%[ @exit, @status.pid, @stdout.chomp, @stderr.chomp ] end def is_failed? @exit != 0 end def is_ignored? @ignored end def mark_ignored @ignored = true end end end end <file_sep>/lib/fireap/config.rb require 'diplomat' require 'toml' require 'fireap/validator' require 'fireap/view_model/config' module Fireap class Config Error = Class.new(StandardError) @@app_props = %w[ max_semaphores wait_after_fire watch_timeout on_command_failure before_commands exec_commands after_commands ] @me = nil @appc = nil def initialize(path: ENV['FIREAP_CONFIG_PATH'] || 'config/fireap.toml') @me = TOML.load_file(path) @appc = {} configure_diplomat() end def method_missing(method) if @me.has_key?(method.to_s) @me[method.to_s] end end def validate rule = Fireap::Validator.new( 'url' => { isa: String, optional: 1 }, 'enable_debugging' => { isa: String, optional: 1 }, 'log' => { isa: Hash, optional: 1, rule: { 'level' => { isa: String, optional: 1 }, 'rotate' => { isa: String, optional: 1 }, 'file' => { isa: String, optional: 1 }, }, }, 'task' => { isa: Hash, rule: { 'max_semaphores' => { isa: Fixnum, optional: 1 }, 'wait_after_fire' => { isa: Fixnum, optional: 1 }, 'watch_timeout' => { isa: Fixnum, optional: 1 }, 'on_command_failure' => { isa: String, optional: 1 }, 'before_commands' => { isa: Array, optional: 1 }, 'exec_commands' => { isa: Array, optional: 1 }, 'after_commands' => { isa: Array, optional: 1 }, 'apps' => { isa: Hash }, }, }, ) begin result = rule.validate(@me) rescue => e message = <<"EOS" Config validation FAILED!! Please check your configuration. Errors: #{e} EOS raise Error, message end true end def app_list list = [] self.task['apps'].each_key do |name| appc = app_config(name) list << app_config(name) end list end def app_config(appname) @appc[appname] ||= proc { unless appc = self.task['apps'][appname] return nil # Not configured end base = self.task.select { |k,v| @@app_props.include?(k) } conf = base.merge(appc) conf['commands'] = [] %w(before exec after).each do |phase| if cmds = conf.delete("#{phase}_commands") conf['commands'].concat(cmds) end end %w[service tag].each do |key| conf["#{key}_filter"] \ = make_regexp_filter(conf.delete(key), conf.delete("#{key}_regexp")) end App.new(appname, conf) }.call end private def configure_diplomat Diplomat.configure do |config| config.url = self.url if self.url end end def make_regexp_filter(name, regexp) name ? "^#{name}$" : regexp end class App @@accessors = [ :name, :max_semaphores, :wait_after_fire, :watch_timeout, :on_command_failure, :commands, :service_filter, :tag_filter ] @@accessors.each do |acc| attr acc end def initialize(name, stash) @name = name stash.each_pair do |k,v| instance_variable_set("@#{k}", v) end end def is_failure_ignored? /^ignore$/i.match(@on_command_failure) end def to_view stash = {} @@accessors.each do |acc| stash[acc.to_s] = instance_variable_get("@#{acc}") end stash['is_failure_ignored'] = self.is_failure_ignored? Fireap::ViewModel::Config::App.new(stash) end end end end <file_sep>/spec/fireap/model/node_spec.rb require 'fireap/model/node' require 'fireap/util/string' require 'diplomat' describe 'Fireap::Model::Node#find' do n_hash = { 'Node' => 'test1', 'Address' => '192.168.100.1', } data = { 'Node' => n_hash, 'Services' => {}, } context 'when data is found' do before(:example) do allow(Diplomat::Node).to receive_message_chain(:get).and_return(data) @node = Fireap::Model::Node.find('test1') end it 'is a Fireap::Model::Node' do expect(@node).to be_an_instance_of(Fireap::Model::Node) end describe 'parameter matches' do n_hash.each_pair do |k, v| method = (k == 'Node') ? 'name' : k.to_snakecase it "#{method} => #{v}" do expect(@node.send(method)).to eq v end end end end end <file_sep>/lib/fireap/manager/node.rb require 'diplomat' require 'singleton' require 'fireap/model/node' module Fireap::Manager class Node include Singleton attr :nodes def initialize @nodes ||= {} Diplomat::Node.get_all.each do |nod| dnode = Fireap::Model::Node.new(nod['Node'], nod['Address']) @nodes[dnode.name] = dnode end end # @param app [Fireap::Model::Application] def collect_app_info(app, ctx: nil) Fireap::DataAccess::Kv.get_recurse("#{app.name}/nodes/").each do |data| unless %r|#{app.name}/nodes/([^/]+)/([^/\s]+)$|.match(data.key) ctx.die("Unkwon key pattern! key=#{data.key}, val=#{data.value}") end nodename = $1 propkey = $2 ctx.log.debug 'Got kv. %s:%s => %s'%[nodename, propkey, data.value] unless node = @nodes[nodename] ctx.log.warn "Node '#{nodename}' is not in cluster now. Possively the data is out-of-date." next end app = node.apps[app.name] ||= Fireap::Model::Application.new(app.name, node: node) app.set_kv_prop(propkey, data) end @nodes.each_pair do |name, node| unless node.has_app?(app.name) node.apps[app.name] ||= Fireap::Model::Application.new(app.name, node: node) end end end # @param app [Fireap::Model::Application] # @param version [String] # @return [Hash{String => Fireap::Model::Node}] the key [String] means Node's name def select_updated(app, version, ctx: nil) updated = {} @nodes.each_pair do |name, node| unless napp = node.apps[app.name] ctx.log.debug "Not found app:#{app.name} for node:#{name}" next end napph = napp.to_hash nversion = napph[:version] semaphore = napph[:semaphore] ctx.log.debug "Node #{name} - Version = #{nversion}, Semaphore=#{semaphore}" if (nversion == version && semaphore.to_i > 0) or ctx.develop_mode? updated[name] = node end end updated end end end <file_sep>/lib/fireap/data/event.rb require 'base64' require 'json' require 'fireap/model/event' require 'fireap/util/string' module Fireap::Data class Event def initialize(stash) @me = stash end def to_model stash = {} @me.each do |key, val| if key == 'Payload' && val stash[key.to_snakecase] = JSON.parse( Base64.decode64(val) ) else stash[key.to_snakecase] = val end end Fireap::Model::Event.new(stash) end end end <file_sep>/spec/fireap/data/node_spec.rb require 'fireap' require 'fireap/data/node' describe 'Fireap::Data::Node#to_model' do stash = { 'Node' => 'test1', 'Address' => '192.168.100.1', 'ServiceID' => 'web', } data = Fireap::Data::Node.new(stash) node = data.to_model it 'node is a Fireap::Model::Node' do expect(node).to be_an_instance_of(Fireap::Model::Node) end describe 'all params set as instance_variable' do { 'name' => 'Node', 'address' => 'Address' }.each_pair do |key, orig_key| it "#{key} => #{stash[orig_key]}" do expect( node.send(key) ).to eq stash[orig_key] end end it "service_id => #{stash['ServiceID']}" do expect( node.instance_variable_get("@service_id") ).to eq stash['ServiceID'] end end end <file_sep>/CHANGELOG.md ## 0.4.0 (2016/3/20) Feature: - Add `--node-name|-n=<NODE>` option for `fire` subcommand to limit task propagation target. ## 0.3.0 (2016/3/20) Feature: - Add `task` subcommand to show task settings in configuration. ## 0.2.1 (2016/3/20) Improve: - Add config validation before every command execution. ## 0.2.0 (2016/3/20) Feature: - Introduce `service`, `service_regexp` param accompanied with `tag` and `tag_regexp` in configuration to filter task propagation targets. ## 0.1.3 (2016/3/19) Bug Fix: - Add `::` before `Logger::` constant - https://github.com/progrhyme/fireap/commit/d97c6f62019960701d07c61be379ded2908ecf6b - In v0.1.2, when command fails in `reap` mode, program exits irregularly. Improve: - Show caller info and full command-line on every log line. - Add `[Dry-run]` string as header with each log line when `--dry-run` option is given for `fireap reap`. And documentation wiki is available now. ## 0.1.2 (2016/3/18) obsolete Change: - General: - Write log to logfile in addtion to STDIN when logfile is configured. - In `monitor` command: - Suppress logging on continuous monitoring mode. ## 0.1.1 (2016/3/18) Fix: - Not to fail when out-of-date node data is found in Kv. ## 0.1.0 (2016/3/18) First release. <file_sep>/lib/fireap/model/event.rb require 'base64' require 'diplomat' require 'json' require 'fireap' require 'fireap/data/event' module Fireap::Model class Event attr :id, :name, :payload, :node_filter, :service_filter, :tag_filter, :version, :ltime def initialize(stash) stash.each do |key, val| instance_variable_set("@#{key}", val) end @name ||= Fireap::EVENT_NAME end def self.fetch_from_stdin streams = '' while ins = $stdin.gets streams << ins end events = convert_from_streams(streams) return unless events.length > 0 events.last end # @param text [String] JSON text containing Event data list # @return [Array[Fireap::Model::Event]] def self.convert_from_streams(text) JSON.parse(text).map do |stash| Fireap::Data::Event.new(stash).to_model end end def fire filters = filter_to_fire() Diplomat::Event.fire(self.name, self.payload.to_json, *filters) end private def filter_to_fire if @node_filter [nil, @node_filter, nil] else [@service_filter, nil, @tag_filter] end end end end <file_sep>/spec/fireap/logger_spec.rb require 'fireap/logger' require 'logger' class LoggerTester attr :logger, :outs def initialize(level, header) # Create output devices for test @outs = (0..1).map do StringIO.new end @logger = Fireap::Logger.new(@outs, level: level, header: header) end end describe 'Fireap::Logger' do context 'when multi outputs are given with header and WARN level' do header = ':: head ::' message = 'test log message' describe "#log with [WARN] level logger. Message='#{message}'" do level = 'WARN' context %q{given level [ERROR], log appears} do tester = LoggerTester.new(level, header) tester.logger.log(Logger::ERROR, message) tester.outs.each_with_index do |out, idx| expected = /\[ERROR\] #{header} #{message} at / it "out[#{idx}] matches #{expected}" do expect(out.string).to match expected end end end context %q{given level [INFO], log wan't appear} do tester = LoggerTester.new(level, header) tester.logger.log(Logger::INFO, message) tester.outs.each_with_index do |out, idx| it "out[#{idx}] has no output" do expect(out.string).to eq '' end end end end describe "#debug Message='#{message}'" do context "when logger level=INFO" do tester = LoggerTester.new('INFO', header) tester.logger.debug(message) tester.outs.each_with_index do |out, idx| it "out[#{idx}] has no output" do expect(out.string).to eq '' end end end context "when logger level=DEBUG" do tester = LoggerTester.new('DEBUG', header) tester.logger.debug(message) tester.outs.each_with_index do |out, idx| expected = /\[DEBUG\] #{header} #{message} at / it "out[#{idx}] matches #{expected}" do expect(out.string).to match expected end end end end end end <file_sep>/bin/fireap #!/usr/bin/env ruby $LOAD_PATH.push(File.expand_path('../../lib', __FILE__)) require 'fireap' require 'fireap/cli' Fireap::CLI.start(ARGV)
a94cf27828bf5bdd4204cf68b87229f5c6b2b37c
[ "Markdown", "TOML", "Ruby" ]
51
Ruby
key-amb/fireap
77cee9e47a86e4ba18cdeb31b273d6f8545cbeeb
054fe122b192fac8439207ddf0cdb031c5fc0a38
refs/heads/master
<file_sep>/*var userName = prompt("What is your name?"); alert("Nice to meet you, " + userName); console.log(userName); var number = Math.floor(Math.random() * 10) + 0; var guess = prompt("Guess number: "); while(Number(guess) !== Number(number)) { if(Number(guess) > Number(number)) { alert("Too high!"); } else if(Number(guess) < Number(number)) { alert("Too low!"); } else if(guess === "Exit" || guess === "exit") { break; } guess = prompt("Guess number: "); } if(Number(guess) === Number(number)) { alert("Correct! The number is " + number); } var count = 6; count = Number(count); while(Number(count) <= 333) { if(Number(count) % 2 !== 0) { document.write(count + "\n"); } count++; } while(count < 50) { if((count % 5 === 0) && (count % 3 === 0)) { document.write(count + "\n") } count++; } function factorial(num) { count = num; sum = 1; while(count > 0) { sum = sum*count; count = count-1; } return sum; } function kebabToSnake(kebab) { var initial = kebab; var transform = ""; for(var i = 0; i < initial.length; i++) { if(initial.charAt(i) === "-") { transform += "_"; } else { transform += initial.charAt(i); } } return transform; } var fact = [10, 20, 30, 40, 50, 60, 70]; var fact2 = fact.slice(2, fact.length-1); document.write(fact2); var input = prompt("Enter new, list, remove, or quit"); var todo = []; while(input !== "quit") { if(input === "new") { var value = prompt("Enter a value: "); todo.push(value); console.log(value + " added to list!"); } else if(input === "list") { listTodos(); } else if(input === "remove") { var removeItem = prompt("Type the name of the item you want to remove: "); var index = todo.indexOf(removeItem); if(index !== -1) { todo.splice(index, 1); console.log(todo + " after the removal of the element"); } else { console.log("Item doesn't exist in the list!"); } } input = prompt("Enter another command (new, list, or quit)\n"); } function listTodos() { for(var i = 0; i < todo.length; i++) { console.log(todo[i] + " is the " + (i+1) + "th element in the array"); } } var a1 = ["b", "b", "b", 3]; var a2 = [1, 1, 1, 1, 2]; var maxArray = [1, 5, 2, 54, 23, 55, 43, 1023, 24]; function isUniform(array) { if(array.length === 0) { return false; } var compareValue = array[0]; for(var i = 0; i < array.length; i++) { if(compareValue !== array[i]) { return false; } } return true; } function max(array) { var maxVal = array[0]; for(var i = 0; i < array.length; i++) { if(array[i] > maxVal) { maxVal = array[i]; } } return maxVal; } console.log(max(maxArray)); var movieDB = [{title: "In Bruges", rating: 5, seen: false}, {title: "Mad Max", rating: 1, seen: true},{title: "Halloween", rating: 4.5, seen: false}]; movieDB.forEach(function(movie){ console.log(createMovieString(movie)); }) function createMovieString(movie) { var result = ""; if(movie.seen) { result += "Watched: "; } else { result += "Not Watched: "; } result += " Title: " + movie.title; result += " Rating: " + movie.rating; return result; } */ var obj = { name: "Bob", num1: 10, num2: 9, multiply: function(x,y) { return x*y; }, num3: 8 } console.log(obj.multiply(obj.num1, obj.num3));
e02645bc496b1d86764cbe84b2e76c527f758917
[ "JavaScript" ]
1
JavaScript
SpencerJSaunders/SmallProjects
c6c5bec1e482120146f70662ca883dc08e743ea8
25967a6175e7b3dbd1bdc49081ecc26e2721633e
refs/heads/master
<repo_name>aslupin/cpe31-task<file_sep>/aum_task/calender.py m = int(input()) n = int(input()) Day = [31,28,31,30,31,30,31,31,30,31,30,31] LeDay = [31,29,31,30,31,30,31,31,30,31,30,31] def leap(n): if n%4 == 0: if n%100 == 0: if n%400 == 0: return True else: return False else: return True else: return False def day(m,n): D = 0 for i in range(1970,n): if leap(i) == True : D += 366 else : D += 365 return D def year(m): if leap(n) == True : month = [['sun','mon','tue','wed','thu','fri','sat']] count = 0 for i in range(LeDay[m-1]//7+2): month.append([]) for j in range(7): count += 1 if count <= LeDay[m-1] : month[i+1].append(count) else : break return month elif leap(n) == False : month = [['sun','mon','tue','wed','thu','fri','sat']] count = 0 for i in range(Day[m-1]//7+2): month.append([]) for j in range(7): count += 1 if count <= Day[m-1] : month[i+1].append(count) else : break return month def BeCal(month): for i in range(len(month)): for j in range(len(month[i])): print(f'{month[i][j]:3}',end=' ') print() print(leap(n)) print(year(m)) BeCal(year(m)) print(day(m,n))<file_sep>/week3/series.py def a(n): # Code your a(n) function here return 1+(n-1)*2 def b(n): # Code your b(n) function here if(n==1): return 1 else:return b(n-1)*(n-1) def sum_a(n): # Code your sum_a(n) function here sumsq=0 for i in range(1,n+1): sumsq += a(i) return sumsq def sum_b(n): # Code your sum_b(n) function here sumsq = 0 for i in range(1,n+1): sumsq += b(i) return sumsq ### NO CODE AFTER THIS LINE SHOULD BE MODIFIED ### n = int(input()) print("a({}) = {}".format(n,a(n))) print("b({}) = {}".format(n,b(n))) print("sum_a({}) = {}".format(n,sum_a(n))) print("sum_b({}) = {}".format(n,sum_b(n)))<file_sep>/week4/cross_river.py count_wet=0;ans=0;count_ppl=0 ppl = list();wet = list() ppl.append(int(input())) # at index 0 = max ppl wet.append(float(input())) # at index 0 = max weigth while(True): n = int(input()) if(n == -1):break w = float(input()) if(w == -1):break if(w <= wet[0]): ppl.append(n) wet.append(w) print(wet,ppl) for i in range(1,len(ppl)): while(True): count_wet += wet[i] ppl[i] -= 1 count_ppl += 1 if(count_wet + wet[i] > wet[0] or count_ppl == ppl[0] or (ppl[i] == 0 and i == len(ppl)-1)): ans += 1 count_wet = 0 count_ppl = 0 if(ppl[i] == 0):break print(ans)<file_sep>/week3/kon_la_chun.py import sys ppl = list() count = 0;mdthree = 0;do = 0 n = int(input()) for i in range(n): ppl.append(int(input())) if(ppl[i] > 8):sys.exit("error") ppl.sort() for i in range(n): mdthree += 1 if(ppl[i] - ppl[i-1] > 1 and i != 0): do+=1 mdthree = 1 elif(mdthree == 1):do+=1 elif(mdthree == 3):mdthree = 0 print(do)<file_sep>/week6/day_of_the_week.py def check_leap_y(y): if(y%4==0): if(y%100==0): if(y%400==0): return True else:return False else:return True else: return False def get_year(year,n=0): for i in range(1,year): if(check_leap_y(i)):n+=1 getyear = ((year - 1 - n) * 365 ) + (n * 366) return getyear ans = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'] lim_y = {1:0,2:31,3:59,4:90,5:120,6:151,7:181,8:212,9:243,10:273,11:304,12:334} day = 0;date = list(map(int,input().split())) day = get_year(date[2]) if(date[1] >= 3 and check_leap_y(date[2])):day += (1 + lim_y[date[1]] + date[0]) else:day += (lim_y[date[1]] + date[0]) print(ans[day % 7])<file_sep>/week3/fibonacci_sum.py def fibonacci_sum(n): # Code your fibonacci_sum(n) here def sumWithSol(n): if(n==1):return 1 elif(n==0):return 0 else:return sumWithSol(n-1) + sumWithSol(n-2) return sumWithSol(n+2)-1 ### NO CODE AFTER THIS LINE SHOULD BE MODIFIED ### inp = int(input()) print(fibonacci_sum(inp))<file_sep>/week8/grep.py import re def fn1(name_list,relist=[]): # In <NAME> or <NAME> for i in name_list: if(re.search(r' Chiang ',i)):relist.append(i) return relist def fn2(name_list,relist=[]): # Name begins with Kan relist=[] for i in name_list: if(re.search(r'Kan',i.split()[0])):relist.append(i) return relist def fn3(name_list,relist=[]): # Name ends with chai relist=[] for i in name_list: if(re.search(r'chai',i.split()[0])):relist.append(i) return relist def fn4(name_list,relist=[]): # Doesn't use mobile phone relist=[] for i in name_list: if((not re.search(r'08\d-\d\d\d-\d\d\d\d',i)) and (not re.search(r'09\d-\d\d\d-\d\d\d\d',i))):relist.append(i) relist.pop(0) return relist def fn5(name_list,relist=[]): # Phone ends with odd number relist=[] for i in name_list: if(re.search(r'\d',i[len(i)-1])): if(int(i[len(i)-1]) % 2 == 1):relist.append(i) return relist # Do not edit codes below. name_list = open('contact_list.txt').read().strip().split('\n') fn_list = [fn1, fn2, fn3, fn4, fn5] n = int(input("Which function? (1-5): ")) fn = fn_list[n-1] search_result = fn(name_list) for result in search_result: print(result)<file_sep>/week3/basen.py def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"): return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b]) print(baseN(3,2))<file_sep>/week5/fortune_cookie_advanced.py import threading def left_threading(sum,data): for i in range(1,(len(data)+1)//2): if((str((sum - int(data[i-1]))) in data ) and ( data.index(str(sum - int(data[i-1]))) != i-1)): print(i,end=" ") exit def right_threading(sum,data): for i in range((len(data)+1)//2,len(data)+1): if((str((sum - int(data[i-1]))) in data ) and ( data.index(str(sum - int(data[i-1]))) != i-1)): print(i,end=" ") exit sum = int(input()) data = input().split(' ') left_th = threading.Thread(name = 'left_threading',target=left_threading,args=(sum,data)) right_th = threading.Thread(name = 'right_threading',target=right_threading,args=(sum,data)) left_th.start() right_th.start() # sum = int(input()) # data = input().split(' ') # for i in range(1,len(data)+1): # if((str((sum - int(data[i-1]))) in data ) and ( data.index(str(sum - int(data[i-1]))) != i-1)): # print(i,end=" ") # # import math # sum = int(input()) # min = [9999,0] # data = input().split(' ') # dp_sum = list() # for i in range(len(data)): # if(len(dp_sum) == 0):dp_sum.append(0 + int(data[i])) # else:dp_sum.append(int(data[i]) + dp_sum[i-1]) # if(abs(sum - dp_sum[i]) < min[0]):min[0],min[1] = sum - dp_sum[i],i # if(min == 0): # if((sum - data[i]) in data != -1):print(data[i],(sum - data[i]) in data) # # print(dp_sum) # print(min[1]) # # print(sum - int(data[min[1]])) # print(data[min[1]],sum - int(data[min[1]])) # print(data[i-1]) # print(((sum - int(data[i-1])) in data ) ) # print(data.index(sum - int(data[i-1]))) <file_sep>/review-midterm/mainact.py import printa_ctivity print(__name__) printa_ctivity.print_a()<file_sep>/week7/tiling_colours.py def til(n,txt): if(n==0):return 1 else: if(txt == 'r'):return til(n-1,'x') + til(n-1,'x') else:return til(n-1,'x') + til(n-1,'x') + til(n-1,'r') n = int(input()) print(til(n-1,'r') + til(n-1,'x') + til(n-1,'x'))<file_sep>/week3/cat_is_fluid.py import math def gettime(t): if(t%5!=0): if(t%5 < 3):return process(t//5*3) + process(t%5) else:return process(t//5*3) + process(3) else:return process(t//5*3) def process(t): if t==0 :return 0 elif(t > 3):return (t//3)*((27*3-(3**4)/4)/10-0.075) else:return ((27*t-(t**4)/4)/10-0.075) t = int(input()) print("%g"%gettime(t))<file_sep>/week7/parameters_count.py def parameters_count(*argv): return len(argv) # Write your `parameters_count(n)` here ########## DON'T EDIT CODES BELOW ########## n = int(input()) if n == 1: print(parameters_count(1)) elif n == 2: print(parameters_count(1,2,3)) elif n == 3: print(parameters_count(1,2,3,4,5)) elif n == 4: print(parameters_count([1,2,3])) elif n == 5: print(parameters_count())<file_sep>/week4/square.py def hdraw(n): for i in range((n*4) - (n-1)):print("*",end="") print('') for i in range(2): for i in range((n*4) - (n-1)): if(i % 3 == 0):print("*",end="") else:print(" ",end="") print('') for i in range((n*4) - (n-1)):print("*",end="") def vdraw(n): for i in range(n): if(i==0):print("****\n* *\n* *\n****") else:print("* *\n* *\n****") while(True): vh = input("Select mode (v or h): ") if(vh == 'v' or vh == 'h'):break while(True): n = int(input("Input n (1-15): ")) if(n >= 1 and n <= 15):break if(vh == 'v'):vdraw(n) elif(vh == 'h'):hdraw(n)<file_sep>/week7/super_digit.py def super_digit(txt): def cut(txt): if(len(txt)==1):return int(txt[0]) else:return int(cut(txt[1:])) + int(txt[0]) txt = str(cut(txt)) if(len(txt) == 1):return txt else:return super_digit(txt) print(super_digit(input()))<file_sep>/week7/predict.py ################################################## ## Problem: predict.py ## Std: std09 ## Name: <NAME> ## StudentId: 6010500109 ################################################## # You can edit the parameters in parenthesis (). def predict(getData): if(type(getData) == list): for i in range(len(getData)):getData[i] = getData[i] * 200000 * (1.05**getData[i]) else:getData = getData * 200000 * (1.05**getData) return getData ########## DON'T EDIT CODES BELOW ########## print(predict(eval(input())))<file_sep>/week7/52.py # Please do not forget to `genheader` def satu_48(n,out = 0): # Write your `satu_48(n)` here txt_heap = str(n) if(len(txt_heap) == 0):return out else: if(txt_heap[0] == '5' or txt_heap[0] == '2'):out += 1 return satu_48(txt_heap[1::],out) ########## DON'T EDIT CODES BELOW ########## print(satu_48(int(input())))<file_sep>/week8/special_mode.py def ch_sp_mod(key,f,ans=[],save=None): if(not key):return False ans.append(key[f.index(max(f))]) key.pop(f.index(max(f)));save = f.pop(f.index(max(f))) if(len(key) > 0): while(max(f) == save): if(not (key[f.index(max(f))] in ans)):ans.append(key[f.index(max(f))]) key.pop(f.index(max(f)));f.pop(f.index(max(f))) if(not f or not key):break if(len(ans) <= 2): if(len(ans) == 1):print(ans[0]) else:print(ans[0],ans[1]) return True else:return False key=[];f=[];i=0 txt = input() while(txt != 'end'): if(not key): key.append(txt) f.append(1) i+=1 else: if(txt == key[i-1]):f[i-1] += 1 else: key.append(txt) f.append(1) i+=1 txt = input() if(ch_sp_mod(key,f)): pass else:print("Don't have mode") <file_sep>/week4/sojtus.py def findpirmeBT(n): if(n==1):return False for i in range(1,n+1): if(n%i == 0): if(i != 1 and i != n): return False return True ans = 0;ignorePair = list() n = int(input()) for i in range(1,n+1): for j in range(1,n+1): if( i+j == n and findpirmeBT(i) and findpirmeBT(j)): if(not(i in ignorePair)): ignorePair.append(j) ans += 1 print(ans)<file_sep>/week5/note.py a,b = 5.0,10.0 x,y = 2,9 print(a/x+y*b//y) # item = [33,1,2,3] # item.sort() # print(item) # import threading # def a(): # for i in range(1,50): # print(str(i) + " a ") # __self__.exit() # def b(): # for i in range(1,50): # print(str(i) + " b ") # th = threading.Thread(name = 'a',target=a) # thh = threading.Thread(name = 'b',target=b) # th.start() # thh.start() # n = int(input()) # n2 = n//2 # numbers = input().split(' ') # goodnums = {n-int(x) for x in numbers if int(x)<=n2} & {x for x in numbers if int(x)>n2} # pair = {(n-int(x), int(x)) for x in goodnums} # for a,b in pair: # print(numbers.index(a) + 1, numbers.index(b) + 1) <file_sep>/week3/oh_my_math.py def my_ceiling(x): return int(x)+1 def my_floor(x): return int(x)-1 def my_fabs(x): if(x<0):return x*(-1) else:return x def my_factorial(x): if(x==0):return 1 else:return my_factorial(x-1) * x def my_exp(x): e = 1 if(x==0):return e else: for i in range(x): e *= 2.71828 return e def my_pow(x,y): if(y == 0):return 1 elif(y == 1):return x elif(y < 0): for i in range(y-1): x *= x return 1/x else: for i in range(y-1): x *= x return x #https://en.wikipedia.org/wiki/Methods_of_computing_square_roots def my_sqrt(x,xpro = 1): if(x < 10):xpro = 2 * my_pow(10,x//10) else:xpro = 6 * my_pow(10,x//10) for i in range(10): xpro = (1/2) * (xpro + (x / xpro)) return xpro def my_cos(x,summ=0,i=0): for j in range(0,11): getplus = my_pow(x,i)/my_factorial(i) if(j%2!=0):getplus*=-1 summ += getplus i += 2 return summ def my_sin(x,summ=0,i=1): for j in range(0,11): getplus = my_pow(x,i)/my_factorial(i) if(j%2!=0):getplus*=-1 summ += getplus i += 2 return summ def my_tan(x): return my_sin(x)/my_cos(x) def my_degree(x): return x*(180/my_pi()) def my_radian(x): return x*(my_pi()/180) def my_pi(): return 3.14159265359 def my_e(): return 2.71828 print(my_sqrt(4))<file_sep>/week3/exceed.py while(True): distance = float(input("Input distance (m) : ")) if(distance == 0): print("You have 100%% internet signal [0.0 m]") break elif(distance > 0 and distance <= 1): print("You have 75%% internet signal [In 0 - 1 : %.5f m]"%distance) elif(distance > 1 and distance <= 2): print("You have 50%% internet signal [In 1 - 2 : %.5f m]"%distance) elif(distance > 2 and distance <= 10): print("You have 25%% internet signal [In 2 - 10 : %.2f m]"%distance) else:print("You : I need healing!!!\nYou do not have internet signal [%d m]"%distance) print("You : GG Ez kid")<file_sep>/week3/note.py mat = [[1,2,3],['x','a','b']] print(mat[0][0],mat[0][1])<file_sep>/week6/matrix_multiplication.py ################################################## ## Problem: matrix_multiplication.py ## Std: std09 ## Name: <NAME> ## StudentId: 6010500109 ################################################## def matrix_multiplication(a,b,c=list()): # Write your programme here. n=len(a);m=len(b[0]) if(n==m): for i in range(n): c.append([]) for j in range(m): temp = 0 for k in range(m): temp += (a[i][k] * b[k][j]) c[i].append(temp) return c # Code further from this line must NOT be edited. a = [] b = [] a_line_len = int(input()) for _ in range(a_line_len): a.append([int(x) for x in input().split()]) b_line_len = int(input()) for _ in range(b_line_len): b.append([int(x) for x in input().split()]) print(matrix_multiplication(a,b))<file_sep>/week3/dating_simulator.py def repl(): repl = input() if(repl == 'Y'):return True else:return False point = [0,0,0,0] while(True): print("Dating with Emilia ?:") if(repl()): point[0] += 1 print("Run into Stella ?:") if(repl()):continue print("Dating with Rem?:") if(repl()): point[1] += 1 print("Run into Stella ?:") if(repl()):continue print("Dating with Stella ?:") if(repl()): point[2] += 1 continue print("Dating with Roswaal?:") if(repl()): point[3] += 1 break break print("Subari : %d\nEmilia : %d\nRem : %d\nStella : %d\nRoswaal : %d"%(point[0]+point[1]+point[2]+point[3],point[0],point[1],point[2],point[3]))<file_sep>/review-midterm/note.py def printMyname(name,n): return name * n <file_sep>/review_i/mm.py m = int(input()) n = int(input()) # m = 4 # n = 4 mm = [[int(i) for i in range(n)] for x in range(m)] print(mm) # for i in range(len(mm)): for j in range(len(mm[0])-1): itr_r = j itr_c = 0 while(itr_r != -1 and itr_c != len(mm)+1): print(mm[itr_c][itr_r],end=" ") itr_c += 1 itr_r -= 1 print('') for j in range(len(mm)): itr_r = len(mm[0])-1 itr_c = j while(itr_c != len(mm) and itr_r != -1): print(mm[itr_c][itr_r],end=" ") itr_c += 1 itr_r -= 1 print('') <file_sep>/week4/life_bee.py from collections import deque def killb(wbee,sbee,kill,i): #kill bee T_T kill[i-1] -= ( sbee[i-1] + wbee[i-1] ) if(kill[i-1] > 0): if(sbee[i] > kill[i-1]):sbee[i] -= kill[i-1] else: kill[i-1] -= sbee[i] sbee[i] = 0 if(wbee[i] > kill[i-1]):wbee[i] -= kill[i-1] else:wbee[i] = 0 return wbee,sbee,kill,i kill=list() #list of bee will be killed wbee = deque() #Worker bee sbee = deque() #Soider bee sbee.append(int(input())) wbee.append(int(input())) year = int(input()) for i in range(year): kill.append(int(input())) for i in range(1,year+1): wbee.append( wbee[i-1] + sbee[i-1] + 1 ) #add new gen of wbee to queue sbee.append( wbee[i-1] ) #add new gen of sbee to queue killb(wbee,sbee,kill,i) print("{} {}".format(wbee.pop(),sbee.pop())) #print last gen of bee that have been add <file_sep>/week8/tae_histogram.py hisbox = list(map(int,input().split())) wall = [0];sum_subwater=0;use=0 for i in wall: for b in range(hisbox[i],-1,-1): count = 0 for j in range(i+1,len(hisbox)): if(b <= hisbox[j] and (i != j)): if(not(j in wall)):wall.append(j) break count += 1 if(j == len(hisbox)-1):count = 0 sum_subwater += count print(sum_subwater)<file_sep>/week4/365_day_advanced.py import math movement = {"U":1,"R":1,"L":-1,"D":-1} # Const of movement x = [0];y = [0] # list container for pattern lastx=0;lasty=0;tmpx=0;tmpy=0 # declare var check = False fly = input() here_x = int(input()) here_y = int(input()) for i in fly: # get each of pattern if(i == 'U' or i == 'D'):tmpy += movement[i] if(i == 'R' or i == 'L'):tmpx += movement[i] if(not(tmpx in x and tmpy in y)): x.append(tmpx) y.append(tmpy) if(here_x <= 0 and here_y <=0):bignum = math.fabs(min(here_x,here_y)) else:bignum = max(here_x,here_y) # big-number for i in range(len(x)): lastx = x[i] * bignum ;lasty = y[i] * bignum for j in range(len(x)): if(lastx + x[j] == here_x and lasty + y[j] == here_y):check = True if(check):print('Y') else:print('N')<file_sep>/week6/note.py lim_y = {0:0,1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31} summ = 0 for i in range(1,13): if(i==1):print(f"{i}:0,",end="") else: summ += lim_y[i-1] print(f"{i}:{summ},",end="") <file_sep>/week5/mastermind.py import random def checktxt(txt,mom): boxX="";boxO="";boxN="";txt_box = [mom[i] for i in range(len(mom))] for i in range(len(txt)): if(txt[i] == txt_box[i]): boxX += "X" txt_box[i] = 'X' elif(txt[i] in txt_box):boxO += "O" strplus= 4 - (len(boxX) + len(boxO)) if(len(boxX) + len(boxO) < 4):boxN = "-" * strplus print(boxX+boxO+boxN) if(boxX+boxO+boxN == "XXXX"):return False else:return True played=0;GO=True txt_mom = input('#') # txt_mom = str(random.randint(0,9999)).rjust(4,'0') while GO: played += 1 GO = checktxt(input("Guess : "),txt_mom) print(f"You win the game after {played} guess!!!\nThe number was {txt_mom}")<file_sep>/week2/lab/checksinglenum.py def check_aum(name): if(name == 'aum'): return False txtname = input() if(check_aum(txtname)): print("aum is here")<file_sep>/review_i/re_i_a.py x = [' ','*'] n = int(input()) for i in range(1,n+1): print(2*(n-i)*x[0]+2*((2*i)-1)*x[1]+2*(n-i)*x[0]) print(2*(n-i)*x[0]+2*((2*i)-1)*x[1]+2*(n-i)*x[0])<file_sep>/week8/pascal_triangle.py def pascal_triangle(row, col,table=[[1]]): for i in range(1,row+1): table.append([1]) for j in range(1,i+1): if(j == i):table[i].append(1) else:table[i].append(table[i-1][j] + table[i-1][j-1]) return table[row][col] print(pascal_triangle(int(input()),int(input())))<file_sep>/week8/needle_the_perfectionist.py def getF(txt): hmap={} for i in txt: if(i in hmap): hmap[i] += 1 else:hmap[i] = 1 return hmap def travel_F(F): ch_promotion = True;can = F[0] for i in F: if(i != can):return False return True def pef(txt): for i in range(-1,len(txt)): if(i==-1):txt_tmp = txt else:txt_tmp = txt[:i] + txt[i+1:] hach={};F=[] hach = getF(sorted(list(txt_tmp))) F = list(hach.values()) if(travel_F(F)):return True return False if(pef(input())):print('Perfect') else:print('Imperfect') <file_sep>/week6/roman_number.py txt = '' roman = {1000:'M',900:'CM',500:'D',100:'C',90:'XC',50:'L',10:'X',9:'IX',5:'V',1:'I'} number = int(input()) for i in roman: if(number // i == 4):txt += (roman[i]+roman[i*5]) else:txt += (roman[i] * (number // i)) number = number % i print(txt)<file_sep>/week1/decrypt.py ################################################## ## Problem: one_word_per_line.py ## Std: std09 ## Name: <NAME> ## StudentId: 6010500109 ################################################## txt = input() print(str(txt.replace(" ","\n"))) <file_sep>/review-midterm/ex_midterm.py a = 'poon'*4 print(a)<file_sep>/week2/stack_condition.py def get_top(topostack,stack,stackii,stackiii): if(len(stack) != 0): topostack.append(stack.index(len(stack)-1)) if(len(stackii) != 0): topostack.append(stackii.index(len(stackii)-1)) if(len(stackiii) != 0): topostack.append(stackiii.index(len(stackiii)-1)) topostack.sort() return topostack # print(topostack) def pocess_swapval(stack,stackii,stackiii): print(" ") # var topostack = list() # input num = int(input()) #stack = stackii = stackiii = list() stack = list() stackii = list() stackiii = list() # get data data = num for i in range(num): stack.append(num-i) topostack = get_top(topostack,stack,stackii,stackiii) # travel stack print("stack : "+str(stack)) print("stack ii : "+str(stackii)) print("stack iii : "+str(stackiii)) print("top of stack : "+str(topostack)) <file_sep>/week5/head_tail.py def bye(): exit("Error: Wrong input") headTail = {"t":0,"h":0} txt = input().lower() for i in txt: if(not (i in headTail)):bye() else:headTail[i] += 1 print("H: {:.2f}%".format(( headTail["h"] / (headTail["t"] + headTail["h"]))*100)) print("T: {:.2f}%".format(( headTail["t"] / (headTail["t"] + headTail["h"]))*100))<file_sep>/week3/dining_table.py def dining_table(n,x=1): # Code your dining_table(n) function here if(n==0):return 1 elif(n//x <= x+1):return x+1 else:return dining_table(n//x,x+1) ### NO CODE AFTER THIS LINE SHOULD BE MODIFIED ### n = int(input()) print(dining_table(n))<file_sep>/week4/365av_nine.py ################################################## ## Problem: 365_day_advanced.py ## Std: std05 ## Name: <NAME> ## StudentId: 6010500117 ################################################## def checkMeet(fx,dx,fy,dy):#First of X, D of X, First of Y, D of Y xpass = False #X pass XR ypass = False #Y pass YR nx = ny = -1 if(dx==0 and fx==xr): xpass = True elif(dx!=0): nx = (xr-fx)/dx if(dy==0 and fy==yr): ypass = True elif(dy!=0): ny = (yr-fy)/dy if(nx == ny and nx != -1): return True elif(xpass and (yr-fy)/dy%1==0): return True elif(ypass and (xr-fx)/dx%1==0): return True if(xpass and ypass): return True move = input() #input movement pattern xr = int(input()) #X request yr = int(input()) #Y request x = 0 #X&Y starter y = 0 Find = False if(x==xr and y==yr): Find = True else: l1 = [] l2 = [] for i in move: if(i=='U'): y+=1 elif i=='D': y-=1 elif i=='R': x+=1 elif i=='L': x-=1 if(x==xr and y==yr): Find = True break l1.append((x,y)) for i in move: if(i=='U'): y+=1 elif i=='D': y-=1 elif i=='R': x+=1 elif i=='L': x-=1 if(x==xr and y==yr): Find = True break l2.append((x,y)) for i in range (0,len(l1)): Find = checkMeet(l1[i][0],l2[i][0]-l1[i][0],l1[i][1],l2[i][1]-l1[i][1]) if(Find): break if(not Find): print("N") else: print("Y") <file_sep>/week7/maze.py way = list() control = ['U','D','L','R'] strpos = [0,0] m,n = map(int,input().split()) def can(i,j): if(i<0 or i>=m or j<0 or j>=n):return False return True def ezpass(i,j): if(can(i,j) and (way[i][j] == ' ' or way[i][j] == 'I')):return True return False def fHere(i,j): if(way[i][j] == 'F'):return True return False def showMyWay(txt):print(txt) def go(i,j,went=''): if(can(i,j) and fHere(i,j)):showMyWay(went) else: if(ezpass(i,j)): # nine's algo :DDD way[i][j] = 'X' # Dont trash me go(i,j+1,went + control[3]) go(i,j-1,went + control[2]) go(i+1,j,went + control[1]) go(i-1,j,went + control[0]) way[i][j] = ' ' # Get out def get_chrline(i,txt): if(len(txt)==n): if('I' in txt):strpos[0],strpos[1] = i,txt.index('I') return txt for i in range(m):way.append([j for j in get_chrline(i,input())]) go(strpos[0],strpos[1])<file_sep>/week5/fortune_cookie.py sum = int(input()) n = input().split(' ') for i in range(len(n)): for j in range(i+1,len(n)): if(int(n[i]) + int(n[j]) == sum): print(i+1,j+1) exit()<file_sep>/week3/pao_ying_chup.py def chup(i,ii): if(i[1] == ii[1]): return "It’s a tie!!\nPlease continue" elif(i[1] == 'rock' and ii[1] =='paper'):return str(ii[0]) + " wins" elif(i[1] == 'rock' and ii[1] == 'scissors'):return str(i[0]) + " wins" elif(i[1] == 'paper' and ii[1] =='rock'):return str(i[0]) + " wins" elif(i[1] == 'paper' and ii[1] == 'scissors'):return str(ii[0]) + " wins" elif(i[1] == 'scissors' and ii[1] == 'paper'):return str(i[0]) + " wins" elif(i[1] == 'scissors' and ii[1] == 'rock'):return str(ii[0]) + " wins" else: return "Invalid input \nPlease try again!!!" playerone = ['name','item'] playertwo = ['name','item'] playerone[0] = input("Player 1 name : ") playertwo[0] = input("Player 2 name : ") print("Please input (rock/scissors/paper)") while(True): playerone[1] = input(str(playerone[0]) + " : ") playertwo[1] = input(str(playertwo[0]) + " : ") print(chup(playerone,playertwo)) if(chup(playerone,playertwo) != "Invalid input \nPlease try again!!!"): if(input("Do you want to play another game (yes/no) : ") == 'yes'): continue else:break <file_sep>/week5/pa_ti_sed_yang_rai.py def bfine(var_txt,sub_txt): for i in range(len(var_txt)): if(var_txt[i] == sub_txt[0] and len(var_txt) - i >= len(sub_txt) and var_txt[i:i+len(sub_txt)] == sub_txt):return True return False def nlove(love,n=0): for i in love: if(i):n+=1 return n lovena = [bfine(input().lower(),'somrak') for i in range(5)] if(lovena[0] and lovena[1] and lovena[2]):print('Love Love Somsri\n"somrak" :: {} sentences'.format(nlove(lovena))) elif(lovena[1] and lovena[2] and lovena[3]):print('Love Love Somsri\n"somrak" :: {} sentences'.format(nlove(lovena))) elif(lovena[3] and lovena[4] and lovena[5]):print('Love Love Somsri\n"somrak" :: {} sentences'.format(nlove(lovena))) else:print('Mai rak mai tong ma care\n"somrak" :: {} sentences'.format(nlove(lovena)))<file_sep>/week4/nong_request.py import random def attack(typee,hp,ber_chk): if(typee == 'me'): if(random.randint(1,10) > 3): damage = random.randint(350,450) if(ber_chk): damage *= 2 hp -= damage print("The monster loses %d hp"%damage) else:print("You missed!") if(typee == 'mon'): if(random.randint(1,10) > 2): damage = random.randint(250,350) hp -= damage print("The hero loses %d hp"%damage) else:print("Monster missed!") return hp def defend(): if(random.randint(1,10) > 3): print("Defend success!!!") return True else: return False def heal(hp): healing = random.randint(350,700) print("Hero's hp was restored by %d points"%healing) return hp + healing hp_me = 1500;hp_mon = 2000 count_heal = 2;ber_chk=False while(True): defs = False print("Your hero has {} hp and the monster has {} hp".format(hp_me,hp_mon)) item = input() if(item == 'A'):hp_mon = attack('me',hp_mon,ber_chk) elif(item == 'D'):defs = defend() elif(item == 'U'): item = input() if(item == 'H'): if(count_heal > 0): hp_me = heal(hp_me) count_heal -= 1 print("%d healing potion left"%count_heal) else:print("hero cannot heal (no healing potion left)") print("Your hero has %d hp"%hp_me) if(item == 'B'): print("Berserk mode : on") ber_chk = True if(ber_chk): print("The hero loses 150 hp from berserk mode") hp_me -= 150 if(not defs):hp_me = attack('mon',hp_mon,ber_chk) if(hp_me <= 0 or hp_mon <= 0): if(hp_mon <= 0 and hp_me <= 150 and ber_chk): print("Draw") break else: break<file_sep>/week2/lab/next_day.py import sys def check_leap_y(y): if(y%4==0): if(y%100==0): if(y%400==0): return True else:return False else:return True else: return False def bye(): sys.exit("Invalid input!") lim_y = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31} y = int(input()) m = int(input()) if(m<= 0 or m>12):bye() d = int(input()) if(check_leap_y(y) and m==2 and d>29):bye() elif(d > lim_y[m] and not check_leap_y(y)):bye() if(d == lim_y[m] or (d==29 and m==2)): if(check_leap_y(y) and m==2): #y+1 if(d == 29):print("The next date is %d-%02d-%02d"%(y ,m+1,1)) else:print("The next date is %d-%02d-%02d"%(y ,m,d+1)) #y+1 elif(m == 12):print("The next date is %d-%02d-%02d"%(y+1,1,1)) else: print("The next date is %d-%02d-%02d"%(y,m+1,1)) #y+1 else: print("The next date is %d-%02d-%02d"%(y,m,d+1)) if(check_leap_y(y)):print("Year %d is leap year."%y) else:print("Year %d is not leap year."%y) <file_sep>/week7/secure_password.py # 32 - 47 hyperchar # 48 - 57 number # 58 - 64 hyperchar # 65 - 90 char-bigger # 91 - 96 hyperchar # 97 - 122 char-litle # 123 - 126 hyperchar def ch_hyperchar(order): if(order >= 32 and order <=47): return True if(order >= 58 and order <=64): return True if(order >= 91 and order <=96): return True if(order >= 123 and order <=126): return True return False def ch_number(order): if(order >=48 and order <= 57): return True return False def ch_bigchar(order): if(order >= 65 and order <= 90): return True return False def ch_litchar(order): if(order >= 97 and order <= 122): return True return False def ch_hexlen(txt): if(len(txt) >= 8): return True return False def ch_fourlen(txt): if(len(txt) >= 4): return True return False def secure_pass(password,chbig=False,chlit=False,chnum=False,chhy=False): if(ch_hexlen(password)): for i in password: i = ord(i) if(ch_bigchar(i)):chbig = True if(ch_litchar(i)):chlit = True if(ch_number(i)):chnum = True if(ch_hyperchar(i)):chhy = True if(chbig and chlit and chnum and chhy): return True else: return False def ch_each_word(password): words = password.split() if(len(words) < 4): return False else: for i in words: if(len(i) < 5): return False return True def good_pass(password,chbig=False,chlit=False,chnum=False,chhy=False): if(ch_each_word(password)): return True return False def main_secure(password): if(secure_pass(password)): return 'secure password' elif(good_pass(password)): return 'good password' else:return 'bad password' print(main_secure(input()))<file_sep>/week7/note.py if(chr(97).islower):print('dw')<file_sep>/week4/hi_low.py from random import randint dice = int(input()) mon = int(input()) mondy=mon;count_dic = 0;score = 0 while(True): count_dic += 1 mondy -= 10*count_dic if(mondy < 0): print("not enough money to bet") break play = int(input()) if(play > dice*6):break if(play == randint(1,dice * 6)): score = count_dic * (mon/mondy) print("%.2f"%score) print(count_dic) print(mondy) break<file_sep>/review-midterm/printa_ctivity.py import math def main(): pass def print_a(): print("A") # if(__name__ == '__main__'): # main() # else: # print(__name__ + 'ss')<file_sep>/week2/lab/logic.py def comp_one(p,q):return not(ifso(p,not q)) def comp_two(r,s):return r or (not s) def ifso(a,b): if(a == True and b == False):return False else:return True def ans(p,q,r,s):return not(comp_one(p,q) != comp_two(r,s)) sqbool = list() # p q r s = 0 1 2 3 for i in range(4): boow = input() if boow == str(True):sqbool.append(True) else:sqbool.append(False) print("[~[%s -> ~ %s]<->[%s v ~%s]] -> ~%s == %s"%(sqbool[0],sqbool[1],sqbool[2],sqbool[3],sqbool[3],ifso(ans(sqbool[0],sqbool[1],sqbool[2],sqbool[3]),not sqbool[3]))) <file_sep>/week8/note.py import re def fn1(name_list): # In <NAME> or <NAME> lis = [] for s in name_list: if re.search(r' Chiang ',s): lis.append(s) return lis def fn2(name_list): # Name begins with Kan lis = [] for s in name_list: if re.search(r' Kan',s): continue if re.search(r'Kan',s): lis.append(s) return lis def fn3(name_list): # Name ends with chai lis = [] for s in name_list: if re.search(r'chai',s.split()[0]): lis.append(s) return lis def fn4(name_list): # Doesn't use mobile phone lis = [] for s in name_list: if re.search(r'08\d-\d\d\d-\d\d\d\d',s) or re.search(r'09\d-\d\d\d-\d\d\d\d',s): continue lis.append(s) lis.pop(0) return lis def fn5(name_list): # Phone ends with odd number name_list.pop(0) lis = [] for s in name_list: if int(s[len(s)-1])%2==1: lis.append(s) return lis # Do not edit codes below. name_list = open('contact_list.txt').read().strip().split('\n') #name_list = open('/home/public/week_8/contact_list.txt').read().strip().split('\n') fn_list = [fn1, fn2, fn3, fn4, fn5] n = int(input("Which function? (1-5): ")) fn = fn_list[n-1] search_result = fn(name_list) for result in search_result: print(result)<file_sep>/week6/codon_counting_v2.py rna = input("Enter RNA:\n") if(input("Left side is (5' or 3'): ") == '3'):process(rna[::-1]) else:process(rna)<file_sep>/week4/365_day.py movement = {"U":1,"R":1,"L":-1,"D":-1} x = 0;y = 0;check = False fly = input() here_x = int(input()) here_y = int(input()) for i in fly: if(i == 'U' or i == 'D'):y += movement[i] if(i == 'R' or i == 'L'):x += movement[i] if(x == here_x and y == here_y):check=True if(check):print('Y\n%d'%(here_x+here_y)) else:print('N') print(x,y)<file_sep>/week5/codon_counting.py def initiationCheck(txt): if(txt == 'AUG'):return True else: return False def terminationCheck(txt): ignore = ['UAA','UAG','UGA'] if(txt in ignore):return True else: return False def process(mRna,count_codon=1,codon=0,i=0,stopCodon=False,startCodon=False): while i < len(mRna): if(startCodon): if(mRna[i] == 'U' and count_codon==1):stopCodon = terminationCheck(mRna[i:i+3]) if(stopCodon): break count_codon += 1 if(len(mRna) - i < 2): codon += 1 break if(count_codon == 4): codon += 1 count_codon = 1 else: startCodon = initiationCheck(mRna[i:i+3]) if(startCodon):i+=2 i += 1 print("Codon: {} \nFound stop codon: {}".format(codon,stopCodon)) mRna = str(input("Enter RNA: ")) if(input("Left side is (5' or 3'): ") == '3'): process(mRna[::-1]) else:process(mRna) <file_sep>/review_i/note.py if(input() == ''): print('ya') else: print('ha')<file_sep>/week6/tic-tac-toe-table.py def t(n): nloop = (n*3)+2+1 for _ in range(n): for i in range(1,nloop): if(i==n+1 or i==(n+1)*2):print('|',end='') else:print(' ',end='') print('\n') def tt(n): nloop = (n*3)+2+1 for i in range(1,nloop): if(i==n+1 or i==(n+1)*2):print('+',end='') else:print('-',end='') print('\n') def tttt(n): t(n) tt(n) t(n) tt(n) t(n) n = int(input()) tttt(n)<file_sep>/week2/triangle_valid.py a = int(input()) b = int(input()) c = int(input()) if(a+b > c and a+c > b and b+c > a) : print('triangle is valid') else : print('triangle is not vai') <file_sep>/week1/one_word_per_line.py ## Problem: one_word_per_line.py ## Std: std09 ## Name: <NAME> ## StudentId: 6010500109 ################################################## txt = input() #print(str(txt.replace(" ","\n"))) for i in txt: if(i == ' ' and i != txt[len(txt)-1]): print('\n') else: print(i,end = "") <file_sep>/week3/find_factor.py def findFacBt(a,pairi,pairii): if(a>-1):end = a+1 if(a>-1):a *= -1 for i in range(a,end): for j in range(a,i+1): if(i*j == a): pairi.append(i) pairii.append(j) #if(i*j > a):break return pairi;pairii pairi_a = list();pairii_a= list() pairi_c = list();pairii_c= list() print("Standard form is ax**2+bx+c") a = int(input("Enter value of a: ")) b = int(input("Enter value of b: ")) c = int(input("Enter value of c: ")) findFacBt(a,pairi_a,pairii_a) findFacBt(c,pairi_c,pairii_c) print(pairi_a) print(pairii_a) print(pairi_c) print(pairii_c) print(len(pairi_a)) # print(pairi_a[0]) # for i in range(0,len(pairi_a)): # print("({} {}) ({} {})".format(pairi_a[i],pairi_c[i],pairii_a[i],pairii_c[i])) # if(b == (pairi_a[i]*pairii_c[i]) + (pairii_a[i]*pairi_c[i]) ): # print("({} {}) ({} {})".format(pairi_a[i],pairi_c[i],pairii_a[i],pairii_c[i])) <file_sep>/week4/just_another_sum.py def fac(n): if(n==0):return 1 else:return fac(n-1)*n n = int(input()) k = int(input()) for i in range(1,fac(n)+1): if(i%n == 0 and i%k == 0): print(i) <file_sep>/week4/basenumber_note.py def conBase(number): print(number%2,end="") if(number == 1):return '1' else:return conBase(number//2) conBase(int(input()))<file_sep>/week6/new.c #include <stdio.h> enum name_ss {poon,shota}; int main(){ enum name_ss ooo; ooo = shota; printf("%d",ooo); } <file_sep>/week2/lab/calculate_two_sequence.py import sys def seqii(a,n,d): if n==1 : print("Your answer is "+str(a)) else: seqii(a+d,n-1,d*2) a = input("First order: ") b = input("Second order: ") c = input("Third order: ") ans = input("What order you want to find: ") # basic task if(ans == 1):print("First order: %d"%a) elif(ans ==2):print("Second order: %d"%b) elif(ans ==3):print("Third order: %d"%c) else: # check input if(ans > 15 or ans <= 0):sys.exit("Error") # check sqe if(a-b == b-c):print("Your answer is %d"%(a+((ans-1)*(b-a))) ) else:seqii(a,ans,b-a) <file_sep>/week6/a_z_cycle.py def getchr(plus,txt,it=97): if(txt.isupper()):it=65 tmp = ord(txt) - it # 0-25 input tmp = (tmp+plus)%26 # 0-25 ans return chr(tmp + it) plus = int(input()) txt = input() print(getchr(plus,txt))
b958551bde844d2bfaa4dd7cb670c4ebab4ff17b
[ "C", "Python" ]
68
Python
aslupin/cpe31-task
c15ec9be94b899120db39b076a4d1c644f0af24b
d97d3e495634826d6752c1ee82192cc58045a883
refs/heads/master
<file_sep>package webscraper; public class AppMain { public static void main(String[] args) { Scraper s = new Scraper(); s.loopAndGrab(); s.closeBrowser(); } } <file_sep># webScraping-seed Assuming you have a Java IDE and the latest JDK, this will get you started with a basic webScrape using Java, Selenium, and Chromedriver. All the needed libraries are in the lib folder. After cloning or downloading the seed, just add everthing from the lib folder to the libraries for the project. That should take care of all the initial errors. Next, you will have to specify the path to chromedriver.exe. This will be the path to the project followed by /lib/chromedriver.exe. Then you are ready to run the project. It will loop through the urlArray and output the education info (found on city-data.com) to the console for each of the five cities. Links -[Selenium](http://www.seleniumhq.org/) -[Robots.txt](http://www.robotstxt.org/robotstxt.html) -[Chromedriver.exe](https://sites.google.com/a/chromium.org/chromedriver/downloads)
4064c797ca249d2008ff202182932a57e5c8bbb7
[ "Markdown", "Java" ]
2
Java
spencercope/webScraping-seed
3e3813abe2b31591037091d0dd896f5e5ddfd682
c4a954a182bc5b1d165232d645c7da319c78fd19
refs/heads/master
<file_sep>#!/bin/bash set -e # Create directories mkdir -p /data/clients \ /data/torrents cp /default/clients/* /data/clients if [ ! -f /data/config.json ]; then cp /default/config.json /data/ fi java -jar /joal/joal.jar "$@"
5648d23a55c06126a443869598a266155d762008
[ "Shell" ]
1
Shell
Nomuas/joal
c1f58be7be52156e07703a97e96319b0259fe8e5
ad9416077a07861e1dd41fcc21e3ff1a9f5c9e7d
refs/heads/master
<repo_name>HenryMameds/4tech-backend<file_sep>/src/services/user/user.service.ts import { Injectable, BadRequestException } from '@nestjs/common'; import { UserRepository } from 'src/repositories/repository/user-repository' import { UserViewModel } from 'src/domain/user.viewmodel'; import { LoginViewModel } from 'src/domain/login.viewmodel'; @Injectable() export class UserService { constructor(readonly userRepository: UserRepository){ } getUsers() { return this.userRepository.getUsers(); } async createNewUser(newUser: UserViewModel) { const userList = await this.userRepository.getUsers(); const existingUser = userList.find(x => x.userName === newUser.userName); if (existingUser){ throw new BadRequestException('This username already exists!') } return this.userRepository.createUser(newUser); } createGroupUser(newUser: UserViewModel[]) { return newUser // for (let i = 0; i < newUser.length; i++) { // console.log(newUser) // } // for i = 0 // // const userList = this.userRepository.getUsers(); // // const existingUser = userList.find(x => x.userName === newUser.userName); // if (existingUser){ // throw new BadRequestException('This username already exists!') // } // // return this.userRepository.createUser(newUser); } async updateUser(updateUser: UserViewModel) { const userList = await this.userRepository.getUsers(); const userIndex = userList.findIndex((x => x.userName === updateUser.userName)); const existingUser = userList.find(x => x.userName === updateUser.userName); if (existingUser){ // userList[userIndex] = updateUser; return " Updated User "; } return "User Not Found"; } async deleteUser(deleteUser: UserViewModel) { const userList = await this.userRepository.getUsers(); const existingUser = userList.find(x => x.userName === deleteUser.userName); if (existingUser){ userList.splice(userList.findIndex((x => x.userName === deleteUser.userName))); return "User Deleted"; } return "User Not Found"; } async attempLogin(login: LoginViewModel) { const userList = await this.userRepository.getUsers(); const foundLogin = userList.find(x => x.userLogin === login.userLogin && x.password === login.password); return foundLogin; } } <file_sep>/src/services/auth/jwt.strategy.ts import {Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy, ExtractJwt } from 'passport-jwt'; // NUNCA DEVE SER EXPOSTA PUBLICAMENTE // // A CHAVE SECREAT SÓ ESTA A MOSTRA A FINS DE DEIXAR CLARO O QUE // O CÓDIGO ESTÁ FAZENDO. EM UM AMBIENTE DE PRODUÇÃO, A CHAVE // DEVE ESTAR PROTEGIDA POR MEDIDAS APROPRIADAS (COMO POR EXEMPLO //SECRET VAULTS, VARIAVEIS DE AMBIENTE OU SERVIÇOS DE CONFIGURAÇÃO) export const secretKey = 'wingardium leviosa'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy){ constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), igonreExpiration: false, secretOrKey: secretKey, }) } async validate(payload: any){ return { userLogin: payload.userLogin }; } }
cef635e923d85b0d315cc58646c5a7ea0eade0d2
[ "TypeScript" ]
2
TypeScript
HenryMameds/4tech-backend
803c961976400c00a7862803cda5df3ebd369017
1d48665d81824a9bbc9ae2ecfaabef0836747c31
refs/heads/master
<file_sep>using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Windows.Forms; namespace wesingchangescore { public partial class Form1 : Form { string datapath = @"C:\Users\" + Environment.UserName + @"\\AppData\Roaming\Tencent\WeSing\User Data\KSongsDataInfo.xml"; string data = ""; public Form1() { InitializeComponent(); } private ArrayList getmidtextarraylist(string origintext, string lefttext, string righttext) { int start = 0; int left = origintext.IndexOf(lefttext, start); int right; int length; ArrayList re = new ArrayList(); while (left != -1) { right = origintext.IndexOf(righttext, left) + righttext.Length; length = right - left; re.Add(origintext.Substring(left, right - left)); left = origintext.IndexOf("<Outputs", right); } return re; } private string getmidtext(string origintext, string lefttext, string righttext) { int start = 0; int left = origintext.IndexOf(lefttext, start) + lefttext.Length; int right; string re = ""; right = origintext.IndexOf(righttext, left); re = origintext.Substring(left, right - left); return re; } private void Form1_Load(object sender, EventArgs e) { StreamReader sr = new StreamReader(datapath); data = sr.ReadToEnd(); sr.Close(); ArrayList datalist = getmidtextarraylist(data, "<Outputs", @"/>"); for (int i = 0; i < datalist.Count; i++) { ListViewItem lvItem = new ListViewItem(); lvItem.Text = getmidtext(datalist[i].ToString(), "Name=\"", "\""); lvItem.SubItems.Add(getmidtext(datalist[i].ToString(), "Score=\"", "\"")); switch (getmidtext(datalist[i].ToString(), "ScoreRank=\"", "\"")) { case "0": lvItem.SubItems.Add("D"); break; case "1": lvItem.SubItems.Add("C"); break; case "2": lvItem.SubItems.Add("B"); break; case "3": lvItem.SubItems.Add("A"); break; case "4": lvItem.SubItems.Add("S"); break; case "5": lvItem.SubItems.Add("SS"); break; case "6": lvItem.SubItems.Add("SSS"); break; } lvItem.SubItems.Add((getmidtext(datalist[i].ToString(), "AllScores=\"", "\"").Split(',').Length - 1).ToString()); lvItem.SubItems.Add(((getmidtext(datalist[i].ToString(), "AllScores=\"", "\"").Split(',').Length - 1) * 100).ToString()); listView1.Items.Add(lvItem); } } private void listView1_SelectedIndexChanged(object sender, EventArgs e) { if (listView1.SelectedIndices != null && listView1.SelectedIndices.Count > 0) { ArrayList datalist = getmidtextarraylist(data, "<Outputs", @"/>"); textBox1.Text = listView1.SelectedItems[0].SubItems[1].Text; comboBox1.Text = listView1.SelectedItems[0].SubItems[2].Text; textBox2.Text = getmidtext(datalist[listView1.SelectedItems[0].Index].ToString(), "AllScores=\"", "\""); label4.Text = listView1.SelectedItems[0].Index.ToString(); } } private void button1_Click(object sender, EventArgs e) { ArrayList datalist = getmidtextarraylist(data, "<Outputs", @"/>"); string scorerank = ""; string line = datalist[Int32.Parse(label4.Text)].ToString(); switch (comboBox1.SelectedItem.ToString()) { case "D": scorerank = "0"; break; case "C": scorerank = "1"; break; case "B": scorerank = "2"; break; case "A": scorerank = "3"; break; case "S": scorerank = "4"; break; case "SS": scorerank = "5"; break; case "SSS": scorerank = "6"; break; } string[] a = textBox2.Text.Split(','); int s = 0; for (int i = 0; i < a.Length - 1; i++) { s += Int32.Parse(a[i]); } line = line.Replace("Score=\"" + getmidtext(datalist[Int32.Parse(label4.Text)].ToString(), "Score=\"", "\""), "Score=\"" + s); line = line.Replace("ScoreRank=\"" + getmidtext(datalist[Int32.Parse(label4.Text)].ToString(), "ScoreRank=\"", "\""), "ScoreRank=\"" + scorerank); line = line.Replace(getmidtext(datalist[Int32.Parse(label4.Text)].ToString(), "AllScores=\"", "\""), textBox2.Text); data = data.Replace(datalist[Int32.Parse(label4.Text)].ToString(), line); //MessageBox.Show(data); StreamWriter sw = new StreamWriter(datapath); sw.Write(data); sw.Flush(); sw.Close(); listView1.Items.Clear(); Form1_Load(this, new EventArgs()); } private void button2_Click(object sender, EventArgs e) { listView1.Items.Clear(); Form1_Load(this, new EventArgs()); } private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e) { string s = textBox2.Text; string[] _s = s.Split(','); string res = ""; int r = 0; try { foreach (string a in _s) { r += Int32.Parse(a); } } catch { } int chazhi = 0; if (comboBox1.SelectedIndex == 0) { if (r < Int32.Parse(listView1.SelectedItems[0].SubItems[4].Text) * 0.6) { chazhi = (int)(Int32.Parse(listView1.SelectedItems[0].SubItems[4].Text) * 0.6 - r); } } if (comboBox1.SelectedIndex == 1) { if (r < Int32.Parse(listView1.SelectedItems[0].SubItems[4].Text) * 0.5) { chazhi = (int)(Int32.Parse(listView1.SelectedItems[0].SubItems[4].Text) * 0.5 - r); } } if (comboBox1.SelectedIndex == 2) { if (r < Int32.Parse(listView1.SelectedItems[0].SubItems[4].Text) * 0.4) { chazhi = (int)(Int32.Parse(listView1.SelectedItems[0].SubItems[4].Text) * 0.4 - r); } } if (comboBox1.SelectedIndex == 3) { } if (comboBox1.SelectedIndex == 4) { if (r < Int32.Parse(listView1.SelectedItems[0].SubItems[4].Text) * 0.7) { chazhi = (int)(Int32.Parse(listView1.SelectedItems[0].SubItems[4].Text) * 0.7 - r); } } if (comboBox1.SelectedIndex == 5) { if (r < Int32.Parse(listView1.SelectedItems[0].SubItems[4].Text) * 0.8) { chazhi = (int)(Int32.Parse(listView1.SelectedItems[0].SubItems[4].Text) * 0.8 - r); } } if (comboBox1.SelectedIndex == 6) { if (r < Int32.Parse(listView1.SelectedItems[0].SubItems[4].Text) * 0.9) { chazhi = (int)(Int32.Parse(listView1.SelectedItems[0].SubItems[4].Text) * 0.9 - r); } } if (chazhi > 0) { for (int i = 0; i < _s.Length - 1; i++) { if (Int32.Parse(_s[i]) < 100) { int _chazhi = Int32.Parse(_s[i]) + chazhi - 100; if (_chazhi > 0) { chazhi = _chazhi; _s[i] = "100"; } else { _s[i] = chazhi.ToString(); break; } } } } foreach (string a in _s) { if (a != "") { res += a + ","; } } textBox2.Text = res; } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("explorer.exe","https://www.nitian1207.top"); } } }
d3d850f1414443e8b1408f18797e43b03c5ae0b4
[ "C#" ]
1
C#
nitezs/WeSing_Score_Changer
66a26f02283b6954861369c1c4854a5a4571e8ba
c1b552fc8db104b01c246a5f653d987502bceba7
refs/heads/master
<repo_name>MAJOR-BEAST/Project<file_sep>/project_cbs/quickstart-file.py from azure.cognitiveservices.vision.computervision import ComputerVisionClient from azure.cognitiveservices.vision.computervision.models import TextOperationStatusCodes from azure.cognitiveservices.vision.computervision.models import TextRecognitionMode from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes from msrest.authentication import CognitiveServicesCredentials import pandas as pc import unicodedata import os import sys import time import re import csv # Add your Computer Vision subscription key to your environment variables. if 'COMPUTER_VISION_SUBSCRIPTION_KEY' in os.environ: subscription_key = os.environ['COMPUTER_VISION_SUBSCRIPTION_KEY'] else: print("\nSet the COMPUTER_VISION_SUBSCRIPTION_KEY environment variable.\n**Restart your shell or IDE for changes to take effect.**") sys.exit() # Add your Computer Vision endpoint to your environment variables. if 'COMPUTER_VISION_ENDPOINT' in os.environ: endpoint = os.environ['COMPUTER_VISION_ENDPOINT'] else: print("\nSet the COMPUTER_VISION_ENDPOINT environment variable.\n**Restart your shell or IDE for changes to take effect.**") sys.exit() computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key)) ''' Recognize handwritten text - local This example extracts text from a handwritten local image, then prints results. This API call can also recognize printed text (not shown). ''' print("===== Detect handwritten text - local =====") # Get image of handwriting local_image_handwritten_path = "100775.jpg" # Open the image local_image_handwritten = open(local_image_handwritten_path, "rb") # Call API with image and raw response (allows you to get the operation location) recognize_handwriting_results = computervision_client.batch_read_file_in_stream(local_image_handwritten, raw=True) # Get the operation location (URL with ID as last appendage) operation_location_local = recognize_handwriting_results.headers["Operation-Location"] # Take the ID off and use to get results operation_id_local = operation_location_local.split("/")[-1] # Call the "GET" API and wait for the retrieval of the results while True: recognize_handwriting_result = computervision_client.get_read_operation_result(operation_id_local) if recognize_handwriting_result.status not in ['NotStarted', 'Running']: break time.sleep(1) #choice = int(input()) csv_data = {} date = "" sr="" tot=10000 # Print results, line by line if recognize_handwriting_result.status == TextOperationStatusCodes.succeeded: for text_result in recognize_handwriting_result.recognition_results: for line in text_result.lines: '''comp_name = re.match(r"^Computer ",line.text) if comp_name: print comp_name.string''' dates = re.match(r"(\b\d{1,2}\D{0,3})?\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember)?)\D?(\d{1,2}\D?)?\D?((19[7-9]\d|20\d{2})|\d{2})",line.text) if dates: date = str(dates.string) print dates.string srno = re.match(r"(\ASR. NO)",line.text) if srno: sr = str(srno.string) print srno.string total = re.match(r"(?:Rs\.?|INR)\s*(\d+(?:[.,]\d+)*)|(\d+(?:[.,]\d+)*)\s*(?:Rs\.?|INR)",line.text) if total: tot = float(total.string) print total.string csv_data = {'Date':date,'Serial No': sr,'Grand Total': tot} with open('test.csv', 'w') as f: for key in csv_data.keys(): f.write("%s,%s\n"%(key,csv_data[key])) '''dates = re.match(r"(\b\d{1,2}\D{0,3})?\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember)?)\D?(\d{1,2}\D?)?\D?((19[7-9]\d|20\d{2})|\d{2})",line.text) if dates: print dates.string srno = re.match(r"(\ABatch )",line.text) if srno: print srno.string total = re.match(r"(?:Rs\.?|INR)\s*(\d+(?:[.,]\d+)*)|(\d+(?:[.,]\d+)*)\s*(?:Rs\.?|INR)",line.text) if total: print total.string''' '''dates = re.match(r"^([0-2][0-9]|(3)[0-1])(\-)(((0)[0-9])|((1)[0-2]))(\-)\d{4}$",line.text) if dates: print dates.string srno = re.match(r"(\AS.No)",line.text) if srno: print srno.string total = re.match(r"(?:Rs\.?|INR)\s*(\d+(?:[.,]\d+)*)|(\d+(?:[.,]\d+)*)\s*(?:Rs\.?|INR)",line.text) if total: print total.string #comp_name = line.text[5] # print comp_name''' '''comp_name = re.match(r"\AVinayak",line.text) if comp_name:''' '''dates = re.match(r"^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$",line.text) if dates: print dates.string srno = re.match(r"(\ASerial.no )",line.text) if srno: print srno.string total = re.match(r"(?:Rs\.?|INR)\s*(\d+(?:[.,]\d+)*)|(\d+(?:[.,]\d+)*)\s*(?:Rs\.?|INR)",line.text) if total: print total.string''' #print(line.text) #po+=[line.text] #print(line.bounding_box) #pc.DataFrame(po).to_excel('output.xlsx', header=False, index=False) #print() ''' END - Recognize handwritten text - local '''
12a8077f4a2f46841bf89e8dd21ed42940ffc25a
[ "Python" ]
1
Python
MAJOR-BEAST/Project
330e256bf3848a344e3374eedc4736c465d5a9e4
d6cc4615e9ce6c8a81dfec096f712eade31295d8
refs/heads/master
<file_sep>import { CURSOR_DIRECTIONS } from "../constants"; import { useCallback, useEffect, useMemo, useState } from "react"; import { Keyboard } from "react-native"; import usePuzzlesContext from "./usePuzzlesContext"; const generateLine = (currentLine, line, y) => { const currentChars = currentLine.split(""); const chars = line.split(""); const startX = chars.findIndex(char => char !== " "); return { y, startX, endX: line.length, cells: chars .map((correctValue, x) => ({ x, value: currentChars[x], correctValue })) .slice(startX) }; }; const generateGrid = ({ currentSolution, solution, columnX }) => { const currentLines = (currentSolution || "").split("\n"); const lines = solution.split("\n"); return { width: Math.max(...lines.map(line => line.length)), height: lines.length, columnX, rows: lines.map((line, y) => generateLine(currentLines[y] || "", line, y)) }; }; const isValidChar = char => char === "" || (char.charCodeAt(0) >= 65 && char.charCodeAt(0) <= 90); const advanceCursor = (cursor, grid) => cursor === null ? null : cursor.direction === CURSOR_DIRECTIONS.VERTICAL ? cursor.y < grid.height - 1 ? { ...cursor, y: cursor.y + 1 } : null : cursor.x < grid.rows[cursor.y].endX - 1 ? { ...cursor, x: cursor.x + 1 } : null; const usePuzzle = ({ puzzleId }) => { const { puzzles, save } = usePuzzlesContext(); const puzzle = useMemo(() => puzzles.find(puzzle => puzzle.id === puzzleId), [ puzzles, puzzleId ]); const [{ cursor, grid, isSolved }, setState] = useState({ cursor: null, grid: generateGrid(puzzle), isSolved: puzzle.isSolved }); const setCursor = useCallback( v => setState(state => { const nextCursor = typeof v === "function" ? v(state.cursor) : v; return { ...state, cursor: nextCursor }; }), [] ); const inputValue = useCallback(s => { const char = s.charAt(0).toUpperCase(); if (!isValidChar(char)) { return; } setState(({ cursor, grid, ...state }) => ({ ...state, cursor: char ? advanceCursor(cursor, grid) : cursor, grid: { ...grid, rows: cursor === null ? grid.rows : grid.rows.map(row => row.y === cursor.y ? { ...row, cells: row.cells.map(cell => cell.x === cursor.x ? { ...cell, value: char } : cell ) } : row ) } })); }, []); useEffect(() => { if (cursor === null) { Keyboard.dismiss(); } }, [cursor]); useEffect(() => { if ( grid.rows.every(row => row.cells.every(cell => cell.value === cell.correctValue) ) ) { setState(state => ({ ...state, isSolved: true })); } }, [puzzle, grid]); useEffect(() => { return () => setState(state => { save( puzzleId, state.grid.rows .map(row => " " .repeat(row.startX) .concat(row.cells.map(cell => cell.value || " ").join("")) ) .join("\n") ); return state; }); }, []); return { puzzle, grid, cursor, setCursor, inputValue, isSolved }; }; export default usePuzzle; <file_sep>import { CURSOR_DIRECTIONS } from "../constants"; import React, { useCallback, useRef } from "react"; import { ScrollView } from "react-native"; import usePuzzleContext from "../hooks/usePuzzleContext"; import PuzzleGrid from "./PuzzleGrid"; import TextInput from "./TextInput"; import Questions from "./Questions"; const updateCursor = (x, y, cursor, grid) => { if (!cursor) { return { x, y, direction: CURSOR_DIRECTIONS.HORIZONTAL }; } if ( cursor.direction === CURSOR_DIRECTIONS.VERTICAL && x === cursor.x && y !== cursor.y ) { return { x, y, direction: CURSOR_DIRECTIONS.VERTICAL }; } if (x !== cursor.x || y !== cursor.y) { return { x, y, direction: CURSOR_DIRECTIONS.HORIZONTAL }; } if (x === grid.columnX && cursor.direction === CURSOR_DIRECTIONS.HORIZONTAL) { return { x, y, direction: CURSOR_DIRECTIONS.VERTICAL }; } return null; }; const Puzzle = () => { const inputRef = useRef(null); const { puzzle, grid, cursor, setCursor, inputValue } = usePuzzleContext(); const onCellPress = useCallback( (x, y) => { setCursor(cursor => { const nextCursor = updateCursor(x, y, cursor, grid); const input = inputRef.current; if (input && nextCursor) { input.focus(); } return nextCursor; }); }, [grid, setCursor] ); return ( <> <PuzzleGrid grid={grid} cursor={cursor} onCellPress={onCellPress} /> <TextInput ref={inputRef} autoCorrect={false} caretHidden value="" onChangeText={char => inputValue(char)} onKeyPress={event => { if (event.nativeEvent.key === "Backspace") { inputValue(""); } }} /> <ScrollView height="50%"> <Questions questions={puzzle.questions} /> </ScrollView> </> ); }; export default Puzzle; <file_sep>import React from "react"; import styled from "styled-components"; const Wrapper = styled.TouchableOpacity` display: flex; align-items: center; justify-content: center; width: 80px; height: 80px; margin: 8px; border: 1px solid #0002; border-radius: 16px; box-shadow: 0 2px 6px #0004; background-color: ${props => (props.isSolved ? "#4caf50" : "#fff")}; `; const Number = styled.Text` font-weight: bold; font-size: 32px; color: ${props => (props.isSolved ? "#fff" : "#000")}; `; const PuzzleThumb = ({ isSolved, number, onClick }) => ( <Wrapper isSolved={isSolved} onPress={onClick}> <Number isSolved={isSolved}>{number}</Number> </Wrapper> ); export default PuzzleThumb; <file_sep>import styled from "styled-components"; const TextInput = styled.TextInput` display: none; `; export default TextInput; <file_sep>import { useContext } from "react"; import { PuzzlesContext } from "../contexts"; const usePuzzlesContext = () => useContext(PuzzlesContext); export default usePuzzlesContext; <file_sep>import { useCallback, useEffect, useState } from "react"; import { AsyncStorage } from "react-native"; import puzzles from "../data/puzzles.json"; const usePuzzles = () => { const [currentSolutionMap, setCurrentSolutionMap] = useState({}); const save = useCallback((puzzleId, currentSolution) => { setCurrentSolutionMap(currentSolutionMap => { const next = { ...currentSolutionMap, [puzzleId]: currentSolution }; AsyncStorage.setItem("puzzles", JSON.stringify(next)); return next; }); }, []); useEffect(() => { const load = async () => { const currentSolutionMapJSON = await AsyncStorage.getItem("puzzles"); setCurrentSolutionMap(JSON.parse(currentSolutionMapJSON) || {}); }; load(); }, []); return { puzzles: puzzles.map(puzzle => ({ ...puzzle, currentSolution: currentSolutionMap[puzzle.id], isSolved: currentSolutionMap[puzzle.id] === puzzle.solution })), save }; }; export default usePuzzles; <file_sep>import { CURSOR_DIRECTIONS } from "../constants"; import React from "react"; import { Text } from "react-native"; import styled from "styled-components"; import usePuzzleContext from "../hooks/usePuzzleContext"; const Wrapper = styled.View` flex: 1; min-height: 32px; padding: 16px 0; border-top-left-radius: 8px; border-top-right-radius: 8px; background-color: #fff; `; const Question = styled.View` padding: 4px 16px; background-color: ${props => (props.isFocused ? "#fff59d" : "#fff")}; `; const Strong = styled.Text` font-weight: bold; `; const Questions = ({ questions }) => { const { cursor } = usePuzzleContext(); return ( <Wrapper pointerEvents="none"> {questions.map((q, i) => ( <Question key={i} isFocused={ cursor && (cursor.direction === CURSOR_DIRECTIONS.VERTICAL ? i === 0 : i === cursor.y + 1) } > <Text> <Strong>{i === 0 ? "Verticaal: " : `${i}. `}</Strong> <Text>{q}</Text> </Text> </Question> ))} </Wrapper> ); }; export default Questions; <file_sep>import { createContext } from "react"; export const PuzzlesContext = createContext(null); export const PuzzleContext = createContext(null); export default { PuzzlesContext, PuzzleContext }; <file_sep>export const CURSOR_DIRECTIONS = { HORIZONTAL: 0, VERTICAL: 1 }; export default { CURSOR_DIRECTIONS }; <file_sep>import React, { useCallback } from "react"; import styled from "styled-components"; import { LinearGradient } from "expo-linear-gradient"; import PuzzleThumbs from "../components/PuzzleThumbs"; const Wrapper = styled.View` width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; `; const Title = styled.Text` margin-bottom: 32px; font-size: 32px; font-weight: bold; `; const HomeScreen = ({ navigation }) => { const startPuzzle = useCallback( puzzleId => navigation.navigate("Puzzle", { puzzleId }), [navigation] ); return ( <LinearGradient colors={["#fdd835", "#fff"]} locations={[0.5, 0.5001]} start={[0, 0]} end={[1, 1]} > <Wrapper> <Title>Woordgraptogram</Title> <PuzzleThumbs onThumbClick={startPuzzle} /> </Wrapper> </LinearGradient> ); }; export default HomeScreen; <file_sep>import React from "react"; import { PuzzlesContext } from "../contexts"; import usePuzzles from "../hooks/usePuzzles"; const Puzzles = ({ puzzleId, children }) => { const value = usePuzzles({ puzzleId }); return ( <PuzzlesContext.Provider value={value}>{children}</PuzzlesContext.Provider> ); }; export default Puzzles; <file_sep>import React from "react"; import styled from "styled-components"; const Wrapper = styled.TouchableOpacity` position: absolute; top: 32px; left: 16px; display: flex; align-items: center; justify-content: center; width: 48px; height: 48px; border: 1px solid #0002; border-radius: 24px; box-shadow: 0 2px 6px #0004; background-color: #fff; `; const Number = styled.Text` font-weight: bold; font-size: 32px; line-height: 28px; `; const BackButton = ({ onPress }) => ( <Wrapper onPress={onPress}> <Number>&larr;</Number> </Wrapper> ); export default BackButton; <file_sep>import React from "react"; import styled from "styled-components"; const Wrapper = styled.View` position: absolute; top: 32px; right: 16px; display: flex; align-items: center; justify-content: center; width: 48px; height: 48px; border-radius: 24px; box-shadow: 0 2px 6px #0004; background-color: #4caf50; `; const CheckMark = styled.Text` font-weight: bold; font-size: 32px; color: #fff; `; const CompletionBadge = ({ onPress }) => ( <Wrapper onPress={onPress}> <CheckMark>✓</CheckMark> </Wrapper> ); export default CompletionBadge;
1dca6f57a21caf2b6ec23f392c7b7e228742df44
[ "JavaScript" ]
13
JavaScript
wouterraateland/woordgraptogram
3f687a4f75515b3b96ccc7f845ba513d8966bbf4
3e6735462c0e8840782bc55cff41e06442ea6590
refs/heads/master
<repo_name>Raging-Tiger/SE_project<file_sep>/app/Http/Controllers/ApartmentController.php <?php namespace App\Http\Controllers; use App\Models\Apartment; use App\Models\ApartmentInhabitant; use App\Models\Inhabitant; use Illuminate\Http\Request; class ApartmentController extends Controller { public function __construct() { $this->middleware('admin')->only(['adminApartmentView', 'editApartmentView', 'saveApartmentView']); $this->middleware('tenant')->only(['index', 'email']); } /*Tenant*/ public function index() { $mail = auth()->user()->email_notifications; if($mail == 1) { $mail=TRUE; } else{ $mail=FALSE; } $inh = Inhabitant::where('user_id', auth()->user()->id)->first(); if(!isset($inh)) { return view('general/error'); } $userid = ApartmentInhabitant::where('inhabitant_id', $inh->id)->get(); return view('tenant/appartment_data', ['ai' => $userid, 'email' => $mail]); } public function email (Request $request) { if($request->mail==TRUE) { $mail = auth()->user(); $mail ->email_notifications = 1; $mail ->save(); } else { $mail = auth()->user(); $mail ->email_notifications = 0; $mail ->save(); } return redirect()->action('ApartmentController@index'); } /*Admin*/ public function adminApartmentView() { return view('/admin/apartment_management/apartment', ['apartments' => Apartment::orderBy('number')->get()]); } public function editApartmentView($id) { return view('/admin/apartment_management/apartment_edit', ['apartment' => Apartment::where('id', $id)->first()]); } public function saveApartmentView(Request $request){ $rules = array( 'area' => 'required|numeric', 'floor' => 'required|numeric', 'number' => 'required|numeric', ); $this->validate($request, $rules); $apartment = Apartment::where('id', $request->id)->first(); $apartment->area_m2 = $request->area; $apartment->floor = $request->floor; $apartment->number = $request->number; $apartment->save(); return view('/admin/apartment_management/apartment', ['apartments' => Apartment::orderBy('number')->get()]); #return view('/admin/user_management/users', array('users' => User::orderBy('role_id')->get())); } } <file_sep>/resources/lang/en/general_messages.php <?php /*ENG*/ return [ 'appartment' => "Appartment's data", 'about' => "About us", 'fines' => 'Fines', 'bills' => 'Bills', 'notifications' => 'Manage notifications', 'admin' => 'Admin actions', 'roles' => 'Manage user roles', 'man_inh' => 'Manage inhabitants', 'add_inh' => 'Add new inhabitant', 'man_bills' => 'Manage bills', 'man_fines' => 'Manage fines', 'logout' => 'Logout', 'login' => 'Login', 'register' => 'Register', 'dashboard' => 'Dashboard', 'logged_in' => ' You are logged in as', 'with_name' => 'with name', 'You_have' => 'You have', 'f_t' => 'fines in total for the whole period.', 'f_m' => 'fines in total for the past month.', 'b_t' => 'not paid bills for the whole time.', 'register' => 'Register', 'name' => 'Name', 'email' => 'E-Mail Address', 'pass' => '<PASSWORD>', 'conf_pass' => '<PASSWORD>', 'remember' => 'Remember Me', 'forgot' => 'Forgot Your Password?', 'Close_to_Sea' => 'Close to sea!', 'Close_to_Sea_text' => 'Located on the first line, really close to the sea!', 'tour' => 'Order private tour', 'project' => 'New unique project!', 'project_text' => '84 nice appartments to fit all possible needs!', 'location' => 'Location', 'project_new' => 'New project', 'log' => 'User actions log', 'user_management' => 'User management', 'apartment_management' => 'Apartment management', 'man_meters' => 'Manage meters', 'meters' => 'Meters', ]; <file_sep>/app/Http/Controllers/InhabitantController.php <?php namespace App\Http\Controllers; use App\Models\Apartment; use App\Models\ApartmentInhabitant; use App\Models\Inhabitant; use Illuminate\Http\Request; class InhabitantController extends Controller { public function __construct() { $this->middleware('admin')->only(['addInhView', 'addInh', 'adminInhabitantView', 'connectWithInh', 'destroyInhApp', 'addInhApp']); } public function addInhView() { return view('/admin/inhabitant_management/inhabitant_add'); } public function addInh(Request $request) { $rules = array( 'name' => 'required|alpha|max:255', 'surname' => 'required|alpha|max:255', 'pers' => 'required|regex:/[0-9]{6}[-]{1}[0-9]{5}/|unique:inhabitants,personal_code', ); $this->validate($request, $rules); $inhabitant = new Inhabitant(); $inhabitant->name = $request->name; $inhabitant->surname = $request->surname; $inhabitant->personal_code = $request->pers; // $inhabitant->user_id = 'NULL'; $inhabitant->save(); return view('/admin/inhabitant_management/inhabitant', ['inhs' => Inhabitant::orderBy('user_id')->get(), 'app_inh' => ApartmentInhabitant::all()]); // return view('/admin/inhabitant_add'); } public function adminInhabitantView() { return view('/admin/inhabitant_management/inhabitant', ['inhs' => Inhabitant::orderBy('user_id')->get(), 'app_inh' => ApartmentInhabitant::all()]); } public function connectWithInh ($id) { $inh = ApartmentInhabitant::where('inhabitant_id', $id)->get(); $inh_app = $inh->pluck('apartment_id','apartment_id'); $app = Apartment::all(); $app = $app->pluck('number', 'id'); foreach($inh_app as $key => $value) { unset($app[$key]); } return view('/admin/inhabitant_management/app_inh', ['inhid' => $id, 'apps' => $app, 'inh' => Inhabitant::where('id', $id)->first()]); } public function destroyInhApp ($id, Request $request) { ApartmentInhabitant::where('id',$request->iaid)->delete(); return redirect('admin/inhabitants/'.$id); } public function addInhApp ($id, Request $request) { $rules = array( 'appno' => 'required', ); $this->validate($request, $rules); $ai = new ApartmentInhabitant(); $ai->apartment_id= $request->appno; $ai->inhabitant_id= $request->inhid; $ai->save(); return redirect('admin/inhabitants/'.$id); } } <file_sep>/resources/lang/ru/adm_messages.php <?php /*RU*/ return [ 'name' => 'Имя', 'surname' => 'Фамилия', 'pk' => 'Персональный код', 'app_no' => '№ кв.', 'inh_no' => '№ жильца', 'status' => 'Статус', 'del' => 'Удалить', 'app' => 'Квартира', 'connect' => 'Соединить', 'bill_new' => 'Создать новый счет', 'month' => 'Месяц', 'ac_per_app' => 'Административные расходы / кв.', 'ac_per_m2' => 'Административные расходы / m2', 'reserve' => 'Резервный фонд', 'renovation' => 'Реновация', 'bill_create' => 'Создать счета для всех квартир', 'bill_see' => 'Просмотреть список счетов', 'bill_id' => '№ счета', 'rts' => 'Тип реновации и сумма', 'mc' => 'Общие расходы', 'total' => 'Итого', 'bill_status' => 'Статус счета', 'change_data' => 'Изменить данные', 'bill_change' => 'Изменить данные счета', 'bill_all' => 'Все счета', 'bill_month' => 'Просмотреть счета за выбранный месяц', 'edit' => 'Редактировать', 'see_payment' => 'Платеж', 'download' => 'Скачать', 'fine_id' => '№ штрафа ', 'fname' => 'Полное имя', 'reason' => 'Причина', 'sum' => 'Сумма', 'fine_change' => 'Изменить данные штрафа', 'sum_left' => 'Сумма штрафа (оставить пустым, если предупреждение)', 'fine_add' => 'Добавить штраф', 'fine_add_new' => 'Добавить новый штраф', 'type' => 'Тип', 'username' => '<NAME>', 'ada' => 'Добавить/удалить квартиру', 'inh_no' => 'У этого жильца нет аккаунта', 'add' => 'Добавить', 'add_inh' => 'Добавить нового жильца', 'user_name' => 'Имя пользователя', 'user_email' => 'Email пользователя', 'user_connect' => 'Соединить жильца с пользователем', 'role_change' => 'Изменить права пользователя', 'role_add' => 'Сохранить', 'role_select' => 'Выберите роль', 'role' => 'Права', 'user_not_connected' => 'Пользователь не соединен с жильцом', 'inh_no_acc' => 'Не соединен с пользователем', 'area' => 'Площадь', 'floor' => 'Этаж', 'app_change' => "Изменить данные квартиры", 'change_status' => 'Изменить статус', 'change' => 'Изменить', ]; <file_sep>/app/Http/Controllers/BillController.php <?php namespace App\Http\Controllers; use App\Models\Apartment; use App\Models\ApartmentInhabitant; use App\Models\Bill; use App\Models\BillStatus; use App\Models\Inhabitant; use App\Models\Meter; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Barryvdh\DomPDF\Facade as PDF; class BillController extends Controller { public function __construct() { $this->middleware('admin')->only(['listBills', 'makeBillView', 'setBills', 'editBill', 'setBillEdit', 'downloadBill']); $this->middleware('tenant')->only(['index', 'showUploadFile', 'download']); } public function index() { $user = auth()->user()->id; $inhabitant = Inhabitant::where('user_id', $user)->first(); if(isset($inhabitant->id)) { $inhabitant = $inhabitant->id; $apps = ApartmentInhabitant::where('inhabitant_id', $inhabitant)->get(); $apps_numbers = array(); foreach($apps as $app) { array_push($apps_numbers, $app->apartment_id); } $queries = array(); foreach($apps_numbers as $number) { array_push($queries, Bill::where('apartment_id', $number)->get()); } return view('/tenant/bill', ['apps' => $apps, 'numbers' => $apps_numbers, 'js' => $queries]); } return view('/general/error'); } public function showUploadFile(Request $request) { $rules = array( 'bill' => 'required|mimetypes:application/pdf', ); $this->validate($request, $rules); $file = $request->file('bill'); $bill_id = $request->billid.'.pdf'; $bill = Bill::where('id', $request->billid)->first(); $bill->bill_status_id = 4; $bill->save(); $file->storeAs('/public/uploads/bills', $bill_id); return redirect()->action('BillController@index'); } public function download(Request $request) { $bill = Bill::where('id', $request->billid)->first(); $appartment = Apartment::where('id', $bill->apartment_id)->first(); $inh = Inhabitant::where('user_id' ,auth()->user()->id) ->first(); $name = 'Bill_'.$request->billid.'.pdf'; $path = public_path('img/1.jpg'); $type = pathinfo($path, PATHINFO_EXTENSION); $datai = file_get_contents($path); $base64 = 'data:image/' . $type . ';base64,' . base64_encode($datai); $data = [ 'bill' => $bill, 'appartment' => $appartment, 'inh' => $inh, 'name' => $name, 'pic' => $base64 ]; $pdf = PDF::loadView('/tenant/pdf/bill', $data); return $pdf->download($name); } /*Admin*/ public function listBills(Request $request) { $bills = Bill::orderBy('created_at', 'desc')->get(); return view ('/admin/bill_management/billist_view', ['bills' => $bills]); } public function makeBillView() { return view ('/admin/bill_management/bill'); } public function setBills(Request $request) { $rules = array( 'admsum' => 'required|numeric', 'admsummeter' => 'required|numeric', 'hot' => 'required|numeric', 'cold' => 'required|numeric', 'heat' => 'required|numeric', ); $this->validate($request, $rules); $apps = Apartment::all(); foreach($apps as $app) { $bill = new Bill(); $bill->apartment_id = $app->id; $bill->cost_per_m2 = ($app->area_m2 * $request->admsum); $bill->management_cost = ($app->area_m2 * $request->admsummeter); $sum_utilities = 0; $month = date("m",strtotime($request->date)); $year = date("Y",strtotime($request->date)); for ($i = 1; $i < 4; $i++) { $meter_last = Meter::where('apartment_id', '=', $app->id) ->where('meter_type_id', '=', $i) ->whereMonth('created_at', '=', $month) ->whereYear('created_at', '=', $year) ->orderBy('created_at', 'desc')->first(); $meter_prev = Meter::where('apartment_id', '=', $app->id)->where('meter_type_id', '=', $i)->orderBy('created_at', 'desc')->skip(1)->take(1)->first(); if($meter_last == NULL || $meter_prev == NULL) { $average = Bill::avg('total_meters_cost'); $sum_utilities = $average; break; } $meter_total = $meter_last->amount - $meter_prev->amount; if ($i == 1) { $sum_utilities+= $meter_total*$request->cold; } if ($i == 2) { $sum_utilities+= $meter_total*$request->hot; } if ($i == 3) { $sum_utilities+= $meter_total*$request->heat; } } $bill->total_meters_cost = $sum_utilities; $bill->bill_status_id = 1; $bill->created_at = $request->date; $bill->save(); } return redirect()->action('BillController@listBills'); } public function editBill($id) { $status = BillStatus::all(); $status = $status->pluck('name', 'id'); return view ('/admin/bill_management/bill_edit', ['bill' => Bill::where('id', $id)->first(), 'status' => $status]); } public function setBillEdit(Request $request) { $rules = array( 'admsum' => 'required|numeric', 'admsummeter' => 'required|numeric', 'total' => 'required|numeric', 'status' => 'required', ); $this->validate($request, $rules); $bill = Bill::where('id', $request->billid)->first(); $bill->cost_per_m2 = $request->admsum; $bill->management_cost = $request->admsummeter; $bill->total_meters_cost = $request->total; $bill->bill_status_id=$request->status; $bill->save(); //return view ('/admin/bill_management/billist_view', ['bills' => $bills]); return redirect()->action('BillController@listBills'); } public function downloadBill(Request $request) { $path = '/public/uploads/bills/'.$request->billid.'.pdf'; return Storage::download($path); } } <file_sep>/app/Http/Controllers/FineController.php <?php namespace App\Http\Controllers; use App\Models\Fine; use App\Models\FineReason; use App\Models\FineStatus; use App\Models\Inhabitant; use Illuminate\Http\Request; use Illuminate\Support\Carbon; use Barryvdh\DomPDF\Facade as PDF; class FineController extends Controller { public function __construct() { $this->middleware('admin')->only(['finesView', 'addFinesView', 'postSearch', 'fineShow', 'setFine', 'editFine', 'deleteFine', 'setFineEdit', 'editFineStatus', 'setFineStatus']); $this->middleware('tenant')->only(['index', 'download']); } /*Tenant*/ public function index() { $user = auth()->user()->id; $inh = Inhabitant::where('user_id', $user)->first(); return view('/tenant/fines', array('fines' => Fine::where('inhabitant_id', $inh->id)->orderBy('id', 'desc')->get())); //return view('/fines', array('fines' => Fine::where('status_id')->get())); } public function download(Request $request) { $fine = Fine::where('id', $request->fineid)->first(); $inhabitant = Inhabitant::where('id', $fine->inhabitant_id)->first(); $reason = FineReason::where('id', $fine->fine_reason_id)->first(); $name = 'Fine_'.$request->fineid.'.pdf'; $path = public_path('img/1.jpg'); $type = pathinfo($path, PATHINFO_EXTENSION); $datai = file_get_contents($path); $base64 = 'data:image/' . $type . ';base64,' . base64_encode($datai); $data = [ 'fine' => $fine, 'inhabitant' => $inhabitant, 'reason' => $reason, 'name' => $name, 'pic' => $base64 ]; $pdf = PDF::loadView('/tenant/pdf/fine', $data); return $pdf->download($name); } /*Admin*/ public function finesView() { $n = Fine::orderBy('updated_at', 'desc')->paginate(10); return view('/admin/fine_management/fines', array('fines' => $n)); } public function addFinesView() { return view('/admin/fine_management/fines_add'); } public function postSearch(Request $request) { return Inhabitant::where('name', 'LIKE', '%'.$request->get('search').'%') ->orWhere('surname', 'LIKE', '%'.$request->get('search').'%')->get(); } public function fineShow($id) { $reason = FineReason::all(); $reason = $reason->pluck('name', 'id'); return view('/admin/fine_management/fine_info', ['status' => $reason, 'inh' => Inhabitant::where('id', $id)->first()]); } public function setFine(Request $request) { $rules = array( 'status' => 'required', 'fsum' => 'numeric|nullable', ); $this->validate($request, $rules); $fine = new Fine(); $fine->inhabitant_id = $request->inhid; $fine->fine_reason_id = $request->status; $fine->sum = $request->fsum; if($request->fsum == NULL) { $fine->fine_status_id = 3; } else{ $fine->fine_status_id = 1; } $fine->save(); return redirect()->action('FineController@finesView'); // return view('/admin/fines', array('fines' => Fine::orderBy('status_id')->get())); } public function editFine($id) { $reason = FineReason::all(); $reason = $reason->pluck('name', 'id'); return view('/admin/fine_management/editfine', ['fine' => Fine::where('id', $id)->first(), 'status' => $reason]); } public function deleteFine(Request $request) { Fine::where('id',$request->fineid)->delete(); return redirect()->action('FineController@finesView'); // $n = Fine::orderBy('updated_at', 'desc')->paginate(10); // return view('/admin/fines', array('fines' => $n)); } public function setFineEdit(Request $request) { $rules = array( 'status' => 'required', 'fs' => 'numeric|nullable', ); $this->validate($request, $rules); $fine = Fine::where('id', $request->fineid)->first(); $fine->fine_reason_id = $request->status; $fine->sum = $request->fs; $fine->updated_at = Carbon::now(); if($request->fs == NULL) { $fine->fine_status_id = 3; } else { $fine->fine_status_id = 1; } $fine->save(); return redirect()->action('FineController@finesView'); //$n = Fine::orderBy('updated_at', 'desc')->paginate(10); //return view('/admin/fines', array('fines' => $n)); } public function editFineStatus($id) { $status = FineStatus::all(); $status = $status->pluck('name', 'id'); return view('/admin/fine_management/editfine_status', ['fine' => Fine::where('id', $id)->first(), 'status' => $status]); } public function setFineStatus(Request $request) { $rules = array( 'status' => 'required', ); $this->validate($request, $rules); $fine = Fine::where('id', $request->fineid)->first(); $fine->fine_status_id = $request->status; $fine->save(); $n = Fine::orderBy('updated_at', 'desc')->paginate(10); return view('/admin/fine_management/fines', array('fines' => $n)); return redirect()->action('FineController@finesView'); } } <file_sep>/app/Models/Fine.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Fine extends Model { use HasFactory; public function fineReason(){ return $this->belongsTo(FineReason::class); } public function fineStatus(){ return $this->belongsTo(FineStatus::class); } public function inhabitant(){ return $this->belongsTo(Inhabitant::class); } } <file_sep>/resources/lang/en/inh_messages.php <?php /*EN*/ return [ /*Bill*/ 'app_no' => 'App. no', 'bill_id' => 'Bill ID', 'renovation' => 'Renovation', 'man_cost' => 'Man. Cost', 'reserve' => 'Reserve funds', 'total' => 'Total', 'status' => 'Status', 'upload_file' => 'Upload File', /*Fines*/ 'name' => 'Full name', 'reason' => 'Reason', 'sum' => 'Sum', 'invoice' => 'Invoice PDF', 'download' => 'Download PDF', 'list_fines' => 'List of fines', /*Appartment*/ 'app_no_full' => 'Number of appartment', 'area' => 'Area', 'floor' => 'floor', 'denial' => "You don't have appartment connected with your account", 'email' => 'Email notifications', 'confirm' => 'Confirm', /*Notifications*/ 'ntf_create' => 'Create new notification', 'ntf_delete' => 'Delete notification', 'ntf_edit' => 'Edit notification', 'ntf_author' => 'Author', 'ntf_date' => 'Date', 'ntf_type' => 'Type', 'ntf_add_new' => 'Add new notification', 'ntf_header' => 'Header', 'ntf_body' => 'Notification Body Text', 'ntf_visibility' => 'Visibility', 'ntf_create_new' => 'Create', 'ntf_apply' => 'Apply changes', 'lang' => 'Language', 'bill_pdf' => 'Bill PDF', ]; <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('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); #Route::get('/home', [HomeController, 'index'])->name('home'); ###ADMIN routes /*User management routes*/ Route::get('/admin/users', 'UserController@adminUsersView'); Route::get('/admin/users/{id}/change_role', 'UserController@adminUsersRoleShow'); Route::post('/admin/users/{id}/change_role', 'UserController@setRole'); Route::get('/admin/users/set_inh', 'UserController@assignInh'); Route::post('/admin/users/set_inh', 'UserController@setUser'); /*Inhabitant management*/ Route::get('/admin/addinh', 'InhabitantController@addInhView'); Route::post('/admin/addinh', 'InhabitantController@addInh'); Route::get('/admin/inhabitants', 'InhabitantController@adminInhabitantView'); Route::get('/admin/inhabitants/{id}', 'InhabitantController@connectWithInh'); Route::post('/admin/inhabitants/{id}', 'InhabitantController@connectWithInh'); Route::delete('/admin/inhabitants/{id}', 'InhabitantController@destroyInhApp'); Route::match(['get', 'post'],'/admin/inhabitants/{id}/extra', 'InhabitantController@addInhApp'); /*Apartment management*/ Route::get('/admin/apartments', 'ApartmentController@adminApartmentView'); //Route::post('/admin/apartments', 'ApartmentController@adminApartmentView'); Route::post('/admin/apartments/{id}', 'ApartmentController@editApartmentView'); Route::get('/admin/apartments/{id}', 'ApartmentController@editApartmentView'); Route::match(['get', 'post'],'/admin/apartments/data/save', 'ApartmentController@saveApartmentView'); /*Fines - routes under admin middleware*/ Route::get('/admin/fines', 'FineController@finesView'); Route::get('/admin/fines/add', 'FineController@addFinesView'); Route::post('/admin/fines/add', 'FineController@postSearch'); Route::get('/admin/fines/add/{id}', 'FineController@fineShow'); Route::match(['get', 'post'],'/admin/fines/list', 'FineController@setFine'); Route::post('/admin/fines/edit/{id}', 'FineController@editFine'); Route::get('/admin/fines/edit/{id}', 'FineController@editFine'); Route::match(['get', 'post'],'/admin/fines/delete', 'FineController@deleteFine'); Route::match(['get', 'post'], '/admin/fines/edit', 'FineController@setFineEdit'); Route::post('/admin/fines/edit/status/{id}', 'FineController@editFineStatus'); Route::get('/admin/fines/edit/status/{id}', 'FineController@editFineStatus'); Route::match(['get', 'post'], '/admin/fines/status', 'FineController@setFineStatus'); /*Meters */ Route::get('/admin/meters', 'MeterController@adminMeterView'); Route::match(['get', 'post'],'/uploadfile','MeterController@uploadFile'); Route::post('/admin/meters/edit/{id}', 'MeterController@editMeter'); Route::get('/admin/meters/edit/{id}', 'MeterController@editMeter'); Route::match(['get', 'post'], '/admin/meters/edit', 'MeterController@setMeterEdit'); /*Notifications*/ Route::get('/notifications', 'NotificationController@see'); Route::match(['get', 'post'], '/notifications/delete', 'NotificationController@delete'); Route::post('/notifications/edit/{id}', 'NotificationController@edit'); Route::match(['get', 'post'], '/notifications/save', 'NotificationController@save'); Route::post('/notifications/add', 'NotificationController@addNewView'); Route::match(['get', 'post'],'/notifications/added', 'NotificationController@addNew'); Route::get('/notifications/add', 'NotificationController@addNewView'); Route::get('/notifications/edit/{id}', 'NotificationController@edit'); /*Bills*/ Route::match(['get', 'post'],'/admin/bills', 'BillController@listBills'); Route::match(['get', 'post'],'/admin/bill/add', 'BillController@makeBillView'); Route::match(['get', 'post'],'/admin/bills/set', 'BillController@setBills'); Route::match(['get', 'post'],'/admin/bills/edit/{id}', 'BillController@editBill'); Route::match(['get', 'post'],'/admin/bills/edit', 'BillController@setBillEdit'); Route::match(['get', 'post'],'/admin/bills/download', 'BillController@downloadBill'); ###LOCALIZATION routes /*Localization - according to NFR*/ Route::get('lang/{locale}', 'LanguageController'); /*General*/ Route::get('/', 'NotificationController@index'); /*Tenant*/ Route::get('/appartment', 'ApartmentController@index'); Route::match(['get', 'post'],'/appartment/email', 'ApartmentController@email'); Route::get('/fines', 'FineController@index'); Route::match(['get', 'post'],'/fines/pdf', 'FineController@download'); Route::get('/bills', 'BillController@index'); Route::match(['get', 'post'],'/uploadbill','BillController@showUploadFile'); Route::match(['get', 'post'],'/bills/pdf', 'BillController@download'); <file_sep>/app/Models/Meter.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Meter extends Model { use HasFactory; public function meterType(){ return $this->belongsTo(MeterType::class); } public function apartment(){ return $this->belongsTo(Apartment::class); } } <file_sep>/app/Models/ApartmentInhabitant.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class ApartmentInhabitant extends Model { use HasFactory; protected $table = 'apartment_inhabitants'; public $timestamps = false; public function apartment() { return $this->belongsTo(Apartment::class); } public function inhabitants() { return $this->belongsTo(Inhabitant::class); } } <file_sep>/resources/lang/en/adm_messages.php <?php /*EN*/ return [ 'name' => 'Name', 'surname' => 'Surname', 'pk' => 'Personal code', 'app_no' => 'Appartment no.', 'inh_no' => 'Inhabitant no.', 'status' => 'Status', 'del' => 'Delete', 'app' => 'Appartment', 'connect' => 'Add connection', 'bill_new' => 'Make new bill', 'month' => 'Month', 'ac_per_app' => 'Administrative cost per app', 'ac_per_m2' => 'Administrative cost per m2', 'reserve' => 'Reserve funds', 'renovation' => 'Renovation', 'bill_create' => 'Create bill for all appartments', 'bill_see' => 'See bill list', 'bill_id' => 'Bill ID', 'rts' => 'Renovation type and sum', 'mc' => 'Management cost', 'total' => 'Total', 'bill_status' => 'Bill status', 'change_data' => 'Change data', 'bill_change' => 'Change bill data', 'bill_all' => 'All bills', 'bill_month' => 'See bills for this month', 'edit' => 'Edit', 'see_payment' => 'See payment', 'download' => 'Download', 'fine_id' => 'Fine ID', 'fname' => 'Full name', 'reason' => 'Reason', 'sum' => 'Sum', 'fine_change' => 'Change fine data', 'sum_left' => 'Sum of fine (if warning - left empty)', 'fine_add' => 'Add fine', 'fine_add_new' => 'Add new fine', 'type' => 'Type', 'username' => 'Username', 'ada' => 'Add/delete appartments', 'inh_no' => 'This inhabitant does not have account', 'add' => 'Add entry', 'add_inh' => 'Add new inhabitant', 'role_change' => 'Change user role', 'role_add' => 'Save role', 'user_name' => 'Username', 'user_email' => 'User email', 'user_connect' => 'Connect inhabitant with user', 'role_select' => 'Select role', 'role' => 'Role', 'user_not_connected' => 'User not associated with inhabitant', 'inh_no_acc' => 'Not connected to user', 'area' => 'Area', 'floor' => 'Floor', 'app_change' => "Change apartment's data", 'change_status' => 'Change status', 'change' => 'Change', ]; <file_sep>/database/seeders/DatabaseSeeder.php <?php namespace Database\Seeders; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { /* \App\Models\Role::create(array('name' => 'Admin')); \App\Models\Role::create(array('name' => 'User')); \App\Models\Role::create(array('name' => 'Inhabitant')); \App\Models\Role::create(array('name' => 'Privileged user')); \App\Models\Role::create(array('name' => 'Blocked')); \App\Models\User::create(array('name' => 'Administrator', 'email' => '<EMAIL>', 'password' => <PASSWORD>('<PASSWORD>'), 'email_notifications' => True, 'role_id' => 1)); \App\Models\NotificationType::create(array('name' => 'Public', 'description' => 'Any visitor will see the announcement')); \App\Models\NotificationType::create(array('name' => 'House', 'description' => 'Only Inhabitant, Privileged user and Admin will see the announcement')); \App\Models\Language::create(array('name' => 'English', 'language_code' => 'en')); \App\Models\Language::create(array('name' => 'Russian', 'language_code' => 'ru')); \App\Models\FineStatus::create(array('name' => 'Issued', 'description' => 'Fine with sum that is issued')); \App\Models\FineStatus::create(array('name' => 'Paid', 'description' => 'Fine, that was paid by inhabitant')); \App\Models\FineStatus::create(array('name' => 'Warning', 'description' => 'Fine without the sum to be paid')); \App\Models\FineStatus::create(array('name' => 'Cancelled', 'description' => 'Fine that is cancelled due to some reason, but not deleted')); \App\Models\FineReason::create(array('name' => 'Broken property', 'description' => 'Broken property in house')); \App\Models\FineReason::create(array('name' => 'Unconfirmed renovation', 'description' => 'Renovation without notifying managing company')); \App\Models\FineReason::create(array('name' => 'Dangerous items', 'description' => 'Storing potentially dangerous items')); \App\Models\FineReason::create(array('name' => 'Unappropriate behavior', 'description' => 'Any kind of loud/drunk/etc. behavior')); \App\Models\FineReason::create(array('name' => 'Being in restricted zones', 'description' => 'Walking over lawn, etc.')); \App\Models\FineReason::create(array('name' => 'Smoking', 'description' => 'Smoking nearer 10m to the house')); \App\Models\BillStatus::create(array('name' => 'Sent', 'description' => 'Bill is sent to the inhabitant, yet no payment confirmation is received')); \App\Models\BillStatus::create(array('name' => 'Paid', 'description' => 'Bill is paid and no more actions are needed')); \App\Models\BillStatus::create(array('name' => 'Underpaid', 'description' => 'Bill is partially paid')); \App\Models\BillStatus::create(array('name' => 'Waiting for confirmation', 'description' => 'Payment confirmation has been uploaded, but no decision made yet')); \App\Models\BillStatus::create(array('name' => 'Overdue', 'description' => 'Bill is not paid in the time')); \App\Models\MeterType::create(array('name' => 'Cold water')); \App\Models\MeterType::create(array('name' => 'Hot water')); \App\Models\MeterType::create(array('name' => 'Heating')); \App\Models\Apartment::create(array('number' => 1,'area_m2' => 32.20,'floor' => 1)); \App\Models\Apartment::create(array('number' => 24,'area_m2' => 56.45,'floor' => 2)); \App\Models\Apartment::create(array('number' => 52,'area_m2' => 66.51,'floor' => 3)); \App\Models\Apartment::create(array('number' => 58,'area_m2' => 82.88,'floor' => 4)); \App\Models\Apartment::create(array('number' => 82,'area_m2' => 106.22,'floor' => 5)); \App\Models\Meter::create(array('amount' => 555.26,'verified_till' => '2021/12/17', 'meter_type_id' => 1, 'apartment_id' => 1)); \App\Models\Meter::create(array('amount' => 315.44,'verified_till' => '2021/12/17', 'meter_type_id' => 2, 'apartment_id' => 1)); \App\Models\Meter::create(array('amount' => 22659.65,'verified_till' => '2020/12/15', 'meter_type_id' => 3, 'apartment_id' => 1)); \App\Models\Meter::create(array('amount' => 555.26,'verified_till' => '2021/12/17', 'meter_type_id' => 1, 'apartment_id' => 2)); \App\Models\Meter::create(array('amount' => 315.44,'verified_till' => '2021/12/17', 'meter_type_id' => 2, 'apartment_id' => 2)); \App\Models\Meter::create(array('amount' => 22659.65,'verified_till' => '2020/12/15', 'meter_type_id' => 3, 'apartment_id' => 2)); \App\Models\Meter::create(array('amount' => 0.00,'verified_till' => '2021/12/17', 'meter_type_id' => 1, 'apartment_id' => 3)); \App\Models\Meter::create(array('amount' => 0.00,'verified_till' => '2021/12/17', 'meter_type_id' => 2, 'apartment_id' => 3)); \App\Models\Meter::create(array('amount' => 0.00,'verified_till' => '2020/12/15', 'meter_type_id' => 3, 'apartment_id' => 3)); \App\Models\Meter::create(array('amount' => 115.59,'verified_till' => '2021/12/17', 'meter_type_id' => 1, 'apartment_id' => 4)); \App\Models\Meter::create(array('amount' => 105.99,'verified_till' => '2021/12/17', 'meter_type_id' => 2, 'apartment_id' => 4)); \App\Models\Meter::create(array('amount' => 659.65,'verified_till' => '2020/12/15', 'meter_type_id' => 3, 'apartment_id' => 4)); \App\Models\Meter::create(array('amount' => 555.26,'verified_till' => '2021/12/17', 'meter_type_id' => 1, 'apartment_id' => 5)); \App\Models\Meter::create(array('amount' => 315.44,'verified_till' => '2021/12/17', 'meter_type_id' => 2, 'apartment_id' => 5)); \App\Models\Meter::create(array('amount' => 22659.65,'verified_till' => '2020/12/15', 'meter_type_id' => 3, 'apartment_id' => 5)); \App\Models\Meter::create(array('amount' => 555.26,'verified_till' => '2021/12/17', 'meter_type_id' => 1, 'apartment_id' => 5)); \App\Models\Meter::create(array('amount' => 315.44,'verified_till' => '2021/12/17', 'meter_type_id' => 2, 'apartment_id' => 5)); \App\Models\Meter::create(array('amount' => 22659.65,'verified_till' => '2020/12/15', 'meter_type_id' => 3, 'apartment_id' => 5)); */ \App\Models\Meter::create(array('amount' => 562.26,'verified_till' => '2021/12/17', 'meter_type_id' => 1, 'apartment_id' => 1)); \App\Models\Meter::create(array('amount' => 320.44,'verified_till' => '2021/12/17', 'meter_type_id' => 2, 'apartment_id' => 1)); \App\Models\Meter::create(array('amount' => 22759.65,'verified_till' => '2020/12/15', 'meter_type_id' => 3, 'apartment_id' => 1)); \App\Models\Meter::create(array('amount' => 580.26,'verified_till' => '2021/12/17', 'meter_type_id' => 1, 'apartment_id' => 2)); \App\Models\Meter::create(array('amount' => 345.44,'verified_till' => '2021/12/17', 'meter_type_id' => 2, 'apartment_id' => 2)); \App\Models\Meter::create(array('amount' => 22659.65,'verified_till' => '2020/12/15', 'meter_type_id' => 3, 'apartment_id' => 2)); \App\Models\Meter::create(array('amount' => 0.00,'verified_till' => '2021/12/17', 'meter_type_id' => 1, 'apartment_id' => 3)); \App\Models\Meter::create(array('amount' => 0.00,'verified_till' => '2021/12/17', 'meter_type_id' => 2, 'apartment_id' => 3)); \App\Models\Meter::create(array('amount' => 0.00,'verified_till' => '2020/12/15', 'meter_type_id' => 3, 'apartment_id' => 3)); \App\Models\Meter::create(array('amount' => 116.59,'verified_till' => '2021/12/17', 'meter_type_id' => 1, 'apartment_id' => 4)); \App\Models\Meter::create(array('amount' => 107.99,'verified_till' => '2021/12/17', 'meter_type_id' => 2, 'apartment_id' => 4)); \App\Models\Meter::create(array('amount' => 699.65,'verified_till' => '2020/12/15', 'meter_type_id' => 3, 'apartment_id' => 4)); \App\Models\Meter::create(array('amount' => 655.26,'verified_till' => '2021/12/17', 'meter_type_id' => 1, 'apartment_id' => 5)); \App\Models\Meter::create(array('amount' => 415.44,'verified_till' => '2021/12/17', 'meter_type_id' => 2, 'apartment_id' => 5)); \App\Models\Meter::create(array('amount' => 23659.65,'verified_till' => '2020/12/15', 'meter_type_id' => 3, 'apartment_id' => 5)); } } <file_sep>/app/Http/Controllers/NotificationController.php <?php namespace App\Http\Controllers; use App\Models\Notification; use App\Models\NotificationType; use App\Models\User; use Illuminate\Http\Request; class NotificationController extends Controller { public function __construct() { $this->middleware('privadmin')->only(['see', 'edit', 'delete', 'save', 'addNewView', 'addNew']); } public function index(Request $request) { $lang = $request->cookie('language'); if (isset($lang)) { if ($lang == 'en') { $lang = 1; } else { $lang = 2; } $n = Notification::where('language_id', $lang)->orderBy('id', 'desc')->paginate(5); $p = Notification::where('language_id', $lang)->where('notification_type_id',1)->orderBy('id', 'desc')->paginate(5); return view('general/index', ['notifications' => $n, 'publics' => $p, 'lang' => $lang]); } else { $n = Notification::where('language_id', 1)->orderBy('id', 'desc')->paginate(5); $p = Notification::where('language_id', 1)->where('notification_type_id',1)->orderBy('id', 'desc')->paginate(5); return view('general/index', ['notifications' => $n, 'publics' => $p, 'lang' => $lang]); } } public function see() { $role = User::where('id', auth()->user()->id) -> first(); if($role->role_id == 1) { $n = Notification::orderBy('id', 'desc')->paginate(5); return view('notification/notification_list', ['notifications' => $n]); } elseif($role->role_id == 4) { $n = Notification::where('user_id', auth()->user()->id)->orderBy('id', 'desc')->paginate(5); return view('notification/notification_list', ['notifications' => $n]); } } public function edit(Request $request, $id) { $type = NotificationType::all(); $type = $type->pluck('name', 'id'); $notification = Notification::where('id', $id)->first(); $user = auth()->user(); //$user = $notification->user(); if(!isset($notification)) { return view('general/error'); } if($user->role_id!=1 && $user->id != $notification->user_id) { return view('general/error'); } return view('notification/notification_edit', ['notification' => $notification, 'status' => $type]); } public function delete(Request $request) { Notification::where('id', $request->notid)->delete(); return redirect()->action('NotificationController@index'); } public function save(Request $request) { $rules = array( 'header' => 'required', 'message' => 'required', 'status' => 'required', ); $this->validate($request, $rules); $notification = Notification::where('id', $request->notid)->first(); $notification->header = $request->header; $notification->message = $request->message; $notification->notification_type_id = $request->status; $notification->save(); return redirect()->action('NotificationController@index'); } public function addNewView() { $type = NotificationType::all(); $type = $type->pluck('name', 'id'); return view('notification/notification_new', ['status' => $type]); } public function addNew(Request $request) { $rules = array( 'header' => 'required', 'message' => 'required', 'status' => 'required', 'lang' => 'required', ); $this->validate($request, $rules); $notification = new Notification(); $notification->header = $request->header; $notification->message = $request->message; $notification->notification_type_id = $request->status; $notification->language_id = $request->lang; $notification->user_id = auth()->user()->id; $notification->save(); return redirect()->action('NotificationController@index'); } } <file_sep>/resources/lang/ru/validation.php <?php return [ /*Bill*/ 'required' => 'Поле должно быть заполнено.', 'mimetypes' => 'Прикрепленный файл должен быть в формате: :values.', 'numeric' => 'Значение поля должно быть числом.', 'max' => [ 'string' => 'Число символов в поле не должно превышать :max .', ], 'regex' => 'Формат не соответстует.', 'unique' => 'Такое значение уже существует.', 'alpha_num' => 'Поле может содержать только буквы и цифры.', ]; <file_sep>/app/Http/Controllers/UserController.php <?php namespace App\Http\Controllers; use App\Models\ApartmentInhabitant; use App\Models\Inhabitant; use App\Models\Role; use App\Models\User; use Illuminate\Http\Request; class UserController extends Controller { public function __construct() { $this->middleware('admin')->only(['adminUsersView', 'adminUsersRoleShow', 'assignInh', 'setRole', 'setUser']); } public function adminUsersView() { return view('/admin/user_management/users', array('users' => User::orderBy('role_id')->get())); } public function adminUsersRoleShow($id, Request $request) { $user = User::where('id', $id)->first(); $roles = Role::all(); $roles = $roles->pluck('name', 'id'); return view('/admin/user_management/user_change', ['user' => $user,'role' => $roles]); } public function assignInh(Request $request) { $user = User::where('id', $request->userid)->first(); return view('/admin/user_management/inhabitant_assign', ['user' => $user, 'inhs' => Inhabitant::where('user_id', NULL)->get()]); } public function setRole(Request $request) { $rules = array( 'status' => 'required', ); $this->validate($request, $rules); $user = User::where('id', $request->userid)->first(); $user->role_id = $request->status; $user->save(); return view('/admin/user_management/users', array('users' => User::orderBy('role_id')->get())); } public function setUser(Request $request) { $inh = Inhabitant::where('id', $request->inhid)->first(); $inh->user_id = $request->userid; $inh->save(); return view('/admin/inhabitant_management/inhabitant', ['inhs' => Inhabitant::orderBy('user_id')->get(), 'app_inh' => ApartmentInhabitant::all()]); } } <file_sep>/resources/lang/ru/general_messages.php <?php /*RU*/ return [ 'appartment' => 'Квартира', 'about' => 'О нас', 'fines' => 'Штрафы', 'bills' => 'Счета', 'notifications' => 'Управление уведомлениями', 'admin' => 'Действия админа', 'roles' => 'Управление правами пользователей', 'man_inh' => 'Управление жильцами', 'add_inh' => 'Добавить нового жильца', 'man_bills' => 'Управление счетами', 'man_fines' => 'Управление штрафами', 'logout' => 'Выйти', 'login' => 'Войти', 'register' => 'Зарегистрироваться', 'dashboard' => 'Информация', 'logged_in' => ' Вы зашли как', 'with_name' => 'с именем', 'You_have' => 'У Вас', 'f_t' => 'штрафов за весь период.', 'f_m' => 'штрафов за последний месяц.', 'b_t' => 'неоплаченных счетов за все время.', 'register' => 'Зарегистрироваться', 'name' => '<NAME>', 'email' => 'Электронная почта', 'pass' => '<PASSWORD>', 'conf_pass' => 'Подтвер<PASSWORD>', 'remember' => 'Запомнить', 'forgot' => 'Забыли пароль?', 'Close_to_Sea' => 'Близко к морю!', 'Close_to_Sea_text' => 'Комплекс расположен на первой линии, близко к морю!', 'tour' => 'Заказать индивидуальный тур', 'project' => 'Новый уникальный проект!', 'project_text' => '84 квартиры на все вкусы!', 'location' => 'Расположение', 'project_new' => 'Новый проект', 'log' => 'Лог действий пользователя', 'user_management' => 'Управление пользователями', 'apartment_management' => 'Управление квартирами', 'man_meters' => 'Управление счетчиками', 'meters' => 'Счетчики', ]; <file_sep>/resources/lang/ru/inh_messages.php <?php /*RU*/ return [ /*Bill*/ 'app_no' => '№ кв.', 'bill_id' => '№ счета', 'renovation' => 'Реновация', 'man_cost' => 'Упр. расх.', 'reserve' => 'Резервный фонд', 'total' => 'Итого', 'status' => 'Статус', 'upload_file' => 'Загрузить файл', /*Fines*/ 'name' => 'Полное имя', 'reason' => 'Причина', 'sum' => 'Сумма', 'invoice' => 'Счет в PDF', 'download' => 'Скачать PDF', 'list_fines' => 'Список штрафов', /*Appartment*/ 'app_no_full' => 'Номер квартиры', 'area' => 'Площадь', 'floor' => 'Этаж', 'denial' => "У Вашего аккаунта нет квартиры", 'email' => 'Получать уведомления по электронной почте', 'confirm' => 'Подтвердить', /*Notifications*/ 'ntf_create' => 'Создать уведомление', 'ntf_delete' => 'Удалить уведомление', 'ntf_edit' => 'Редактировать уведомление', 'ntf_author' => 'Автор', 'ntf_date' => 'Дата', 'ntf_type' => 'Тип', 'ntf_add_new' => 'Добавить новое уведомление', 'ntf_header' => 'Заголовок', 'ntf_body' => 'Основной текст', 'ntf_visibility' => 'Видимость', 'ntf_create_new' => 'Создать', 'ntf_apply' => 'Сохранить изменения', 'lang' => 'Язык', 'bill_pdf' => 'Счет в PDF', ]; <file_sep>/app/Http/Controllers/MeterController.php <?php namespace App\Http\Controllers; use App\Models\Meter; use Illuminate\Http\Request; use Illuminate\Support\Carbon; class MeterController extends Controller { public function __construct() { $this->middleware('admin')->only(['adminMeterView', 'uploadFile', 'editMeter', 'setMeterEdit']); } public function adminMeterView() { return view('/admin/meter_management/meters', ['meters' => Meter::orderBy('created_at', 'desc')->get()]); } public function upload() { return view('uploadfile'); } public function uploadFile(Request $request) { $rules = array( 'meter' => 'required|mimetypes:application/pdf', ); $this->validate($request, $rules); $file = $request->file('meter'); $time = Carbon::today()->toDateString(); $meter = Meter::where('id', $request->meterid)->first(); $meter_id = $meter->apartment->number.'_'.$time.'_'.$meter->meterType->name.'.pdf'; $meter->verified_till = $time; $meter->save(); $file->storeAs('/public/uploads/verifications', $meter_id); return view('/admin/meter_management/meters', ['meters' => Meter::orderBy('created_at')->get()]); return redirect()->action('MeterController@adminMeterView'); } public function editMeter($id) { return view('/admin/meter_management/meter_edit', ['meter' => Meter::where('id', $id)->first()]); } public function setMeterEdit(Request $request) { $rules = array( 'amount' => 'required|numeric', 'date' => 'required', ); $this->validate($request, $rules); $meter = Meter::where('id', $request->meterid)->first(); $meter->amount = $request->amount; $meter->verified_till = $request->date; $meter->updated_at = Carbon::now(); $meter->save(); $apart_id = $meter->apartment_id; $meter_type = $meter->meter_type_id; Meter::where('apartment_id', $apart_id)->where('meter_type_id', $meter_type)->update(['verified_till' => $request->date]); return redirect()->action('MeterController@adminMeterView'); } } <file_sep>/app/Models/Bill.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Bill extends Model { use HasFactory; public function billStatus(){ return $this->belongsTo(BillStatus::class); } public function apartment(){ return $this->belongsTo(Apartment::class); } }
db62e2cb62408f8922f8b572666cc0ee3f8dcbb2
[ "PHP" ]
20
PHP
Raging-Tiger/SE_project
1b6f57591c0be2ae2a6f95d03cc5cb0ed7247bf1
4676ec7a79a111f7a487929c6b61435c3d3f8ac4
refs/heads/master
<repo_name>blackspherefollower/video-mre<file_sep>/src/app.ts /*! * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import * as MRE from '@microsoft/mixed-reality-extension-sdk'; /** * The main class of this app. All the logic goes here. */ export default class HelloWorld { private curve: MRE.Actor = null; private video: MRE.VideoStream = null; private assets: MRE.AssetContainer = null; private videoUrl: string = 'https://bitmovin-a.akamaihd.net/content/playhouse-vr/m3u8s/105560.m3u8'; constructor(private context: MRE.Context, private params: MRE.ParameterSet, private baseUrl: string) { this.context.onStarted(() => this.started()); const value = params["vs"]; if (typeof(value) === 'string') { this.videoUrl = decodeURIComponent(value); } else if (Array.isArray(value)) { this.videoUrl = decodeURIComponent(value[value.length - 1]); } } /** * Once the context is "started", initialize the app. */ private started() { // eslint-disable-next-line max-len // See https://github.com/microsoft/mixed-reality-extension-sdk/blob/master/packages/functional-tests/src/tests/livestream-test.ts this.assets = new MRE.AssetContainer(this.context); this.video = this.assets.createVideoStream("videoStream", { uri: this.videoUrl }); // Load a glTF model this.curve = MRE.Actor.CreatePrimitive(this.assets, { definition: { shape: MRE.PrimitiveShape.Box, dimensions: { z:1 } } }); this.curve.startVideoStream(this.video.id, { looping: true }); } }
ad3f3fde24621ecbb06e8c277c699850c486b1a1
[ "TypeScript" ]
1
TypeScript
blackspherefollower/video-mre
ce194aa5f3f359619c8694ab0d19987d5c8c822d
a3478691ab0e5fb31288ff52ff7e69b58be2d83d
refs/heads/master
<file_sep>using System; using System.Data.SqlClient; namespace Grau_James_991443203_Assignment_3 { public partial class Profile : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Check if there is no active session if (Session["signedIn"] == null || !Session["signedIn"].Equals("True")) { // Redirect the user to the login page as they're not logged in Response.Redirect("Default.aspx"); } // Set the database connection instance SqlConnection connection = new SqlConnection(Properties.Settings.Default.DBConnectionString); // Check if the page is being posted to if(IsPostBack) { // Store the form data into a collection System.Collections.Specialized.NameValueCollection frmData = Request.Form; // Check if year is not empty if(frmData["year"] == null || frmData["year"].Trim().Equals("")) { // Display error message placeOrderErrors.InnerText = "Oops... You forgot the fill in the year. Please try again."; placeOrderErrors.Attributes.Add("class", placeOrderErrors.Attributes["class"].Replace("d-none", "")); }else{ // Try and connection to the DB try { // Open the connection to the DB connection.Open(); // Create and set the needed variables SqlCommand command = new SqlCommand("INSERT INTO dbo.Orders (customer, brand, model, year, color, price) VALUES (@customer, @brand, @model, @year, @color, @price)", connection); command.Parameters.AddWithValue("@customer", Session["id"]); command.Parameters.AddWithValue("@brand", frmData["Brand"]); command.Parameters.AddWithValue("@model", frmData["Model"]); command.Parameters.AddWithValue("@year", frmData["Year"]); command.Parameters.AddWithValue("@color", frmData["Color"]); command.Parameters.AddWithValue("@price", frmData["Price"]); // Execute the query and insert into the database command.ExecuteNonQuery(); // Display the success Message and hide any error messages placeOrderErrors.InnerText = "Success! Your order has been placed!"; placeOrderErrors.Attributes.Add("class", "alert alert-success"); placeOrderErrors.Attributes.Add("class", placeOrderErrors.Attributes["class"].Replace("d-none", "")); }catch (Exception ex) { // Print Connection Error to DB // Display error message placeOrderErrors.InnerText = "Oops... Looks like something went wrong. Please try again. (" + ex.Message + ")"; placeOrderErrors.Attributes.Add("class", "alert alert-danger"); placeOrderErrors.Attributes.Add("class", placeOrderErrors.Attributes["class"].Replace("d-none", "")); placeOrderErrors.Attributes.Add("class", placeOrderErrors.Attributes["class"].Replace("success", "danger")); } finally{ // Close the connection to the database connection.Close(); } } } // Try and connect and get all customer orders try { // Open the connection to the DB connection.Open(); // Create and set the needed variables SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM dbo.ORDERS WHERE customer = @id", connection); command.Parameters.AddWithValue("@id", Session["id"]); // Store the count of returned items Int32 count = (Int32)command.ExecuteScalar(); // Check to make sure that there is more than 0 returned orders stored in the data table if (count > 0) { // Set the command to a new SQL Query and bind the customers id command = new SqlCommand("SELECT * FROM dbo.ORDERS WHERE customer = @id", connection); command.Parameters.AddWithValue("@id", Session["id"]); // Using the reader, perform the writing of data using (SqlDataReader reader = command.ExecuteReader()) { // Clear the list of Previous Orders previousOrders.InnerHtml = ""; // Loop through each returned item and add it to the list while (reader.Read()) { // Append the list item to the list previousOrders.InnerHtml = previousOrders.InnerHtml + "<div class='list-group-item flex-column align-items-start'><div class='d-flex w-100 justify-content-between'><h5 class='mb-1'>" + reader["year"] + " " + reader["brand"] + " " + reader["model"] + " ($" + Math.Round(double.Parse(reader["price"].ToString()), 2) + ") - " + reader["color"] + "</h5><time class='timeago' datetime='" + DateTime.Parse(reader["orderdate"].ToString()) + "'>" + DateTime.Parse(reader["orderdate"].ToString()) + "</time><small></small></div></div>"; } } }else{ // Add the message to display customer has no previous orders previousOrders.InnerHtml = "<div class='list-group-item flex-column align-items-start'><div class='d-flex w-100 justify-content-between'><h5 class='mb-1'>Oops... You don't have any Previous Orders.</h5></div></div>"; } } catch (Exception ex) { // Display error message previousOrders.InnerHtml = "<div class='list-group-item flex-column align-items-start'><div class='d-flex w-100 justify-content-between'><h5 class='mb-1'>Oops... Something happened. Please try again later (" + ex.Message + ").</h5></div></div>"; } finally { // Close the connection to the database connection.Close(); } } } }<file_sep>/** * * Date: July 26, 2018 * Author: <NAME> * Student Number: 991443203 * **/ // Include needed packages using System; using System.Data.SqlClient; namespace Grau_James_991443203_Assignment_3 { public partial class Registration : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Check if the page is being posted to if(IsPostBack) { // Store the form data into an array System.Collections.Specialized.NameValueCollection frmData = Request.Form; // Take the entered password and hash it using SHA-512 string passwordHash = (BitConverter.ToString(new System.Security.Cryptography.SHA512Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(frmData["Password"]))).Replace("-", "").ToLower()).ToString(); // Set the database connection instance SqlConnection connection = new SqlConnection(Properties.Settings.Default.DBConnectionString); // Try and check to make sure that, that user name is not taken try { // Open the connection to the DB connection.Open(); // Create and set the needed variables SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM dbo.Customers WHERE username = @username", connection); command.Parameters.AddWithValue("@username", frmData["UserName"]); Int32 count = (Int32)command.ExecuteScalar(); // Check to make sure that there is more than 0 returned users stored in the data table if (count > 0) { // Display email not matching error registrationAccountErrors.InnerText = "Oops... That username is already taken. Please try again."; registrationAccountErrors.Attributes.Add("class", registrationAccountErrors.Attributes["class"].Replace("d-none", "")); // Return out of validation return; } } catch(Exception ex) { // Print Connection Error to DB // Display error message registrationSuccess.InnerText = "Oops... Looks like something went wrong. Please try again. (" + ex.Message + ")"; registrationSuccess.Attributes.Add("class", "alert alert-danger"); registrationSuccess.Attributes.Add("class", registrationSuccess.Attributes["class"].Replace("d-none", "")); registrationSuccess.Attributes.Add("class", registrationSuccess.Attributes["class"].Replace("success", "danger")); } finally { // Close the connection to the database connection.Close(); } // Try and connection to the DB try { // Open the connection to the DB connection.Open(); // Create and set the needed variables SqlCommand command = new SqlCommand("INSERT INTO dbo.Customers (username, email, password, name, address, postalCode, phoneNumber) VALUES (@username, @email, @password, @name, @address, @postalcode, @phoneNumber)", connection); command.Parameters.AddWithValue("@username", frmData["UserName"]); command.Parameters.AddWithValue("@email", frmData["Email"]); command.Parameters.AddWithValue("@password", <PASSWORD>); command.Parameters.AddWithValue("@name", frmData["FullName"]); command.Parameters.AddWithValue("@address", frmData["Address"]); command.Parameters.AddWithValue("@postalCode", frmData["PostalCode"]); command.Parameters.AddWithValue("@phoneNumber", frmData["PhoneNumber"]); // Execute the query and insert into the database command.ExecuteNonQuery(); // Display the success Message and hide any error messages registrationSuccess.Attributes.Add("class", registrationSuccess.Attributes["class"].Replace("d-none", "")); registrationAccountErrors.Attributes.Add("class", "d-none"); }catch(Exception ex) { // Print Connection Error to DB // Display error message registrationSuccess.InnerText = "Oops... Looks like something went wrong. Please try again. (" + ex.Message + ")"; registrationSuccess.Attributes.Add("class", "alert alert-danger"); registrationSuccess.Attributes.Add("class", registrationSuccess.Attributes["class"].Replace("d-none", "")); registrationSuccess.Attributes.Add("class", registrationSuccess.Attributes["class"].Replace("success", "danger")); } finally{ // Close the connection to the database connection.Close(); } // Close the connection to the DB connection.Close(); } } } }<file_sep>/** * * Date: July 26, 2018 * Author: <NAME> * Student Number: 991443203 * **/ // Include needed packages using System; using System.Data.SqlClient; // This is the name space at which this file resides namespace Grau_James_991443203_Assignment_3 { // This the the Default pages class public partial class Default : System.Web.UI.Page { // This method is performed when the page is loaded protected void Page_Load(object sender, EventArgs e) { // Check if there is a set session if(Session["signedIn"] != null && Session["signedIn"].Equals("True")) { // Redirect the user to the profile page Response.Redirect("Profile.aspx"); } // Check if the page is being posted to if(IsPostBack) { // Store the form data into a collection System.Collections.Specialized.NameValueCollection frmData = Request.Form; // Set the database connection instance SqlConnection connection = new SqlConnection(Properties.Settings.Default.DBConnectionString); // Try and connection to the DB try { // Open the connection to the DB connection.Open(); // Create and set the needed variables SqlCommand command = new SqlCommand("SELECT * FROM dbo.Customers WHERE username = @username", connection); command.Parameters.AddWithValue("@username", frmData["UserName"]); // Execute the query and get the result(s) using (SqlDataReader reader = command.ExecuteReader()) { // Check to make sure that there is more than 0 returned users stored in the data table if (reader.HasRows) { // Check to make sure that the returned row has data if (reader.Read()) { // Take the entered password and hash it using SHA-512 string passwordHash = (BitConverter.ToString(new System.Security.Cryptography.SHA512Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(frmData["password"]))).Replace("-", "").ToLower()).ToString(); // Check to make sure that the entered password matches the DB password if (passwordHash.Equals(reader["password"])) { // Convert Error Message to success message loginErrors.InnerText = "Success! You are now being logged in!"; loginErrors.Attributes.Add("class", loginErrors.Attributes["class"].Replace("alert-danger", "alert-success")); loginErrors.Attributes.Add("class", loginErrors.Attributes["class"].Replace("d-none", "")); // Create the session variables Session.Add("signedIn", "True"); Session.Add("id", reader["id"].ToString()); Session.Add("name", reader["name"].ToString()); Session.Add("username", reader["username"].ToString()); Session.Add("email", reader["email"].ToString()); Session.Add("phoneNumber", reader["phoneNumber"].ToString()); Session.Add("address", reader["address"].ToString()); Session.Add("postalCode", reader["postalCode"].ToString()); // Move to the profile page Response.Redirect("Profile.aspx"); } else { // Display error message loginErrors.InnerText = "Oops... Your username/password cannot be validated. Please try again."; loginErrors.Attributes.Add("class", loginErrors.Attributes["class"].Replace("d-none", "")); } } } else { // Display error message loginErrors.InnerText = "Oops... Looks like that account is not registered. You can go ahead and register that account!"; loginErrors.Attributes.Add("class", "alert alert-danger"); loginErrors.Attributes.Add("class", loginErrors.Attributes["class"].Replace("d-none", "")); } } } catch (Exception ex) { // Print Connection Error to DB // Display error message loginErrors.InnerText = "Oops... Looks like something went wrong. Please try again. (" + ex.Message + ")"; loginErrors.Attributes.Add("class", "alert alert-danger"); loginErrors.Attributes.Add("class", loginErrors.Attributes["class"].Replace("d-none", "")); } finally { // Close the DB Connection connection.Close(); } } } } }<file_sep>/** * * Date: July 26, 2018 * Author: <NAME> * Student Number: 991443203 * **/ // Include needed packages using System; // This is the name space at which this file resides namespace Grau_James_991443203_Assignment_3 { // This the the Logouts class public partial class Logout : System.Web.UI.Page { // This method is performed when the user desides to logout protected void Page_Load(object sender, EventArgs e) { // Clean any Session variables Session.Clear(); // Redirect to the Default/login page Response.Redirect("Default.aspx"); } } }
2a690be8f23b3e7dd86f18ce58c9d0f76bfdde4e
[ "C#" ]
4
C#
backartificial/Grau_James_991443203_Assignment_3
710770fa8c2e18b41c11f3f1c759501499bb20b4
30be5b427926dfcd8f9c6e9e151ade568b5f800f
refs/heads/master
<repo_name>chungdeveloper/SubtitleConvert<file_sep>/nbproject/private/private.properties compile.on.save=true do.depend=false do.jar=true file.reference.hamcrest-core-1.3.jar=C:\\Users\\shoot\\Documents\\Project\\EclipseProject\\audiolib\\hamcrest-core-1.3.jar file.reference.jl1.0.jar=C:\\Users\\shoot\\Documents\\Project\\EclipseProject\\audiolib\\jl1.0.jar file.reference.jlayer-1.0.1.jar=C:\\Users\\shoot\\Documents\\Project\\EclipseProject\\audiolib\\jlayer-1.0.1.jar file.reference.junit-4.11.jar=C:\\Users\\shoot\\Documents\\Project\\EclipseProject\\audiolib\\junit-4.11.jar file.reference.mp3spi1.9.4.jar=C:\\Users\\shoot\\Documents\\Project\\EclipseProject\\audiolib\\mp3spi-1.9.4.jar file.reference.pdj.jar=C:\\Users\\shoot\\Documents\\Project\\EclipseProject\\audiolib\\pdj.jar file.reference.tritonus_aos.jar=C:\\Users\\shoot\\Documents\\Project\\EclipseProject\\audiolib\\tritonus_aos.jar file.reference.tritonus_share.jar=C:\\Users\\shoot\\Documents\\Project\\EclipseProject\\audiolib\\tritonus_share.jar javac.debug=true javadoc.preview=true user.properties.file=C:\\Users\\shoot\\AppData\\Roaming\\NetBeans\\8.2\\build.properties <file_sep>/src/audiotool/LyricTool.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package audiotool; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; /** * * @author MSi-Gaming */ public class LyricTool { private List<File> mFiles; private List<String> mCurrentLines; private Thread mMainThread; private OnLyricListener listener; public interface OnLyricListener { void onSuccess(String lyric); void onFail(String msg); } public LyricTool() { mFiles = new ArrayList<>(); mCurrentLines = new ArrayList<>(); } public void processInputFile(List<File> files, OnLyricListener listener) { this.listener = listener; mFiles.clear(); mFiles.addAll(files); mMainThread = new Thread(mMainRunnable); mMainThread.start(); } private Runnable mMainRunnable = new Runnable() { @Override public void run() { for (File file : mFiles) { processFile(file); } } }; private void processFile(File file) { try { listener.onSuccess(readFile(file)); } catch (Exception ex) { listener.onFail(file.getName() + " - fail: " + ex.toString()); } } private String readFile(File file) throws IOException { String uri; mCurrentLines.clear(); mCurrentLines.addAll(Files.readAllLines(file.toPath(), Charset.forName("UTF-8"))); // mCurrentLines.add("Dialogue: 0,0:00:40.83,0:00:42.05,Default,,0,0,0,,{\\k22}F: và {\\k31}đôi {\\k30}mắt {\\k39}em"); File dir = new File(file.getParent() + "/lyricTrans"); if (!dir.exists()) { dir.mkdir(); } uri = file.getParent() + "/lyricTrans/" + file.getName().replace(".ass", ".lrc"); PrintWriter writer = new PrintWriter(uri, "UTF-8"); boolean hasMissing = false; for (String line : mCurrentLines) { if (!line.startsWith("Dialogue")) { continue; } hasMissing = hasMissing ? hasMissing : (hasMissing = hasMissing(line)); writer.println(processLine(line)); } writer.close(); return uri + (hasMissing ? CONTENT_TAG : ""); } public static final String CONTENT_TAG = "[missing expected chungld]"; private boolean hasMissing(String line) { return line.split(",").length > 10; } private int startTime; private String processLine(String line) { String result; String[] entry = line.split(","); startTime = getTimeFromString(entry[1]); String content = getContentString(entry).replace("\\k", "");// entry[9].replace("\\k", ""); String[] contentEntry = content.split("\\{"); result = packageStartTime(getTimeFromInt(startTime)); for (String string : contentEntry) { result += processEntryWord(string); } System.out.println("result: " + result); return result; } private String getContentString(String[] entry) { if (entry.length < 10) { return ""; } String content = entry[9]; for (int i = 10; i < entry.length; i++) { content += "," + entry[i]; } return content; } private String processEntryWord(String entry) { String[] entries = entry.split("\\}"); if (!entries[0].equals("")) { startTime += convertStringToInt(entries[0]) * 10; } System.out.println("StartTime: " + startTime); if (entries.length < 2) { return ""; } return entries[1] + packageTimeEntry(getTimeFromInt(startTime)); } private String packageString(String value, String symbolS, String symbolE) { return symbolS + value + symbolE; } private String packageStartTime(String value) { return packageString(value, "[", "]"); } private String packageTimeEntry(String value) { return packageString(value, "<", ">"); } private int getTimeFromString(String time) { String[] times = time.split(":"); return convertStringToInt(times[0]) * 60 * 60 * 1000 + convertStringToInt(times[1]) * 60 * 1000 + convertStringToInt(times[2].replace(".", "") + "0"); } private String getTimeFromInt(int time) { float second = time * 1.0F / 1000; int millis = time % 1000; int minutes = (int) (second / 60); second = second % 60; return String.format("%02d:%02.03f", minutes, second/*, millis /*< 100 ? millis * 10 : millis*/); } private int convertStringToInt(String value) { return Integer.parseInt(value); } }
ad4951df5305c70ff31a10520bbd5be976878497
[ "Java", "INI" ]
2
INI
chungdeveloper/SubtitleConvert
e96083658ed575e84d3fee28df6053cc6a006f63
4eac5696ba0a3eccf7df02e176e962f3f0034a19
refs/heads/master
<repo_name>volumeskies/Vanilla-JavaScript-Quiz<file_sep>/README.md # Vanilla-JavaScript-Quiz Quiz using only HTML + CSS + JavaScript ## Live demo [Click here](https://volumeskies.github.io/Vanilla-JavaScript-Quiz/) :herb::herb::herb: <file_sep>/index.js (function(){ /* FROM START SCREEN TO QUIZ SCREEN */ var startButton = document.querySelector('[data-click="start"]'); startButton.addEventListener('click', function(){ //If clicking start button if(event.target.dataset.click === 'start'){ //Hiding start view elements var quizWrapper = document.querySelector('.Bussquiz'); quizWrapper.classList.add('Bussquiz-quiz'); quizWrapper.firstElementChild.style.display = 'none'; quizWrapper.firstElementChild.nextElementSibling.style.display = 'none'; //Showing quiz view elements var quizElements = document.getElementsByClassName('quiz'); for(let elem of quizElements){ if(elem.classList[0] === 'Bussquiz__choices'){ elem.style.display = 'flex'; continue; } elem.style.display = 'block'; } //Changing action button startButton.dataset.click = 'next'; startButton.textContent = 'Продолжить'; setQuizQuestion(); return; }//If clicking 'next question' button if(event.target.dataset.click === 'next'){ if(appQuiz.getCurrentQuestion() === 8){ event.target.dataset.click = 'refresh'; event.target.textContent = 'Пройти еще раз'; showResults(); return; } appQuiz.nextQuestion(); updateQuizQuestion(); return; } if(event.target.dataset.click === 'refresh'){ event.target.dataset.click = 'next'; event.target.textContent = 'Продолжить'; var images = document.querySelector('.result-bg'); images.parentNode.removeChild(images); var question = document.querySelector('.Bussquiz__question'); question.classList.toggle('Bussquiz__result'); var links = document.querySelector('.Bussquiz__link'); links.parentNode.removeChild(links); appQuiz.refresh(); updateQuizQuestion(); return; } }); /* QUIZ SCREEN */ //Function which handles answer button behavior function onAnswerButton(event){ event.preventDefault(); //Removing current button listener event.target.removeEventListener('click', onAnswerButton); event.target.disabled = 'true'; var parent = event.target.parentNode; var children = parent.children; //Removing others but current button children = Array.prototype.slice.call(children); children.forEach(function(child){ if(child.dataset.index !== event.target.dataset.index){ child.classList.add('hide'); } }); //Adding class according to result if(event.target.dataset.index === appQuestions.getQuestionCorrectAnswer(appQuiz.getCurrentQuestion())){ event.target.classList.add('success'); //If answer is right incrementing correct answers counter appQuiz.increaseCorrAnswCount(); } else event.target.classList.add('error'); //Showing comment var comment = document.createElement('div'); var choices = document.querySelector('.Bussquiz__choices'); comment.classList.add('Bussquiz__comment'); comment.innerHTML = appQuestions.getComment(appQuiz.getCurrentQuestion(), event.target.dataset.index); choices.after(comment); //Showing next question button var nextQuestionButton = document.querySelector('[data-click="next"]'); nextQuestionButton.style.display = 'block'; } function setQuizQuestion(){ var questionWrapper = document.querySelector('.Bussquiz__question'); var currentIndex = appQuiz.getCurrentQuestion(); questionWrapper.textContent = appQuestions.getQuestionByIndex(currentIndex); var questionCounter = document.querySelector('.Bussquiz__counter'); questionCounter.textContent = currentIndex + '/8'; var questionButtons = document.getElementsByClassName('Bussquiz__choice-button'); for(var i = 0; i < questionButtons.length; i++){ questionButtons[i].textContent = appQuestions.getAnswersByIndex(currentIndex)[i]; questionButtons[i].addEventListener('click', onAnswerButton); } } function createButton(){ var button = document.createElement('button'); button.classList.add('Bussquiz__choice-button'); return button; } function updateQuizQuestion(){ //Changing question text var questionWrapper = document.querySelector('.Bussquiz__question'); var currentIndex = appQuiz.getCurrentQuestion(); questionWrapper.textContent = appQuestions.getQuestionByIndex(currentIndex); //Changing questions counter var questionCounter = document.querySelector('.Bussquiz__counter'); questionCounter.textContent = currentIndex + '/8'; //Removing comment section var commentSection = document.querySelector('.Bussquiz__comment'); var commentParent = commentSection.parentNode; commentParent.removeChild(commentSection); //Adding listeners to choices buttons var questionButtons = document.getElementsByClassName('Bussquiz__choice-button'); for(var i = 0; i < questionButtons.length; i++){ questionButtons[i].classList.remove('hide', 'error', 'success'); questionButtons[i].disabled = false; questionButtons[i].textContent = appQuestions.getAnswersByIndex(currentIndex)[i]; questionButtons[i].addEventListener('click', onAnswerButton); } //Hiding next question button //Showing next question button var nextQuestionButton = document.querySelector('[data-click="next"]'); nextQuestionButton.style.display = 'none'; } /* RESULT SCREEN */ function showResults(){ //Hiding buttons var questionButtons = document.getElementsByClassName('Bussquiz__choice-button'); for(var i = 0; i < questionButtons.length; i++){ questionButtons[i].classList.add('hide'); questionButtons[i].disabled = true; } //Showing number of correct answers var counter = document.querySelector('.Bussquiz__counter'); counter.textContent = appQuiz.getCorrAnswCount() + ' из 8 правильных ответов'; //Hiding comment section var comment = document.querySelector('.Bussquiz__comment'); comment.classList.add('hide'); //Showing result message var question = document.querySelector('.Bussquiz__question'); question.classList.toggle('Bussquiz__result'); question.innerHTML = appResult.getResultComment(appQuiz.getCorrAnswCount()); //Showing result image var resultBg = document.createElement('div'); resultBg.classList.add(appResult.getImage(appQuiz.getCorrAnswCount()), 'result-bg'); counter.before(resultBg); //Showing links question.after(createLinksWrapper()); } function createLink(){ var link = document.createElement('a'); return link; } function createImage(){ var img = document.createElement('img'); return img; } function createLinksWrapper(){ var linksWrapper = document.createElement('div'); linksWrapper.classList.add('Bussquiz__link'); for(var i = 0; i < 3; i++){ var link = createLink(); var img = createImage(); switch(i){ case 0: link.classList.add('Bussquiz__link-facebook'); link.target = '_blank'; link.rel = 'noopener noreferrer'; link.href = 'https://youtu.be/dQw4w9WgXcQ'; img.src = './images/facebook.png'; link.append(img); link.innerHTML += 'Поделиться'; break; case 1: link.classList.add('Bussquiz__link-vk'); link.target = '_blank'; link.rel = 'noopener noreferrer'; link.href = 'https://youtu.be/dQw4w9WgXcQ'; img.src = './images/vk.png'; link.append(img); break; case 2: link.classList.add('Bussquiz__link-twitter'); link.target = '_blank'; link.rel = 'noopener noreferrer'; link.href = 'https://youtu.be/dQw4w9WgXcQ'; img.src = './images/twitter.png'; link.append(img); break; } linksWrapper.append(link); } return linksWrapper; } })();<file_sep>/sources/result.js var resultHandling = (function(){ var resultObj = { '0':{ comment: 'Мне больше<br>интересен футбол', image: 'imgAnswer1' }, '3':{ comment: 'Читаю vc.ru<br>с экрана попутчика в метро', image: 'imgAnswer2' }, '5':{ comment: 'Бизнес это интересно,<br> но где взять столько времени?', image: 'imgAnswer3' }, '7':{ comment: 'Читаю vc.ru каждый<br> день, но работать тоже нужно', image: 'imgAnswer4' }, '8':{ comment: 'Я работаю<br> в редакции vc.ru', image: 'imgAnswer5' } } function Result(){ this.constructor(resultObj); } Result.prototype = { results: undefined, constructor: function(){ this.results = JSON.parse(JSON.stringify(resultObj)); }, getResultComment: function(number){ if(number === 0) return this.results['0'].comment; if(number > 0 && number <= 3) return this.results['3'].comment; if(number > 3 && number <= 5) return this.results['5'].comment; if(number > 5 && number <= 7) return this.results['7'].comment; if(number === 8) return this.results['8'].comment; }, getImage: function(number){ if(number === 0) return this.results['0'].image; if(number > 0 && number <= 3) return this.results['3'].image; if(number > 3 && number <= 5) return this.results['5'].image; if(number > 5 && number <= 7) return this.results['7'].image; if(number === 8) return this.results['8'].image; } } return Result; })(); var appResult = new resultHandling();
b9f0bb6e9d36f106fc8c12008c8f74db37602df1
[ "Markdown", "JavaScript" ]
3
Markdown
volumeskies/Vanilla-JavaScript-Quiz
0fcfcfcfdac6c6b83571ed82e2023cb016a67800
95369bf7435d676313f632f14f2c7d899b8d05f2
refs/heads/master
<file_sep># GDot5-Real-Estate-System<file_sep>-- phpMyAdmin SQL Dump -- version 4.7.9 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Mar 28, 2018 at 12:57 PM -- Server version: 10.1.31-MariaDB -- PHP Version: 7.2.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `gdot5` -- -- -------------------------------------------------------- -- -- Table structure for table `accounttype` -- CREATE TABLE `accounttype` ( `AccTypeID` int(11) NOT NULL, `Name` varchar(255) NOT NULL, `PlanLevel` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `building` -- CREATE TABLE `building` ( `BuildingID` int(11) NOT NULL, `BuildingName` int(11) NOT NULL, `RelatedCompanyID` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `company` -- CREATE TABLE `company` ( `CompanyID` int(11) NOT NULL, `CompanyName` varchar(255) NOT NULL, `AccessLevel` int(11) NOT NULL, `RelatedAccTypeID` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `room` -- CREATE TABLE `room` ( `RoomID` int(11) NOT NULL, `RoomName` varchar(255) NOT NULL, `RelatedBuildingID` int(11) NOT NULL, `RelatedRoomTypeID` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `roomtype` -- CREATE TABLE `roomtype` ( `RoomTypeID` int(11) NOT NULL, `RoomTypeName` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `useraccount` -- CREATE TABLE `useraccount` ( `UserAccID` int(11) NOT NULL, `Username` varchar(255) NOT NULL, `Password_salt` varchar(255) NOT NULL, `Password_hash` varchar(255) NOT NULL, `RelatedUserID` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `usermemberships` -- CREATE TABLE `usermemberships` ( `UserMembershipID` int(11) NOT NULL, `RelatedUserID` int(11) NOT NULL, `RelatedCompanyID` int(11) NOT NULL, `RelatedRoleID` int(11) NOT NULL, `Email` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `userrole` -- CREATE TABLE `userrole` ( `RoleID` int(11) NOT NULL, `RoleName` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `UserID` int(11) NOT NULL, `FirstName` varchar(255) NOT NULL, `LastName` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `accounttype` -- ALTER TABLE `accounttype` ADD PRIMARY KEY (`AccTypeID`); -- -- Indexes for table `building` -- ALTER TABLE `building` ADD PRIMARY KEY (`BuildingID`), ADD KEY `RelatedCompanyID` (`RelatedCompanyID`); -- -- Indexes for table `company` -- ALTER TABLE `company` ADD PRIMARY KEY (`CompanyID`), ADD KEY `RelatedAccTypeID` (`RelatedAccTypeID`); -- -- Indexes for table `room` -- ALTER TABLE `room` ADD PRIMARY KEY (`RoomID`), ADD KEY `RelatedBuildingID` (`RelatedBuildingID`), ADD KEY `RelatedRoomTypeID` (`RelatedRoomTypeID`); -- -- Indexes for table `roomtype` -- ALTER TABLE `roomtype` ADD PRIMARY KEY (`RoomTypeID`); -- -- Indexes for table `useraccount` -- ALTER TABLE `useraccount` ADD PRIMARY KEY (`UserAccID`), ADD KEY `RelatedUserID` (`RelatedUserID`); -- -- Indexes for table `usermemberships` -- ALTER TABLE `usermemberships` ADD PRIMARY KEY (`UserMembershipID`), ADD KEY `RelatedCompanyID` (`RelatedCompanyID`), ADD KEY `RelatedUserID` (`RelatedUserID`), ADD KEY `RelatedRoleID` (`RelatedRoleID`); -- -- Indexes for table `userrole` -- ALTER TABLE `userrole` ADD PRIMARY KEY (`RoleID`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`UserID`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `accounttype` -- ALTER TABLE `accounttype` MODIFY `AccTypeID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `building` -- ALTER TABLE `building` MODIFY `BuildingID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `company` -- ALTER TABLE `company` MODIFY `CompanyID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `room` -- ALTER TABLE `room` MODIFY `RoomID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `roomtype` -- ALTER TABLE `roomtype` MODIFY `RoomTypeID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `useraccount` -- ALTER TABLE `useraccount` MODIFY `UserAccID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `usermemberships` -- ALTER TABLE `usermemberships` MODIFY `UserMembershipID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `userrole` -- ALTER TABLE `userrole` MODIFY `RoleID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `UserID` int(11) NOT NULL AUTO_INCREMENT; -- -- Constraints for dumped tables -- -- -- Constraints for table `building` -- ALTER TABLE `building` ADD CONSTRAINT `building_ibfk_1` FOREIGN KEY (`RelatedCompanyID`) REFERENCES `company` (`CompanyID`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `company` -- ALTER TABLE `company` ADD CONSTRAINT `company_ibfk_1` FOREIGN KEY (`RelatedAccTypeID`) REFERENCES `accounttype` (`AccTypeID`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `room` -- ALTER TABLE `room` ADD CONSTRAINT `room_ibfk_1` FOREIGN KEY (`RelatedBuildingID`) REFERENCES `building` (`BuildingID`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `room_ibfk_2` FOREIGN KEY (`RelatedRoomTypeID`) REFERENCES `roomtype` (`RoomTypeID`); -- -- Constraints for table `useraccount` -- ALTER TABLE `useraccount` ADD CONSTRAINT `useraccount_ibfk_1` FOREIGN KEY (`RelatedUserID`) REFERENCES `users` (`UserID`) ON DELETE CASCADE; -- -- Constraints for table `usermemberships` -- ALTER TABLE `usermemberships` ADD CONSTRAINT `usermemberships_ibfk_1` FOREIGN KEY (`RelatedCompanyID`) REFERENCES `company` (`CompanyID`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `usermemberships_ibfk_2` FOREIGN KEY (`RelatedUserID`) REFERENCES `users` (`UserID`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `usermemberships_ibfk_3` FOREIGN KEY (`RelatedRoleID`) REFERENCES `userrole` (`RoleID`) ON DELETE CASCADE ON UPDATE CASCADE; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>-- phpMyAdmin SQL Dump -- version 4.7.7 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: Feb 12, 2018 at 06:50 PM -- Server version: 10.1.30-MariaDB -- PHP Version: 7.2.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `gdot5_database` -- -- -------------------------------------------------------- -- -- Table structure for table `agent` -- CREATE TABLE `agent` ( `agent_id` int(11) NOT NULL, `landlord_id` int(11) NOT NULL, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `contact` varchar(255) NOT NULL, `password` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `building` -- CREATE TABLE `building` ( `building_id` int(11) NOT NULL, `landlord_id` int(11) NOT NULL, `building_type` text NOT NULL, `building_name` varchar(255) NOT NULL, `number_of_rooms` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `landlord` -- CREATE TABLE `landlord` ( `landlord_id` int(11) NOT NULL, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `contact` varchar(255) NOT NULL, `password` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `lease` -- CREATE TABLE `lease` ( `lease_id` int(11) NOT NULL, `tenant_id` int(11) NOT NULL, `lease_start` date NOT NULL, `lease_end` date NOT NULL, `deposit` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `payment` -- CREATE TABLE `payment` ( `pay_id` int(11) NOT NULL, `rent_id` int(11) NOT NULL, `pay_date` date NOT NULL, `pay_amount` int(11) NOT NULL, `pay_method` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `payment_method` -- CREATE TABLE `payment_method` ( `method_id` int(11) NOT NULL, `method_name` varchar(255) NOT NULL, `pay_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `receipt` -- CREATE TABLE `receipt` ( `receipt_id` int(11) NOT NULL, `pay_id` int(11) NOT NULL, `date` date NOT NULL, `tenant_id` int(11) NOT NULL, `pay_amount` int(11) NOT NULL, `pay_method` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `rent` -- CREATE TABLE `rent` ( `rent_id` int(11) NOT NULL, `lease_id` int(11) NOT NULL, `rent_fee` int(11) NOT NULL, `late_fee` int(11) NOT NULL, `due_date` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `room` -- CREATE TABLE `room` ( `room_id` int(11) NOT NULL, `building_id` int(11) NOT NULL, `room_name` varchar(255) NOT NULL, `room_type` text NOT NULL, `rent` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `tenant` -- CREATE TABLE `tenant` ( `tenant_id` int(11) NOT NULL, `room_id` int(11) NOT NULL, `landlord_id` int(11) NOT NULL, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `contact` varchar(255) NOT NULL, `password` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `agent` -- ALTER TABLE `agent` ADD PRIMARY KEY (`agent_id`), ADD KEY `landlord_id` (`landlord_id`); -- -- Indexes for table `building` -- ALTER TABLE `building` ADD PRIMARY KEY (`building_id`), ADD KEY `landlord_id` (`landlord_id`); -- -- Indexes for table `landlord` -- ALTER TABLE `landlord` ADD PRIMARY KEY (`landlord_id`); -- -- Indexes for table `lease` -- ALTER TABLE `lease` ADD PRIMARY KEY (`lease_id`), ADD KEY `tenant_id` (`tenant_id`); -- -- Indexes for table `payment` -- ALTER TABLE `payment` ADD PRIMARY KEY (`pay_id`), ADD KEY `rent_id` (`rent_id`); -- -- Indexes for table `payment_method` -- ALTER TABLE `payment_method` ADD PRIMARY KEY (`method_id`), ADD KEY `pay_id` (`pay_id`); -- -- Indexes for table `receipt` -- ALTER TABLE `receipt` ADD PRIMARY KEY (`receipt_id`), ADD KEY `pay_id` (`pay_id`); -- -- Indexes for table `rent` -- ALTER TABLE `rent` ADD PRIMARY KEY (`rent_id`), ADD KEY `lease_id` (`lease_id`); -- -- Indexes for table `room` -- ALTER TABLE `room` ADD PRIMARY KEY (`room_id`), ADD KEY `building_id` (`building_id`); -- -- Indexes for table `tenant` -- ALTER TABLE `tenant` ADD PRIMARY KEY (`tenant_id`), ADD KEY `room_id` (`room_id`), ADD KEY `landlord_id` (`landlord_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `agent` -- ALTER TABLE `agent` MODIFY `agent_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `building` -- ALTER TABLE `building` MODIFY `building_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `landlord` -- ALTER TABLE `landlord` MODIFY `landlord_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `lease` -- ALTER TABLE `lease` MODIFY `lease_id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `payment` -- ALTER TABLE `payment` MODIFY `pay_id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `payment_method` -- ALTER TABLE `payment_method` MODIFY `method_id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `rent` -- ALTER TABLE `rent` MODIFY `rent_id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `room` -- ALTER TABLE `room` MODIFY `room_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `tenant` -- ALTER TABLE `tenant` MODIFY `tenant_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- Constraints for dumped tables -- -- -- Constraints for table `agent` -- ALTER TABLE `agent` ADD CONSTRAINT `agent_ibfk_1` FOREIGN KEY (`landlord_id`) REFERENCES `landlord` (`landlord_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `building` -- ALTER TABLE `building` ADD CONSTRAINT `building_ibfk_1` FOREIGN KEY (`landlord_id`) REFERENCES `landlord` (`landlord_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `lease` -- ALTER TABLE `lease` ADD CONSTRAINT `lease_ibfk_1` FOREIGN KEY (`tenant_id`) REFERENCES `tenant` (`tenant_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `payment` -- ALTER TABLE `payment` ADD CONSTRAINT `payment_ibfk_1` FOREIGN KEY (`rent_id`) REFERENCES `rent` (`rent_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `payment_method` -- ALTER TABLE `payment_method` ADD CONSTRAINT `payment_method_ibfk_1` FOREIGN KEY (`pay_id`) REFERENCES `payment` (`pay_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `receipt` -- ALTER TABLE `receipt` ADD CONSTRAINT `receipt_ibfk_1` FOREIGN KEY (`pay_id`) REFERENCES `payment` (`pay_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `rent` -- ALTER TABLE `rent` ADD CONSTRAINT `rent_ibfk_1` FOREIGN KEY (`lease_id`) REFERENCES `lease` (`lease_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `room` -- ALTER TABLE `room` ADD CONSTRAINT `room_ibfk_1` FOREIGN KEY (`building_id`) REFERENCES `building` (`building_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `tenant` -- ALTER TABLE `tenant` ADD CONSTRAINT `tenant_ibfk_1` FOREIGN KEY (`room_id`) REFERENCES `room` (`room_id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `tenant_ibfk_2` FOREIGN KEY (`landlord_id`) REFERENCES `landlord` (`landlord_id`) ON DELETE CASCADE ON UPDATE CASCADE; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
4ef51fe2eeb36af15e081a07663ff7abcbb33cd6
[ "Markdown", "SQL" ]
3
Markdown
GithinjiWanjohi/GDot5-Real-Estate-System
d8afa96be8d5d1318b9c683096f4d9175fcf87ce
c371b8f22c945709127041220bf366390d5e97b8
refs/heads/main
<repo_name>SabrianJ/6426-1822<file_sep>/6426-1822/Week6/DoublyLinkedList.cs using System; using System.Collections.Generic; using System.Text; namespace Week6 { public class DLNode { public DLNode forward; public DLNode backward; public int data; public DLNode() { this.forward = null; this.backward = null; this.data = 0; } public DLNode(int value) : this() { this.data = value; } } class DoublyLinkedList { public DLNode head; public DLNode end; public int count; public DoublyLinkedList() { this.head = null; this.end = null; this.count = 0; } public void Append(int data) { DLNode newnode = new DLNode(data); if (count == 0) { this.head = newnode; this.end = newnode; } else { this.end.forward = newnode; newnode.backward = this.end; this.end = newnode; this.count++; } } public void Insert(int data, DLNode insertAfter) { DLNode newnode = new DLNode(data); DLNode next = insertAfter.forward; insertAfter.forward = newnode; newnode.forward = next; next.backward = newnode; newnode.backward = insertAfter; this.count++; } public int Delete(DLNode deleteme) { DLNode prev = deleteme.backward; DLNode next = deleteme.forward; if (prev != null) { prev.forward = next; } if (next != null) { next.backward = prev; } ++this.count; return deleteme.data; } } } <file_sep>/README.md # 6426-1822 A repo setup for you to practice using Git without worrying about mistakes. Email me your username to get admin access. <file_sep>/6426-1822/Week8/ArrayTree.cs using System; using System.Collections.Generic; using System.Text; namespace Week8 { class ArrayTree { } } <file_sep>/6426-1822/Week10/Graph.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Week10 { /// <summary> /// Node contains a name and a list of connected nodes, with paired /// weight value (int) to represent distance or time to travel /// </summary> public class Vertex : IEquatable<Vertex> { public int ID; public int data; public List<Vertex> vertices; public Vertex(int ID, int data) { this.ID = ID; this.data = data; vertices = new List<Vertex>(); } public override string ToString() { string toReturn = string.Format("[Node] ID: {0}, Data: {1}, Neighbours: ", ID, data); vertices.ForEach(node => toReturn += string.Format("{0}, ", node.ID)); return toReturn; } public bool Equals(Vertex node) { return this.ID == node.ID; } } public class Edge { public Vertex from; public Vertex to; public bool bIsWeighted = false; public bool bIsDirected = false; public int weight = 0; public Edge() { } public Edge(Vertex from, Vertex to) { this.from = from; this.to = to; } public Edge(Vertex from, Vertex to, bool isDirected, int weight = 0) : this(from, to) { bIsDirected = isDirected; this.weight = weight; bIsWeighted = weight > 0; } public override string ToString() { return string.Format("[Edge] From: {0}, To: {1}", from, to); } } public class Subset { public Vertex parent; public int rank; public override string ToString() { return $"Subset with rank {rank}, parent: {parent.data}(ID: { parent.ID})"; } } public class Graph { public List<Vertex> vertices; public Graph() { this.vertices = new List<Vertex>(); } public Vertex AddNode(int ID, int value) { Vertex node = new Vertex(ID, value); vertices.Add(node); return node; } public void AddEdge(Vertex from, Vertex to) { from.vertices.Add(to); to.vertices.Add(from); } public void RemoveVertex(Vertex toRemove) { vertices.Remove(toRemove); foreach (Vertex node in vertices) { RemoveEdge(node, toRemove); } } public void RemoveEdge(Vertex from, Vertex to) { foreach (Vertex vertex in from.vertices) { if (vertex == to) from.vertices.Remove(vertex); } } public List<Edge> GetEdges() { List<Edge> edges = new List<Edge>(); foreach (Vertex from in vertices) { foreach (Vertex to in from.vertices) { Edge edge = new Edge(); edge.from = from; edge.to = to; edges.Add(edge); } } return edges; } ////////////////////////////////////////////// ////////////////////////////////////////////// ////////////// Traversal ////////////////// public List<Vertex> DFS() { List<Vertex> result = new List<Vertex>(); DFS(vertices[0], result); return result; } private void DFS(Vertex trav, List<Vertex> result) { result.Add(trav); foreach(Vertex neighbour in trav.vertices) { if (!result.Contains(neighbour)) { DFS(neighbour, result); } } } public List<Vertex> BFS() { return BFS(vertices[0]); } private List<Vertex> BFS(Vertex node) { List<Vertex> result = new List<Vertex>(); Queue<Vertex> queue = new Queue<Vertex>(); queue.Enqueue(node); while (queue.Count > 0) { Vertex next = queue.Dequeue(); result.Add(next); foreach(Vertex neighbour in next.vertices) { if (!result.Contains(neighbour) && !queue.Contains(neighbour)) { queue.Enqueue(neighbour); } } } return result; } public List<Edge> MSTKruskal() { List<Edge> edges = GetEdges(); edges.Sort((a, b) => a.weight.CompareTo(b.weight)); Queue<Edge> queue = new Queue<Edge>(edges); Subset[] subsets = new Subset[vertices.Count]; for (int i = 0; i < vertices.Count; i++) { subsets[i] = new Subset() { parent = vertices[i] }; } List<Edge> result = new List<Edge>(); while (result.Count < vertices.Count - 1) { Edge edge = queue.Dequeue(); Vertex from = GetRoot(subsets, edge.from); Vertex to = GetRoot(subsets, edge.to); if (from != to) { result.Add(edge); Union(subsets, from, to); } } return result; } private Vertex GetRoot(Subset[] subsets, Vertex vertex) { if (subsets[vertex.ID].parent != vertex) { subsets[vertex.ID].parent = GetRoot(subsets, subsets[vertex.ID].parent); } return subsets[vertex.ID].parent; } private void Union(Subset[] subsets, Vertex a, Vertex b) { if (subsets[a.ID].rank > subsets[b.ID].rank) { subsets[b.ID].parent = a; } else if (subsets[a.ID].rank < subsets[b.ID].rank) { subsets[a.ID].parent = b; } else { subsets[b.ID].parent = a; subsets[a.ID].rank++; } } } } <file_sep>/6426-1822/Week3/LinkedList.cs using System; using System.Collections.Generic; using System.Text; namespace Week3 { public class Node { public int value; public Node next; public Node(int value) { this.value = value; } } class LinkedList { public Node head; public LinkedList() { } public void Addnode(int value) { Node newNode = new Node(value); if (this.head == null) this.head = newNode; else { Node trav = this.head; while (trav.next != null) trav = trav.next; trav.next = newNode; } } public Node searchNode(int v) { Node trav = head; while (trav != null) { // check values if (trav.value == v) return trav; // traverse trav = trav.next; } return null; } public void DeleteTemp() { Node trav = this.head; Node trailingtrav = this.head; trailingtrav = trav; trav = trav.next; } } } <file_sep>/6426-1822/sfml-menu/Program.cs using System; using SFML.Window; using SFML.Graphics; using SFML.System; namespace sfml_menu { class Program { /// <summary> /// Program starting point. /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine("Press ESC key to close window"); MyWindow window = new MyWindow(); window.Run(); Console.WriteLine("All done"); } } /// <summary> /// Game engine class. Creates a game window, runs the game loop /// and handle user inputs. /// </summary> class MyWindow { RenderWindow window; Clock clock; Time delta; float angle; float speed; Font font; Text text, helptext; GameMenu menu; bool showMainMenu = false; /// <summary> /// Constructor to setup the game window /// </summary> public MyWindow() { VideoMode mode = new VideoMode(1280, 720); window = new RenderWindow(mode, "SFML.NET Menu Example", Styles.Titlebar); window.Closed += this.Window_close; window.KeyPressed += this.Key_press; window.MouseButtonPressed += this.Mouse_press; clock = new Clock(); delta = Time.Zero; angle = 0f; speed = 200f; font = new Font(@"C:\\Windows\Fonts\Arial.ttf"); text = new Text("Hello World!", font, 100); helptext = new Text("Press Escape to open and close Game Menu", font, 20); var textBounds = text.GetLocalBounds(); float xOffset = textBounds.Width / 2f + textBounds.Left; float yOffset = textBounds.Height / 2f + textBounds.Top; text.Origin = new Vector2f(xOffset, yOffset); text.Position = (Vector2f)window.Size / 2; setupMenu(); } ////////////// Game Window Critical Methods /////////////// public void Run() { /// Game loop while (window.IsOpen) { this.Update(); this.Draw(); } } /// <summary> /// Method for updating the valid elements of the game /// </summary> public void Update() { window.DispatchEvents(); delta = clock.Restart(); /// Check if the menu is being displayed. If not, update the game. if (showMainMenu) { } else { angle += speed * delta.AsSeconds(); text.Rotation = angle; } } /// <summary> /// Method for drawing the game elements to the game window /// </summary> public void Draw() { /// clear the window window.Clear(); /// draw game scene window.Draw(text); /// draw menu if (showMainMenu) { menu.Draw(window, RenderStates.Default); } /// draw help text window.Draw(helptext); /// display the window to the screen window.Display(); } ////////////// Game Window Event Methods /////////////// /// <summary> /// Event for handling keyboard button presses /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void Key_press(object sender, KeyEventArgs e) { Window window = (Window)sender; switch (e.Code) { case Keyboard.Key.Escape: this.showMainMenu = !showMainMenu; break; default: break; } } /// <summary> /// Event for handling mouse button presses /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void Mouse_press(object sender, MouseButtonEventArgs e) { switch (e.Button) { case Mouse.Button.Left: if (showMainMenu) { menu.DispatchEvents(e.X, e.Y); } break; case Mouse.Button.Right: break; default: break; } } /// <summary> /// Event for closing the game window /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void Window_close(object sender, EventArgs e) { Window window = (Window)sender; window.Close(); } /// <summary> /// Create a menu, and add a title and 3 buttons to it /// </summary> public void setupMenu() { Font font = new Font(@"C:\\Windows\Fonts\Arial.ttf"); this.menu = new GameMenu(window.Size.X / 2, window.Size.Y / 2, 300, 400); this.menu.setMenuStyle(new Color(255, 255, 255, 150), Color.Red, 2); float menuCenterX = this.menu.getCentre().X; float menuCenterY = this.menu.getCentre().Y; MenuText title = new MenuText(menuCenterX, menuCenterY - 160, "Main Menu", font, 30); title.setTextStyle(Color.White, Color.Black, 1); this.menu.AddText(title); MenuButton btn1 = new MenuButton(menuCenterX, menuCenterY - 75, 200, 75, "White Text", font); btn1.setButtonStyle(Color.White, Color.Black, 2); btn1.setTextStyle(Color.Black, Color.Black, 0, 20); btn1.Click += Menu_WhiteText_Click; this.menu.AddButton(btn1); MenuButton btn2 = new MenuButton(menuCenterX, menuCenterY + 25, 200, 75, "Red Text", font); btn2.setButtonStyle(Color.White, Color.Black, 2); btn2.setTextStyle(Color.Black, Color.Black, 0, 20); btn2.Click += Menu_RedText_Click; this.menu.AddButton(btn2); MenuButton btn3 = new MenuButton(menuCenterX, menuCenterY + 125, 200, 75, "Exit", font); btn3.setButtonStyle(Color.White, Color.Black, 2); btn3.setTextStyle(Color.Black, Color.Black, 0, 20); btn3.Click += Menu_Exit_Click; this.menu.AddButton(btn3); } /// <summary> /// Method for button event to call /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void Menu_WhiteText_Click(object sender, MouseButtonEventArgs e) { this.text.FillColor = Color.White; } /// <summary> /// Method for button event to call /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void Menu_RedText_Click(object sender, MouseButtonEventArgs e) { this.text.FillColor = Color.Red; } /// <summary> /// Method for button event to call /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void Menu_Exit_Click(object sender, MouseButtonEventArgs e) { window.Close(); } } } <file_sep>/6426-1822/sfml-1/Program.cs using System; using SFML.Window; using SFML.Graphics; using SFML.System; namespace sfml_list_example { class Program { static void Main(string[] args) { Console.WriteLine("Press ESC key to close window"); MyWindow window = new MyWindow(); window.Run(); Console.WriteLine("All done"); } } class MyWindow { RenderWindow window; Clock clock; Time delta; LinkedList<Ball> balls; float circleSize; Random random; float speed; Font font; Text text; public MyWindow() { VideoMode mode = new VideoMode(1280, 720); window = new RenderWindow(mode, "SFML.NET Data Structure Example", Styles.Titlebar); window.Closed += this.Window_close; window.KeyPressed += this.Key_press; window.MouseButtonPressed += this.Mouse_press; clock = new Clock(); delta = Time.Zero; balls = new LinkedList<Ball>(); circleSize = 20f; random = new Random(); speed = 200f; font = new Font(@"C:\\Windows\Fonts\Arial.ttf"); text = new Text("Left-click to add a node. Right-click to remove a node. Escape to quit.", font, 25); } ////////////// Game Window Critical Methods /////////////// public void Run() { while (window.IsOpen) { this.Update(); this.Display(); } } public void Update() { window.DispatchEvents(); delta = clock.Restart(); this.UpdateCircles(); } public void Display() { /// clear the window window.Clear(); /// draw shapes to the window this.DrawCircles(); /// draw the help text window.Draw(text); /// display the window to the screen window.Display(); } ////////////// Game Window Event Methods /////////////// public void Key_press(object sender, KeyEventArgs e) { Window window = (Window)sender; switch(e.Code) { case Keyboard.Key.Escape: window.Close(); break; default: break; } } public void Mouse_press(object sender, MouseButtonEventArgs e) { switch(e.Button) { case Mouse.Button.Left: this.AddBall(e.X, e.Y); break; case Mouse.Button.Right: this.balls.Dequeue(); break; default: break; } } public void Window_close(object sender, EventArgs e) { Window window = (Window)sender; window.Close(); } public void AddBall(float x, float y) { for(int i = 0; i < 1; i++) { float velocityX = (float)(random.NextDouble() - 0.5) * speed; float velocityY = (float)(random.NextDouble() - 0.5) * speed; Ball ball = new Ball(Color.Red, Color.White, circleSize); ball.setPosition(x, y); ball.setVelocity(velocityX, velocityY); balls.Enqueue(ball); } } public void DrawCircles() { if (this.balls.count == 0) return; // draw all the ball links first so they don't draw over the balls for (Node<Ball> trav = this.balls.head; trav != null; trav = trav.next) { trav.data.DrawLink(window, RenderStates.Default); } for (Node<Ball> trav = this.balls.head; trav != null; trav = trav.next) { trav.data.Draw(window, RenderStates.Default); } } public void UpdateCircles() { if (this.balls.count == 0) return; for (Node<Ball> trav = this.balls.head; trav != null; trav = trav.next) { Vector2f linktarget = trav.next != null ? trav.next.data.Position : trav.data.Position; // line above is the same as: // if (trav.next != null) // linktarget = trav.next.data.Position; // else // linktarget = trav.data.Position; trav.data.Update(this.delta.AsSeconds(), linktarget, 0, 0, window.Size.X, window.Size.Y); } } } } <file_sep>/6426-1822/Week3/Node.cs using System; using System.Collections.Generic; using System.Text; namespace Week3 { public interface INode<T> { public T value { get; set; } public INode<T> next { get; set; } public string ToString(); public bool Equals(); } } <file_sep>/6426-1822/Week3/inClassLib.cs using System; using System.Collections.Generic; using System.Text; namespace Week3 { public static class inClassLib { public static bool ArrayLinearSearch<T>(T[] array, T value) { /// loop through the array for (var i = 0; i < array.Length; i++) { /// if the i'th value in the array is what we want if (array[i].Equals(value)) { /// return the index it was found at return true; } } /// return a fail to find return false; } public static int ArrayBinarySearch(int[] array, int value) { return 0; } } } <file_sep>/6426-1822/Week9/Program.cs using System; using System.Linq; namespace Week9 { class Program { static void Main(string[] args) { Heap myHeap = new Heap(); foreach (int i in Enumerable.Range(1, 10)) { myHeap.insert(i); Console.WriteLine(myHeap.ToString()); } foreach (int i in Enumerable.Range(1, 10)) { Console.WriteLine("deleted: {0}", myHeap.delete()); Console.WriteLine(myHeap.ToString()); } } } } <file_sep>/6426-1822/Week3/Program.cs using System; using System.Linq; namespace Week3 { class Program { static void Main(string[] args) { int[] myNewArray = Enumerable.Range(0, 100).ToArray(); Console.WriteLine("Hello World!"); Random r = new Random(); int[] array = new int[100]; for (int i = 0; i < array.Length; i++) { array[i] = r.Next(0, 100); Console.Write("{0}, ", array[i]); } int[] sortedArray = Enumerable.Range(0, 100).ToArray(); for (int i = 0; i < array.Length; i++) if (array[i] == 17) Console.WriteLine("Found at index {0}", i); Console.WriteLine("Recursive looking for {0}: {1}", 17, Search.ArrayRecursiveLinearSearch(sortedArray, 0, 17)); Console.WriteLine("Recursive binary looking for {0}: {1}", 17, Search.ArrayRecursiveBinarySearch(sortedArray, sortedArray.Length - 1, 0, 17)); } } }<file_sep>/6426-1822/Week11/Program.cs using System; using System.Collections; namespace Week11 { class Program { static void Main(string[] args) { FloodFill fill = new FloodFill(); //fill.Run(); Hashtable phonebook = new Hashtable(); phonebook.Add("<NAME>", "0211111111"); phonebook.Add("<NAME>", "0212222222"); phonebook.Add("<NAME>", "0223333333"); phonebook.Add("<NAME>", "0224444444"); Console.WriteLine(phonebook["<NAME>"]); Hashtable People = new Hashtable(); People.Add("<NAME>", new Person { name = "<NAME>", age = 34 }); People.Add("<NAME>", new Person { name = "<NAME>", age = 35 }); People.Add("<NAME>", new Person { name = "<NAME>", age = 19 }); Random r = new Random(); Stack stack = new Stack(); stack.Add(r.Next(1, 20)); int[] myArray = new int[r.Next(10, 20)]; for(int i = 0; i < myArray.Length; i++) { myArray[i] = r.Next(1, 1000); Console.WriteLine(myArray[i]); } } } public class Stack { public Stack() { } public void Add(int i) { } } public class Person { public string name; public int age; } } <file_sep>/6426-1822/Week4/Sort.cs using System; using System.Collections.Generic; using System.Text; namespace Week4 { static class Sort { /// <summary> /// Helper method. Prints the elements of an array /// to the console. /// </summary> /// <param name="array"></param> public static void PrintArray(int[] array) { Console.Write("[ "); foreach (int i in array) Console.Write(i + ", "); Console.WriteLine("]\n"); } /// <summary> /// Helper method. Allows us to handle variable swapping /// in arrays the same way for all sorting algorithms. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <param name="a"></param> /// <param name="b"></param> public static void Swap<T>(T[] array, int a, int b) where T : IComparable { T temp = array[a]; array[a] = array[b]; array[b] = temp; } /// <summary> /// Bubble sort implementation. Highy inefficient. /// Iterates through the array and 'bubbles' the highest /// value to the end by swapping it with the right-hand neighbour /// continuously until it cannot go any further. /// </summary> /// <param name="array"></param> public static void BubbleSort(int[] array) { /// loop for each element in the array (i is not used) for (int i = 0; i < array.Length; i++) { /// flag for checking if any change has been made bool isAnyChange = false; /// the 'bubble' loop. for (int j = 0; j < array.Length - 1; j++) { /// check each index against its neighbour. /// If bigger, swap them. if (array[j] > array[j + 1]) { Swap(array, j, j + 1); /// update the flag to show a change has been made isAnyChange = true; } } /// If no changes were made on a pass, sorting is finished early. if (!isAnyChange) { break; } } } /// <summary> /// Selection Sort implementation. /// Iterates through the array, finds the lowest value, /// and moves it to the front of the array /// </summary> /// <param name="array"></param> public static void SelectionSort(int[] array) { /// Loop over array for (int i = 0; i < array.Length - 1; i++) { /// Keep track of the lowest value and index int minIndex = i; int minValue = array[i]; /// loop over the unmoved elements. /// After "i" loops, the number of sorted elements /// is equal to 'i + 1', so we can avoid checking /// these sorted elements next time through for (int j = i + 1; j < array.Length; j++) { /// check current element against known smallest if (array[j] < minValue) { /// current element is the new smallest minIndex = j; minValue = array[j]; } } /// After a pass, move the smallest found element to /// the front (elements 0 to i are sorted). Swap(array, i, minIndex); } } /// <summary> /// Insertion Sort implementation. /// Separates the array into sorted and unsorted parts. /// Take an unsorted value and loop over the sorted part /// until we find where it fits. Repeat until no more /// unsorted elements remain. /// </summary> /// <param name="array"></param> public static void InsertionSort(int[] array) { /// Loop over array (skip the first element, it is the /// first element of the sorted part. All elements left /// of i are sorted. for (int i = 1; i < array.Length; i++) { int j = i; /// Keep shuffling the unsorted element along the /// sorted array (right-to-left) until it is in /// a sorted location while (j > 0 && array[j] < array[j - 1]) { Swap(array, j, j - 1); j--; } } } /// <summary> /// Quicksort starter method. Calls the overloaded method /// with a specified lower and upper value. /// </summary> /// <param name="array"></param> public static void Quicksort(int[] array) { Quicksort(array, 0, array.Length - 1); } /// <summary> /// Overloaded Quicksort method. /// Gets a pivot point in the array and splits the array /// into 2 halves. Recursively calls itself with each half. /// </summary> /// <param name="array"></param> /// <param name="lower"></param> /// <param name="upper"></param> /// <returns></returns> public static int[] Quicksort(int[] array, int lower, int upper) { /// If lower is smaller than upper, the array has not /// been completely sorted. Split it and keep sorting. if (lower < upper) { int p = Partition(array, lower, upper); Quicksort(array, lower, p); Quicksort(array, p + 1, upper); } return array; } /// <summary> /// The pivoting and sorting part of the quicksort algorithm. /// </summary> /// <param name="array"></param> /// <param name="lower"></param> /// <param name="upper"></param> /// <returns></returns> public static int Partition(int[] array, int lower, int upper) { int i = lower; int j = upper; /// Choose a location between lower and upper to pivot from. /// The value of pivot can be set to any index from lower /// to upper (inclusively). /// EG: pivot = array[lower] /// EG: pivot = array[upper] /// etc int pivot = array[(lower + upper) / 2]; /// While the lower and upper indices haven't met while (i <= j) { /// move the lower to the right until it hits the pivot while (array[i] < pivot) i++; /// move the upper to the left until it hits the pivot while (array[j] > pivot) j--; /// if i is equal or greater than j, the section is sorted. /// Return. if (i >= j) return j; /// If not done, swap the elements and move the lower and /// upper bounds inwards. Swap(array, i, j); i++; j--; } /// Lower and upper have met. Elements are sorted. return j; } } } <file_sep>/6426-1822/Week3/inClassNode.cs using System; using System.Collections.Generic; using System.Text; namespace Week3 { public class inClassNode { public int value; public inClassNode next; public inClassNode(int value) { this.value = value; } public bool Equals(inClassNode node) { if (this.value == node.value) { return true; } return false; } } } <file_sep>/6426-1822/Week5/Stack.cs using System; using System.Collections.Generic; using System.Text; namespace Week5 { /// <summary> /// Node class using generics and inheritence requirements. /// The data type of value is the datatype passed to the /// constructor. /// EG: Node<int> myNode = new Node<int>(1); /// The 'where T : IComparable' makes sure that the T datatype /// can only be a type that inherits from the IComparable interface. /// This means that all Nodes can use the .CompareTo() method. /// </summary> /// <typeparam name="T"></typeparam> public class Node<T> where T : IComparable { private T _value; public T value { get { return _value; } set { if (!value.Equals(null)) this._value = value; } } public Node<T> next; public Node(T value) { this.value = value; } } public class Stack { int max = 10; /// arbitrary default max size int count = 0; Node<int> head = null; public Stack() { } public Stack(int sizeLimit) { this.max = sizeLimit; } /// overloaded constructor that uses ctor chaining to reduce /// replicating code across constructors. public Stack(int sizeLimit, int[] startingValues) : this(sizeLimit) { foreach(int val in startingValues) { this.push(val); } } /// Add a new node to the top of the stack public void push(int value) { ++this.count; Node<int> newNode = new Node<int>(value); newNode.next = this.head; this.head = newNode; } /// remove the top node from the stack and return /// the value public int pop() { if (this.head == null) return -1; --this.count; var v = this.head.value; this.head = this.head.next; return v; } /// Remove the entire stack by separating the link /// and let gc clean it up later public void delete() { /// It is tempting to do this: /// while (this.count > 0) /// this.pop(); /// /// But it achieves the same result as: this.head = null; this.count = 0; } /// <summary> /// Method for traversing and printing the contents /// of the stack. /// Uses a stringbuilder instead of appending strings /// manually to save on memory. /// </summary> /// <returns></returns> public override string ToString() { if (this.count < 1) return "Stack is empty"; StringBuilder sb = new StringBuilder(); sb.Append("[ "); Node<int> trav = this.head; while (trav.next != null) { sb.Append(trav.value.ToString() + ", "); trav = trav.next; } sb.Append(trav.value.ToString() + " ]"); return sb.ToString(); } } } <file_sep>/6426-1822/Week6/Program.cs using System; namespace Week6 { class Program { static void Main(string[] args) { SFML_HelloWorld SFML_Demo = new SFML_HelloWorld(); SFML_Demo.Run(); } } } <file_sep>/6426-1822/Week10/Program.cs using System; using System.Collections.Generic; namespace Week10 { class Program { static void Main(string[] args) { Graph graph = new Graph(); //Edge e2 = new Edge(n1, n3); //Edge e3 = new Edge(n2, n4); //Edge e4 = new Edge(n2, n5); //Edge e5 = new Edge(n3, n5); //Edge e6 = new Edge(n5, n6); Vertex n1 = graph.AddNode(0, 10); Vertex n2 = graph.AddNode(1, 4); Vertex n3 = graph.AddNode(2, 7); Vertex n4 = graph.AddNode(3, 9); Vertex n5 = graph.AddNode(4, 8); Vertex n6 = graph.AddNode(5, 3); graph.AddEdge(n1, n2); graph.AddEdge(n1, n3); graph.AddEdge(n2, n4); graph.AddEdge(n3, n5); graph.AddEdge(n5, n6); Print(graph.DFS()); Console.WriteLine("\n\n\n"); Print(graph.BFS()); Console.WriteLine("\n\n\n"); Print(graph.MSTKruskal()); } public static void Print<T>(List<T> nodes) { nodes.ForEach(n => Console.WriteLine(n)); } } } <file_sep>/6426-1822/Week4/Program.cs using System; namespace Week4 { class Program { static void Main(string[] args) { Console.WriteLine("\n\nBubble Sort:"); Test.RunTest(Sort.BubbleSort); Console.WriteLine("\n\nInsertion Sort:"); Test.RunTest(Sort.InsertionSort); Console.WriteLine("\n\nSelection Sort:"); Test.RunTest(Sort.SelectionSort); Console.WriteLine("\n\nQuicksort:"); Test.RunTest(Sort.Quicksort); } } } <file_sep>/6426-1822/Week2/Program.cs using System; using System.Linq; namespace Week2 { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); FizzBuzz(); LinkedList myLinkedList = new LinkedList(); /// Enumerable.Range is available in System.Linq namespace. /// Remember to include it at the top of your file. foreach (int i in Enumerable.Range(1, 10)) { myLinkedList.AddNode(i); } } /// <summary> /// FizzBuzz method. /// Uses the static keyword to allow the method to be called /// without needing an instance of the class /// </summary> public static void FizzBuzz() { /// Ask for a number from user Console.WriteLine("Enter a number:"); /// Take the input, save to a local string var string input = Console.ReadLine(); /// Convert string to int int inputNum = Convert.ToInt32(input); /// For each int from 1 to given number for (int i = 1; i < inputNum; i++) { /// If i is multiple of 3 and 5 if (i % 3 == 0 && i % 5 == 0) Console.WriteLine("FizzBuzz"); /// If not multiple of both, is multiple of just 3 else if (i % 3 == 0) Console.WriteLine("Fizz"); /// If not multiple of both, is multiple of just 5 else if (i % 5 == 0) Console.WriteLine("Buzz"); /// If none of the above, print the number else Console.WriteLine(i); } } } } <file_sep>/6426-1822/6426-1822/Program.cs using System; namespace _6426_1822 { class Program { /// <summary> /// The starting point of the program. Add code here to /// initialise an instance of your class(es). /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine("Hello World!"); SampleClass sampleClass = new SampleClass(); sampleClass.sampleGlobalVarB = 5; Console.WriteLine(sampleClass.ToString()); } } } <file_sep>/6426-1822/Week5/Program.cs using System; namespace Week5 { class Program { static void Main(string[] args) { Stack stack = new Stack(20, new int[] { 1, 2, 3 }); Console.WriteLine(stack.ToString()); stack.push(4); stack.push(5); stack.push(6); Console.WriteLine(stack.ToString()); stack.pop(); Console.WriteLine(stack.ToString()); stack.pop(); Console.WriteLine(stack.ToString()); stack.delete(); Console.WriteLine(stack.ToString()); } } } <file_sep>/6426-1822/Week3/Search.cs using System; using System.Collections.Generic; using System.Text; namespace Week3 { public static class Search { public static int ArrayLinearSearch<T>(T[] array, T value) { for (int i = 0; i < array.Length; i++) { if (array[i].Equals(value)) { Console.WriteLine("Found value({0}) at index {1}.", value, i); return i; } } Console.WriteLine("failed to find {0} in array", value); return -1; } public static INode<T> ADTLinearSearch<T>(INode<T> ADT, T value) { var trav = ADT; int travCount = 0; while (trav.next != null) { travCount++; if (trav.Equals(value)) { Console.WriteLine("Found value({0}) at the traversed node {1}.", value, travCount); return trav; } } Console.WriteLine("failed to find {0} in ADT", value); return null; } public static int ArrayBinarySearch(int[] array, int value) { int min = 0; int max = array.Length - 1; while (min <= max) { int mid = (min + max) / 2; if (value == array[mid]) { return ++mid; } else if (value < array[mid]) { max = mid - 1; } else { min = mid + 1; } } return -1; } public static int ArrayRecursiveLinearSearch(int[] array, int index, int value) { if (index >= array.Length) return -1; if (array[index] == value) return index; return ArrayRecursiveLinearSearch(array, index + 1, value); } public static int ArrayRecursiveBinarySearch(int[] array, int high, int low, int value) { if (high >= low) { int mid = (high + low) / 2; // Console.WriteLine("h: {0}, m: {1}, l: {2}", high, mid, low); if (array[mid] == value) return mid; if (array[mid] > value) return ArrayRecursiveBinarySearch(array, mid - 1, low, value); return ArrayRecursiveBinarySearch(array, high, mid + 1, value); } return -1; } } } <file_sep>/6426-1822/Week5/InclassStack.cs using System; using System.Collections.Generic; using System.Text; namespace Week5 { public class InclassNode { public InclassNode next; public int value { get { return this.value; } set { this.value = value; } } public InclassNode() { this.next = null; this.value = 0; } public InclassNode(int value) { this.next = null; this.value = value; } public void setValue(int value) { this.value = value; } public int getValue() { return this.value; } } public class InclassStack { public InclassNode top; public int count; public InclassStack() { this.top = null; this.count = 0; } public InclassStack(int value) { this.top = new InclassNode(value); this.count++; } public void Push(int value) { InclassNode newNode = new InclassNode(value); newNode.next = this.top; this.top = newNode; this.count++; } public int Pop() { InclassNode temp = this.top; this.top = this.top.next; this.count--; return temp.value; } public int StackTop() { if (this.top != null) return this.top.value; return -1; } } } <file_sep>/6426-1822/Week6/ADT.cs using System; using System.Collections.Generic; using System.Text; namespace Week6 { class ADTNode { ADTNode link; int data; public ADTNode(int value) { this.link = null; this.data = value; } } class ADT { ADTNode head; int count; public ADT() { this.head = null; this.count = 0; } } } <file_sep>/6426-1822/Week11/FloodFill.cs using System; using System.Collections.Generic; using System.Text; using SFML.System; using SFML.Graphics; using SFML.Window; namespace Week11 { public enum tileState { empty, flooded, wall } public class Tile { public RectangleShape shape; private tileState state; public Tile(float x, float y, float width, float height, tileState state) { shape = new RectangleShape(new Vector2f(width, height)); shape.Position = new Vector2f(x, y); shape.OutlineThickness = 1; shape.OutlineColor = Color.White; SetState(state); } public void SetState(tileState state) { this.state = state; switch (this.state) { case tileState.empty: shape.FillColor = Color.Black; break; case tileState.flooded: shape.FillColor = Color.Red; break; case tileState.wall: shape.FillColor = Color.White; break; } } public tileState GetState() { return state; } public void Draw(RenderWindow window) { window.Draw(this.shape); //if (this.shape.FillColor != Color.Black) // Console.WriteLine(this.shape.FillColor); } } class FloodFill { RenderWindow window; Clock clock; double updateTime = 0.1; Time delta; Tile[,] tiles; float tileW, tileH; Queue<int> queue; bool isFlood = false; public FloodFill() { VideoMode mode = new VideoMode(700, 700); window = new RenderWindow(mode, "SFML.NET Flood Fill example", Styles.Titlebar); window.Closed += this.Window_close; window.KeyPressed += this.Key_press; window.MouseButtonPressed += this.Mouse_press; clock = new Clock(); delta = Time.Zero; int tilesPerSide = 10; tiles = new Tile[tilesPerSide, tilesPerSide]; tileW = mode.Width / tilesPerSide; tileH = mode.Height / tilesPerSide; for (int y = 0; y < tiles.GetLength(0); y++) { for (int x = 0; x < tiles.GetLength(1); x++) { tiles[x, y] = new Tile(x * tileW, y * tileH, tileW, tileH, tileState.empty); } } queue = new Queue<int>(); } ////////////// Game Window Critical Methods /////////////// public void Run() { while (window.IsOpen) { this.Update(); this.Display(); } } public void Update() { window.DispatchEvents(); //delta += clock.Restart(); if (clock.ElapsedTime.AsSeconds() > updateTime) { clock.Restart(); if (isFlood) FloodNext(1); } } public void Display() { /// clear the window window.Clear(); /// draw the help text foreach (Tile tile in tiles) tile.Draw(window); /// display the window to the screen window.Display(); } ////////////// Game Window Event Methods /////////////// public void Key_press(object sender, KeyEventArgs e) { Window window = (Window)sender; switch (e.Code) { case Keyboard.Key.Escape: window.Close(); break; case Keyboard.Key.Space: isFlood = !isFlood; Console.WriteLine(isFlood); break; default: break; } } public void Mouse_press(object sender, MouseButtonEventArgs e) { switch (e.Button) { case Mouse.Button.Left: Flood( Convert.ToInt32(e.X / tileW) - 1, Convert.ToInt32(e.Y / tileH) - 1); break; case Mouse.Button.Right: Wall(e.X, e.Y); break; default: break; } } public void Window_close(object sender, EventArgs e) { Window window = (Window)sender; window.Close(); } public void Flood(int x, int y) { tiles[x, y].SetState(tileState.flooded); for (int i = x - 1; i <= x + 1; i++) { for (int j = y - 1; j <= y + 1; j++) { //Console.WriteLine($"i:{i}, j:{j}"); if (i >= 0 && i < tiles.GetLength(1) && j >= 0 && j < tiles.GetLength(0)) { //Console.WriteLine("valid"); if (tiles[i, j].GetState() == tileState.empty) { //Console.WriteLine("empty"); int index = i * tiles.GetLength(1) + j; //Console.WriteLine("not in queue"); if (queue.Contains(index) == false) { queue.Enqueue(index); } } } } } Console.WriteLine(queue.Count); } public void FloodNext(int count) { for (int i = 0; i < count; i++) { if (queue.Count == 0) return; int num = queue.Dequeue(); int x = num / tiles.GetLength(1); int y = num % tiles.GetLength(1); Console.WriteLine($"flood:{x}, {y}"); Flood(x, y); } } public void Wall(float x, float y) { tiles[ Convert.ToInt32(x / tileW), Convert.ToInt32(y / tileH) ].SetState(tileState.wall); } } } <file_sep>/6426-1822/Week4/Test.cs /* * Author: <NAME> */ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace Week4 { public class Test { /// <summary> /// Static method that takes a reference to a method as a parameter. /// The passed method must take an integer parameter that is used /// to determine the number of times an action is performed. /// </summary> /// <param name="runFunc"></param> public static void RunTest(Action<int> runFunc) { /// Create 2 arrays, 1 for test sizes, 1 for holding the elapsed times int[] inputLengths = { 10, 100, 1000, 10000, 100000, 200000 }; TimeSpan[] elapsedTimes = new TimeSpan[6]; Console.WriteLine("Beginning tests..."); /// start the timer var watch = Stopwatch.StartNew(); /// loop over the test lengths for (int i = 0; i < inputLengths.Length; i++) { /// restart the timer watch.Restart(); Console.Write("Running function with {0} length...", inputLengths[i]); /// call the passed method with the test length as parameter runFunc(inputLengths[i]); /// save the time taken to perform elapsedTimes[i] = watch.Elapsed; Console.WriteLine("Function completed execution."); } /// print out the results for the tests Console.WriteLine("\nFinished tests... Results below:\n"); for (int i = 0; i < elapsedTimes.Length; i++) { Console.WriteLine("iterations: {0:0000000}\t Elapsed Time: {1}", inputLengths[i], elapsedTimes[i]); } } /// <summary> /// Method to run the passed method (runFunc) with a different /// number of inputs and measure computation time. /// </summary> /// <param name="runFunc"></param> public static void RunTest(Action<int[]> runFunc) { /// Create 2 arrays, 1 for test sizes, 1 for holding the elapsed times int[] inputLengths = { 10, 100, 1000, 10000, 50000}; TimeSpan[] elapsedTimes = new TimeSpan[5]; int[] testArray; Console.WriteLine("Beginning tests..."); /// start the timer var watch = Stopwatch.StartNew(); /// loop over the test lengths for (int i = 0; i < inputLengths.Length; i++) { testArray = new int[inputLengths[i]]; FillRandom(testArray, 1, 100); /// restart the timer watch.Restart(); Console.Write("Running function with {0} length...", inputLengths[i]); /// call the passed method with the test length as parameter runFunc(testArray); /// save the time taken to perform elapsedTimes[i] = watch.Elapsed; Console.WriteLine("Function completed execution."); } /// print out the results for the tests Console.WriteLine("\nFinished tests... Results below:\n"); for (int i = 0; i < elapsedTimes.Length; i++) { Console.WriteLine("iterations: {0:0000000}\t Elapsed Time: {1}", inputLengths[i], elapsedTimes[i]); } } /// <summary> /// Helper method. Sets each element of the array to a random number /// in the specified range. /// </summary> /// <param name="array"></param> /// <param name="min"></param> /// <param name="max"></param> public static void FillRandom(int[] array, int min, int max) { for (int i = 0; i < array.Length; i++) { array[i] = new Random().Next(min, max); } } } } <file_sep>/6426-1822/Week7/BinaryTree.cs using System; using System.Collections.Generic; using System.Text; namespace Week7 { public class TreeNode { public int data; public TreeNode parent; public TreeNode left; public TreeNode right; /// We could put the child nodes in a list instead. /// This would allow the nodes to be dynamic in structure. /// public List<TreeNode> children; public TreeNode() { data = 0; parent = null; left = null; right = null; } public TreeNode(TreeNode parent) : this() { this.parent = parent; } public TreeNode(TreeNode parent, int num) : this(parent) { data = num; } public TreeNode(int num) : this() { data = num; } } public class Tree { public TreeNode root; public int maxDepth; public int size; public Tree() { root = null; maxDepth = 0; size = 0; } public void Add(int data) { Add(new TreeNode(data)); } public void Add(TreeNode node) { AddNode(node, root, true, 0); } private void AddNode(TreeNode newNode, TreeNode travNode, bool isLeft, int depth) { if (root == null) { root = newNode; maxDepth = 0; size = 1; return; } if (newNode.data <= travNode.data) { if (travNode.left == null) { travNode.left = newNode; maxDepth = depth > maxDepth ? depth : maxDepth; size++; } else { AddNode(newNode, travNode.left, true, depth + 1); } } else { if (travNode.right == null) { travNode.right = newNode; newNode.parent = travNode; maxDepth = depth > maxDepth ? depth : maxDepth; size++; } else { AddNode(newNode, travNode.right, false, depth + 1); } } } public void Remove(int value) { Remove(value, root); } private void Remove(int value, TreeNode node) { if (node == null) { // data doesn't exist throw new ArgumentException("value not found in tree"); } // traverse to next subtree if (value < node.data) Remove(value, node.left); else if (value > node.data) Remove(value, node.right); else // found the node to replace { // if no children, replace with nothing if (node.left == null && node.right == null) { ReplaceParent(node, null); size--; } else if (node.left == null) // only a right child, use it { ReplaceParent(node, node.right); size--; } else if (node.right == null) // only a left child, use it { ReplaceParent(node, node.left); size--; } else // both children exist. Grab the next highest value and use it { TreeNode nextSmallest = GetSmallest(node.right); node.data = nextSmallest.data; Remove(nextSmallest.data, nextSmallest); } } } private void ReplaceParent(TreeNode node, TreeNode replacementNode) { if (node.parent == null) { root = replacementNode; } else { if (node.parent.left == node) node.parent.left = replacementNode; else node.parent.right = replacementNode; } if (replacementNode != null) replacementNode.parent = node.parent; } public List<TreeNode> Traverse() { List<TreeNode> nodes = new List<TreeNode>(); TraversePreOrder(root, nodes); return nodes; } /// <summary> /// Traversal method for returning the tree as a list of nodes. /// Pre-order traversal /// </summary> /// <param name="node"></param> /// <param name="nodes"></param> public void TraversePreOrder(TreeNode node, List<TreeNode> nodes) { if (node != null) { nodes.Add(node); TraversePreOrder(node.left, nodes); TraversePreOrder(node.right, nodes); } } /// <summary> /// Traversal method for returning the tree as a list of nodes. /// In-order traversal /// </summary> /// <param name="node"></param> /// <param name="nodes"></param> public void TraverseInOrder(TreeNode node, List<TreeNode> nodes) { if (node != null) { TraverseInOrder(node.left, nodes); nodes.Add(node); TraverseInOrder(node.right, nodes); } } /// <summary> /// Traversal method for returning the tree as a list of nodes. /// Post-order traversal /// </summary> /// <param name="node"></param> /// <param name="nodes"></param> public void TraversePostOrder(TreeNode node, List<TreeNode> nodes) { if (node != null) { TraversePostOrder(node.left, nodes); TraversePostOrder(node.right, nodes); nodes.Add(node); } } /// <summary> /// Return a string of the tree nodes in pre-order /// </summary> /// <returns></returns> public override string ToString() { string treeString = ""; string indent = ""; PrintTree(root, ref treeString, indent, true); return treeString; } /// <summary> /// traversal method for the ToString functionality /// </summary> /// <param name="tree"></param> /// <param name="result"></param> /// <param name="indent"></param> /// <param name="last"></param> public void PrintTree(TreeNode tree, ref string result, string indent, bool last) { if (tree != null) { result += (indent + "+- " + tree.data.ToString() + "\n"); indent += last ? " " : "| "; PrintTree(tree.left, ref result, indent, false); PrintTree(tree.right, ref result, indent, true); } } public bool Contains(int value) { TreeNode node = root; while (node != null) { if (node.data == value) return true; else if (node.data <= value) node = node.left; else node = node.right; } return false; } private TreeNode GetSmallest(TreeNode node) { while (node.left != null) node = node.left; return node; } private TreeNode GetLargest(TreeNode node) { while (node.right != null) node = node.right; return node; } } } <file_sep>/6426-1822/6426-1822/SampleClass.cs using System; using System.Collections.Generic; using System.Text; namespace _6426_1822 { class SampleClass { /// global variable with public access public int sampleGlobalVarA; /// code shortcut to add get() and set() methods /// for a member. In this case, sampleGlobalVarB. public int sampleGlobalVarB { /// returns the value get { return sampleGlobalVarB; } /// checks if the attempted value is valid before setting. /// E.G.: condition ? ifTrue : ifFalse; /// if you try this: sampleGlobalVarB = 2 /// it will check that 2 is greater than 0 before setting /// it to the var. If not, it will set it to 1 set { sampleGlobalVarB = (value > 0 ? value : 1); } } /// a global variable, like sampleGlobalVar, /// however, it has no access modifier. /// By default it will have a private access modifier. int samplePrivateGlobalVar; /// <summary> /// Basic constructor. Initialise globals here. /// </summary> public SampleClass() { sampleGlobalVarA = 0; sampleGlobalVarB = 1; samplePrivateGlobalVar = 2; } /// <summary> /// overloaded constructor. If this class is initialised /// with an integer parameter, this constructor will be used /// instead of the basic one above. /// </summary> /// <param name="value"></param> public SampleClass(int value) { /// do something with the passed value samplePrivateGlobalVar = value; } /// <summary> /// Override the default ToString() method to ouput /// our choice of data. Return value must be string. /// </summary> /// <returns></returns> public override string ToString() { return "Sample Class: " + sampleGlobalVarB.ToString() + ", " + samplePrivateGlobalVar.ToString(); } /// <summary> /// A simple method that takes no parameters and returns no values. /// </summary> public void SampleMethod() { Console.WriteLine("You have successfully called a class method!"); } } } <file_sep>/6426-1822/sfml-menu/GameMenu.cs  using System; using System.Collections.Generic; using System.Text; using SFML.Graphics; using SFML.System; using SFML.Window; namespace sfml_menu { /// <summary> /// Class for creating and drawing a game menu (like an escape menu). /// </summary> public class GameMenu { /// Background rectangle RectangleShape recMenuBackground; /// Lists for holding all the text and buttons added to the menu List<MenuButton> buttons; List<MenuText> texts; /// <summary> /// Constructor /// </summary> public GameMenu() { recMenuBackground = new RectangleShape(); buttons = new List<MenuButton>(); texts = new List<MenuText>(); } /// <summary> /// Constructor that sets position and size of menu /// </summary> /// <param name="position"></param> /// <param name="size"></param> public GameMenu(Vector2f position, Vector2f size) : this() { recMenuBackground.Size = size; recMenuBackground.Origin = size / 2; recMenuBackground.Position = position; } /// <summary> /// Constructor that takes position and size as floats and /// passes them as vectors to the other constructor /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> public GameMenu(float x, float y, float width, float height) : this(new Vector2f(x, y), new Vector2f(width, height)) { } /// <summary> /// Return the center coordinates of the menu /// </summary> /// <returns></returns> public Vector2f getCentre() { return recMenuBackground.Position; } /// <summary> /// Set the style attributes of the menu background /// </summary> /// <param name="fillColour"></param> /// <param name="outlineColour"></param> /// <param name="outlineWidth"></param> public void setMenuStyle(Color fillColour, Color outlineColour, float outlineWidth) { recMenuBackground.FillColor = fillColour; recMenuBackground.OutlineColor = outlineColour; recMenuBackground.OutlineThickness = outlineWidth; } /// <summary> /// Check if the mouse click overlaps with any buttons /// and invoke the event if it does /// </summary> /// <param name="X"></param> /// <param name="Y"></param> public void DispatchEvents(int X, int Y) { foreach(MenuButton btn in buttons) { if (btn.checkOverlap(X, Y)) { btn.OnClick(X, Y); } } } /// <summary> /// Add button to the list /// </summary> /// <param name="button"></param> public void AddButton(MenuButton button) { buttons.Add(button); } /// <summary> /// Create a menu button and add it to the list /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="text"></param> /// <param name="font"></param> public void AddButton(float x, float y, float width, float height, string text, Font font) { AddButton(new MenuButton(x, y, width, height, text, font)); } /// <summary> /// Add a menu text label to the list /// </summary> /// <param name="text"></param> public void AddText(MenuText text) { texts.Add(text); } /// <summary> /// Create a menu text label and add it to the list /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="text"></param> /// <param name="font"></param> /// <param name="charsize"></param> public void AddText(float x, float y, string text, Font font, uint charsize) { AddText(new MenuText(x, y, text, font, charsize)); } /// <summary> /// Draw all of the elements of the menu /// </summary> /// <param name="target"></param> /// <param name="state"></param> public void Draw(RenderTarget target, RenderStates state) { /// draw the background first target.Draw(this.recMenuBackground, state); /// draw the buttons over the background foreach (MenuButton btn in buttons) { btn.Draw(target, state); } /// draw the text labels foreach (MenuText text in texts) { text.Draw(target, state); } } } /// <summary> /// Menu Text label class. Provides a way to setup text /// to be used in a game menu /// </summary> public class MenuText { Text text; /// <summary> /// Constructor that creates a menu text label based on the /// passed parameter values /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="text"></param> /// <param name="font"></param> /// <param name="charsize"></param> public MenuText(float x, float y, string text, Font font, uint charsize) { this.text = new Text(text, font, charsize); this.text.Position = new Vector2f(x, y); centerText(); } /// <summary> /// Set the design attributes of the menu text label /// </summary> /// <param name="fillColour"></param> /// <param name="outlineColour"></param> /// <param name="outlineWidth"></param> public void setTextStyle(Color fillColour, Color outlineColour, float outlineWidth) { text.FillColor = fillColour; text.OutlineColor = outlineColour; text.OutlineThickness = outlineWidth; } /// <summary> /// Move the origin of the text object to the centre of the text /// </summary> private void centerText() { var bounds = text.GetLocalBounds(); text.Origin = new Vector2f(bounds.Width / 2, bounds.Height / 2); } /// <summary> /// Check if a point overlaps with the bounds of the text /// </summary> /// <param name="point"></param> /// <returns></returns> public bool checkOverlap(Vector2f point) { return MathLib2D.isPointInRect(text.GetGlobalBounds(), point); } /// <summary> /// Draw the text to the target /// </summary> /// <param name="target"></param> /// <param name="state"></param> public void Draw(RenderTarget target, RenderStates state) { target.Draw(text, state); } } /// <summary> /// Menu Button class. Provides a way to setup a button /// to be used in a game menu and provide click functionality /// </summary> public class MenuButton { RectangleShape recButtonBackground; Text txtButtonText; /// Event handler for the button click. Allows a function to /// be called when a condition passes public event EventHandler<MouseButtonEventArgs> Click; /// <summary> /// Constructor /// </summary> public MenuButton() { recButtonBackground = new RectangleShape(); txtButtonText = new Text(); } /// <summary> /// Constructor that sets up the position and size of the button, /// and the text that is written on the button /// </summary> /// <param name="position"></param> /// <param name="size"></param> /// <param name="text"></param> /// <param name="font"></param> public MenuButton(Vector2f position, Vector2f size, string text, Font font) : this() { recButtonBackground.Origin = size / 2; recButtonBackground.Size = size; recButtonBackground.Position = position; txtButtonText.DisplayedString = text; txtButtonText.Font = font; txtButtonText.Position = position; } /// <summary> /// Contructor that sets up the position and size of the button as /// floats instead of vectors /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="text"></param> /// <param name="font"></param> public MenuButton(float x, float y, float width, float height, string text, Font font) : this(new Vector2f(x, y), new Vector2f(width, height), text, font) { } /// <summary> /// method to invoke the click functionality of the button. /// </summary> /// <param name="X"></param> /// <param name="Y"></param> public void OnClick(int X, int Y) { MouseButtonEventArgs e = new MouseButtonEventArgs(new MouseButtonEvent()); e.X = X; e.Y = Y; this.Click.Invoke(this, e); } /// <summary> /// Set the design attributes of the button /// </summary> /// <param name="fillColour"></param> /// <param name="outlineColour"></param> /// <param name="outlineWidth"></param> public void setButtonStyle(Color fillColour, Color outlineColour, float outlineWidth) { recButtonBackground.FillColor = fillColour; recButtonBackground.OutlineColor = outlineColour; recButtonBackground.OutlineThickness = outlineWidth; } /// <summary> /// Set the design attributes of the text on the button /// </summary> /// <param name="colour"></param> /// <param name="outlineColour"></param> /// <param name="outlineWidth"></param> /// <param name="fontSize"></param> public void setTextStyle(Color colour, Color outlineColour, float outlineWidth, uint fontSize) { txtButtonText.FillColor = colour; txtButtonText.CharacterSize = fontSize; txtButtonText.OutlineColor = outlineColour; txtButtonText.OutlineThickness = outlineWidth; centreText(); } /// <summary> /// Set the origin of the button text to the middle of the text /// </summary> private void centreText() { var bounds = txtButtonText.GetLocalBounds(); txtButtonText.Origin = new Vector2f(bounds.Width / 2, bounds.Height / 2); } /// <summary> /// Check if a point overlaps with the button /// </summary> /// <param name="point"></param> /// <returns></returns> public bool checkOverlap(Vector2f point) { return MathLib2D.isPointInRect(recButtonBackground.GetGlobalBounds(), point); } /// <summary> /// Make a vector from given floats and check for overlaps /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public bool checkOverlap(float x, float y) { return checkOverlap(new Vector2f(x, y)); } /// <summary> /// Draw the button to the target, and draw the text over the top /// </summary> /// <param name="target"></param> /// <param name="state"></param> public void Draw(RenderTarget target, RenderStates state) { target.Draw(recButtonBackground, state); target.Draw(txtButtonText, state); } } } <file_sep>/6426-1822/sfml-1/LinkedList.cs using System; using System.Collections.Generic; using System.Text; using SFML.Graphics; using SFML.System; namespace sfml_list_example { public class Node<T> where T : Shape { public Node<T> next; public T data; public Node(T data) { this.data = data; } public void Delete() { this.next = null; this.data = null; } } public class LinkedList<T> where T : Shape { public Node<T> head; public int count; public LinkedList() { count = 0; } public void Enqueue(T data) { Node<T> newNode = new Node<T>(data); newNode.next = this.head; this.head = newNode; this.count++; Console.WriteLine(this.count); } public T Dequeue() { if (this.head == null) return null; Node<T> trav = this.head; Node<T> trav_trail = this.head; while (trav.next != null) { trav_trail = trav; trav = trav.next; } trav_trail.next = null; this.count--; if (this.count == 0) this.head = null; Console.WriteLine(this.count); GC.Collect(); return trav.data; } public void Empty() { while (this.count > 0) this.Dequeue(); } } } <file_sep>/6426-1822/Week9/Heap.cs using System; using System.Collections.Generic; using System.Text; namespace Week9 { class Heap { List<int> heapList; public Heap() { heapList = new List<int>(); } public void reheapUp(int index) { if (index != 0) { int parentIndex = getParent(index); if (heapList[index] > heapList[parentIndex]) { int temp = heapList[index]; heapList[index] = heapList[parentIndex]; heapList[parentIndex] = temp; reheapUp(parentIndex); } } } public void reheapDown(int root) { int left = getLeft(root); int right = getRight(root); if (heapList.Count > left) // left child exist { int biggestChild; if (heapList.Count > right) // right child exist { biggestChild = heapList[left] > heapList[right] ? left : right; } else // right child does not exist { biggestChild = left; } // if root smaller than biggest child: swap, recur if (heapList[root] < heapList[biggestChild]) { swap(root, biggestChild); reheapDown(biggestChild); } } } public void insert(int value) { heapList.Add(value); reheapUp(heapList.Count - 1); } public int delete() { if (heapList.Count == 0) return -1; int removedValue = heapList[0]; heapList[0] = heapList[heapList.Count - 1]; heapList.RemoveAt(heapList.Count - 1); reheapDown(0); return removedValue; } private int getLeft(int index) { return 2 * index + 1; } private int getRight(int index) { return 2 * index + 2; } private int getParent(int index) { if (index % 2 == 1)// odd number = left { return (index - 1) / 2; } else { return (index - 2) / 2; } } private void swap(int a, int b) { int temp = heapList[a]; heapList[a] = heapList[b]; heapList[b] = temp; } public override string ToString() { return string.Join(',', heapList.ToArray()); } } } <file_sep>/6426-1822/Week2/LinkedList.cs using System; using System.Collections.Generic; using System.Text; namespace Week2 { /// <summary> /// Node class. Responsible for holding a value and /// a reference to another node. That's it. /// </summary> public class LLNode { public int value; public LLNode next; public LLNode(int value) { this.value = value; } } /// <summary> /// Data type class. Handles the creation, manipulation, /// modification and removal of values. /// </summary> public class LinkedList { /// The entry point of the list public LLNode start; /// <summary> /// Empty constructor /// </summary> public LinkedList() { } /// <summary> /// Helper method that takes an int and adds it /// to the list in the form of a node /// </summary> /// <param name="value"></param> public void AddNode(int value) { /// new node to be added LLNode newNode = new LLNode(value); /// If no nodes have been added yet set the /// start of the list to the new node if (this.start == null) this.start = newNode; /// A node has been added already, find /// the end of the chain else { /// Create a reference to the starting node LLNode traversalNode = this.start; /// Until we get to the end of the chain while (traversalNode.next != null) { /// Move the reference to the next node /// in the chain traversalNode = traversalNode.next; } /// Once the while loop finishes, we will be /// at the end of the chain. /// Point the last node in the chain to the /// newly-created node, adding it to our chain traversalNode.next = newNode; } } } } <file_sep>/6426-1822/Week7/Program.cs using System; using System.Linq; using System.Collections.Generic; namespace Week7 { class Program { static void Main(string[] args) { var myTree = new Tree(); Random random = new Random(); List<int> myList = new List<int>(Enumerable.Range(1, 20).OrderBy(num => random.Next())); foreach (int i in myList) myTree.Add(i); Console.WriteLine(myTree.ToString()); myTree.Add(30); Console.WriteLine(myTree.ToString()); myTree.Remove(15); Console.WriteLine(myTree.ToString()); List<TreeNode> preList = myTree.Traverse(); Console.ReadLine(); } } } <file_sep>/6426-1822/Week3/inClassLinkedList.cs using System; using System.Collections.Generic; using System.Text; namespace Week3 { public class inClassLinkedList { public inClassNode head; public int max = 0; public int min = 0; public int length = 0; public inClassLinkedList() { } public inClassLinkedList(int value) { inClassNode tempNode = new inClassNode(value); this.head = tempNode; } public void AddNode(int value) { // added node here if (value > max) max = value; if (value < min) min = value; ++length; } } } <file_sep>/6426-1822/sfml-menu/2DMath.cs using System; using System.Collections.Generic; using System.Text; using SFML.System; using SFML.Graphics; namespace sfml_menu { /// <summary> /// Static helper class to provide commonly used functionality in one place /// </summary> public static class MathLib2D { /// <summary> /// Check if a point (CheckX, CheckY) is inside the bounds of a rectangle(x, y, width, height) /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="checkX"></param> /// <param name="checkY"></param> /// <returns></returns> public static bool isPointInRect(float x, float y, float width, float height, float checkX, float checkY) { return (checkX >= x && checkX <= x + width && checkY >= y && checkY <= y + height); } /// <summary> /// Check if a point is inside the bounds of a rectangle, using vector inputs /// </summary> /// <param name="pos"></param> /// <param name="size"></param> /// <param name="point"></param> /// <returns></returns> public static bool isPointInRect(Vector2f pos, Vector2f size, Vector2f point) { return isPointInRect(pos.X, pos.Y, size.X, size.Y, point.X, point.Y); } /// <summary> /// Check if a point is inside the bounds of a rectangle, using FloatRect input /// </summary> /// <param name="bounds"></param> /// <param name="point"></param> /// <returns></returns> public static bool isPointInRect(FloatRect bounds, Vector2f point) { return isPointInRect(bounds.Left, bounds.Top, bounds.Width, bounds.Height, point.X, point.Y); } } }
c2292cc294d44451d2d11cc6d092d0aa20d01f0d
[ "Markdown", "C#" ]
35
C#
SabrianJ/6426-1822
be1596973efe8b2ba7fdfc6a351eed5a436acbc2
513349c1f123b6716fc24185eba0d408759c0276
refs/heads/master
<repo_name>dherik/check-password<file_sep>/src/main/java/io/github/dherik/CheckPasswordRS.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package io.github.dherik; import io.github.dherik.dto.PasswordDto; import io.github.dherik.dto.ResultDto; import io.github.dherik.password.Complexity; import static spark.Spark.*; import static io.github.dherik.util.JsonTransformer.*; import io.github.dherik.password.PasswordValidate; import io.github.dherik.password.ResultValidate; /** * * @author dherik */ class CheckPasswordRS { public static void main(String[] args) { staticFileLocation("/public"); //apenas para iniciar o spark server get("/hello", (req, res) -> "Avaliador de segurança para senhas"); post("/checkPwd", (req, res) -> { String body = req.body(); PasswordDto passwordDto = fromJson(body, PasswordDto.class); ResultValidate result = new PasswordValidate(passwordDto.getPassword()).checkPwd(); final Complexity complexity = result.getComplexity(); ResultDto resultDto = new ResultDto(translate(complexity), result.getScore()); return toJson(resultDto); }); } private static String translate(Complexity complexity) { if (complexity == Complexity.VeryWeak) { return "Muito Fraca"; } else if (complexity == Complexity.Weak) { return "Fraca"; } else if (complexity == Complexity.Good) { return "Boa"; } else if (complexity == Complexity.Strong) { return "Forte"; } return "Muito Forte"; } } <file_sep>/src/test/java/io/github/dherik/util/PasswordValidateTest.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package io.github.dherik.util; import io.github.dherik.password.Complexity; import io.github.dherik.password.ResultValidate; import io.github.dherik.password.PasswordValidate; import org.junit.Test; import static org.junit.Assert.*; /** * * @author dherik */ public class PasswordValidateTest { @Test public void testeMuitoFraca() { String password = "<PASSWORD>"; ResultValidate result = new PasswordValidate(password).checkPwd(); assertEquals(Complexity.VeryWeak, result.getComplexity()); assertEquals(4, result.getScore()); } @Test public void testeMuitoFraca2() { String password = "11"; ResultValidate result = new PasswordValidate(password).checkPwd(); assertEquals(Complexity.VeryWeak, result.getComplexity()); assertEquals(0, result.getScore()); } @Test public void testeFraca() { String password = "<PASSWORD>"; ResultValidate result = new PasswordValidate(password).checkPwd(); assertEquals(Complexity.Weak, result.getComplexity()); assertEquals(38, result.getScore()); } @Test public void testeBoa() { String password = "<PASSWORD>"; ResultValidate result = new PasswordValidate(password).checkPwd(); assertEquals(Complexity.Good, result.getComplexity()); assertEquals(40, result.getScore()); } @Test public void testeBoa2() { String password = "<PASSWORD>#"; ResultValidate result = new PasswordValidate(password).checkPwd(); assertEquals(Complexity.Good, result.getComplexity()); assertEquals(52, result.getScore()); } @Test public void testeBoa3() { String password = "<PASSWORD>$"; ResultValidate result = new PasswordValidate(password).checkPwd(); assertEquals(Complexity.Good, result.getComplexity()); assertEquals(52, result.getScore()); } @Test public void testeForte() { String password = "<PASSWORD>"; ResultValidate result = new PasswordValidate(password).checkPwd(); assertEquals(Complexity.Strong, result.getComplexity()); assertEquals(71, result.getScore()); } @Test public void testeForte2() { String password = <PASSWORD>"; ResultValidate result = new PasswordValidate(password).checkPwd(); assertEquals(Complexity.Strong, result.getComplexity()); assertEquals(69, result.getScore()); } @Test public void testeForte3() { String password = "<PASSWORD>"; ResultValidate result = new PasswordValidate(password).checkPwd(); assertEquals(Complexity.VeryStrong, result.getComplexity()); assertEquals(83, result.getScore()); } @Test public void testeForte4() { String password = "<PASSWORD>"; ResultValidate result = new PasswordValidate(password).checkPwd(); assertEquals(Complexity.VeryStrong, result.getComplexity()); assertEquals(99, result.getScore()); } @Test public void testeForte5() { String password = "<PASSWORD>"; ResultValidate result = new PasswordValidate(password).checkPwd(); assertEquals(Complexity.VeryStrong, result.getComplexity()); assertEquals(100, result.getScore()); } } <file_sep>/src/main/resources/public/js/password.js function changeWeaknessTo(weakness){ $('#colorComplexity').removeClass('muito-fraca fraca boa forte muito-forte').addClass(weakness); } var delay = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); $('#passwordPwd').keyup(function() { var password = this.value; delay(function(){ $.ajax({ url: '/checkPwd', type: 'POST', data: JSON.stringify({ 'password': <PASSWORD> }), contentType: 'application/json; charset=utf-8', dataType: 'json', async: false, success: function(data) { $('#score').text(data.score + '%'); $('#complexity').text(data.complexity); changeBackgroundColorComplexity(data.score); } }); }, 1000 ); }); function changeBackgroundColorComplexity(nScore){ if (nScore > 100) { nScore = 100; } else if (nScore < 0) { changeWeaknessTo('muito-fraca');} if (nScore >= 0 && nScore < 20) { changeWeaknessTo('muito-fraca');} else if (nScore >= 20 && nScore < 40) { changeWeaknessTo('fraca');} else if (nScore >= 40 && nScore < 60) { changeWeaknessTo('boa');} else if (nScore >= 60 && nScore < 80) { changeWeaknessTo('forte');} else if (nScore >= 80 && nScore <= 100) { changeWeaknessTo('muito-forte');} } <file_sep>/README.md # check-password Java code to show the strength of the password, using Java 8, Spark, Bootstrap and jQuery # Requirements - Java 8 # Build mvn clean install # Run 1. Run `CheckPasswordRS` to start the Spark server. 2. Access [http://localhost:4567/index.html](http://localhost:4567/index.html) 3. Enjoy # TODO - Translate to English - Break the main check password code in more classes - Clear CSS - Add more tests - Change the rest service to check the password from POST do GET
d61f203f0bd18777aba5e137fb3777cdb0d15dc4
[ "JavaScript", "Java", "Markdown" ]
4
Java
dherik/check-password
dc819584036cdf06ef5bced4908252a0ef5e3536
e31d5229b3df62984d3118b032d55ccbab4d5c23
refs/heads/master
<file_sep>let name = prompt('<NAME>',''); let fname = document.getElementById('inp') console.log(fname) fname.innerHTML = `welcome ${name}`; let input1 = document.querySelector('#name') let input2 = document.querySelector('#num') let input3 = document.querySelector('#address') let addToCart = document.querySelector('#btn1') let removeFromCart = document.querySelector('#btn2') let products = [] addToCart.addEventListener('click',(e)=>{ let product = { 'Product' : input1.value, 'Price' : input2.value, 'Delivery_Adress' : input3.value } products.push(product) localStorage.setItem('User_Products',JSON.stringify(products)) console.log(products) e.preventDefault() } ) removeFromCart.addEventListener('click',(e)=>{ localStorage.removeItem() }) function myFunction() { location.replace("file:///home/mrphython/Documents/Web_Development/chibykes%20assignment/message.html") } function myFunction1() { alert('Good-bye') location.replace("file:///home/mrphython/Documents/Web_Development/chibykes%20assignment/chat.html") } function myFunction2() { location.replace("file:///home/mrphython/Documents/Web_Development/chibykes%20assignment/message.html") }
4b15c1fc7c9459fd4d65fc3f8cc633cf94126a03
[ "JavaScript" ]
1
JavaScript
BlessedEmoefe/japhets-project
6d70f0fc06e380cc1e1d3ee7e07d9f1d878b9406
39d077af83b179e80b3f6e8fe75698000012fdc7
refs/heads/master
<file_sep>$( document ).ready(function() { $('.form-search').on('submit',function(){return false;}); $('.form-search .btn').on('click', function(e){ var query = $.trim($(this).prevAll('.search-query').val()).toLowerCase(); $('div.product-grid__product-wrapper .product-grid__title').each(function(){ var $this = $(this); if($this.text().toLowerCase().indexOf(query) === -1) $this.closest('div.product-grid__product-wrapper').fadeOut(); else $this.closest('div.product-grid__product-wrapper').fadeIn(); }); }); }); function addCart(title, image, price) { localStorage.setItem("title", title); localStorage.setItem("image", image); localStorage.setItem("price", price); window.location.href = "./cart.html"; }<file_sep>$( document ).ready(function() { $('.product-grid__img').attr("src", localStorage.getItem("image")); $('.product-grid__title').html(localStorage.getItem("title")); $('.product-grid__price').html(localStorage.getItem("price")); localStorage.clear(); });
6d9881927c45d8c5d94737914b840110ea73cc25
[ "JavaScript" ]
2
JavaScript
Thejashwini96/e-commerce
0bbe40b55f53ccb196d88b876433c941ada9a835
15140ad3bc18d0814c6944da8a37195b8a33aa74
refs/heads/master
<repo_name>mbondyra/inspector-dom<file_sep>/src/index.js var VALID_CLASSNAME = /^[_a-zA-Z\- ]*$/ var constructCssPath = el => { if (!(el instanceof Element)) return let path = [] while (el.nodeType === Node.ELEMENT_NODE) { let selector = el.nodeName.toLowerCase() if (el.id) { selector += `#${el.id}` path.unshift(selector) break } else if (el.className && VALID_CLASSNAME.test(el.className)) { selector += `.${(el.className.trim()).replace(/\s+/g, '.')}` } else { let sib = el, nth = 1 while ((sib = sib.previousElementSibling)) { if (sib.nodeName.toLowerCase() == selector) nth++ } if (nth != 1) selector += ':nth-of-type(' + nth + ')' } path.unshift(selector) el = el.parentNode } return path.join(' > ') } var defaultProps = { root: 'body', outlineStyle: '5px solid rgba(204, 146, 62, 0.3)', onClick: el => console.log('Element was clicked:', constructCssPath(el)) } var Inspector = ((props = {}) => { const {root, excluded, outlineStyle} = { ...defaultProps, ...props } let onClick = props.onClick || defaultProps.onClick let selected, excludedElements const removeHighlight = el => { if (el) el.style.outline = 'none' } const highlight = el => { el.style.outline = outlineStyle el.style.outlineOffset = `-${el.style.outlineWidth}` } const shouldBeExcluded = ev => { if (excludedElements && excludedElements.length && excludedElements.some(parent => (parent === ev.target || parent.contains(ev.target)))){ return true } } const handleMouseOver = ev => { if (shouldBeExcluded(ev)){ return } selected = ev.target highlight(selected) } const handleMouseOut = ev => { if (shouldBeExcluded(ev)){ return } removeHighlight(ev.target) } const handleClick = ev => { if (shouldBeExcluded(ev)){ return } ev.preventDefault() ev.stopPropagation() onClick(ev.target) return false } const prepareExcluded = (rootEl) => { if (!excluded.length){ return [] } const excludedNested = excluded.flatMap(element => { if (typeof element === 'string' || element instanceof String){ return Array.from(rootEl.querySelectorAll(element)) } else if (element instanceof Element){ return [element] } else if (element.length>0 && element[0] instanceof Element){ return Array.from(element) } }) return Array.from(excludedNested).flat() } const enable = onClickCallback => { const rootEl = document.querySelector(root) if (!rootEl) return if (excluded){ excludedElements = prepareExcluded(rootEl) } rootEl.addEventListener('mouseover', handleMouseOver, true) rootEl.addEventListener('mouseout', handleMouseOut, true) rootEl.addEventListener('click', handleClick, true) if (onClickCallback){ onClick = onClickCallback } } const cancel = () => { const rootEl = document.querySelector(root) if (!rootEl) return rootEl.removeEventListener('mouseover', handleMouseOver, true) rootEl.removeEventListener('mouseout', handleMouseOut, true) rootEl.removeEventListener('click', handleClick, true) removeHighlight(selected) } return { enable, cancel } }) module.exports = Inspector <file_sep>/README.md # Inspector Dom Pure vanilla-js ultra-lightweight dom inspector similiar to built-in tool in chrome browser with a custom callback onClick. ![](inspector.gif) ## Install yarn add inspector-dom `const Inspector = require('inspector-dom')` `import Inspector from 'inspector-dom'` ## Usage Initialize: `const inspector = Inspector()` Props: ```javascript const inspector = Inspector({ root: 'body', // root element excluded: [], // excluded children, string or node Element outlineStyles: '2px solid orange', // styles onClick: el => console.log('Element was clicked:', constructCssPath(el) //onClick callback }); ``` ## API `inspector.enable() // turn the inspector on` `inspector.cancel() // turn the inspector off`
f3f839593985e652377d4cb7e8453e138f2a1a48
[ "JavaScript", "Markdown" ]
2
JavaScript
mbondyra/inspector-dom
7986d375cf9ef6ec68a50e205bff54d1b0984782
1898f005348862ec912fdd174c2d3cb5ec9bef11
refs/heads/master
<repo_name>freezeChen/blog<file_sep>/src/api/Mock.js // var axios = require('axios') // let MockAdapter = require('axios-mock-adapter') // // // export default { // init() { // let mock = new MockAdapter(axios); // // // mock.onGet('/getList').reply(200, { // code: 0, // msg: 'success', // data: { // author: 'ming', // time: '2019-01-01 23:11:34', // language: 'go' // } // }) // // } // } // // // <file_sep>/src/api/api.js import axios from 'axios' let URL = "http://localhost:8081/" const getMainList = (page, size, callback) => { let url = URL + "getHomeList?page=" + page + "&size=" + size axios.get(url).then(num => { callback && callback(num.data) }) } export { getMainList } <file_sep>/src/router/index.js import Vue from 'vue' import Router from 'vue-router' import Aboutme from '../pages/Aboutme' import Home from '../pages/Home' import Type from '../pages/type' Vue.use(Router) export default new Router({ routes: [ { path: '/aboutme', component: Aboutme, name: 'Aboutme' }, { path: '/home', component: Home, name: 'home' }, { path: '/type', component: Type, name: 'type', } ] })
068e080fed21a2a1233dd203484f29683aa38a0b
[ "JavaScript" ]
3
JavaScript
freezeChen/blog
0ba619b03956974d846054b92b5e79e685e1c417
3febd940844c525bd6d664177796ab66ff71e0e3
refs/heads/master
<repo_name>vishal1565/Networking<file_sep>/misc/README.md # README This contains some of miscellaneous networking codes. <file_sep>/tcp_server_single_request.c #include<stdio.h> #include<stdlib.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<unistd.h> #include<string.h> #define PORT 1555 int main(){ struct sockaddr_in address; int sd = socket(AF_INET,SOCK_STREAM,0); char *serverMsg = "Hello Client"; char buffer[1024] = {0}; if(sd == -1){ perror("Server's Socket Creation Failed!!\n"); exit(0); } printf("Server's Socket created successfully!!\n"); address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); bind(sd,(struct sockaddr*)&address,sizeof(address)); listen(sd,1); printf("Server is in LISTEN MODE\n"); int add_len = sizeof(address); int accept_conn = accept(sd,(struct sockaddr*)&address,(socklen_t*)&add_len); printf("Reading Message from Client\n"); int readMsg = read(accept_conn,buffer,1024); if(readMsg == -1){ printf("\nFailed to read message from client\n"); } printf("Message from Client:\n"); printf("%s\n",buffer); printf("\nNow Sending Message to client\n"); int sendMsg = send(accept_conn,serverMsg,strlen(serverMsg),0); if(sendMsg == -1){ printf("\nFailed to send message to client\n"); } printf("Message sent to Client\n"); return 0; }<file_sep>/Assignment3/packetSniffing.py import socket import struct import os import sys # Unpack Ethernet frames def ethernetFrame(data): dest, src, proto = struct.unpack('! 6s 6s H', data[:14]) return macAddr(dest), macAddr(src), socket.htons(proto), data[14:] # Fomatting Mac Address def macAddr(byteAddr): byteStr = map('{:02x}'.format, byteAddr) macAddress = ':'.join(byteStr).upper() return macAddress # Unpack IPv4 packet def ipv4Packet(data): versionLength = data[0] version = versionLength >> 4 headerLength = (versionLength & 15)*4 ttl, proto, src, target = struct.unpack('! 8x B B 2x 4s 4s', data[:20]) return version, ttl, proto, ipv4Format(src), ipv4Format(target), data[versionLength:] # Format IPv4 address def ipv4Format(addr): return '.'.join(map(str,addr)) # Unpack ICMP packet def icmpPacket(data): icmpType, code, checkSum = struct.unpack('! B B H', data[:4]) return icmpType, code, checkSum, data[4:] # Unpack TCP Segment def tcpSegment(data): srcPort, destPort, seq, ack, offsetFlag = struct.unpack('! H H L L H', data[:14]) offset = (offsetFlag >> 12)*4 flagUrg = (offsetFlag & 32) >> 5 flagAck = (offsetFlag & 16) >> 5 flagPsh = (offsetFlag & 8) >> 5 flagRst = (offsetFlag & 4) >> 5 flagSyn = (offsetFlag & 2) >> 5 flagFin = (offsetFlag & 1) return srcPort, destPort, seq, ack, flagUrg, flagAck, flagPsh, flagRst, flagSyn, flagFin, data[offset:] # Unpack UDP Segment def udpSegment(data): srcPort, destPort, size = struct.unpack('! H H 2x H', data[:8]) return srcPort, destPort, size, data[8:] sd = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3)) while True: rawData, addr = sd.recvfrom(65536) destMac, srcMac, ethProto, data = ethernetFrame(rawData) print("\n\n************************************************************************************") print("Ethernet Frame :") print("\nProtocol:", ethProto) print("Destination:",destMac) print("Source:",srcMac,"\n") if ethProto == 8: version, ttl, proto, src, target, ipv4Data = ipv4Packet(rawData) print("\t-IPv4 Packet :") print("\t>>Version :",version) print("\t>>TTL :",ttl) print("\t>>Protocol : ",proto) print("\t>>Source : ",src) print("\t>>Destination : ",target) if proto == 1: icmpType, code, checkSum, icmpData = icmpPacket(data) print("\n\n\t-ICMP Packet :") print("\t>>Type : ",icmpType) print("\t>>Code : ",code) print("\t>>CheckSum : ",checkSum) print("\t>>Data : ",icmpData) elif proto == 6: srcPort, destPort, seq, ack, flagUrg, flagAck, flagPsh, flagRst, flagSyn, flagFin, tcpData = tcpSegment(data) print("\n\n\t-TCP Segment : ") print("\t>>Source Port : ",srcPort) print("\t>>Destination Port : ",destPort) print("\t>>Sequence : ",seq) print("\t>>Acknowledgement : ",ack) print("\t>>Flags: ") print("\t>>URG : ",flagUrg,"\tACK : ",flagAck,"\tPSH : ",flagPsh,"\tRST : ",flagRst,"\tSYN : ",flagSyn,"\tFIN : ",flagFin) print("\t>>Data : ",tcpData) elif proto == 17: srcPort, destPort, length, data = udpSegment(data) print("\n\n\t-UDP Segment : ") print(">>Source Port : ",srcPort) print(">>Destination Port : ",destPort) print(">>Length : ",length) print(">>Data : ",data) else: print(">>Data : ",data) else: print(">>Data : ",data) <file_sep>/Assignment2/ftpServer.c #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<string.h> #define PORT 1600 #define cipherKey 'S' #define sendrecvflag 0 #define nofile "File Not Found!" void clearBuf(char* b) { int i; for (i = 0; i < 1024; i++) b[i] = '\0'; } // funtion to encrypt char Cipher(char ch) { return ch ^ cipherKey; } // funtion sending file int sendFile(FILE* fp, char* buf, int s) { int i, len; if (fp == NULL) { strcpy(buf, nofile); len = strlen(nofile); buf[len] = EOF; for (i = 0; i <= len; i++) buf[i] = Cipher(buf[i]); return 1; } char ch, ch2; for (i = 0; i < s; i++) { ch = fgetc(fp); ch2 = Cipher(ch); buf[i] = ch2; if (ch == EOF) return 1; } return 0; } int main(){ int sd; struct sockaddr_in server; int addrlen = sizeof(server); char buffer[1024], command[10]; sd = socket(AF_INET,SOCK_DGRAM,0); if(sd==-1){ printf("Socket Creation Failed...\n"); exit(0); } else{ printf("Socket Creation Successful!!...\n"); } server.sin_family=AF_INET; server.sin_addr.s_addr=INADDR_ANY; server.sin_port=htons(PORT); int binding=bind(sd,(struct sockaddr *)&server,sizeof(server)); if(binding==-1){ printf("Binding Failed!!...\n"); } else{ printf("\nSocket Binding Successful!!...\n"); } listen(sd,3); accept(sd,(struct sockaddr *)&server,(socklen_t*)&addrlen); FILE *fp; while(1){ printf("\nWaiting for Client's Request....\n"); clearBuf(buffer); int nBytes=recvfrom(sd,buffer,2048,sendrecvflag,(struct sockaddr *)&server,&addrlen); printf("\nClient is requesting file: %s\n",buffer); fp=fopen(buffer,"r"); if(fp==NULL){ printf("\nFailed to Open File !!\n"); } printf("Now sending file to client..\n"); while (1) { // process if (sendFile(fp, buffer, 2048)) { sendto(sd, buffer, 2048, sendrecvflag, (struct sockaddr*)&server, addrlen); break; } // send sendto(sd, buffer, 2048, sendrecvflag, (struct sockaddr*)&server, addrlen); clearBuf(buffer); } if (fp != NULL) fclose(fp); } }<file_sep>/pyServer.py import socket import sys sd = socket.socket(socket.AF_INET,socket.SOCK_STREAM) serverAdd = (input("Enter Host: "),1555) sd.bind(serverAdd) sd.listen(1) print("Server is UP and RUNNING!!\n") conn, addr = sd.accept() print("Client Connected:",addr,"\n") fileName = conn.recv(1024).decode() print("Client is sending file",fileName,"\n") fp = open(fileName,"wb") while True: filesize = conn.recv(1024).decode() print(filesize,type(filesize)) data = conn.recv(int(filesize)+100) #data = conn.recv(100000) if not data: break fp.write(data) fp.close() print("File Received Successfully!!!\nClosing Connection....\n") sys.exit(0)<file_sep>/Assignment1/UDPserver.c #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include<time.h> #define PORT 1555 int main(){ struct sockaddr_in serverAdd, cliAdd; int sd = socket(AF_INET,SOCK_DGRAM,0); if(sd<0){ perror("Failed to create Socket...\n"); exit(EXIT_FAILURE); } memset(&serverAdd, 0, sizeof(serverAdd)); memset(&cliAdd, 0, sizeof(cliAdd)); serverAdd.sin_family = AF_INET; serverAdd.sin_addr.s_addr = INADDR_ANY; serverAdd.sin_port = htons(PORT); int bindStatus = bind(sd,(struct sockaddr*)&serverAdd,sizeof(serverAdd)); if(bindStatus<0){ perror("Binding Failed..\n"); exit(EXIT_FAILURE); } int len,n,i; len = sizeof(cliAdd); char buffer[1024]; for(i=0;i<10;i++){ n = recvfrom(sd, (char *)buffer, 1024, MSG_WAITALL, (struct sockaddr *)&cliAdd, &len); buffer[n] = '\0'; printf("Client: %s\n",buffer); char *msg = "PONG from Server"; sendto(sd, (char *)msg, strlen(msg), MSG_CONFIRM, (struct sockaddr *)&cliAdd, len); printf("Server: %s\n",msg); } return 0; }<file_sep>/Assignment2/ftpClient.c #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<string.h> #define PORT 1600 #define cipherKey 'S' #define sendrecvflag 0 #define nofile "File Not Found!" // funtion to clear buffer void clearBuf(char* b) { int i; for (i = 0; i < 1024; i++) b[i] = '\0'; } // function for decryption char Cipher(char ch) { return ch ^ cipherKey; } // function to receive file int recvFile(char* fileName, char* buf, int s){ int i; char ch; FILE *fp; fp = fopen(fileName,"w"); for (i = 0; i < s; i++) { ch = buf[i]; ch = Cipher(ch); if (ch == EOF){ printf("\nFile Saved Successfully in '%s'\n",fileName); fclose(fp); return 1; } else{ fprintf(fp,"%c",ch); } } return 0; } int main(){ int sock; struct sockaddr_in client; char buffer[1024]; int addrlen=sizeof(client); sock=socket(AF_INET,SOCK_DGRAM,0); if(sock==-1){ printf("Not created\n"); } client.sin_family=AF_INET; client.sin_addr.s_addr=INADDR_ANY; client.sin_port=htons(PORT); while(1){ char *fileName = malloc(sizeof(char)); printf("\nEnter the FileName:\n>> "); scanf("%s",fileName); sendto(sock, fileName, 2048, sendrecvflag, (struct sockaddr *)&client, addrlen); while (1) { // receive clearBuf(buffer); int nBytes = recvfrom(sock, buffer, 2048, sendrecvflag, (struct sockaddr*)&client, &addrlen); // process if (recvFile(fileName, buffer, 2048)) { break; } } } }<file_sep>/Assignment1/README.md # Problem Statement 1 Develop a simple web server which is capable of processing only one request. Develop a simple client which sends a request for an image file (i.e., pgm format) and the server sends the file to the client. The client after receiving the file, inverts it and sends it to the server. The server after receiving it, displays theinverted image and the original image side by side. # Problem Statement 2 Write a client ping program using UDP. The corresponding server will send a pong message back. Determine the delay between when the client sent the ping message and received the pong message. This delay is called the Round Trip Time (RTT). Report the average the RTT for 10 such ping messages. <file_sep>/Assignment1/client.py import socket import sys import os def imgHeader(height,width,fp,fileName): fp.write("P2\n") fp.write(("# "+fileName+"\n")) fp.write((str(height)+" "+str(width)+"\n")) fp.write("15") sd = socket.socket(socket.AF_INET,socket.SOCK_STREAM) serverAdd = ("127.0.0.1",1555) sd.connect(serverAdd) print("Connected to Server...\nNow requesting Image...") msg = "Requesting Image" sd.send(msg.encode()) # Now receiving dimensions of image height = int(sd.recv(1024).decode()) width = sd.recv(1024).decode() width = int(width) print("Height: ",height) print("Width: ",width) # Now Receiving Image print("\nNow Receiving Image from Server...") img = [] fileName = "receivedImage.pgm" fp = open(fileName,"w") imgHeader(height,width,fp,fileName) for _ in range(height): temp = sd.recv(1024).decode() fp.write(("\n"+temp)) img.append(temp) fp.close() print("\nSuccessfully received the Image...") # Now inverting Image print("\nInverting the Image...") fileName = "invertedImage.pgm" fp = open(fileName,"w") imgHeader(height,width,fp,fileName) print("\nNow Inverting Image...") invImage = [] for i in img: temp = [(15-int(j)) for j in i.split()] temp1 = " ".join(str(k) for k in temp) fp.write(("\n"+temp1)) invImage.append(temp) fp.close() print("\nImage Inversion Successful...\n") # Now Sending Inverted Image to Server print("\nNow sending Inverted Image to Server") for i in invImage: sd.send((" ".join(str(j) for j in i)).encode()) print("\nInverted Image Sent to Server...") sd.close()<file_sep>/misc/GeolocationFromIP/locFromIP.py import geoip2 import geoip2.database import webbrowser import os import sys readDB = geoip2.database.Reader('./Geolite2-City.mmdb') add = input("Enter IP Address: ") print(add) a = input() getLoc = readDB.city(add) print("Country :",getLoc.country.name) print("City :",getLoc.city.name) print("Postal Code :",getLoc.postal.code) print("Latitude :",getLoc.location.latitude) print("Longitude :",getLoc.location.longitude) lat, lon = getLoc.location.latitude,getLoc.location.longitude mapUrl = 'http://www.google.com/maps/place/49.46800006494457,17.11514008755796'+str(lat)+','+str(lon) webbrowser.open(mapUrl) <file_sep>/Assignment1/UDPclient.c #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include<time.h> #define PORT 1555 int main(){ struct sockaddr_in serverAdd, cliAdd; clock_t start,end; double t1, avg=0; int sd = socket(AF_INET,SOCK_DGRAM,0); if(sd<0){ perror("Failed to create Socket...\n"); exit(EXIT_FAILURE); } serverAdd.sin_family = AF_INET; serverAdd.sin_addr.s_addr = INADDR_ANY; serverAdd.sin_port = htons(PORT); int len,n,i; char buffer[1024]; char *msg = "PING from Client"; for (i=0;i<10;i++){ start = clock(); sendto(sd, (char *)msg, strlen(msg), MSG_CONFIRM, (struct sockaddr *)&serverAdd, sizeof(serverAdd)); printf("Client: %s\n",msg); n = recvfrom(sd, (char *)buffer, 1024, MSG_WAITALL, (struct sockaddr *)&cliAdd, &len); buffer[n] = '\0'; printf("Server: %s\n",buffer); end = clock(); t1 = (double)((end-start)/CLOCKS_PER_SEC)*1000000; avg += t1; } avg /= 10; printf("Average RTT is %f\n",avg); return 0; }<file_sep>/Assignment1/pyServer.py import socket import sys import random def imgHeader(height,width,fp,fileName): fp.write("P2\n") fp.write(("# "+fileName+"\n")) fp.write((str(height)+" "+str(width)+"\n")) fp.write("15") sd = socket.socket(socket.AF_INET,socket.SOCK_STREAM) serverAdd = ("127.0.0.1",1555) sd.bind(serverAdd) sd.listen(1) print("Server is UP and RUNNING!!\n") conn, addr = sd.accept() print("Client Connected:",addr,"\n") msg = conn.recv(1024).decode() print("Client:",msg) print("\nNow Generating a Random Image\n") fileName = "generatedImage.pgm" fp = open(fileName,"w") height, width, img = 10, 10, [] imgHeader(height,width,fp,fileName) for i in range(height): temp = [] for j in range(width): temp.append(random.randint(0,15)) temp1 = " ".join(str(k) for k in temp) fp.write(("\n"+temp1)) img.append(temp) fp.close() print("Random Image generated Successfully..\nSaving File in 'generatedImage.pgm'") # Sending dimensions of Image conn.send(str(height).encode()) conn.send(str(width).encode()) # Now sending Image to Client for i in img: conn.send((" ".join(str(j) for j in i)).encode()) # Receiving Inverted Image from Client invImage = [] fileName = "invertedImage.pgm" fp = open(fileName,"w") imgHeader(height,width,fp,fileName) print("\nReceiving Inverted Image from Client\n") for _ in range(height): temp = conn.recv(1024).decode() fp.write(("\n"+temp)) invImage.append(temp) fp.close() print("Successfully Received Inverted Image from Client\n") sd.close() <file_sep>/Assignment2/Geolocation/README.md # Python Code to find GeoLocation using Public IP Address ## How to Use webbrowser</br> ``` pip install webbrowser ``` GeoIP2</br> ``` pip install geoip2 ``` Next Download GeoIP2 database using ``` wget https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz ``` Extract the database ``` tar -xzf GeoLite2-City.tar.gz ``` </br> Now run the Python code:+1:</br></br> <b>NOTE:</b> You can only track a public IP Address using this. Private IP Addresses like 10.24.x.x or 192.168.x.x cannot be tracked by it. <file_sep>/README.md # Networking This repository contains all of my codes of Networking Lab and some miscellaneous codes. <file_sep>/tcp_client.c #include<stdio.h> #include<stdlib.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<unistd.h> #include<string.h> #define PORT 1555 int main(){ struct sockaddr_in address; int sd = socket(AF_INET,SOCK_STREAM,0); if(sd == -1){ perror(" Client's Socket Creation Failed!!\n"); exit(0); } printf("Client's Socket created successfully!!\n"); address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); printf("Client now trying to connect\n"); int new_conn = connect(sd,(struct sockaddr*)&address,sizeof(address)); if(new_conn == -1){ printf("Connection Failed %d\n",new_conn); } else{ printf("Connection Established \n"); } char *msg = "Hello Server"; char buffer[1024] = {0}; printf("Sending Message to Server\n"); int sendMsg = send(sd, msg, strlen(msg),0); if(sendMsg == -1){ printf("\nMessage Sending Failed\n"); } printf("Message sent to Server\n"); int readMsg = read(sd,buffer,1024); if(readMsg == -1){ printf("\nFailed to read message from Client\n"); } printf("Reading Message from Server\n"); printf("\nMessage from Server:\n"); printf("%s\n",buffer); return 0; }<file_sep>/client.py import socket import sys import os from PIL import Image, ImageOps sd = socket.socket(socket.AF_INET,socket.SOCK_STREAM) serverAdd = (input("Enter Server Address: "),1555) sd.connect(serverAdd) fileName = input("ENter filename to send: ") sd.send(fileName.encode()) # inverting image img = Image.open(fileName) img = ImageOps.invert(img) s = 'inverted.jpg' img.save(s) with open(s, "rb") as fp: print("\nSending File:",fileName) sd.send((str(os.stat(s).st_size)).encode()) data = fp.read() sd.sendall(data) print("File Sent Successfully!!!\nClosing Connection...") sd.close()<file_sep>/Assignment2/README.md # PROBLEM STATEMENT 1 Write a ftp server and client.</br></br> # PROBLEM STATEMENT 2 Find the geolocation of a client connecting to your server.
2eb9ff8420ac5fdc3e7cc9f99892be97b0360994
[ "Markdown", "C", "Python" ]
17
Markdown
vishal1565/Networking
808213b47f4613e4a9bd03fb917edcc5445949df
87575126707ee8d0e7380b39635ab1483bbc6388
refs/heads/main
<repo_name>workmodeactivate/3D-Creator-Website<file_sep>/README.md # 3D-Creator-Website #### link: https://professorcodedz.github.io/3D-Creator-Website/ <file_sep>/js/app.js //VARIABLES let base = document.querySelector(".base"); let block = document.querySelector(".block"); let colorInput = document.querySelector(".colorInput"); let deleteInput = document.querySelector(".delete"); let cubes = document.querySelectorAll(".cube") var deleteVal = false let color = 'red'; //GENERATE BLOCKS function blocks(max){ let blocks = "" for(let i = 0;i < max;i++){ blocks += "<div class='block'></div>" } return blocks } //CHANGE COLORS function changeColor(){ color = colorInput.value; } //BLOCKS EVENTS base.innerHTML = blocks(160); base.childNodes.forEach(el => { el.addEventListener("mouseenter",(e)=>{ e.target.style.backgroundColor = "#7c7c7c" }) el.addEventListener("mouseleave",(e)=>{ e.target.style.backgroundColor = "#cecece" }) el.addEventListener("click",(e)=>{ if(!deleteVal){ e.target.innerHTML = ` <div class="cube"> <div class="top" style='background-color:${color}'></div> <div class="down" style='background-color:${color}'></div> <div class="left" style='background-color:${color}'></div> <div class="right" style='background-color:${color}'></div> <div class="front" style='background-color:${color}'></div> <div class="back" style='background-color:${color}'></div> </div> ` } }) }) //MOVEMENT let z = 0; let x = 45; function left(){ z -= 10 base.style.transform = `translate(-50%,-50%) rotateX(${x}deg) rotateZ(${z}deg)`; } function right(){ z += 10 base.style.transform = `translate(-50%,-50%) rotateX(${x}deg) rotateZ(${z}deg)`; } function up(){ x -= 10 base.style.transform = `translate(-50%,-50%) rotateX(${x}deg) rotateZ(${z}deg)`; } function down(){ x += 10 base.style.transform = `translate(-50%,-50%) rotateX(${x}deg) rotateZ(${z}deg)`; } //MOVEMENT WITH KEYBOARD document.addEventListener("keyup",(e)=>{ if(e.key == "ArrowLeft"){ left(); }else if(e.key == "ArrowRight"){ right(); }else if(e.key == "ArrowUp"){ up(); }else if(e.key == "ArrowDown"){ down(); } }) //DELETE BLOCK function deleteBlock(){ deleteVal = deleteInput.checked; if(deleteVal){ document.querySelectorAll(".cube").forEach(el => { for(let i = 0;i < el.children.length ; i++){ el.children[i].onclick = e =>{ //change color to transparent e.target.parentNode.childNodes[1].style.backgroundColor = "transparent"; e.target.parentNode.childNodes[3].style.backgroundColor = "transparent"; e.target.parentNode.childNodes[5].style.backgroundColor = "transparent"; e.target.parentNode.childNodes[7].style.backgroundColor = "transparent"; e.target.parentNode.childNodes[9].style.backgroundColor = "transparent"; e.target.parentNode.childNodes[11].style.backgroundColor = "transparent"; //delete borders e.target.parentNode.childNodes[1].style.border = "none"; e.target.parentNode.childNodes[3].style.border = "none"; e.target.parentNode.childNodes[5].style.border = "none"; e.target.parentNode.childNodes[7].style.border = "none"; e.target.parentNode.childNodes[9].style.border = "none"; e.target.parentNode.childNodes[11].style.border = "none"; } } }) } }
ec6c8d1eed66b82101ea459f1158b76dbd1b2466
[ "Markdown", "JavaScript" ]
2
Markdown
workmodeactivate/3D-Creator-Website
e3dcb29af36757623d47eafdbdf76d29f07bab2d
24661696e05de88ef053730fdbe279a4e2ae8556
refs/heads/master
<file_sep>import React from "react"; import logo from "./logo.svg"; import "./App.css"; import Header from "./components/Header"; import TodoList from "./components/TodoList"; import "react-bulma-components/dist/react-bulma-components.min.css"; import { Button, Card } from "react-bulma-components"; import SubmitForm from "./components/SubmitForm"; class App extends React.Component { state = { tasks: ["task1", "tassssssssssssssssk2", "task3"], }; handleDelete = (index) => { const newArr = [...this.state.tasks]; newArr.splice(index, 1); this.setState({ tasks: newArr }); }; handleSubmit = (task) => { this.setState({ tasks: [...this.state.tasks, task] }); }; render() { return ( <> <div className="wrapper"> <Card> <Header numTodos={this.state.tasks.length} /> <TodoList tasks={this.state.tasks} onDelete={this.handleDelete} /> <SubmitForm onFormSubmit={this.handleSubmit} /> </Card> </div> </> ); } } export default App; <file_sep>import React from "react"; import { IonPage, IonContent, IonItem, IonLabel, IonInput, IonRow, IonCol, IonButton, } from "@ionic/react"; import NavHeader from "../../components/Header/NavHeader"; import { toast } from "../../helpers/toast"; import useForm from "../../hooks/useForm"; import firebase from "../../firebase"; const INITIAL_STATE = { name: "", email: "", password: "", }; const Signup = (props) => { return ( <IonPage> <NavHeader title="Sign Up" /> <IonContent> <IonItem lines="full"> <IonLabel position="floating">UserName</IonLabel> <IonInput name="name" type="text" required></IonInput> </IonItem> <IonItem lines="full"> <IonLabel position="floating">Email</IonLabel> <IonInput name="email" type="text" required></IonInput> </IonItem> <IonItem lines="full"> <IonLabel position="floating">Password</IonLabel> <IonInput name="password" type="<PASSWORD>" required></IonInput> </IonItem> <IonRow> <IonCol> <IonButton type="submit" color="primary" expand="block"> Sign Up </IonButton> </IonCol> </IonRow> </IonContent> </IonPage> ); }; export default Signup; <file_sep>const db = require("./db"); const { Movie, Person } = db.models; (async () => { await db.sequelize.sync({ force: true }); try { const movie = await Movie.create({ title: "Toy Story", runtime: 81, releaseDate: "1995-11-22", isAvailableOnVHS: false, }); //console.log(movie.toJSON()); const movie2 = await Movie.create({ title: "The Incredibles", runtime: 115, releaseDate: "2004-04-14", isAvailableOnVHS: true, }); //console.log(movie2.toJSON()); const movie3 = await Movie.build({ title: "Knives Out", runtime: 105, releaseDate: "2020-04-14", isAvailableOnVHS: false, }); await movie3.save(); // save the record // console.log(movie3.toJSON()); // New Person record const person = await Person.create({ firstName: "Tom", lastName: "Hanks", }); // console.log(person.toJSON()); const movieById = await Movie.findByPk(1); //console.log(movieById.toJSON()); const movieByRuntime = await Movie.findOne({ attributes: ["id", "title"], where: { runtime: 115 }, order: [["id", "DESC"]], }); console.log(movieByRuntime.toJSON()); const movies = await Movie.findAll(); //console.log(movies.map((movie) => movie.toJSON())); const newmovie = await Movie.findByPk(3); newmovie.isAvailableOnVHS = true; await newmovie.save(); const toyStory = await Movie.findByPk(1); await toyStory.destroy(); const moviesAll = await Movie.findAll(); console.log(moviesAll.map((movieA) => movieA.toJSON())); } catch (error) { //console.error("Error connecting to the database: ", error); if (error.name === "SequelizeValidationError") { const errors = error.errors.map((err) => err.message); console.error("Validation errors: ", errors); } else { throw error; } } })(); <file_sep>const router = require("express").Router(); let Daily = require("../models/daily.model"); router.route("/").get((req, res) => { Daily.find() .then((daily) => res.json(daily)) .catch((err) => res.status(400).json("Error" + err)); }); router.route("/add").post((req, res) => { const date = Date.parse(req.body.date); const mood = req.body.mood; const note = req.body.note; const newDaily = new Daily({ date, mood, note }); newDaily .save() .then(() => res.json("Daily Journal Updated")) .catch((err) => res.status(400).json("Error: " + err)); }); router.route("/:id").get((req, res) => { Daily.findById(req.params.id) .then((daily) => res.json(daily)) .catch((err) => res.status(400).json("Error: " + err)); }); module.exports = router; <file_sep>import React, { Component } from "react"; import axios from "axios"; var divStyle = { width: "18rem", //display: "inline-block", }; const Daily = (props) => ( <div class="card border-primary mb-3 mx-auto " style={divStyle}> <div class="card-header">{props.daily.date}</div> <div class="card-body text-primary"> <h5 class="card-title">{props.daily.mood}</h5> <p class="card-text">{props.daily.note}</p> </div> </div> ); class Dailies extends Component { state = { dailies: [], }; componentDidMount() { this.getDaily(); } getDaily = () => { axios .get("http://localhost:3001/daily") .then((res) => { if (res.data) { this.setState({ dailies: res.data }); //console.log(res.data); } }) .catch((err) => console.log(err)); }; dailyList() { return this.state.dailies.map((currentdaily) => { return <Daily daily={currentdaily} key={currentdaily._id} />; }); } render() { //let { dailies } = this.state; return ( <> <div class="container"> <div className="row ">{this.dailyList()}</div> </div> </> ); } } export default Dailies; <file_sep>import React from "react"; import "bootstrap/dist/css/bootstrap.css"; import Header from "./components/Header"; import TodoList from "./components/TodoList"; import SubmitForm from "./components/SubmitForm"; import { Button, Card, Container, Col, Row } from "react-bootstrap"; import { throwStatement } from "@babel/types"; class App extends React.Component { state = { tasks: ["milk", "eggs", "cheese", "strawberries", "blueberries"], }; handleSubmit = (task) => { this.setState({ tasks: [...this.state.tasks, task] }); }; handleDelete = (index) => { const newArr = [...this.state.tasks]; newArr.splice(index, 1); this.setState({ tasks: newArr }); }; render() { return ( <Container fluid> <Row> <Col> <Card sborder="primary" style={{ width: "18rem" }}> <Header numTodos={this.state.tasks.length} /> <TodoList tasks={this.state.tasks} onDelete={this.handleDelete} /> <SubmitForm onFormSubmit={this.handleSubmit} /> </Card> </Col> </Row> </Container> ); } } export default App; <file_sep>require("dotenv").config(); const express = require("express"); const app = express(); const server = app.listen(process.env.PORT || 3000); var bodyParser = require("body-parser"); //console.log(process.env.MESSAGE_STYLE); const absolutePath = __dirname + "/views/" + "index.html"; app.use(express.static(__dirname + "/public/")); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.get("/", function (req, res) { res.sendFile(absolutePath); }); /* app.get("/json", function (req, res) { }); */ app.get("/json", (req, res, next) => { if (process.env.MESSAGE_STYLE == "uppercase") { res.json({ message: "HELLO JSON", }); } else { res.json({ message: "Hello json", }); } console.log(`${req.method} ${req.path} - ${req.ip}`); next(); }); app.get( "/now", function (req, res, next) { req.time = new Date().toString(); console.log(req.time); next(); }, function (req, res) { res.json({ time: req.time, }); } ); app.get("/echo/:word", function (req, res) { res.json({ echo: req.params.word, }); }); app.get("/name", function (req, res) { res.json({ name: `${req.query.first} ${req.query.last}`, }); }); module.exports = server; <file_sep>import React from "react"; import "./App.css"; class App extends React.Component { constructor() { super(); this.state = { loading: false, price: {}, }; } componentDidMount() { this.setState({ loading: true }); fetch("https://blockchain.info/ticker") .then((response) => { if (response.ok) { return response.json(); } else { throw new Error("NETWORK RESPONSE ERROR"); } }) .then((data) => { console.log(data); this.setState({ price: data.USD, loading: false, }); }) .catch((error) => this.setState({ error, loading: false })); } render() { const { loading, price } = this.state; const output = loading ? "LOADING..." : "$" + price.last; return ( <div className="btc"> <img className="btc-logo" src="https://img.icons8.com/offices/50/000000/bitcoin.png" alt="Bitcoin" /> <span className="btc-price">{output}</span> </div> ); } } export default App; <file_sep>import React, { useState, useEffect } from "react"; function App() { const [username, setUsername] = useState([]); useEffect(() => { fetch("/users") .then((res) => res.json()) .then((username) => setUsername(username)); }, []); return ( <div className="App"> {username.map((names) => ( <li key={names.id}>{names.username}</li> ))} </div> ); } export default App; <file_sep>import React, { useEffect, useState } from "react"; import { Card, CardImg, CardText, CardBody, CardTitle, CardSubtitle, Button, CardHeader, Cardfooter, CardFooter, CardGroup, } from "reactstrap"; import "./index.css"; const App = () => { // const contacts = [ // { name: "<NAME>", email: "<EMAIL>", age: 25 }, // { name: "<NAME>", email: "<EMAIL>", age: 45 }, // { name: "<NAME>", email: "<EMAIL>", age: 100 }, // ]; const [contacts, setContacts] = useState([]); useEffect(() => { fetch("https://randomuser.me/api/?results=3") .then((response) => response.json()) .then((data) => { setContacts(data.results); console.log(data); }) .catch((err) => console.log(err)); }, []); return ( <> <CardGroup> {contacts.map((contact) => ( <ContactCard avatar={contact.picture.large} name={contact.name.first + " " + contact.name.last} email={contact.email} age={contact.dob.age} /> ))} </CardGroup> <CardGroup> {contacts.map((contact) => ( <ContactCard avatar={contact.picture.large} name={contact.name.first + " " + contact.name.last} email={contact.email} age={contact.dob.age} /> ))} </CardGroup> <CardGroup> {contacts.map((contact) => ( <ContactCard avatar={contact.picture.large} name={contact.name.first + " " + contact.name.last} email={contact.email} age={contact.dob.age} /> ))} </CardGroup> </> ); }; const ContactCard = (props) => { const [showAge, setShowAge] = useState(false); console.log(props.avatar); return ( // <div className="contact-card"> // <img src={props.avatar} alt="" /> // <div className="user-details"> // <p>Name: {props.name}</p> // <p>Email:{props.email}</p> // <button // onClick={() => { // setShowAge(!showAge); // }} // > // Toggle Age // </button> // {showAge && <p> Age: {props.age}</p>} // </div> // </div> <Card body outline color="primary" className="text-center"> <CardBody> <CardHeader>{props.name}</CardHeader> <img top width="128px" src={props.avatar} alt="profile pic" /> <CardText> {showAge && <p> Age: {props.age}</p>}</CardText> <button className="btn btn-primary" onClick={() => { setShowAge(!showAge); }} > Toggle Age </button> </CardBody> <CardFooter> {props.email} </CardFooter> </Card> ); }; export default App; <file_sep>import { v4 as uuidv4 } from "uuid"; const idOne = uuidv4(); const idTwo = uuidv4(); // pseudo database let users = { [idOne]: { id: "1", firstName: "Robin", lastName: "Wieruch", isDeveloper: true, }, [idTwo]: { id: "2", firstName: "Dave", lastName: "Davddis", isDeveloper: false, }, }; const getUser = (id) => new Promise((resolve, reject) => { const user = users[id]; if (!user) { return setTimeout(() => reject(new Error("User not found")), 250); } setTimeout(() => resolve(users[id]), 250); }); // usage const doGetUsers = async (id) => { try { const result = await getUser(id); console.log(result); } catch (error) { console.log(error); } }; doGetUsers("1"); const createUser = (data) => new Promise((resolve, reject) => { if (!data.firstName || !data.lastName) { reject(new Error("Not all information provided")); } const id = uuidv4(); const newUser = { id, ...data }; users = { ...users, [id]: newUser }; setTimeout(() => resolve(true), 250); }); // usage const doCreateUser = async (data) => { try { const result = await createUser(data); console.log(result); } catch (error) { console.log(error); } }; doCreateUser({ firstName: "Liam", lastName: "Wieruch" }); const updateUser = (id, data) => new Promise((resolve, reject) => { if (!users[id]) { return setTimeout(() => reject(new Error("User not found")), 250); } users[id] = { ...users[id], ...data }; return setTimeout(() => resolve(true), 250); }); // usage const doUpdateUser = async (id, data) => { try { const result = await updateUser(id, data); console.log(result); } catch (error) { console.log(error); } }; doUpdateUser("1", { isDeveloper: false }); const deleteUser = (id) => new Promise((resolve, reject) => { const { [id]: user, ...rest } = users; if (!user) { return setTimeout(() => reject(new Error("User not found")), 250); } users = { ...rest }; return setTimeout(() => resolve(true), 250); }); // usage const doDeleteUser = async (id) => { try { const result = await deleteUser(id); console.log(result); } catch (error) { console.log(error); } }; doDeleteUser("1"); <file_sep>import React from "react"; import { IonPage, IonContent, IonItem, IonLabel, IonInput, IonRow, IonCol, IonButton, IonRouterLink, } from "@ionic/react"; import NavHeader from "../../components/Header/NavHeader"; const Login = () => { return ( <IonPage> <NavHeader title="Login" /> <IonContent> <IonItem lines="full"> <IonLabel position="floating">Email</IonLabel> <IonInput name="email" type="text" required></IonInput> </IonItem> <IonItem lines="full"> <IonLabel position="floating">Password</IonLabel> <IonInput name="password" type="<PASSWORD>" required></IonInput> </IonItem> <IonRow> <IonCol> <IonButton type="submit" color="primary" expand="block"> Login </IonButton> </IonCol> </IonRow> <IonRow> <IonCol class="ion-text-center ion-padding-vertical"> <IonRouterLink routerLink={"/forgot"}> {" "} Forgot Password </IonRouterLink> </IonCol> </IonRow> </IonContent> </IonPage> ); }; export default Login; <file_sep>import React from "react"; import { IonPage, IonContent, IonItem, IonLabel, IonInput, IonRow, IonCol, IonButton, IonRouterLink, } from "@ionic/react"; import NavHeader from "../../components/Header/NavHeader"; const Forgot = () => { return ( <IonPage> <NavHeader title="Password Reset" /> <IonContent> <IonItem lines="full"> <IonLabel position="floating">Email</IonLabel> <IonInput name="email" type="text" required></IonInput> </IonItem> <IonRow> <IonCol> <IonButton type="submit" color="primary" expand="block"> Get Reset Link </IonButton> </IonCol> </IonRow> </IonContent> </IonPage> ); }; export default Forgot; <file_sep>### Day 1: June 5th 2021 1. Code test with Automattic <file_sep>import React from "react"; import Todo from "./Todo"; import { ListGroup } from "react-bootstrap"; const TodoList = (props) => { const todos = props.tasks.map((todo, index) => { return ( <Todo content={todo} key={index} id={index} onDelete={props.onDelete} /> ); // return <p id={index}> {todo}</p>; }); return <ListGroup variant="flush">{todos}</ListGroup>; }; export default TodoList; <file_sep>import React from "react"; function Header() { return ( <header> <img src="https://d.pr/i/OTRCVr+" alt="troll" /> <p>Meme Generator</p> </header> ); } export default Header; <file_sep>import React from "react"; import { Button, Card, Container, Col, Row } from "react-bootstrap"; const Header = (props) => { return <Card.Header>You have {props.numTodos} tasks!</Card.Header>; }; export default Header; <file_sep>// Print an Array var scores = new Array(90, 34, 12, 11, 56, 86, 43, 22); for (var i = 0; i < scores.length; i++) { //console.log(scores[i] + "\n"); } // Maximum Value in an array function max(arrays) { for (var i = 0; i < arrays.length - 1; i++) { if (arrays[i] > arrays[i + 1]) { var temp = arrays[i]; arrays[i] = arrays[i + 1]; arrays[i + 1] = temp; } } var maxValue = scores[scores.length - 1]; return maxValue; } //console.log(max(scores)); // Bubble Sort class BubbleSort { static sort(arrays) { for (var i = 0; i <= arrays.length; i++) { for (var j = 0; j < arrays.length; j++) { if (arrays[j] > arrays[j + 1]) { let temp = arrays[j]; arrays[j] = arrays[j + 1]; arrays[j + 1] = temp; } } } } } var scores = [60, 50, 95, 80, 70]; BubbleSort.sort(scores); for (var i = 0; i < scores.length; i++) { console.log(scores[i] + "\n"); } // Minimum value in an array function min(arrays) { var minIndex = 0; for (let j = 1; j < arrays.length; j++) { if (arrays[minIndex] > arrays[j]) { minIndex = j; } } return arrays[minIndex]; } console.log (min(scores));<file_sep>import React from "react"; import { FaRegStar, FaStarHalfAlt, FaStar } from "react-icons/fa"; import styles from "./StarRatings.module.css"; function StarRatings({ rating }) { let stars = []; //Add filled in Stars for (let i = 0; i < Math.floor(rating); i++) { stars.push(<FaStar key={`star-${i}`} />); } // Add half star if (rating % 1 > 0) stars.push(<FaStarHalfAlt key={`star-half`} />); // Add empty Star while (stars.length < 5) stars.push(<FaRegStar key={`star-empty=${stars.length}`} />); return <span className={styles.star}>{stars}</span>; } export default StarRatings; <file_sep>import React from "react"; import { useHarperDB } from "use-harperdb"; import "./Reviews.css"; import StarRatings from "./StarRatings"; function Reviews() { let [data, loading, error, refresh] = useHarperDB({ query: { operation: "sql", sql: `select * from reviews.books`, }, interval: 10000, }); if (loading) { return <div>Loading...</div>; } if (data && data.length > 0) { return ( <> <table> <thead> <tr> <td>Book</td> <td>Author</td> <td>Rating</td> </tr> </thead> <tbody> {data.map((b, index) => { return ( <tr key={index}> <td>{b.name}</td> <td>{b.author}</td> <td> <StarRatings rating={b.review} /> </td> </tr> ); })} </tbody> </table> <button onClick={refresh}>Refresh!</button> </> ); } else { return <div>{data}</div>; } //console.log(data); } export default Reviews; <file_sep>//import "./styles.css"; const baseURL = "https://pokeapi.co/api/v2/pokemon/"; const app = document.createElement("div"); app.id = "app"; document.body.appendChild(app); const loading = document.createElement("p"); loading.innerText = "Loading..."; loading.classList.add("loading"); let currentPokemon = 1; async function loadAndRenderPokemon() { // Clear the existing Pokemon. const pokemonElement = document.getElementById("pokemonContainer"); pokemonElement.remove(); // Show the loading element app.appendChild(loading); const pokemon = await getPokemon(); loading.remove(); app.appendChild(createPokemon(pokemon)); } function goPrev() { if (currentPokemon <= 1) return; currentPokemon -= 1; loadAndRenderPokemon(); } function goNext() { if (currentPokemon >= 893) return; currentPokemon += 1; loadAndRenderPokemon(); } function createButtons() { const buttonContainer = document.createElement("div"); buttonContainer.classList.add("button-container"); const prevButton = document.createElement("button"); prevButton.innerText = "Prev."; buttonContainer.appendChild(prevButton); const nextButton = document.createElement("button"); nextButton.innerText = "Next"; buttonContainer.appendChild(nextButton); nextButton.addEventListener("click", goNext); prevButton.addEventListener("click", goPrev); return buttonContainer; } async function getPokemon() { const response = await fetch(`${baseURL}${currentPokemon}`); const result = await response.json(); return result; } function createPokemon(pokemon) { const pokemonElement = document.createElement("div"); pokemonElement.id = "pokemonContainer"; pokemonElement.classList.add("pokemon-container"); const pokemonImage = document.createElement("img"); // Get the dream world sprite, falling back on the official artwork and then the default artwork. // Set the src attribute directly on the element. pokemonImage.src = pokemon.sprites?.other?.dream_world?.front_default || pokemon.sprites?.other?.["official-artwork"]?.front_default || pokemon.sprites?.front_default; pokemonImage.classList.add("pokemon-image"); pokemonElement.appendChild(pokemonImage); const pokemonInfo = document.createElement("div"); pokemonElement.appendChild(pokemonInfo); const pokemonId = document.createElement("p"); pokemonId.classList.add("pokemon-id"); pokemonId.innerText = pokemon.id; pokemonInfo.appendChild(pokemonId); const pokemonName = document.createElement("p"); // Capitalize the first character pokemonName.innerText = pokemon.name[0].toUpperCase() + pokemon.name.slice(1); pokemonName.classList.add("pokemon-name"); pokemonInfo.appendChild(pokemonName); const pokemonTypes = document.createElement("div"); pokemonTypes.classList.add("pokemon-types"); // Loop over all of the types and create a type badge. pokemon.types.forEach((type) => { const typeElement = document.createElement("div"); typeElement.classList.add(type.type.name); typeElement.innerText = type.type.name; pokemonTypes.appendChild(typeElement); }); pokemonInfo.appendChild(pokemonTypes); const buttons = createButtons(); pokemonElement.appendChild(buttons); return pokemonElement; } async function init() { app.appendChild(loading); const pokemon = await getPokemon(1); loading.remove(); app.appendChild(createPokemon(pokemon)); } init();
e8227918c3c95d8d5b55ed4ae4e9a51e961b97bf
[ "JavaScript", "Markdown" ]
21
JavaScript
potential-octo-parakeet/100DaysofCode
534d5c91a75d4be28cd1424051ce8654d64f0880
0410b2c87eec42c3a6a45ee558e5edb8e7ab7bcc
refs/heads/master
<file_sep>const seedData = require("../../../seedData"); const createNotes = (knex, note) => { return knex("notes") .insert( { title: note.title }, "id" ) .then(noteId => { let notePromises = []; note.listitems.forEach(item => { notePromises.push( createLists(knex, { noteItem: item.noteItem, isComplete: item.isComplete, note_id: noteId[0] }) ); }); return Promise.all(notePromises); }); }; const createLists = (knex, listitem) => { return knex("listitems").insert(listitem); }; exports.seed = function(knex) { return knex("listitems") .del() .then(() => knex("notes").del()) .then(() => { let listPromises = []; seedData.forEach(note => { listPromises.push(createNotes(knex, note)); }); return Promise.all(listPromises); }) .catch(error => console.log(`error: ${error}`)); }; <file_sep>const notesData = [ { title: "Evaluation To-Do", listitems: [ { noteItem: "Weep with joy at our success", isComplete: false }, { noteItem: "Applaud and bow", isComplete: false }, { noteItem: "Give us perfect scores on everything", isComplete: false }, { noteItem: "ROCK IT!", isComplete: false } ] }, { title: "Team To-Do", listitems: [ { noteItem: "Show project at demo night", isComplete: false }, { noteItem: "Get jobs", isComplete: false }, { noteItem: "Keep nailing it", isComplete: true }, { noteItem: "ROCK OUT", isComplete: false } ] } ]; module.exports = notesData; <file_sep>const express = require("express"); const environment = process.env.NODE_ENV || "development"; const configuration = require("./knexfile")[environment]; const database = require("knex")(configuration); const app = express(); app.use(express.json()); app.get("/", (req, res) => { res.status(200).send("hello world"); }); app.get("/api/v1/notes", (req, res) => { database("notes") .select() .then(notes => { res.status(200).json(notes); }) .catch(error => res.status(500).json({ error })); }); app.get("/api/v1/listitems", (req, res) => { database("listitems") .select() .then(listitems => { res.status(200).json(listitems); }) .catch(error => res.status(500).json({ error })); }); app.get("/api/v1/notes/:id", (req, res) => { database("notes") .where("id", req.params.id) .select() .then(note => { if (note.length) { res.status(200).json(note); } else { res.statusCode(404).json({ error: `could not find note with id: ${req.params.id}` }); } }) .catch(error => res.status(500).json({ error })); }); app.get("/api/v1/listitems/:id", (req, res) => { database("listitems") .where("id", req.params.id) .select() .then(listitem => { if (listitem.length) { res.status(200).json(listitem); } else { res.statusCode(404).json({ error: `could not find listitem with id: ${req.params.id}` }); } }) .catch(error => res.status(500).json({ error })); }); app.post("/api/v1/notes", (req, res) => { const { title } = req.body; const note = req.body; if (!title) { return res.status(422).json(`please enter a title for your note`); } else { database("notes") .insert(note, "id") .then(note => { res.status(201).json({ id: note[0] }); }) .catch(error => { res.status(500).json({ error }); }); } }); app.post("/api/v1/listitems", (req, res) => { const { noteItem, isComplete, note_id } = req.body; const listitem = req.body; if ((!noteItem, !isComplete, !note_id)) { return res.status(422).json(); } else { database("listitems") .insert(listitem, "id") .then(listitem => { res.status(201).json({ id: listitem[0] }); }) .catch(error => { res.status(500).json({ error }); }); } }); app.patch("/api/v1/notes/:id", (req, res) => { const { id } = req.params; const { title } = req.body; if (!title) return res.status(422).json("Please provide a title."); database("notes") .where({ id }) .update({ title }) .then(res.status(200).json("Title successfully updated")) .catch(error => res.status(500).json({ error })); }); app.patch("/api/v1/listitems/:id", (req, res) => { const { id } = req.params; const { noteItem, isComplete, } = req.body; if (!noteItem) return res.status(422).json("Please provide a noteItem."); database("listitems") .where({ id }) .update({ noteItem, isComplete }) .then(res.status(200).json("List Items successfully updated")) .catch(error => res.status(500).json({ error })); }); app.delete("/api/v1/notes/:id", (req, res) => { const { id } = req.params; database("notes") .where("id", id) .del() .then(result => { if (!result) { res .status(404) .json( `I'm sorry that id doesn't exist in notes table, maybe this is good news seeing you were trying to delete it anyway.` ); } else { res.status(200).json(`id: ${id} deleted`); } }); }); app.delete("/api/v1/listitems/:id", (req, res) => { const { id } = req.params; database("listitems") .where("id", id) .del() .then(result => { if (!result) { res .status(404) .json( `I'm sorry that id doesn't exist in listitems table, maybe this is good news seeing you were trying to delete it anyway.` ); } else { res.status(200).json(`id: ${id} deleted`); } }); }); module.exports = app;
f5dfed9cbcea457794324b70f15f0e6c23ef943b
[ "JavaScript" ]
3
JavaScript
MatthewKaplan/trapper-keeper-api
934b80c4d341354787d5d43432bc77d2044ff332
419d71b3b126a4153357c64be524c97a0bd7d3df
refs/heads/master
<repo_name>kareypowell/CakePHP-InPlace-Editing<file_sep>/src/View/Helper/InPlaceEditingHelper.php <?php namespace InPlaceEditing\View\Helper; use Cake\View\Helper; /* * ---------------------------------------------------------------------------- * Package: CakePHP InPlaceEditing Plugin * Version: 0.0.1 * Date: 2012-12-31 * Description: CakePHP plugin for in-place-editing functionality of any * form element. * Author: <NAME> * Author URL: http://kareypowell.com/ * Repository: http://github.com/kareypowell/CakePHP-InPlace-Editing * ---------------------------------------------------------------------------- * Copyright (c) 2012 <NAME> * Dual licensed under the MIT and GPL licenses. * ---------------------------------------------------------------------------- */ class InPlaceEditingHelper extends Helper { public $helpers = ['Html']; /* * Returns a script which contains a html element (type defined in a parameter) with the field contents. * And includes a script required for the inplace update ajax request logic. */ public function input($modelName, $fieldName, $id, $settings = null) { $value = $this::extractSetting($settings, 'value', ''); $actionName = $this::extractSetting($settings, 'actionName', 'inPlaceEditing'); $type = $this::extractSetting($settings, 'type', 'textarea'); $cancelText = $this::extractSetting($settings, 'cancelText', 'Cancel'); $submitText = $this::extractSetting($settings, 'submitText', 'Save'); $toolTip = $this::extractSetting($settings, 'toolTip', 'Click to edit.'); $containerType = $this::extractSetting($settings, 'containerType', 'div'); $elementID = 'inplace_'.$modelName.'_'.$fieldName.'_'.$id; $input = '<'.$containerType.' id="'.$elementID.'" class="in_place_editing">'.$value.'</'.$containerType.'>'; $script = "$(function(){ $('#$elementID').editable( '..$actionName/$id', { name : '$fieldName', type : '$type', cancel : '$cancelText', submit : '$submitText', tooltip : '$toolTip', rows : 5 } ); });"; $this->Html->scriptBlock($script, ['block' => true]); return $input; } /* * Extracts a setting under the provided key if possible, otherwise, returns a provided default value. */ protected static function extractSetting($settings, $key, $defaultValue = '') { if ( ! $settings && empty($settings)) { return $defaultValue; } if (isset($settings[$key])) { return $settings[$key]; } else { return $defaultValue; } } }<file_sep>/README.md # InPlace Editing Plugin Version 1.0.0 An in-place-edit plugin for [CakePHP](http://cakephp.org), which uses the power of jQuery. This plugin allows you to easily make any field in your views become editable. Combined with the awesomeness of Ajax you can make changes to your data right from the view without even reloading the page. ## Requirements * [jQuery](http://jquery.com/) * [Jeditable](https://github.com/NicolasCARPi/jquery_jeditable) * PHP version: PHP 7.1+ * CakePHP version: 3.5.X ## Installation 1. Go to your CakePHP App directory using a terminal. 2. type `composer require emilushi/in-place-editing` 3. To load the plugin type: `bin/cake plugin load InPlaceEditing` 4. Under `src/View/Application.php` on `initialize` method add the following line: `$this->loadHelper('InPlaceEditing.InPlaceEditing');` #### Using InPlaceEditing on your view The editing helper will allow you to add an `input` control to your views that will behave like the a div element (by default, or any other HTML element if you wish) on your view until you click/double-click/hover/etc on it, then it will appear as a text input, or a drop-down list, or any element supported by [Jeditable](https://github.com/NicolasCARPi/jquery_jeditable) jQuery plugin. Let's assume our Model is **OrdersTable**, Controller **Orders** and field to edit is called **comments**. Add the code below under your view to generate the needed to field which will trigger `jeditable`. <?= $this->InPlaceEditing->input('Order', 'comments', $order->id, [ 'value' => $order->comments, 'actionName' => $this->Url->build([ 'controller' => 'orders', 'action' => 'in_place_editing' ]), 'type' => 'textarea', 'rows' => 4, 'cancelText' => 'Cancel', 'submitText' => 'Save', 'toolTip' => 'Click to edit', 'containerType' => 'div' ]) ?> #### Add an action handler in your controller Before you may need to disable security component for this specific action by adding: `$this->Security->setConfig('unlockedActions', ['inPlaceEditing']);` on `beforeFilter` method of your controller. Then add the following action on your controller which will update our **$order->comments** field and return the new value to the view. public function inPlaceEditing($id = null) { $this->getRequest()->allowMethod('ajax'); $order = $this-Orders->get($id); //You may need to unset data['id'] if(isset($data['id'])) { unset($data['id']); } $order = $this->Orders->pathchEntity($order, $data); if($this->Orders->save($order)) { $comment = $order->comments; $this->set(compact('comment')); $this->set('_serialize', 'comment'); $this->viewBuilder()->disableAutoLayout(); $this->viewBuilder()->setClassName('Ajax'); } } #### Create the action handler view Since we set the view class name to **Ajax** on our action we need to create a new ajax view on the above path: src/Template/Orders/ajax/in_place_editing.ctp **Note, that you need to replace Orders with your own controller Name.** and on the new file you created add the above code: echo $comment; **Note, here as well you need to replace `$comment` with you own field.** #### Loading JS InPlaceEditingHelper will generate an input for your field and a piece of jQuery code for each field. The generated jQuery code is injected using `$this->Html->scriptBlock()` method which requires that you have somewhere on your layout a `fetch` method and it needs to be below the code you use for loading `jQuery` and `jquery-jeditable`. Which will look like: `<?= $this->fetch('script') ?>` ## ToDo This version of the plugin is by no means perfect, but it works. I'll be working on making things a lot easier in the future updates. * Write tests. ## License This code is licensed under the [MIT license](http://www.opensource.org/licenses/mit-license.php). ## Notes Feel free to submit bug reports or suggest improvements in a ticket or fork this project and improve upon it yourself. Contributions welcome.
4f3d3540e128c3442fe1118833e683b643f060ae
[ "Markdown", "PHP" ]
2
PHP
kareypowell/CakePHP-InPlace-Editing
84b887c2fc5036e0f3d2534d56ec2b6f7ee3a12c
9fd3ca9b9b55b86cf8ebc364a4ca52e12a8bbe5f
refs/heads/master
<file_sep><?php namespace App\Http\Controllers\Frontend\Job; use Auth; use App\Notifications\Frontend\Job\UserHired; use App\Http\Controllers\Controller; use App\Repositories\Frontend\Job\EmployeeRepository; use Illuminate\Support\Facades\Notification; class EmployController extends Controller { protected $employee; public function __construct(EmployeeRepository $employeeRepository) { $this->employee = $employeeRepository; } public function enroll($id) { $response = redirect() ->route('frontend.jobs.show', $id); if (!$this->employee->isEnrolled($id)) { $this->employee->enroll($id); $response = $response ->withFlashSuccess('success'); } else { $response = $response ->withFlashDanger('you have joined'); } return $response; } public function hire($id) { $enroll = $this->employee->findByID($id); $enroll->status = 1; $enroll->save(); Notification::send($enroll->user, new UserHired($enroll->job)); return redirect() ->route('frontend.jobs.show', $enroll->job->id) ->withFlashSuccess('Hire Success'); } } <file_sep><?php /** * Created by PhpStorm. * User: nicholas * Date: 17-1-11 * Time: 下午3:44 */ namespace App\Repositories\Frontend\Job; use Auth; use App\Models\Job; use Illuminate\Http\Request; use App\Repositories\Repository; use Illuminate\Support\Facades\Storage; class JobRepository extends Repository { const MODEL = Job::class; protected $job; public function __construct(Job $job) { $this->job = $job; } /** * @param Request $request * @return JobRepository */ public function create(Request $request) { $job = self::MODEL; $input = $request->only([ 'title', 'reward', 'describe', 'max_hire', 'location', 'start_at', 'maintain', 'work_hours_pre_day', ]); $input['reward'] = number_format($input['reward'], 2, '.', ''); $input['cover'] = Storage::url($request->file('cover')->store('public/jobs')); $job = new $job(); $job->fill($input); $job->publisher_id = Auth::user()->id; $job->status = 0; $job->save(); return $job; } public function updateJob(Request $request, $id) { $input = $request->only([ 'title', 'reward', 'describe', 'max_hire', 'location', 'start_at', 'maintain', 'work_hours_pre_day', ]); $input['reward'] = number_format($input['reward'], 2, '.', ''); if ($request->hasFile('cover')) { $input['cover'] = Storage::url($request->file('cover')->store('public/jobs')); } $job = $this->job->where('id', $id)->first(); return parent::update($job, $input); } public function findPublishedByUser() { return Auth::user()->PublishedJobs; } public function findInvolvedByUser() { return Auth::user()->jobInvolved; } public function paginate($item_pre_page = 8) { return $this->job->orderBy('created_at', 'desc')->paginate($item_pre_page); } public function findAll() { return $this->query()->get(); } }<file_sep><?php namespace App\Helpers\Macros; use App\Helpers\Macros\Traits\ProfileEdit; use Collective\Html\FormBuilder; /** * Class Macros * @package App\Http */ class Macros extends FormBuilder { use ProfileEdit; }<file_sep><?php namespace App\Http\Middleware; use Auth; use Closure; use DebugBar\DebugBar; class InfoNeedsComplete { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!Auth::check()) { return redirect() ->route('frontend.user.account') ->withFlashDanger(trans('auth.unauthorized')); } if (!$this->isUserCompleted()) { return redirect() ->route('frontend.user.account') ->withFlashDanger(trans('alerts.frontend.jobs.publish.not_complete')); } return $next($request); } private function isUserCompleted() { $user = Auth::user(); return $user->tel && $user->id_number && $user->real_name; } } <file_sep><?php use Faker\Generator; use App\Models\Access\User\User; /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ $factory->define(User::class, function (Generator $faker) { static $password; return [ 'name' => $faker->userName, 'email' => uniqid($faker->safeEmail, true), 'password' => $password ?: $password = bcrypt('<PASSWORD>'), 'remember_token' => str_random(10), 'status' => 1, 'confirmation_code' => md5(uniqid(mt_rand(), true)), 'confirmed' => 1, 'tel' => rand(13000000000, 18999999999), 'qq' => rand(10000, 9999999999), 'we_chat' => $faker->words(3, true), 'real_name' => $faker->name, 'gender' => rand(0, 1), 'birthday' => $faker->date('Y-m-d', 'now'), 'id_number' => rand(100000000000000000, 999999999999999999), 'university' => $faker->words(3, true), 'avatar' => $faker->imageUrl(), 'resume' => $faker->paragraph, 'created_at' => $faker->dateTime('now', date_default_timezone_get()), 'updated_at' => $faker->dateTime('now', date_default_timezone_get()), ]; }); $factory->define(\App\Models\Job::class, function (Generator $faker) { $max_user_id = User::count('id'); return [ 'title' => $faker->words(3, true), 'publisher_id' => rand(4, $max_user_id), 'status' => rand(-1, 1), 'max_hire' => rand(5, 100), 'reward' => rand(0.99, 99999999.99), 'location' => $faker->streetAddress, 'describe' => $faker->paragraph, 'start_at' => $faker->date(), 'maintain' => rand(1, 30), 'work_hours_pre_day' => rand(1, 8), 'cover' => $faker->imageUrl(), 'created_at' => $faker->dateTime, 'updated_at' => $faker->dateTime, ]; }); // //$factory->state(User::class, 'active', function () { // return [ // 'status' => 1, // ]; //}); // //$factory->state(User::class, 'inactive', function () { // return [ // 'status' => 0, // ]; //}); // //$factory->state(User::class, 'confirmed', function () { // return [ // 'confirmed' => 1, // ]; //}); // //$factory->state(User::class, 'unconfirmed', function () { // return [ // 'confirmed' => 0, // ]; //}); /** * Roles */ $factory->define(Role::class, function (Generator $faker) { return [ 'name' => $faker->name, 'all' => 0, 'sort' => $faker->numberBetween(1, 100), ]; }); $factory->state(Role::class, 'admin', function () { return [ 'all' => 1, ]; }); <file_sep><?php Route::group([ 'namespace' => 'Job', 'as' => 'jobs.', ], function () { Route::resource('jobs', 'JobsController', [ 'names' => [ 'index' => 'index', 'create' => 'create', 'store' => 'store', 'show' => 'show', 'edit' => 'edit', 'update' => 'update', 'destroy' => 'destroy', ], ]); Route::group([ 'middleware' => 'needs-complete-info', 'prefix' => 'job', ], function () { Route::get('/enroll/{id}', 'EmployController@enroll')->name('enroll'); Route::get('/hire/{id}','EmployController@hire')->name('hire'); }); });<file_sep><?php namespace App\Http\Controllers\Frontend\User; use App\Http\Controllers\Controller; use App\Http\Requests\Frontend\User\UpdateProfileRequest; use App\Repositories\Frontend\Access\User\UserRepository; use Illuminate\Support\Facades\Storage; /** * Class ProfileController * @package App\Http\Controllers\Frontend */ class ProfileController extends Controller { /** * @var UserRepository */ protected $user; /** * ProfileController constructor. * @param UserRepository $user */ public function __construct(UserRepository $user) { $this->user = $user; } /** * @param UpdateProfileRequest $request * @return mixed */ public function update(UpdateProfileRequest $request) { $input = $request->only([ 'name', 'email', 'tel', 'qq', 'we_chat', 'real_name', 'gender', 'birthday', 'id_number', 'university', 'resume', 'avatar', ]); if ($request->hasFile('avatar')) { $input['avatar'] = Storage::url($request->file('avatar')->store('public/avatars')); } $this->user->updateProfile(access()->id(), $input); return redirect()->route('frontend.user.account')->withFlashSuccess(trans('strings.frontend.user.profile_updated')); } }<file_sep><?php namespace App\Helpers\Macros\Traits; /** * Class Dropdowns * @package App\Services\Macros */ trait ProfileEdit { public function selectGender($name, $selected = null, $options = []) { $list = [ true => '男', false => '女', ]; return $this->select($name, $list, $selected, $options); } public function fileUploadInput($name = file, $id = file) { return '<input type="file" style="opacity:0" accept="image/gif,image/jpeg,image/jpg,image/png" name="' . $name . '" id="' . $id . '">'; } }<file_sep><?php namespace App\Http\Controllers\Backend\Job; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Repositories\Frontend\Job\JobRepository; class JobController extends Controller { protected $job; public function __construct(JobRepository $jobRepository) { $this->job = $jobRepository; } public function index() { $this->job->findAll(); } public function get() { } } <file_sep><?php namespace App\Models; use App\Models\Access\User\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Job extends Model { use SoftDeletes; public $fillable = [ 'title', 'reward', 'describe', 'start_at', 'max_hire', 'location', 'maintain', 'work_hours_pre_day', 'cover', 'deleted_at', 'created_at', 'updated_at', ]; public function publisher() { return $this->belongsTo(User::class, 'publisher_id'); } public function employees() { return $this->hasManyThrough(User::class, Employee::class, 'job_id', 'id'); } public function enrolls() { return $this->hasMany(Employee::class); } public function tags() { return $this->belongsToMany(Tag::class, 'job_tag_pivot'); } } <file_sep><?php namespace App\Http\Controllers\Frontend\Job; use App\Repositories\Frontend\Job\EmployeeRepository; use Auth; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Repositories\Frontend\Job\JobRepository; use App\Http\Requests\Frontend\Job\JobEditRequest; class JobsController extends Controller { protected $job; protected $employee; public function __construct(JobRepository $job, EmployeeRepository $employeeRepository) { $this->job = $job; $this->employee = $employeeRepository; $this->middleware('needs-complete-info', ['except' => ['index', 'destroy']]); $this->middleware('admin', ['only' => ['destroy']]); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return redirect() ->route("frontend.index"); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view("frontend.jobs.edit")->withJob(null)->withEdit(false); } /** * Store a newly created resource in storage. * @middleware("job") * @param JobEditRequest $request * @return \Illuminate\Http\Response */ public function store(JobEditRequest $request) { $this->job->create($request); return redirect() ->route('frontend.user.account') ->withFlashSuccess(trans('alerts.frontend.jobs.publish.success')); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return view("frontend.jobs.show") ->withEnrolled(empty($this->employee->isEnrolled($id)) ? false : true) ->withJob($this->job->find($id)); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { return view("frontend.jobs.edit")->withJob($this->job->find($id))->withEdit(true); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { return $this->job->updateJob($request, $id); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $this->job->where('id', $id)->delete(); } } <file_sep><?php return [ /* |-------------------------------------------------------------------------- | Labels Language Lines |-------------------------------------------------------------------------- | | The following language lines are used in labels throughout the system. | Regardless where it is placed, a label can be listed here so it is easily | found in a intuitive way. | */ 'general' => [ 'all' => 'All', 'yes' => 'Yes', 'no' => 'No', 'custom' => 'Custom', 'actions' => 'Actions', 'active' => 'Active', 'buttons' => [ 'save' => '保存', 'update' => '更新', ], 'hide' => 'Hide', 'inactive' => 'Inactive', 'none' => 'None', 'show' => 'Show', 'toggle_navigation' => 'Toggle Navigation', ], 'backend' => [ 'access' => [ 'roles' => [ 'create' => 'Create Role', 'edit' => 'Edit Role', 'management' => 'Role Management', 'table' => [ 'number_of_users' => 'Number of Users', 'permissions' => 'Permissions', 'role' => 'Role', 'sort' => 'Sort', 'total' => 'role total|roles total', ], ], 'users' => [ 'active' => 'Active Users', 'all_permissions' => 'All Permissions', 'change_password' => '<PASSWORD>', 'change_password_for' => '<PASSWORD> <PASSWORD>', 'create' => 'Create User', 'deactivated' => 'Deactivated Users', 'deleted' => 'Deleted Users', 'edit' => 'Edit User', 'management' => 'User Management', 'no_permissions' => 'No Permissions', 'no_roles' => 'No Roles to set.', 'permissions' => 'Permissions', 'table' => [ 'confirmed' => 'Confirmed', 'created' => 'Created', 'email' => 'E-mail', 'id' => 'ID', 'last_updated' => 'Last Updated', 'name' => 'Name', 'no_deactivated' => 'No Deactivated Users', 'no_deleted' => 'No Deleted Users', 'roles' => 'Roles', 'total' => 'user total|users total', ], 'tabs' => [ 'titles' => [ 'overview' => 'Overview', 'history' => 'History', ], 'content' => [ 'overview' => [ 'avatar' => 'Avatar', 'confirmed' => 'Confirmed', 'created_at' => 'Created At', 'deleted_at' => 'Deleted At', 'email' => 'E-mail', 'last_updated' => 'Last Updated', 'name' => 'Name', 'status' => 'Status', ], ], ], 'view' => 'View User', ], ], ], 'frontend' => [ 'auth' => [ 'login_box_title' => 'Login', 'login_button' => 'Login', 'login_with' => 'Login with :social_media', 'register_box_title' => 'Register', 'register_button' => 'Register', 'remember_me' => 'Remember Me', ], 'passwords' => [ 'forgot_password' => '<PASSWORD>?', 'reset_password_box_title' => 'Reset Password', 'reset_password_button' => 'Reset Password', 'send_password_reset_link_button' => 'Send Password Reset Link', ], 'job' => [ 'title' => '工作名称', 'reward' => '薪酬', 'describe' => '详情', 'start_at' => '开始时间', 'maintain' => '持续时间', 'work_hours_pre_day' => '每日工作时长', 'cover' => '封面', 'max_hire' => '最大招聘人数', 'location' => '工作地点', ], 'user' => [ 'passwords' => [ 'change' => '<PASSWORD>', ], 'profile' => [ 'avatar' => '头像', 'created_at' => '创建于', 'edit_information' => '编辑信息', 'email' => 'E-mail', 'last_updated' => '最后更新于', 'name' => '名字', 'update_information' => '更新信息', 'tel' => '电话', 'qq' => 'QQ', 'we_chat' => '微信', 'real_name' => '真实姓名', 'birthday' => '生日', 'id_number' => '身份证号', 'university' => '在读大学', 'resume' => '个人简介', 'gender' => [ 'name' => '性别', 'male' => '男', 'female' => '女', ], ], ], ], ]; <file_sep><?php Route::group([ 'namespace' => 'Job', 'as' => 'jobs.' ], function () { Route::get('jobs','JobController@index')->name('index'); Route::post('jobs/get','JobController@get')->name('get'); });<file_sep><?php namespace App\Models; use App\Models\Access\User\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Employee extends Model { use SoftDeletes; public $fillable = [ 'user_id', 'job_id', 'status', 'deleted_at', 'created_at', 'updated_at', ]; public function job() { return $this->belongsTo(Job::class); } public function user() { return $this->belongsTo(User::class); } } <file_sep><?php /** * Created by PhpStorm. * User: nicholas * Date: 17-1-12 * Time: 下午5:47 */ namespace app\Repositories\Frontend\Job; use App\Models\Access\User\User; use App\Models\Job; use App\Notifications\Frontend\Job\UserEnroll; use Auth; use App\Models\Employee; use App\Repositories\BaseRepository; class EmployeeRepository extends BaseRepository { protected $employee; const MODEL = Employee::class; public function __construct(Employee $employee) { $this->employee = $employee; } public function findByID($id) { return $this->query()->where('id',$id)->first(); } public function enroll($job_id) { $employee = self::MODEL; $employee = new $employee(); $employee->user_id = Auth::id(); $employee->job_id = $job_id; $employee->status = 0; $job = Job::find($job_id); $job->publisher->notify(new UserEnroll(Auth::user(), $job)); return $employee->save(); } public function isEnrolled($job_id) { return $this->employee->where('user_id', Auth::id())->where('job_id', $job_id)->first(); } }<file_sep><?php namespace App\Http\Controllers\Frontend; use App\Models\Job; use App\Repositories\Frontend\Job\JobRepository; use Auth; use App\Http\Controllers\Controller; /** * Class FrontendController * @package App\Http\Controllers */ class FrontendController extends Controller { /** * @param JobRepository $job * @return \Illuminate\View\View */ public function index(JobRepository $job) { return view('frontend.index')->withJobs($job->paginate(7)); } // /** // * @return \Illuminate\View\View // */ // public function macros() // { // return view('frontend.macros'); // } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AlterJobsAddLocationAndMaxMember extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('jobs', function (Blueprint $table) { $table->addColumn('string', 'location', [ 'after' => 'reward', 'length' => 255, ]); $table->addColumn('tinyInteger', 'max_hire', [ 'unsigned', 'after' => 'status', ]); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('jobs', function (Blueprint $table) { $table->dropColumn('location'); $table->dropColumn('max_hire'); }); } } <file_sep><?php namespace App\Http\Requests\Frontend\User; use App\Http\Requests\Request; /** * Class UpdateProfileRequest * @package App\Http\Requests\Frontend\User */ class UpdateProfileRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required', 'email' => 'sometimes|required|email', 'avatar' => 'image', 'tel' => [ 'string', 'max:16', 'regex:#^1[34578]\d{9}$#', ], 'qq' => [ 'string', 'max:10', 'min:5', 'regex:#^\d+$#', ], 'birthday' => 'date', 'id_number' => [ 'nullable', 'string', 'size:18', 'regex:#(^\d{18}$)|(^\d{17}(\d|X|x)$)#', ], ]; } }
e1b93b573077ee640943ecfe81a7c106d02ce4d0
[ "PHP" ]
18
PHP
NicholasStone/Ultra-Dog
fe6f6f865533aafa9e2427bd0f44dd398ffd3a9d
da24899048360cd70cea9097848bfaf4e0943bca
refs/heads/master
<repo_name>lmhieu612/AI_SpamMail<file_sep>/Main.py __author__ = 'madlife' import sys def read_input_and_train(filename,word_to_index,spam_likelihood,ham_likelihood,prior): fd = open(filename, 'r') line = fd.readline() count_ham = [0 for i in range(0, 100000)] count_spam = [0 for i in range(0, 100000)] last_of_list = 0 num_of_email = 0 num_of_spam_email = 0 num_of_ham_email = 0 while line != "": num_of_email += 1 info = line.split(" ") class_ = info[1] if class_ == 'spam': num_of_spam_email += 1 else: num_of_ham_email += 1 for i in xrange(2, len(info), 2): if info[i] not in word_to_index: word_to_index[info[i]] = last_of_list index = last_of_list last_of_list += 1 else: index = word_to_index[info[i]] if class_ == 'spam': count_spam[index] += int(info[i+1]) else: count_ham[index] += int(info[i+1]) line = fd.readline() for i in range(0,len(word_to_index)): spam_likelihood[i] = float(count_spam[i]) / float((count_spam[i] + count_ham[i])) ham_likelihood[i] = 1 - spam_likelihood[i] prior[0] = float(num_of_spam_email) / float((num_of_spam_email + num_of_ham_email)) prior[1] = float(num_of_ham_email) / float((num_of_spam_email + num_of_ham_email)) fd.close() filename = '/home/madlife/PycharmProjects/SpamMail/spam/spam/data/train' words_limit = 10000 word_to_index = {} spam_likelihood = [0 for i in range(0,words_limit)] ham_likelihood = [0 for i in range(0,words_limit)] prior = [0, 0] # prior = [ spam prior, ham prior] read_input_and_train(filename, word_to_index, spam_likelihood, ham_likelihood, prior) print len(word_to_index) print word_to_index['need'] print spam_likelihood print ham_likelihood print prior
665e1687040744421c950aeac9ad856c89775d4c
[ "Python" ]
1
Python
lmhieu612/AI_SpamMail
bfa49a1692711d8f849e92559b9f489c45c7a039
14f2ca3eef570aa17d8badb392462af22125d5f9
refs/heads/master
<repo_name>Implexx/algorithms<file_sep>/lession_1/task_7.py """ Задача 7 https://drive.google.com/file/d/1lmUebi6gGXK6OeAX-bDrUL3R3FU6YhN6/view?usp=sharing По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним, равнобедренным или равносторонним. """ a = float(input('Введите длину первой стороны треугольника: ')) b = float(input('Введите длину второй стороны треугольника: ')) c = float(input('Введите длину третьей стороны треугольника: ')) if (a + b <= c) and (a + c <= b) and (c + b <= a): print('Треугольник не существует') elif a == b == c: print('Треугольник равносторонний') elif a != b != c: print('Треугольник разносторонний') else: print('Трегуольник равнобедренный')<file_sep>/lession_1/task_6.py """ Задача 6 https://drive.google.com/file/d/1lmUebi6gGXK6OeAX-bDrUL3R3FU6YhN6/view?usp=sharing Пользователь вводит номер буквы в алфавите. Определить, какая это буква. """ alphabet = 'abcdefghijklmnopqrstuvwxyz' number = int(input('Введите порядковый номер буквы в алфавите: ')) char = alphabet[number - 1] print('Ваша буква: ', char) <file_sep>/lession_1/task_1.py """ Задание 1 https://drive.google.com/file/d/1lmUebi6gGXK6OeAX-bDrUL3R3FU6YhN6/view?usp=sharing Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь. """ number = input("Введите трехзначное число: ") num_1 = int(number[0]) num_2 = int(number[1]) num_3 = int(number[2]) result_sum = num_1 + num_2 + num_3 result = num_1 * num_2 * num_3 print('Сумма цифр = ', result_sum) print("Произведение цифр = ", result) <file_sep>/lession_1/task_9.py """ Задание 9 https://drive.google.com/file/d/1lmUebi6gGXK6OeAX-bDrUL3R3FU6YhN6/view?usp=sharing Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого). """ num_1 = int(input("Введите первое число :")) num_2 = int(input("Введите второе число :")) num_3 = int(input("Введите третье число :")) if (num_1 > num_2 > num_3) or (num_3 > num_2 > num_1): print('Среднее число: ', num_2) elif (num_2 > num_1 > num_3) or (num_3 > num_1 > num_2): print("Среднее число: ", num_1) else: print("Среднее число: ", num_3) <file_sep>/lession_1/task_5.py """ Задание 5 https://drive.google.com/file/d/1lmUebi6gGXK6OeAX-bDrUL3R3FU6YhN6/view?usp=sharing Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними находится букв. """ alphabet = 'abcdefgh<KEY>' char_1 = input('Введите первую букву: ') char_2 = input('Введите вторую букву: ') num_1 = alphabet.find(char_1) + 1 num_2 = alphabet.find(char_2) + 1 result = abs(num_1 - num_2) if result > 0: result -= 1 print('Между буквами {} и {} находится {} других букв'.format(char_1, char_2, result))
461f74ab2bd25c005cbc2a6b64852d17b7ae1f22
[ "Python" ]
5
Python
Implexx/algorithms
45852894a9fc7c0663f71e27d5e1ebc91ae4fff2
ef19ee05a0bc3b0f44d4eaf7263329739ca9973c
refs/heads/master
<repo_name>dhutson2/react-atm-homework<file_sep>/src/Account/index.js import React, { Component } from "react"; class Account extends Component { constructor() { super(); this.state = { balance: 0 }; } depositCash = e => { const cashIn = parseInt(this.refs.amount.value); this.setState({ balance: this.state.balance + cashIn }); }; withdrawCash = e => { const cashOut = parseInt(this.refs.amount.value); if (cashOut > this.state.balance) { return false; } this.setState({ balance: this.state.balance - cashOut }); }; render() { let balanceClass = "balance"; if (this.state.balance === 0) { balanceClass = "zero"; } return ( <div className="account"> <h2>{this.props.name}</h2> <div className={balanceClass}>{this.state.balance}</div> <input type="text" ref="amount" placeholder="enter an amount" /> <button onClick={this.depositCash}>Deposit</button> <button onClick={this.withdrawCash}>Withdraw</button> </div> ); } } export default Account;
8a01f3eeb6f4dcc53ee9cc255b7ae59e9d1dc696
[ "JavaScript" ]
1
JavaScript
dhutson2/react-atm-homework
6b95a8b8a8efb2d29c666dce50aa81b27fe881a3
6246416ed73370358387129f8294df5f55f5d367
refs/heads/master
<repo_name>beckodyy/mappingitout<file_sep>/mapitout/ViewController.swift // // ViewController.swift // mapitout // // Created by <NAME> on 6/11/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } /* var arrayofPostion: [Float] = [] for geoPosition in array { guard let geoDic = geoPosition as? [String: Any] else { return } let latitude = geoDic[geoPosition as! DictionaryIndex<_, 0>] print("hello word. lat is") print(latitude); let longitude = geoDic[geoPosition]?[1] as! [Float]! print("hello word. long is") print(longitude); // [geoPosition as! DictionaryIndex<0, 1>] as? [Float] else { print("not a float") } // // guard let longitude = geoDic[geoPosition][1] as? [Float] else { print("not a float") } // // } } catch{ print(error) } print(path ?? "Not a real path") // Do any additional setup after loading the view. } */ <file_sep>/geoPointer.swift // // geoPointer.swift // mapitout // // Created by <NAME> on 6/15/17. // Copyright © 2017 <NAME>. All rights reserved. // //import UIKit //import MapKit // // //class geoPointer: NSObject, MKAnnotation{ // let pawPin = UIImage(named: "paw")! // // // init(friendsName: String, friendsMessage: String, image2: UIImage){ // self.name = friendsName // // self.profileImage = friendsImage // self.textMessage = friendsMessage // self.profileImage = image2 // } //} <file_sep>/mapitout/extension.swift //// //// extension.swift //// mapitout //// //// Created by <NAME> on 6/16/17. //// Copyright © 2017 <NAME>. All rights reserved. //// // //import UIKit //import MapKit // //class extension: UIView, mapViewController { // // func animation(){ // // super.viewDidLoad(animation) // // UIView.animate(withDuration: 0.5, delay: 0, animations: { // self.alpha = 1.0 // // var key = 0 // // while key != // self.annotation(location: mapViewController.location) // }) // // // } // // // //} <file_sep>/mapitout/mapViewController.swift // // mapViewController.swift // mapitout // // Created by <NAME> on 6/14/17. // Copyright © 2017 <NAME>. All rights reserved. import UIKit import SwiftyJSON import MapKit class mapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { var isZoomEnabled: Bool = true var isRotateEnabled: Bool = true @IBOutlet weak var mapIt: MKMapView! var arr: [[Double]] = [] var key: Int = 0 var latitude: Double = 0.0 var longitude: Double = 0.0 private var mapChangedFromUserInteraction = false var annotation: MKPointAnnotation = MKPointAnnotation() let location: CLLocationCoordinate2D? = nil func parseData(){ if let path = Bundle.main.path(forResource: "coordinates", ofType: "json"){ do{ let data = try! Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped) let jsonObj = try JSON(data: data) if jsonObj != JSON.null{ for(key, subJson):(String, JSON) in jsonObj{ arr.append(subJson.arrayObject as! [Double]) } }else { print("cannot get data from file") } } catch let error { print(error.localizedDescription) } }else { print("cannot find") } accessData() } func accessData(){ let sizeOfArr: Int = self.arr.endIndex while key != sizeOfArr{ latitude = arr[key][0] longitude = (arr[key][1]) let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) delayWithSeconds(0.5){ self.animation(location: location) } mapIt.removeAnnotations(mapIt.annotations) zoomIn(latitude: latitude, longitude: longitude) key = key + 1 } } func zoomIn(latitude: Double, longitude: Double){ let span: MKCoordinateSpan = MKCoordinateSpanMake(0.1, 0.1) let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span) mapIt.setRegion(region, animated: true) animation(location: location) print("this is ") print(location) } func populateMap(){ var count = 0 while (count < self.arr.count){ let latitude = getLatAt(index: count) let longitude = getLongAt(index: count) let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) removePrevious() annotateMap(location: location) count += 1 } } func getLatAt(index: Int) -> Double{ return self.arr[index][0] } func getLongAt(index: Int) -> Double{ return self.arr[index][1] } func removePrevious(){ let allAnnotations = self.mapIt.annotations self.mapIt.removeAnnotations(allAnnotations) } func annotateMap(location: CLLocationCoordinate2D){ annotation.coordinate = location DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5), execute: { self.mapIt.addAnnotation(self.annotation) }) } func pinMap(){ let startLoc = self.arr[0][0] let startLat = self.arr[0][1] self.zoomIn(latitude: startLoc, longitude: startLat) } func annotation(location: CLLocationCoordinate2D){ annotation.coordinate = location delayWithSeconds(0.5) { self.mapIt.addAnnotation(self.annotation) } } func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) { DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { completion() } } func animation(location: CLLocationCoordinate2D){ delayWithSeconds(1.5){ UIView.animate(withDuration: 50, delay: 0.5, animations: { self.annotation(location: location) } )} } override func viewDidLoad() { super.viewDidLoad() self.mapIt.delegate = self parseData() accessData() pinMap() populateMap() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } <file_sep>/pawLocations.swift // // pawLocations.swift // mapitout // // Created by <NAME> on 6/16/17. // Copyright © 2017 <NAME>. All rights reserved. // //import UIKit //import MapKit // //class pawArray: NSObject, MKAnnotation{ // var identifier = "paw" // var title: String? // var coordinate: CLLocationCoordinate2D // init(name:String,lat:CLLocationDegrees,long:CLLocationDegrees){ // title = name // coordinate = CLLocationCoordinate2DMake(lat, long) // } //} // // //class pawLocations: NSObject { // var pawPrint: Any // override init(){ //// pawPrint += mapViewController.mapTheCoord(coordinate) // self.pawPrint // // // } //} <file_sep>/README.md # Project - *MappingItOut* **MappingItOut** is a map interface with a visual indicator on the map that animates from one geo-coordinate point to another (based on the given geo-coordinate points). Time spent: *9* hours spent in total The following functionality is completed: - [X] Parse the JSON file - [X] Create an application where map view encompasses most of the screen space. - [0.5] Within the app, you must add an in-map overlay that initially point to the first geo-coordinate point provided from the JSON file. - [0.5] With every passing 0.5 seconds, animate the overlay from the previous (or initial) point to the next geo-coordinate point. - [X] User should be able to pan and zoom the map interface, without affecting the in-map overlay's position relative to the geo-spatial coordinate plane. - [X] User's touch events should not block the animation from being performed, and vice-versa. ## MappingItOut <a href="http://imgur.com/QTXSbXz"><img src="http://i.imgur.com/QTXSbXz.png" title="source: imgur.com" /></a> <a href="http://imgur.com/s4IyRcN"><img src="http://i.imgur.com/s4IyRcN.png" title="source: imgur.com" /></a> ## Notes Describe any challenges encountered while building the app. 1. Parsing local data with Swift 2. Apple loads all annotations at once ## License Copyright [2017] [<NAME>] 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.
3790fd0816cbe7cfc702d40ab8752d1ccd48ac80
[ "Swift", "Markdown" ]
6
Swift
beckodyy/mappingitout
5c834725e80b0b5e9257986a92300991f8202f60
34c79b22df43137699a867ab286cc4fd1cd1dee3
refs/heads/master
<file_sep># vueInitProject a vue initial project includes scss slide, loading-bar fetch and common style etc ## Build Setup ``` bash # install dependencies npm install # serve with hot reload at localhost:1024 npm run dev # serve with api localhost:3000 npm run api # build for production in dev environment npm run build-dev # build for production in pro environment npm run build-pro # run unit tests npm run unit # run e2e tests npm run e2e # run all tests npm test ``` For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader). <file_sep>import Vue from 'vue' import axios from 'axios' import loading from '../../plugins/loading' axios.defaults.timeout = 30 * 1000 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' const API_ROOT = process.env.API_ROOT function fetchData () { async function getResponse (url, params, type) { loading.start() let parameters = {} const api = `${API_ROOT}/${url}` if (type === 'GET') { parameters = { url: params ? `${api}?${translateParams(params)}` : `${api}`, method: 'get' } } else if (type === 'POST') { parameters = { url: `${api}`, method: 'post', data: translateParams(params) } } try { let result = await axios.request(parameters) loading.end() if (result.data.code === 1) { loading.end() } else { loading.error() Vue.prototype.$toast.show(result.data.msg || '请求服务器失败') } return result.data } catch (err) { loading.error() Vue.prototype.$toast.show(err.msg || err.message || '请求服务器失败') return {code: 44000, msg: '接口请求失败,请检查网络'} } } function translateParams (params) { let url = '' for (let param in params) { url += `${param}=${params[param]}&` } return url.substring(0, url.length - 1) } return { get (url, params) { return getResponse(url, params, 'GET') }, post (url, params) { return getResponse(url, params, 'POST') } } } export default fetchData() // export const getRequest = async (url, params) => { // let urlStr = `${API_ROOT}/${url}?${translateParams(params)}` // let parameters = { // url: urlStr, // method: 'get' // } // let data = await axios.request(parameters) // return data.data // } // export const postRequest = async (url, params) => { // let parameters = { // url: `${API_ROOT}/${url}`, // method: 'post', // data: translateParams(params) // } // let data = await axios.request(parameters) // return data.data // } // export function translateParams (params) { // let url = '' // for (let param in params) { // url += `${param}=${params[param]}&` // } // return url.substring(0, url.length - 1) // } <file_sep>export function changeUrl (type, path, params) { const urlDomain = process.env[type] let url = '' for (let param in params) { url += `${param}=${params[param]}&` } const paramsStr = url.substring(0, url.length - 1) window.location.href = `${urlDomain}/jsapp/wechat/${path}/index.html?${paramsStr}` } <file_sep>module.exports = function (app) { const imgUrl = 'https://dlhr.oss-cn-hangzhou.aliyuncs.com/img/170714/d95dcc7a4c35281f4ab053897280ba60.JPG?x-oss-process=image/resize,m_fill,h_100,w_100,limit_1'; // 获取企业详情 app.get('/getArticlesOnColumn', function (req, res, next) { return res.send({ code: 1, msg: '操作成功', total: 3, data: [{ id: 914, title: '测试文章内详情图', introduction: '测试', imageurl: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=415293130,2419074865&fm=27&gp=0.jpg' }, { id: 912, title: '测试文章内详情图2', introduction: '测试', imageurl: imgUrl }] }) }) } <file_sep>export const getParameterValue = (parameter) => { var reg = new RegExp('(^|&)' + parameter + '=([^&]*)(&|$)', 'i') var r = window.location.search.substr(1).match(reg) if (r != null) return unescape(r[2]) return null } /* 获取URL中hash参数的值 */ export const getParameterHashValue = (parameter) => { var reg = new RegExp('(^|&)' + parameter + '=([^&]*)(&|$)', 'i') var r = window.location.hash.substr(3).match(reg) if (r != null) return unescape(r[2]) return null } <file_sep>import fetch from './utils/request' import {getParameterValue} from '../plugins/paramsPlugin' export const getBannerList = () => fetch.get('getArticlesOnColumn', { channelId: getParameterValue('channelId') || '1002', column: 'mbfm', deleteState: 0, pageNo: 1, pageSize: 10, orderDir: 'desc', orderColumn: 'showTime', preRrelease: 0 })
445219b4b9d9cf233050579efb053f235476855a
[ "Markdown", "JavaScript" ]
6
Markdown
WinnerGirl/vueInitProject
bd6ff61d4bdf347562e39b6448f5fde8155754b5
05b1763ce5bcdb678d1f5e23322cd994040d9724
refs/heads/master
<repo_name>snakista/Image-Search-React-App<file_sep>/src/components/imageList.js import React from 'react'; import './imageList.css'; const ImageList=(props)=>{ const imgs=props.foundImages.map(img=>{ return <img key={img.id} src={img.urls.regular} alt={img.alt_description}/> }); return( <div className="image_list">{imgs}</div> ) } export default ImageList;<file_sep>/README.md # Image-Search-React-App Simple app to show images to the user using unsplash api
2c8e5ac303fc4f035089aa272c70173b68ecad17
[ "JavaScript", "Markdown" ]
2
JavaScript
snakista/Image-Search-React-App
e902b78463f9d90e4d514ba3f456ff05e821d202
2b01e42abf8b7a01e168a0e9a5bbf20631e9136d
refs/heads/master
<repo_name>akshatkarani/jus_for_laughs<file_sep>/README.md # jus_for_laughs Twitter bot to mirror Jokes from reddit and post it on [twitter](https://twitter.com/jus_for_laughs). To access Twitter API I have used Tweepy and to access Reddit API I have used PRAW. The bot runs every two hours automatically, for this just set up a cron job. Run the bot using `run.sh`. You can contact me on [gitter](https://gitter.im/akshatkarani). <file_sep>/src/twitter.py import re import tweepy import keys from logger import logger def _init_twitter(): auth = tweepy.OAuthHandler(keys.TWEET_API_KEY, keys.TWEET_API_SECRET) auth.set_access_token(keys.TWEET_ACCESS_KEY, keys.TWEET_ACCESS_SECRET) return auth def _get_api(): return tweepy.API(_init_twitter()) def post_tweet(tweet: str, last_status_id=None): """ Posts a tweet """ api = _get_api() try: status = api.update_status(tweet, last_status_id) logger.info('Tweet id: ' + str(status.id)) return status.id except tweepy.error.TweepError as e: logger.error(e) def post_thread(tweets: list): """ Posts a thread of tweets, received as a list of strings that are less than 280 characters each. """ last_status_id = None for tweet in tweets: last_status_id = post_tweet(tweet, last_status_id) def check(tweets): for tweet in tweets: if len(tweet) > 280: return False return True def split_tweet(tweet): """ Split a tweet into multiple tweets if it exceeds the character limit """ # Try spliting based on new line tweets = tweet.split('\n') if not check(tweets): # Try spliting based on period tweets = re.split('[\n.]', tweet) tweets = [t + '. ' for t in tweets if t] if check(tweets): tweets = [t for t in tweets if t] new = [] curr_tweet = '' for i, tweet in enumerate(tweets): if len(tweet) + len(curr_tweet) > 280: new.append(curr_tweet) curr_tweet = tweet else: curr_tweet += tweet return new + [curr_tweet] return False def post(submission_id, tweet): # Check if tweet exceeds the character limit of 280 logger.info('Reddit id: ' + str(submission_id)) if len(tweet) <= 280: post_tweet(tweet) else: tweets = split_tweet(tweet) if not tweets: return post_thread(tweets) <file_sep>/src/reddit.py import praw import keys from logger import logger # SUBREDDITS is a dictionary with key as subreddit name and value # which indicates status. If status is 0 then it won't be used. SUBREDDITS = {'jokes': 1} def _init_reddit(): try: return praw.Reddit(user_agent='jokes by akshatkarani', client_id=keys.REDDIT_KEY, client_secret=keys.REDDIT_SECRET, username=keys.REDDIT_USERNAME, password=keys.REDDIT_PASSWORD) except KeyError: logger.error('Error occurred') print('Error occurred') def _get_post(submission): """ Given a submission returns the post. In some posts title is re-written in selftext, this takes care of that. """ post = submission.selftext if submission.title.lower() not in post.lower(): post = submission.title + '\n\n' + post return submission.id, post def _get_subreddits(reddit): """ Returns all the subreddits to use from SUBREDDITS """ for sub, status in SUBREDDITS.items(): if status == 1: yield reddit.subreddit(sub) def get_newest(): """ Returns posts from subreddits """ reddit = _init_reddit() if isinstance(reddit, praw.Reddit): subreddits = _get_subreddits(reddit) for subreddit in subreddits: for submission in subreddit.hot(limit=5): if not submission.stickied: yield _get_post(submission) <file_sep>/src/jokes.py from reddit import get_newest from twitter import post def main(): """ Main function """ for submission_id, tweet in get_newest(): post(submission_id, tweet) if __name__ == '__main__': main() <file_sep>/run.sh python3 /home/akshat/Projects/jokes/src/jokes.py
23c03d73342ec9e0c6ea8d74706aaaaddd5a3c1d
[ "Markdown", "Python", "Shell" ]
5
Markdown
akshatkarani/jus_for_laughs
acfa49872e8e715c755a1d67684e553dfec61b89
7db2c60247adaab89c2a71dbc8885caa7fe94108
refs/heads/master
<repo_name>at-shota55/follow-button<file_sep>/src/js/vdom/utils.js //isEventAttr関数で 渡された attrs がonClickやonChengeなど先頭に on が着くかでイベントかどうか判定 export const isEventAttr = (attr) => { return /^on/.test(attr) } //文字列でなければ仮想 DOM オブジェクトとして判定する関数 export const isVNode = (node) => { return typeof node !== "string"; }; //patch 関数の比較変更をするときに判定する関数 export const isTextChild = (node) => { return ( node && node.children && node.children.length > 0 && typeof node.children[0] === "string" ); };<file_sep>/src/js/vdom/render.js import { isEventAttr } from './utils'; const setAttrs = (target, attrs) => { for (const attr in attrs) { if (isEventAttr(attr)) { //もしonが付いたら target.addEventListener(attr.slice(2), attrs[attr]); //ex. onClick => Clickがattrsに入る } else { target.setAttribute(attr, attrs[attr]); } } }; function renderElement({ tagName, attrs, children }) { const $el = document.createElement(tagName); //リアル DOM 要素 $elに class や id、type などの属性を付与 setAttrs($el,attrs); for (const child of children) { //children 要素があるならば一つ一つを要素 $el に appendChildする $el.appendChild(render(child)); } return $el } export function render(vNode) { if (typeof vNode === "string") { //渡された要素が文字列かどうか return document.createTextNode(vNode); } return renderElement(vNode); //文字列でなければrenderElement 関数が呼ばれる }
7fd12f8e75991a2a3f126809a913a22e0fc1c6af
[ "JavaScript" ]
2
JavaScript
at-shota55/follow-button
793a9acfe02048b7055709e652eae22a3033f8a5
e92c26cc7f6c389cd3194ab3cd1af97f477d1e6d
refs/heads/master
<file_sep>package com.example.kamal.saatzanhamrah.VisitLastDateEmployerToEmployee; /** * Created by kamal on 12/19/2017. */ public class LastTimeConfirm { private boolean isSelected; private String startWorkDate; private String startWorkTime; private String endWorkDate; private String endWorkTime; private String workTime; private String confirm_employer; public String getStartWorkTime() { return startWorkTime; } public void setStartWorkTime(String startWorkTime) { this.startWorkTime = startWorkTime; } public String getEndWorkTime() { return endWorkTime; } public void setEndWorkTime(String endWorkTime) { this.endWorkTime = endWorkTime; } public String getStartWorkDate() { return startWorkDate; } public void setStartWorkDate(String startWorkDate) { this.startWorkDate = startWorkDate; } public String getEndWorkDate() { return endWorkDate; } public void setEndWorkDate(String endWorkDate) { this.endWorkDate = endWorkDate; } public String getWorkTime() { return workTime; } public void setWorkTime(String workTime) { this.workTime = workTime; } public boolean getSelected() { return isSelected; } public void setSelected(boolean selected) { isSelected = selected; } } <file_sep>package com.example.kamal.saatzanhamrah.RegisterEmploy; import android.widget.Button; import android.widget.ProgressBar; import java.util.Map; /** * Created by kamal on 12/6/2017. */ public class RegisterPresenter { RegisterView view; RegisterModel model; public RegisterPresenter(RegisterModel model, RegisterView view) { this.view=view; this.model=model; } public void onCreate() { view.setPresenter(this); model.setPresenter(this); } public void passParams(Map<String, String> params, String url, ProgressBar progressBar, Button registerButton) { model.employPostParams(params,url,progressBar,registerButton); } public void resultPresenter(String result) { view.resultView(result); } } <file_sep>package com.example.kamal.saatzanhamrah.RegisterEmploy; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.example.kamal.saatzanhamrah.MySingleton; import com.example.kamal.saatzanhamrah.Share; public class RegisterActivity extends AppCompatActivity { RegisterView view; RegisterModel model; RegisterPresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); view=new RegisterView(this); setContentView(view); model=new RegisterModel(this); presenter=new RegisterPresenter(model,view); presenter.onCreate(); } @Override protected void onStop() { super.onStop(); if ( MySingleton.getInstance(this).getRequestQueue()!= null) { MySingleton.getInstance(this).getRequestQueue().cancelAll(Share.TAG); } } } <file_sep>package com.example.kamal.saatzanhamrah.LoginEmploy; import android.app.Activity; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.Toast; import com.example.kamal.saatzanhamrah.MainPackage.MainActivity; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.Share; import java.util.logging.Handler; /** * Created by kamal on 12/9/2017. */ public class LoginView extends FrameLayout implements View.OnClickListener, AdapterView.OnItemSelectedListener { LoginPresenter presenter; Activity activity; EditText txtEdituser; EditText txtEditpassword; Button btnLogin, btnRegister, btnForgot; CheckBox checkBox; Spinner spinner; private ProgressBar progressBar; String url = "http://www.kamalroid.ir/login_20190329.php"; int selectionSpinner = 0; String kind=""; private Toolbar toolbar; public LoginView(@NonNull AppCompatActivity activity) { super(activity); this.activity = activity; View view = inflate(activity, R.layout.activity_login, this); txtEdituser = (EditText) view.findViewById(R.id.editText_login_userName); txtEditpassword = (EditText) view.findViewById(R.id.editText_login_password); btnLogin = (Button) view.findViewById(R.id.button_login_signIn); btnRegister = (Button) view.findViewById(R.id.button_login_signUp); btnForgot = (Button) view.findViewById(R.id.button_login_forgot); checkBox = (CheckBox) view.findViewById(R.id.checkBox_login_save); spinner = (Spinner) view.findViewById(R.id.spinner_login_employ); toolbar = (Toolbar) view.findViewById(R.id.toolbar); progressBar = (ProgressBar) view.findViewById(R.id.progressBar_login_loading); activity.setSupportActionBar(toolbar); activity.getSupportActionBar().setDisplayShowHomeEnabled(true); activity.getSupportActionBar().setDisplayShowTitleEnabled(false); toolbar.setBackgroundColor(ContextCompat.getColor(activity, R.color.colorPrimary)); if (Share.loadPref(activity, "userKey") != "" && Share.loadPref(activity, "passKey") != "" && Share.loadPref(activity, "kindKey") != "") { if(Share.loadPref(activity,"userKeyUpdate")==""){ Share.saveSharePref(activity,"userKeyUpdate",Share.loadPref(activity, "userKey")); } Intent intent = new Intent(activity, MainActivity.class); intent.putExtra("user", Share.loadPref(activity, "userKey")); intent.putExtra("kind", Share.loadPref(activity, "kindKey")); activity.startActivity(intent); activity.finish(); } Share.spinnerAdapter(activity, spinner, R.array.arrayemploy); btnRegister.setOnClickListener(this); btnLogin.setOnClickListener(this); btnForgot.setOnClickListener(this); spinner.setOnItemSelectedListener(this); } public void setPresenter(LoginPresenter loginPresenter) { this.presenter = loginPresenter; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button_login_signUp: presenter.registerPresenter(); break; case R.id.button_login_signIn: if (Share.check(getContext())) { if(kind.equals("")){ Toast.makeText(activity, "لطفا نوع شغل تان را انتخاب کنید.", Toast.LENGTH_LONG).show(); return; } btnLogin.setEnabled(false); progressBar.setVisibility(View.VISIBLE); presenter.loginPresenter(txtEdituser.getText().toString().trim(), txtEditpassword.getText().toString().trim(), kind, url, progressBar, btnLogin); break; } else { Toast.makeText(activity, getResources().getString(R.string.noInternet), Toast.LENGTH_LONG).show(); break; } case R.id.button_login_forgot: presenter.forgotPresenter(); break; } } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: break; case 1: selectionSpinner = 1; kind = "employer"; break; case 2: selectionSpinner = 2; kind = "employee"; break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } } <file_sep>package com.example.kamal.saatzanhamrah.DeletePackage; import android.app.Activity; import android.support.v4.app.FragmentActivity; import com.android.volley.Request; import com.example.kamal.saatzanhamrah.Share; import com.example.kamal.saatzanhamrah.VisitLastDate.LastTime; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by kamal on 1/16/2018. */ public class DeleteModel { DeletePresenter presenter; Activity activity; String _workTimeHour, _workTimeMinute, _workTimeSecond; public DeleteModel(DeletePresenter deletePresenter, FragmentActivity activity) { this.presenter=deletePresenter; this.activity=activity; } public void getListDeleteModel(String url, String dateDelete, final String user, final String kind) { final String keyStart = dateDelete.replace("/", ""); Share.getStringResponse(activity, Request.Method.POST, url, null, new Share.StringVolleyCallBack() { @Override public void onSuccessResponse(String result) { try { JSONObject jsonObject = new JSONObject(result); JSONArray jsonArray = jsonObject.getJSONArray("lastVisit"); List<LastTime> lastTimeList = new ArrayList<>(); LastTime lastTime; for (int i = 0; i < jsonArray.length(); i++) { lastTime = new LastTime(); JSONObject jsonObject1 = jsonArray.getJSONObject(i); String startLastDate = jsonObject1.getString("start_date"); String startLastTime = jsonObject1.getString("start_time"); String endLastDate = jsonObject1.getString("end_date"); String endLastTime = jsonObject1.getString("end_time"); String _workTime = jsonObject1.getString("worktime"); if (!_workTime.equals("null")) { int workTime = Integer.parseInt(_workTime); _workTimeHour = workTime / 3600 + ""; _workTimeMinute = workTime % 3600 / 60 + ""; _workTimeSecond = workTime % 3600 % 60 + ""; _workTime = _workTimeHour +":"+ _workTimeMinute +":"+ _workTimeSecond; } lastTime.setStartWorkDate(startLastDate); lastTime.setStartWorkTime(startLastTime); lastTime.setEndWorkDate(endLastDate); lastTime.setEndWorkTime(endLastTime); lastTime.setStartWorkDate(startLastDate); lastTime.setStartWorkTime(startLastTime); lastTime.setEndWorkDate(endLastDate); lastTime.setEndWorkTime(endLastTime); lastTime.setWorkTime(_workTime); lastTimeList.add(lastTime); presenter.passListPresenter(lastTimeList); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onError(String error) { } @Override public Map onMapPost() { Map<String, String> Params1 = new HashMap<>(); Params1.put("user", user); Params1.put("keyStart", keyStart); Params1.put("kind", kind); Params1.put("key_text_android", "ktaa"); return Params1; } }); } } <file_sep>package com.example.kamal.saatzanhamrah.TimeEmploy; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Handler; import android.os.Parcelable; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.NavigationView; import android.support.design.widget.TextInputLayout; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.Chronometer; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.example.kamal.saatzanhamrah.MainPackage.MainActivity; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.Share; import com.example.kamal.saatzanhamrah.VisitLastDate.LastTime; import com.example.kamal.saatzanhamrah.VisitLastDate.VisitLastDateFragment; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import static com.example.kamal.saatzanhamrah.Share.loadPref; public class AutoDateFragment extends Fragment implements View.OnClickListener, MainActivity.PassData, MainActivity.EnableData { Activity activity; String startTimeEmployeeUrl = "http://www.kamalroid.ir/time_register.php"; String endTimeEmployeeUrl = "http://www.kamalroid.ir/end_time_register.php"; String showLastRegisterUrl = "http://kamalroid.ir/last_time.php"; String problemUrl = "http://www.kamalroid.ir/explain_problem.php"; private Button buttonStart; private String user, kind, getUser, getKind; TimePresenter presenter; LinearLayout linearLayoutHandDate, linearLayoutTitle, linearLayoutMessageStart; RelativeLayout relativeLayoutAutoDate; private AutoTimeAdapter adapter; private RecyclerView recyclerView; private ProgressDialog pd; Toolbar toolbar; Animation slide_left_in; Animation slide_right_out; private TextView textLastStartDate, textLastStartTime, textTitle; private ProgressBar progressBar; private CoordinatorLayout coordinatorLayout; private List<LastTime> lastTimeList = new ArrayList<>(); private LastTime lastTime = new LastTime(); private EditText editText; private boolean mIsPremium; private TextView problemTextView; private TextInputLayout textInputLayoutExplain; private NavigationView navigationView; private Chronometer chronometer; private boolean ruuning = false; public static Calendar calendarStart; public static Date dateStart; private CardView cardView; private Calendar calendar1; private Calendar calendar2; Date date2; @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); presenter = new TimePresenter(this); slide_left_in = AnimationUtils.loadAnimation( getContext(), R.anim.slide_left_in); slide_right_out = AnimationUtils.loadAnimation( getContext(), R.anim.slide_right_out); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_autotime, container, false); buttonStart = (Button) view.findViewById(R.id.Button_time_startWork); linearLayoutHandDate = (LinearLayout) view.findViewById(R.id.linear_time_handDate); toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar); textLastStartDate = (TextView) view.findViewById(R.id.textView_autoTime_startDate); textLastStartTime = (TextView) view.findViewById(R.id.textView_autoTime_startTime); linearLayoutTitle = (LinearLayout) view.findViewById(R.id.linear_autoTime_titleLastTime); progressBar = (ProgressBar) view.findViewById(R.id.progressBar_autoTime_loading); editText = (EditText) view.findViewById(R.id.editText_time_explain); problemTextView = (TextView) view.findViewById(R.id.problemExplain); textTitle = (TextView) getActivity().findViewById(R.id.textView_toolbar_title); navigationView = getActivity().findViewById(R.id.navigation_view); textInputLayoutExplain = (TextInputLayout) view.findViewById(R.id.textInput_time_explain); coordinatorLayout = (CoordinatorLayout) view.findViewById(R.id.coordinate_autoTime_layout); recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView_autotime_ListVisit); linearLayoutMessageStart = view.findViewById(R.id.linear_autoTime_messageStart); cardView = view.findViewById(R.id.cardView_autoTime_messageStart); chronometer = view.findViewById(R.id.chronometer); textTitle.setText(getString(R.string.autoDate)); presenter.sendProblem(problemUrl); editText.setText(Share.loadPref(getContext(),"explainKey")); if (loadPref(getActivity(), "start" + user).equals("false")) { recyclerView.setVisibility(View.GONE); linearLayoutTitle.setVisibility(View.GONE); editText.setVisibility(View.VISIBLE); toolbar.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.yellow)); navigationView.getHeaderView(0).setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.yellow)); buttonStart.setText(getString(R.string.endDate)); textInputLayoutExplain.setVisibility(View.VISIBLE); buttonStart.setBackgroundResource(R.drawable.yellowcircle); lastTime = new LastTime(); lastTimeList = new ArrayList<>(); cardView.setVisibility(View.VISIBLE); textLastStartDate.setText(Share.loadPref(getActivity(), "startLastDate" + user)); textLastStartTime.setText(Share.loadPref(getActivity(), "startLastTime" + user)); } else if (loadPref(getActivity(), "end" + user).equals("false")) { recyclerView.setVisibility(View.GONE); linearLayoutTitle.setVisibility(View.GONE); editText.setVisibility(View.GONE); toolbar.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.green_500)); navigationView.getHeaderView(0).setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.green_500)); buttonStart.setText(getString(R.string.startDate)); buttonStart.setBackgroundResource(R.drawable.bluecircle); lastTime = new LastTime(); lastTimeList = new ArrayList<>(); textLastStartDate.setText(""); textLastStartTime.setText(""); cardView.setVisibility(View.INVISIBLE); lastTime.setStartWorkDate(Share.loadPref(getActivity(), "startLastDate" + user)); lastTime.setStartWorkTime(Share.loadPref(getActivity(), "startLastTime" + user)); } else { Share.saveSharePref(getContext(), "end" + user, "false"); Share.saveSharePref(getContext(), "start" + user, "true"); } buttonStart.setOnClickListener(this); return view; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.Button_time_startWork: if (Share.check(getContext())) { if (Share.loadPref(getActivity(), "count").equals("1") || Share.loadPref(getActivity(), "count").equals("2")) { if (loadPref(getActivity(), "start" + user).equals("true")) { progressBar.setVisibility(View.VISIBLE); buttonStart.setEnabled(false); buttonStart.setText("درحال ثبت زمان شروع"); presenter.startChangeDate(startTimeEmployeeUrl, user, kind, progressBar, buttonStart, textLastStartDate, textLastStartTime); break; } else if (loadPref(getActivity(), "end" + user).equals("true")) { progressBar.setVisibility(View.VISIBLE); buttonStart.setEnabled(false); buttonStart.setText("درحال ثبت زمان پایان"); presenter.endChangeDate(endTimeEmployeeUrl, user, kind, editText.getText().toString(), progressBar, buttonStart); break; } } else { Share.showSnackBar(getContext(), coordinatorLayout, getResources().getString(R.string.enableMessage)); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.noInternet), Toast.LENGTH_LONG).show(); break; } case R.id.editText_time_explain: editText.clearFocus(); break; } } public void startRegisterTime(String result) { switch (result) { case "done": chronometer.setBase(SystemClock.elapsedRealtime()); chronometer.start(); cardView.setVisibility(View.VISIBLE); Share.saveSharePref(getContext(), "start" + user, "false"); Share.saveSharePref(getContext(), "end" + user, "true"); recyclerView.setVisibility(View.GONE); linearLayoutTitle.setVisibility(View.GONE); Share.showSnackBar(getActivity(), coordinatorLayout, getString(R.string.startRegister)); editText.setVisibility(View.VISIBLE); textInputLayoutExplain.setVisibility(View.VISIBLE); buttonStart.startAnimation(slide_right_out); new Handler().postDelayed(new Runnable() { @Override public void run() { buttonStart.startAnimation(slide_left_in); buttonStart.setText(getString(R.string.endDate)); buttonStart.setEnabled(true); buttonStart.setBackgroundResource(R.drawable.yellowcircle); toolbar.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.yellow)); navigationView.getHeaderView(0).setBackgroundColor(ContextCompat.getColor(getContext(), R.color.yellow)); } }, 300); break; case "failure_post": Share.showSnackBar(getActivity(), coordinatorLayout, getString(R.string.errorInternet)); if (Share.loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "1"); } else if (Share.loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "2"); } if (loadPref(getActivity(), "start" + user).equals("false")) { buttonStart.setEnabled(true); buttonStart.setText("ثبت زمان شروع"); } else if (loadPref(getActivity(), "end" + user).equals("false")) { buttonStart.setEnabled(true); buttonStart.setText("ثبت زمان شروع"); } break; default: Share.showSnackBar(getActivity(), coordinatorLayout, getString(R.string.errorInternet)); if (Share.loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "1"); } else if (Share.loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "2"); } if (loadPref(getActivity(), "start" + user).equals("false")) { buttonStart.setEnabled(true); buttonStart.setText("ثبت زمان شروع"); } else if (loadPref(getActivity(), "end" + user).equals("false")) { buttonStart.setEnabled(true); buttonStart.setText("ثبت زمان شروع"); } break; } } public void endRegisterTime(String result) { switch (result) { case "done": chronometer.setBase(SystemClock.elapsedRealtime()); chronometer.stop(); cardView.setVisibility(View.INVISIBLE); Share.saveSharePref(getContext(), "end" + user, "false"); Share.saveSharePref(getContext(), "start" + user, "true"); Share.showSnackBar(getActivity(), coordinatorLayout, getString(R.string.endRegister)); if (Share.loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "2"); } else if (Share.loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "3"); } if (Share.loadPref(getActivity(), "mIsPremium").equals("true")) Share.saveSharePref(getActivity(), "count", "1"); recyclerView.setVisibility(View.VISIBLE); linearLayoutTitle.setVisibility(View.VISIBLE); textLastStartDate.setText(""); textLastStartTime.setText(""); editText.setVisibility(View.GONE); textInputLayoutExplain.setVisibility(View.GONE); buttonStart.startAnimation(slide_right_out); new Handler().postDelayed(new Runnable() { @Override public void run() { buttonStart.startAnimation(slide_left_in); buttonStart.setBackgroundResource(R.drawable.bluecircle); buttonStart.setEnabled(true); buttonStart.setText(getString(R.string.startDate)); toolbar.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.green_500)); navigationView.getHeaderView(0).setBackgroundColor(ContextCompat.getColor(getContext(), R.color.green_500)); Share.saveSharePref(getActivity(), "startLastDate", ""); Share.saveSharePref(getActivity(), "startLastTime", ""); Share.saveSharePref(getActivity(), "explainKey", ""); editText.setText(""); } }, 300); break; case "failure_post": Share.showSnackBar(getActivity(), coordinatorLayout, getString(R.string.errorInternet)); if (Share.loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "1"); } else if (Share.loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "2"); } if (loadPref(getActivity(), "start" + user).equals("false")) { buttonStart.setEnabled(true); buttonStart.setText("ثبت زمان پایان"); } else if (loadPref(getActivity(), "end" + user).equals("false")) { buttonStart.setEnabled(true); buttonStart.setText("ثبت زمان پایان"); } break; default: Share.showSnackBar(getActivity(), coordinatorLayout, getString(R.string.errorInternet)); if (Share.loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "1"); } else if (Share.loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "2"); } if (loadPref(getActivity(), "start" + user).equals("false")) { buttonStart.setEnabled(true); buttonStart.setText("ثبت زمان پایان"); } else if (loadPref(getActivity(), "end" + user).equals("false")) { buttonStart.setEnabled(true); buttonStart.setText("ثبت زمان پایان"); } break; } } public void passListView(List<LastTime> lastTimeList) { VisitLastDateFragment visitLastDateFragment = new VisitLastDateFragment(); adapter = new AutoTimeAdapter(visitLastDateFragment, lastTimeList, user, kind); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setAdapter(adapter); } @Override public void sendData(String user, String kind, String userUpdate) { this.user = user; this.kind = kind; } @Override public void sendEnable(boolean mIsPremium,String user, String kind) { this.mIsPremium = mIsPremium; this.user = user; this.kind = kind; } public void resultProblem(String result) { problemTextView.setText(result); recyclerView.setVisibility(View.GONE); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); } @Override public void onPause() { super.onPause(); Long baseCh = SystemClock.elapsedRealtime() - chronometer.getBase();// time chronometer calendarStart = Calendar.getInstance(); dateStart = calendarStart.getTime(); Long pause = dateStart.getTime();//time system Share.saveSharePrefLong(getContext(), "pauseChronometer" + user, pause); Share.saveSharePrefLong(getContext(), "baseChronometer" + user, baseCh); Share.saveSharePref(getContext(),"explainKey",editText.getText().toString()); } @Override public void onStop() { super.onStop(); } @Override public void onStart() { super.onStart(); if (loadPref(getActivity(), "end" + user).equals("false")) { chronometer.setBase(SystemClock.elapsedRealtime()); } else { Long startCh = Share.loadPrefLong(getContext(), "pauseChronometer" + user); Long baseCh = Share.loadPrefLong(getContext(), "baseChronometer" + user); calendarStart = Calendar.getInstance(); Long y = calendarStart.getTime().getTime() - startCh + baseCh; Long most = 31104000000L; if (y > most) { Share.saveSharePrefLong(getContext(), "pauseChronometer" + user, 0L); Share.saveSharePrefLong(getContext(), "baseChronometer" + user, 0L); chronometer.setBase(SystemClock.elapsedRealtime()); chronometer.stop(); } else { chronometer.setBase(SystemClock.elapsedRealtime() - y); chronometer.start(); } } } } <file_sep>package com.example.kamal.saatzanhamrah.VisitLastDateEmployerToEmployee; import android.graphics.Color; import android.support.v4.app.FragmentActivity; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.Share; import java.util.List; /** * Created by kamal on 12/20/2017. */ public class VisitLastDateEmployerToEmployeeAdapter extends RecyclerView.Adapter<VisitLastDateEmployerToEmployeeAdapter.LastTimeViewHolder> { FragmentActivity activity; List<LastTimeConfirm> list; @Override public int getItemViewType(int position) { return super.getItemViewType(position); } PassDataCheck passDataCheck; String user, kind; VisitLastDateEmployerToEmployeeFragment visitLastDateEmployerToEmployeeFragment; public VisitLastDateEmployerToEmployeeAdapter(VisitLastDateEmployerToEmployeeFragment visitLastDateEmployerToEmployeeFragment, List<LastTimeConfirm> list, String user, String kind) { this.activity = visitLastDateEmployerToEmployeeFragment.getActivity(); this.list = list; this.user = user; this.kind = kind; this.visitLastDateEmployerToEmployeeFragment = visitLastDateEmployerToEmployeeFragment; } @Override public LastTimeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_last_time_adapter, parent, false); return new LastTimeViewHolder(view); } @Override public void onBindViewHolder(final LastTimeViewHolder holder, final int position) { final LastTimeConfirm lastTimeConfirm = list.get(position); holder.visitStartDateWork.setText(lastTimeConfirm.getStartWorkDate()); holder.visitStartTimeWork.setText(lastTimeConfirm.getStartWorkTime()); holder.visitEndDateWork.setText(lastTimeConfirm.getEndWorkDate()); holder.visitEndTimeWork.setText(lastTimeConfirm.getEndWorkTime()); holder.sumDate.setText(lastTimeConfirm.getWorkTime()); holder.visitStartDateWork.setTextColor(Color.BLUE); holder.visitStartTimeWork.setTextColor(Color.BLUE); holder.visitEndDateWork.setTextColor(Color.RED); holder.visitEndTimeWork.setTextColor(Color.RED); holder.sumDate.setTextColor(Color.BLACK); holder.checkBox.setChecked(lastTimeConfirm.getSelected()); holder.checkBox.setTag(position); holder.checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Share.check(activity)) { Integer pos=(Integer)holder.checkBox.getTag(); if (!list.get(pos).getSelected()) { passDataCheck = (PassDataCheck) visitLastDateEmployerToEmployeeFragment; passDataCheck.sendDataCheck(activity, VisitLastDateEmployerToEmployeeAdapter.this, holder.visitStartDateWork.getText().toString(), holder.visitStartTimeWork.getText().toString(), list.get(pos),pos,holder.checkBox, 1); } else { passDataCheck = (PassDataCheck) visitLastDateEmployerToEmployeeFragment; passDataCheck.sendDataCheck(activity, VisitLastDateEmployerToEmployeeAdapter.this, holder.visitStartDateWork.getText().toString(), holder.visitStartTimeWork.getText().toString(), list.get(pos), pos,holder.checkBox,0); } } else { Toast.makeText(activity, activity.getResources().getString(R.string.noInternet), Toast.LENGTH_LONG).show(); if(holder.checkBox.isChecked()){ holder.checkBox.setChecked(false); }else{ holder.checkBox.setChecked(true); } } } }); } @Override public int getItemCount() { return list.size(); } class LastTimeViewHolder extends RecyclerView.ViewHolder { TextView visitStartDateWork, visitStartTimeWork, visitEndDateWork, visitEndTimeWork, sumDate; RelativeLayout relativeLayout; CheckBox checkBox; public LastTimeViewHolder(View itemView) { super(itemView); visitStartDateWork = (TextView) itemView.findViewById(R.id.textView_contentLastTimeAdapter_startWorkDate); visitStartTimeWork = (TextView) itemView.findViewById(R.id.textView_contentLastTimeAdapter_startWorkTime); visitEndDateWork = (TextView) itemView.findViewById(R.id.textView_contentLastTimeAdapter_endWorkDate); visitEndTimeWork = (TextView) itemView.findViewById(R.id.textView_contentLastTimeAdapter_endWorkTime); sumDate = (TextView) itemView.findViewById(R.id.textView_contentLastTimeAdapter_sumDate); checkBox = itemView.findViewById(R.id.confirm_employer); } } public interface PassDataCheck { public void sendDataCheck(FragmentActivity activity1, VisitLastDateEmployerToEmployeeAdapter adapter, String startDate, String startTime, LastTimeConfirm lastTimeConfirm,int pos,CheckBox checkBox, int check); } } <file_sep>package com.example.kamal.saatzanhamrah; import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; /** * Created by kamal on 2/3/2018. */ public class CustumButton extends android.support.v7.widget.AppCompatButton { public CustumButton(Context context) { super(context); } public CustumButton(Context context, AttributeSet attrs) { super(context, attrs); Typeface face=Typeface.createFromAsset(context.getAssets(), "fonts/iransans.ttf"); this.setTypeface(face); } public CustumButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); Typeface face=Typeface.createFromAsset(context.getAssets(), "fonts/iransans.ttf"); this.setTypeface(face); } } <file_sep>package com.example.kamal.saatzanhamrah.VisitEmployerToEmployee; import android.support.v4.app.FragmentActivity; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import com.android.volley.Request; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.Share; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by kamal on 12/24/2017. */ public class VisitEmployerModel { FragmentActivity activity; private String user; VisitEmployerPresenter presenter; String userUpdate; public VisitEmployerModel(VisitEmployerPresenter presenter, FragmentActivity activity) { this.activity=activity; this.presenter=presenter; userUpdate=Share.loadPref(activity,"userKeyUpdate"); } public void visitEmployerModel(String url, final String user, final ProgressBar progressbar) { this.user =user; Share.getStringResponse(activity, Request.Method.POST, url, null, new Share.StringVolleyCallBack() { @Override public void onSuccessResponse(String result) { try { JSONObject jsonObject=new JSONObject(result); JSONArray jsonArray=jsonObject.getJSONArray("employer"); List<VisitEmployer> list=new ArrayList<VisitEmployer>(); VisitEmployer visitEmployer; for(int i=0;i<jsonArray.length();i++){ visitEmployer=new VisitEmployer(); JSONObject jsonObject1=jsonArray.getJSONObject(i); String userNameEmployer=jsonObject1.getString("update_employer"); visitEmployer.setUserNameEmployer(userNameEmployer); list.add(visitEmployer); } presenter.passListVisitEmployerPresenter(list); progressbar.setVisibility(View.GONE); } catch (JSONException e) { e.printStackTrace(); progressbar.setVisibility(View.GONE); } } @Override public void onError(String error) { Toast.makeText(activity, activity.getResources().getString(R.string.error), Toast.LENGTH_SHORT).show(); progressbar.setVisibility(View.GONE); } @Override public Map onMapPost() { Map<String, String> Params = new HashMap<>(); Params.put("userEmployee", user); Params.put("key_text_android", "ktaa"); return Params; } }); } } <file_sep>package com.example.kamal.saatzanhamrah.VisitEmployeeToEmployer; import android.widget.ProgressBar; import java.util.List; /** * Created by kamal on 12/24/2017. */ public class VisitEmployeePresenter { VisitEmployeeToEmployerFragment view; VisitEmployeeModel model; public VisitEmployeePresenter(VisitEmployeeToEmployerFragment view) { this.view=view; model=new VisitEmployeeModel(this,view.getActivity()); } public void visitEmployeeToEmployer(String url, String userName, ProgressBar progressbar) { model.visitEmployeeModel(url,userName,progressbar); } public void passListVisitEmployeePresenter(List<VisitEmployee> list) { view.passListVisitEmployeeView(list); } } <file_sep>package com.example.kamal.saatzanhamrah.TimeEmploy; import android.support.v4.app.FragmentActivity; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.Share; import com.example.kamal.saatzanhamrah.VisitLastDate.LastTime; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by kamal on 12/11/2017. */ public class TimeModel { FragmentActivity activity; TimePresenter presenter; List<LastTime> lastTimeList; public TimeModel(TimePresenter presenter, FragmentActivity activity) { this.presenter = presenter; this.activity = activity; } public void startTimeRegister(String timeEmployeeUrl, final String user, final String kind, final ProgressBar progressBar, final Button buttonStart, final TextView textLastStartDate, final TextView textLastStartTime) { Share.getStringResponse(activity, Request.Method.POST, timeEmployeeUrl, null, new Share.StringVolleyCallBack() { @Override public void onSuccessResponse(String result) { try { JSONObject jsonObject = new JSONObject(result); String success = jsonObject.getString("success"); if (success.equals("done")) { JSONArray jsonArray = jsonObject.getJSONArray("startTime"); lastTimeList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject1 = jsonArray.getJSONObject(i); String startDate = jsonObject1.getString("start_date"); String startTime = jsonObject1.getString("start_time"); textLastStartDate.setText(startDate); textLastStartTime.setText(startTime); Share.saveSharePref(activity, "startLastDate" + user, startDate); Share.saveSharePref(activity, "startLastTime" + user, startTime); } presenter.messageStart(success); progressBar.setVisibility(View.GONE); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onError(String error) { presenter.messageStart(error); progressBar.setVisibility(View.GONE); buttonStart.setEnabled(true); } @Override public Map onMapPost() { Map<String, String> timeParams = new HashMap<String, String>(); timeParams.put("user", user); timeParams.put("kind", kind); timeParams.put("key_text_android", "ktaa"); return timeParams; } }); } public void endTimeRegister(String timeEmployeeUrl, final String user, final String kind, final String text, final ProgressBar progressBar, final Button buttonEnd) { Share.getStringResponse(activity, Request.Method.POST, timeEmployeeUrl, null, new Share.StringVolleyCallBack() { @Override public void onSuccessResponse(String result) { try { JSONObject jsonObject = new JSONObject(result); String success = jsonObject.getString("success"); if (success.equals("done")) { JSONArray jsonArray = jsonObject.getJSONArray("endTime"); lastTimeList = new ArrayList<>(); LastTime lastTime; for (int i = 0; i < jsonArray.length(); i++) { lastTime = new LastTime(); JSONObject jsonObject1 = jsonArray.getJSONObject(i); String endLastDate = jsonObject1.getString("end_date"); String endLastTime = jsonObject1.getString("end_time"); String _workTime = jsonObject1.getString("work_time"); if (!_workTime.equals("null")) { int workTime = Integer.parseInt(_workTime); _workTime = Share.changeTime(workTime); } lastTime.setStartWorkDate(Share.loadPref(activity, "startLastDate" + user)); lastTime.setStartWorkTime(Share.loadPref(activity, "startLastTime" + user)); lastTime.setEndWorkDate(endLastDate); lastTime.setEndWorkTime(endLastTime); lastTime.setWorkTime(_workTime); lastTimeList.add(lastTime); } presenter.messageEnd(success); presenter.passListPresenter(lastTimeList); progressBar.setVisibility(View.GONE); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onError(String error) { presenter.messageEnd(error); progressBar.setVisibility(View.INVISIBLE); buttonEnd.setEnabled(true); } @Override public Map onMapPost() { Map<String, String> timeParams = new HashMap<String, String>(); timeParams.put("user", user); timeParams.put("kind", kind); timeParams.put("explains", text); timeParams.put("key_text_android", "ktaa"); return timeParams; } }); } public void handDate(String addEmployeeUrl, final Map<String, String> params1, final ProgressBar progressbar, final Button buttonRegisterHandDate) { try { if (Integer.parseInt(params1.get("dateEnd").replace("/", "")) > Integer.parseInt(params1.get("dateStart").replace("/", ""))) { Share.getStringResponse(activity, Request.Method.POST, addEmployeeUrl, null, new Share.StringVolleyCallBack() { @Override public void onSuccessResponse(String result) { try { JSONObject jsonObject = new JSONObject(result); String success = jsonObject.getString("success"); String workTime = jsonObject.getString("workTime"); presenter.resultHandDate(success, workTime); progressbar.setVisibility(View.GONE); buttonRegisterHandDate.setEnabled(true); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onError(String error) { Toast.makeText(activity, activity.getResources().getString(R.string.registerError), Toast.LENGTH_LONG).show(); progressbar.setVisibility(View.GONE); buttonRegisterHandDate.setEnabled(true); } @Override public Map onMapPost() { Map<String, String> Params = new HashMap<>(); Params.put("user", params1.get("user")); Params.put("kind", params1.get("kind")); Params.put("token", params1.get("dateStart").replace("/", "")); Params.put("token_delete", params1.get("user") + params1.get("dateStart").replace("/", "") + params1.get("timeStart").replace(":", "")); Params.put("date_start", params1.get("dateStart")); Params.put("time_start", params1.get("timeStart")); Params.put("date_end", params1.get("dateEnd")); Params.put("time_end", params1.get("timeEnd")); Params.put("start_date_miladi", params1.get("miladiStart")); Params.put("end_date_miladi", params1.get("miladiEnd")); Params.put("explains", params1.get("explains")); Params.put("key_text_android", "ktaa"); return Params; } }); } else if (Integer.parseInt(params1.get("dateEnd").replace("/", "")) == Integer.parseInt(params1.get("dateStart").replace("/", ""))) { if (Integer.parseInt(params1.get("timeEnd").replace(":", "")) >= Integer.parseInt(params1.get("timeStart").replace(":", ""))) { Share.getStringResponse(activity, Request.Method.POST, addEmployeeUrl, null, new Share.StringVolleyCallBack() { @Override public void onSuccessResponse(String result) { try { JSONObject jsonObject = new JSONObject(result); String success = jsonObject.getString("success"); String workTime = jsonObject.getString("workTime"); presenter.resultHandDate(success, workTime); progressbar.setVisibility(View.GONE); buttonRegisterHandDate.setEnabled(true); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onError(String error) { Toast.makeText(activity, activity.getResources().getString(R.string.registerError), Toast.LENGTH_LONG).show(); progressbar.setVisibility(View.GONE); buttonRegisterHandDate.setEnabled(true); } @Override public Map onMapPost() { Map<String, String> Params = new HashMap<>(); Params.put("user", params1.get("user")); Params.put("kind", params1.get("kind")); Params.put("token", params1.get("dateStart").replace("/", "")); Params.put("token_delete", params1.get("user") + params1.get("dateStart").replace("/", "") + params1.get("timeStart").replace(":", "")); Params.put("date_start", params1.get("dateStart")); Params.put("time_start", params1.get("timeStart")); Params.put("date_end", params1.get("dateEnd")); Params.put("time_end", params1.get("timeEnd")); Params.put("start_date_miladi", params1.get("miladiStart")); Params.put("end_date_miladi", params1.get("miladiEnd")); Params.put("explains", params1.get("explains")); Params.put("key_text_android", "ktaa"); return Params; } }); } else { Toast.makeText(activity, R.string.endLargerStart, Toast.LENGTH_LONG).show(); progressbar.setVisibility(View.GONE); buttonRegisterHandDate.setEnabled(true); return; } } else { Toast.makeText(activity, R.string.endLargerStart, Toast.LENGTH_LONG).show(); progressbar.setVisibility(View.GONE); buttonRegisterHandDate.setEnabled(true); return; } } catch (Exception e) { Toast.makeText(activity, R.string.fill_field, Toast.LENGTH_LONG).show(); progressbar.setVisibility(View.GONE); buttonRegisterHandDate.setEnabled(true); } } public void explain_problem(String problemUrl) { Share.getStringResponse(activity, Request.Method.POST, problemUrl, null, new Share.StringVolleyCallBack() { @Override public void onSuccessResponse(String result) { presenter.resultProblem(result); } @Override public void onError(String error) { } @Override public Map onMapPost() { return null; } }); } } <file_sep>package com.example.kamal.saatzanhamrah.VacationHour; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.kamal.saatzanhamrah.MainPackage.MainActivity; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.Share; import com.example.kamal.saatzanhamrah.TimeEmploy.JalaliCalendar; import com.mohamadamin.persianmaterialdatetimepicker.date.DatePickerDialog; import com.mohamadamin.persianmaterialdatetimepicker.utils.PersianCalendar; import java.util.HashMap; import java.util.Map; import static com.example.kamal.saatzanhamrah.Share.loadPref; public class VacationFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener, MainActivity.EnableData { private EditText editTextHandDateStart, editTextHandDateEnd, explains; private Spinner spinnerHandTimeHourStart, spinnerHandTimeMinuteStart, spinnerHandTimeHourEnd, spinnerHandTimeMinuteEnd; private ImageButton imageButtonHandDateStart, imageButtonHandDateEnd; private int yearStart, monthStart, yearEnd, monthEnd, dayStart, dayEnd; private Button buttonRegisterHandDate; private String user, kind; private String mDay, mMonth, hourStart, minuteStart, hourEnd, minuteEnd, _miladiStart, _miladiEnd; private VacationPresenter presenter; private String handDateUrl = "http://kamalroid.ir/hour_vacation.php"; private String overTimeUrl = "http://kamalroid.ir/over_time.php"; private Map<String, String> params; private TabLayout tabLayout; private TextView textTitle; private CoordinatorLayout coordinatorLayout; private ProgressBar progressbar; private boolean mIsPremium; private HandVerifyVacationFragment handVerifyVacationFragment; private Info_vacation_hour info_vacation_hour; private String flag, url; private Activity activity; private String flagTime; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); presenter = new VacationPresenter(this); activity = getActivity(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_vacation_hour, container, false); buttonRegisterHandDate = (Button) view.findViewById(R.id.button_time_registerHandDateVacation); imageButtonHandDateStart = (ImageButton) view.findViewById(R.id.imageButton_time_setDateStartVacation); imageButtonHandDateEnd = (ImageButton) view.findViewById(R.id.imageButton_time_setDateEndVacation); editTextHandDateStart = (EditText) view.findViewById(R.id.editText_time_setDateStartVacation); editTextHandDateEnd = (EditText) view.findViewById(R.id.editText_time_setDateEndVacation); explains = (EditText) view.findViewById(R.id.editText_time_explain); spinnerHandTimeHourStart = (Spinner) view.findViewById(R.id.spinner_time_handTimeHourStartVacation); spinnerHandTimeMinuteStart = (Spinner) view.findViewById(R.id.spinner_time_handTimeMinuteStartVacation); spinnerHandTimeHourEnd = (Spinner) view.findViewById(R.id.spinner_time_handTimeHourEndVacation); spinnerHandTimeMinuteEnd = (Spinner) view.findViewById(R.id.spinner_time_handTimeMinuteEndVacation); new Handler().post(new Runnable() { @Override public void run() { flag="ساعت شروع"; Share.custumSpinnerAdapter(activity, spinnerHandTimeHourStart, R.array.arrayStartHour, flag); flag="دقیقه شروع"; Share.custumSpinnerAdapter(activity, spinnerHandTimeMinuteStart, R.array.arrayStartMinute, flag); flag="ساعت پایان"; Share.custumSpinnerAdapter(activity, spinnerHandTimeHourEnd, R.array.arrayStartHour, flag); flag="دقیقه پایان"; Share.custumSpinnerAdapter(activity, spinnerHandTimeMinuteEnd, R.array.arrayStartMinute, flag); } }); coordinatorLayout = (CoordinatorLayout) view.findViewById(R.id.coordinate_time_handLayout); progressbar = (ProgressBar) view.findViewById(R.id.progressBar_time_loading); textTitle = (TextView) getActivity().findViewById(R.id.textView_toolbar_title); textTitle.setText(getString(R.string.vacationHour)); imageButtonHandDateStart.setOnClickListener(this); imageButtonHandDateEnd.setOnClickListener(this); buttonRegisterHandDate.setOnClickListener(this); editTextHandDateStart.setOnClickListener(this); editTextHandDateEnd.setOnClickListener(this); spinnerHandTimeHourStart.setOnItemSelectedListener(this); spinnerHandTimeMinuteStart.setOnItemSelectedListener(this); spinnerHandTimeHourEnd.setOnItemSelectedListener(this); spinnerHandTimeMinuteEnd.setOnItemSelectedListener(this); return view; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button_time_registerHandDateVacation: if (Share.check(getContext())) { if (loadPref(getActivity(), "count").equals("1") || loadPref(getActivity(), "count").equals("2")) { buttonRegisterHandDate.setEnabled(false); progressbar.setVisibility(View.VISIBLE); JalaliCalendar.gDate shamsiStart = new JalaliCalendar.gDate(yearStart, monthStart - 1, dayStart); JalaliCalendar.gDate miladiStart = JalaliCalendar.jalaliToMiladi(shamsiStart); _miladiStart = miladiStart.getYear() + "/" + (miladiStart.getMonth() + 1) + "/" + miladiStart.getDay(); JalaliCalendar.gDate shamsiEnd = new JalaliCalendar.gDate(yearEnd, monthEnd - 1, dayEnd); JalaliCalendar.gDate miladiEnd = JalaliCalendar.jalaliToMiladi(shamsiEnd); _miladiEnd = miladiEnd.getYear() + "/" + (miladiEnd.getMonth() + 1) + "/" + miladiEnd.getDay(); createParams(); if (hourStart.equals("ساعت شروع") || hourEnd.equals("ساعت پایان") || minuteStart.equals("دقیقه شروع") || minuteEnd.equals("دقیقه پایان")) { Toast.makeText(getContext(), R.string.fill_field, Toast.LENGTH_LONG).show(); buttonRegisterHandDate.setEnabled(true); progressbar.setVisibility(View.GONE); } else { presenter.presenterHandDate(handDateUrl, params, progressbar, buttonRegisterHandDate); } break; } else { Share.showSnackBar(getContext(), coordinatorLayout, getResources().getString(R.string.enableMessage)); break; } } else { Toast.makeText(getActivity(), getResources().getString(R.string.noInternet), Toast.LENGTH_SHORT).show(); break; } case R.id.editText_time_setDateStartVacation: calenderStart(editTextHandDateStart); break; case R.id.editText_time_setDateEndVacation: calenderEnd(editTextHandDateEnd); break; case R.id.imageButton_time_setDateStartVacation: calenderStart(editTextHandDateStart); break; case R.id.imageButton_time_setDateEndVacation: calenderStart(editTextHandDateStart); break; } } public void calenderStart(final EditText setDate) { PersianCalendar now = new PersianCalendar(); DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) { monthOfYear += 1; if (dayOfMonth < 10) { mDay = "0" + dayOfMonth; } else { mDay = dayOfMonth + ""; } if (monthOfYear < 10) { mMonth = "0" + monthOfYear; } else { mMonth = monthOfYear + ""; } yearStart = year; monthStart = monthOfYear; dayStart = dayOfMonth; setDate.setText(year + "/" + mMonth + "/" + mDay); } }, now.getPersianYear(), now.getPersianMonth(), now.getPersianDay()); datePickerDialog.setThemeDark(true); datePickerDialog.show(getActivity().getFragmentManager(), "tpd"); } public void calenderEnd(final EditText setDate) { PersianCalendar now = new PersianCalendar(); DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) { monthOfYear += 1; if (dayOfMonth < 10) { mDay = "0" + dayOfMonth; } else { mDay = dayOfMonth + ""; } if (monthOfYear < 10) { mMonth = "0" + monthOfYear; } else { mMonth = monthOfYear + ""; } yearEnd = year; monthEnd = monthOfYear; dayEnd = dayOfMonth; setDate.setText(year + "/" + mMonth + "/" + mDay); } }, now.getPersianYear(), now.getPersianMonth(), now.getPersianDay()); datePickerDialog.setThemeDark(true); datePickerDialog.show(getActivity().getFragmentManager(), "tpd"); } private void createParams() { params = new HashMap<>(); params.put("user", user); params.put("kind", kind); params.put("dateStart", editTextHandDateStart.getText().toString()); params.put("dateEnd", editTextHandDateEnd.getText().toString()); params.put("timeStart", hourStart + ":" + minuteStart); params.put("timeEnd", hourEnd + ":" + minuteEnd); params.put("miladiStart", _miladiStart); params.put("miladiEnd", _miladiEnd); params.put("explains", explains.getText().toString()); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { switch (parent.getId()) { case R.id.spinner_time_handTimeHourStartVacation: hourStart = parent.getItemAtPosition(position).toString(); Log.i("hourS",hourStart); break; case R.id.spinner_time_handTimeMinuteStartVacation: minuteStart = parent.getItemAtPosition(position).toString(); Log.i("minuteS",minuteStart); break; case R.id.spinner_time_handTimeHourEndVacation: hourEnd = parent.getItemAtPosition(position).toString(); Log.i("hourE",hourEnd); break; case R.id.spinner_time_handTimeMinuteEndVacation: minuteEnd = parent.getItemAtPosition(position).toString(); Log.i("minuteE",minuteEnd); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } public void resultHandDate(String result, String workTime) { switch (result) { case "done": handVerifyVacationFragment = new HandVerifyVacationFragment(); info_vacation_hour = (Info_vacation_hour) handVerifyVacationFragment; info_vacation_hour.sendInfoHand(params, workTime); getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout_main_containerFragment, handVerifyVacationFragment).commit(); buttonRegisterHandDate.setEnabled(true); if (loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "2"); } else if (loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "3"); } if (Share.loadPref(getActivity(), "mIsPremium").equals("true")) Share.saveSharePref(getActivity(), "count", "1"); break; case "failer_interesting_database": Share.showSnackBar(getContext(), coordinatorLayout, getString(R.string.registerNull)); if (loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "1"); } else if (loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "2"); } buttonRegisterHandDate.setEnabled(true); break; case "failure_post": Share.showSnackBar(getContext(), coordinatorLayout, getString(R.string.registerError)); if (loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "1"); } else if (loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "2"); } buttonRegisterHandDate.setEnabled(true); break; case "this time there is": Share.showSnackBar(getContext(), coordinatorLayout, getString(R.string.vactionHourThereIs)); if (loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "1"); } else if (loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "2"); } buttonRegisterHandDate.setEnabled(true); break; default: Share.showSnackBar(getContext(), coordinatorLayout, getString(R.string.error)); if (loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "1"); } else if (loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "2"); } buttonRegisterHandDate.setEnabled(true); break; } } @Override public void sendEnable(boolean mIsPremium, String user, String kind) { this.mIsPremium = mIsPremium; this.user = user; this.kind = kind; } public interface Info_vacation_hour { public void sendInfoHand(Map<String, String> params, String workTime); } } <file_sep>package com.example.kamal.saatzanhamrah.TimeEmploy; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.kamal.saatzanhamrah.MainPackage.MainActivity; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.Share; import com.example.kamal.saatzanhamrah.VerifyFragment; import com.mohamadamin.persianmaterialdatetimepicker.date.DatePickerDialog; import com.mohamadamin.persianmaterialdatetimepicker.utils.PersianCalendar; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import static com.example.kamal.saatzanhamrah.Share.loadPref; public class HandDateFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener, MainActivity.EnableData { private EditText editTextHandDateStart, editTextHandDateEnd, explains; private Spinner spinnerHandTimeHourStart, spinnerHandTimeMinuteStart, spinnerHandTimeHourEnd, spinnerHandTimeMinuteEnd; private ImageButton imageButtonHandDateStart, imageButtonHandDateEnd; private int yearStart, monthStart, yearEnd, monthEnd, dayStart, dayEnd; private Button buttonRegisterHandDate; private String user, kind; private String mDay, mMonth, hourStart, minuteStart, hourEnd, minuteEnd, _miladiStart, _miladiEnd; private TimePresenter presenter; private String handDateUrl = "http://kamalroid.ir/hand_date_20190501.php"; private Map<String, String> params; private TabLayout tabLayout; private TextView textTitle; private CoordinatorLayout coordinatorLayout; private ProgressBar progressbar; private boolean mIsPremium; private VerifyFragment verifyFragment; private Info_hand_date info_hand_date; private Activity activity; private String flag; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); presenter = new TimePresenter(this); activity=getActivity(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_hand_date, container, false); buttonRegisterHandDate = (Button) view.findViewById(R.id.button_time_registerHandDate); imageButtonHandDateStart = (ImageButton) view.findViewById(R.id.imageButton_time_setDateStart); imageButtonHandDateEnd = (ImageButton) view.findViewById(R.id.imageButton_time_setDateEnd); editTextHandDateStart = (EditText) view.findViewById(R.id.editText_time_setDateStart); editTextHandDateEnd = (EditText) view.findViewById(R.id.editText_time_setDateEnd); explains = (EditText) view.findViewById(R.id.editText_time_explain); spinnerHandTimeHourStart = (Spinner) view.findViewById(R.id.spinner_time_handTimeHourStart); spinnerHandTimeMinuteStart = (Spinner) view.findViewById(R.id.spinner_time_handTimeMinuteStart); spinnerHandTimeHourEnd = (Spinner) view.findViewById(R.id.spinner_time_handTimeHourEnd); spinnerHandTimeMinuteEnd = (Spinner) view.findViewById(R.id.spinner_time_handTimeMinuteEnd); new Handler().post(new Runnable() { @Override public void run() { flag="ساعت شروع کار"; Share.custumSpinnerAdapter(activity, spinnerHandTimeHourStart, R.array.arrayStartHour, flag); flag="دقیقه شروع کار"; Share.custumSpinnerAdapter(activity, spinnerHandTimeMinuteStart, R.array.arrayStartMinute, flag); flag="ساعت پایان کار"; Share.custumSpinnerAdapter(activity, spinnerHandTimeHourEnd, R.array.arrayStartHour, flag); flag="دقیقه پایان کار"; Share.custumSpinnerAdapter(activity, spinnerHandTimeMinuteEnd, R.array.arrayStartMinute, flag); } }); coordinatorLayout = (CoordinatorLayout) view.findViewById(R.id.coordinate_time_handLayout); progressbar = (ProgressBar) view.findViewById(R.id.progressBar_time_loading); textTitle = (TextView) getActivity().findViewById(R.id.textView_toolbar_title); textTitle.setText(getString(R.string.handDate)); imageButtonHandDateStart.setOnClickListener(this); imageButtonHandDateEnd.setOnClickListener(this); buttonRegisterHandDate.setOnClickListener(this); editTextHandDateStart.setOnClickListener(this); editTextHandDateEnd.setOnClickListener(this); spinnerHandTimeHourStart.setOnItemSelectedListener(this); spinnerHandTimeMinuteStart.setOnItemSelectedListener(this); spinnerHandTimeHourEnd.setOnItemSelectedListener(this); spinnerHandTimeMinuteEnd.setOnItemSelectedListener(this); return view; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button_time_registerHandDate: if (Share.check(getContext())) { if (loadPref(getActivity(), "count").equals("1") || loadPref(getActivity(), "count").equals("2")) { buttonRegisterHandDate.setEnabled(false); progressbar.setVisibility(View.VISIBLE); JalaliCalendar.gDate shamsiStart = new JalaliCalendar.gDate(yearStart, monthStart - 1, dayStart); JalaliCalendar.gDate miladiStart = JalaliCalendar.jalaliToMiladi(shamsiStart); _miladiStart = miladiStart.getYear() + "/" + (miladiStart.getMonth() + 1) + "/" + miladiStart.getDay(); JalaliCalendar.gDate shamsiEnd = new JalaliCalendar.gDate(yearEnd, monthEnd - 1, dayEnd); JalaliCalendar.gDate miladiEnd = JalaliCalendar.jalaliToMiladi(shamsiEnd); _miladiEnd = miladiEnd.getYear() + "/" + (miladiEnd.getMonth() + 1) + "/" + miladiEnd.getDay(); createParams(); if(hourStart.equals("ساعت شروع کار")|| hourEnd.equals("ساعت پایان کار") || minuteStart.equals("دقیقه شروع کار")|| minuteEnd.equals("دقیقه پایان کار")){ Toast.makeText(getContext(), R.string.fill_field, Toast.LENGTH_LONG).show(); buttonRegisterHandDate.setEnabled(true); progressbar.setVisibility(View.GONE); }else { presenter.presenterHandDate(handDateUrl, params, progressbar, buttonRegisterHandDate); } break; } else { Share.showSnackBar(getContext(), coordinatorLayout, getResources().getString(R.string.enableMessage)); break; } } else { Toast.makeText(getActivity(), getResources().getString(R.string.noInternet), Toast.LENGTH_SHORT).show(); break; } case R.id.editText_time_setDateStart: calenderStart(editTextHandDateStart); break; case R.id.editText_time_setDateEnd: calenderEnd(editTextHandDateEnd); break; case R.id.imageButton_time_setDateStart: calenderStart(editTextHandDateStart); break; case R.id.imageButton_time_setDateEnd: calenderStart(editTextHandDateStart); break; } } public void calenderStart(final EditText setDate) { PersianCalendar now = new PersianCalendar(); DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) { monthOfYear += 1; if (dayOfMonth < 10) { mDay = "0" + dayOfMonth; } else { mDay = dayOfMonth + ""; } if (monthOfYear < 10) { mMonth = "0" + monthOfYear; } else { mMonth = monthOfYear + ""; } yearStart = year; monthStart = monthOfYear; dayStart = dayOfMonth; setDate.setText(year + "/" + mMonth + "/" + mDay); } }, now.getPersianYear(), now.getPersianMonth(), now.getPersianDay()); datePickerDialog.setThemeDark(true); datePickerDialog.show(getActivity().getFragmentManager(), "tpd"); } public void calenderEnd(final EditText setDate) { PersianCalendar now = new PersianCalendar(); DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) { monthOfYear += 1; if (dayOfMonth < 10) { mDay = "0" + dayOfMonth; } else { mDay = dayOfMonth + ""; } if (monthOfYear < 10) { mMonth = "0" + monthOfYear; } else { mMonth = monthOfYear + ""; } yearEnd = year; monthEnd = monthOfYear; dayEnd = dayOfMonth; setDate.setText(year + "/" + mMonth + "/" + mDay); } }, now.getPersianYear(), now.getPersianMonth(), now.getPersianDay()); datePickerDialog.setThemeDark(true); datePickerDialog.show(getActivity().getFragmentManager(), "tpd"); } private void createParams() { params = new HashMap<>(); params.put("user", user); params.put("kind", kind); params.put("dateStart", editTextHandDateStart.getText().toString()); params.put("dateEnd", editTextHandDateEnd.getText().toString()); params.put("timeStart", hourStart + ":" + minuteStart); params.put("timeEnd", hourEnd + ":" + minuteEnd); params.put("miladiStart", _miladiStart); params.put("miladiEnd", _miladiEnd); params.put("explains", explains.getText().toString()); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { switch (parent.getId()) { case R.id.spinner_time_handTimeHourStart: hourStart = parent.getItemAtPosition(position).toString(); break; case R.id.spinner_time_handTimeMinuteStart: minuteStart = parent.getItemAtPosition(position).toString(); break; case R.id.spinner_time_handTimeHourEnd: hourEnd = parent.getItemAtPosition(position).toString(); break; case R.id.spinner_time_handTimeMinuteEnd: minuteEnd = parent.getItemAtPosition(position).toString(); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } public void resultHandDate(String result, String workTime) { switch (result) { case "done": verifyFragment = new VerifyFragment(); info_hand_date= (Info_hand_date) verifyFragment; info_hand_date.sendInfoHand(params,workTime); getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout_main_containerFragment, verifyFragment).commit(); buttonRegisterHandDate.setEnabled(true); if (loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "2"); } else if (loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "3"); } if(Share.loadPref(getActivity(),"mIsPremium").equals("true")) Share.saveSharePref(getActivity(), "count", "1"); break; case "failer_interesting_database": Share.showSnackBar(getContext(), coordinatorLayout, getString(R.string.registerNull)); if (loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "1"); } else if (loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "2"); } buttonRegisterHandDate.setEnabled(true); break; case "failure_post": Share.showSnackBar(getContext(), coordinatorLayout, getString(R.string.registerError)); if (loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "1"); } else if (loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "2"); } buttonRegisterHandDate.setEnabled(true); break; case "this time there is": Share.showSnackBar(getContext(), coordinatorLayout, getString(R.string.timeThereIs)); if (loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "1"); } else if (loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "2"); } buttonRegisterHandDate.setEnabled(true); break; default: Share.showSnackBar(getContext(), coordinatorLayout, getString(R.string.error)); if (loadPref(getActivity(), "count").equals("1")) { Share.saveSharePref(getActivity(), "count", "1"); } else if (loadPref(getActivity(), "count").equals("2")) { Share.saveSharePref(getActivity(), "count", "2"); } buttonRegisterHandDate.setEnabled(true); break; } } @Override public void sendEnable(boolean mIsPremium,String user, String kind) { this.mIsPremium = mIsPremium; this.user = user; this.kind = kind; } public interface Info_hand_date{ public void sendInfoHand(Map<String, String> params,String workTime); } } <file_sep>package com.example.kamal.saatzanhamrah.VacationDate; import android.support.v4.app.FragmentActivity; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Toast; import com.android.volley.Request; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.Share; import com.example.kamal.saatzanhamrah.VisitLastDate.LastTime; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by kamal on 12/11/2017. */ public class VacationDateModel { FragmentActivity activity; VacationDatePresenter presenter; List<LastTime> lastTimeList; public VacationDateModel(VacationDatePresenter presenter, FragmentActivity activity) { this.presenter = presenter; this.activity = activity; } public void hourVacation(String addEmployeeUrl, final Map<String, String> params1, final ProgressBar progressbar, final Button buttonRegisterHandDate) { try { Share.getStringResponse(activity, Request.Method.POST, addEmployeeUrl, null, new Share.StringVolleyCallBack() { @Override public void onSuccessResponse(String result) { try { JSONObject jsonObject = new JSONObject(result); String success = jsonObject.getString("success"); presenter.resultHandDate(success); progressbar.setVisibility(View.GONE); buttonRegisterHandDate.setEnabled(true); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onError(String error) { Toast.makeText(activity, activity.getResources().getString(R.string.registerError), Toast.LENGTH_LONG).show(); progressbar.setVisibility(View.GONE); buttonRegisterHandDate.setEnabled(true); } @Override public Map onMapPost() { Map<String, String> Params = new HashMap<>(); Params.put("user", params1.get("user")); Params.put("kind", params1.get("kind")); Params.put("token", params1.get("dateStart").replace("/", "")); Params.put("date_start", params1.get("dateStart")); Params.put("start_date_miladi", params1.get("miladiStart")); Params.put("explains", params1.get("explains")); Params.put("key_text_android", "ktaa"); return Params; } }); } catch (Exception e) { Toast.makeText(activity, R.string.fill_field, Toast.LENGTH_LONG).show(); progressbar.setVisibility(View.GONE); buttonRegisterHandDate.setEnabled(true); } } } <file_sep>package com.example.kamal.saatzanhamrah.ForgotPackage; /** * Created by kamal on 1/21/2018. */ public class ForgotPresenter { ForgotView view; ForgotModel model; public ForgotPresenter(ForgotModel model, ForgotView view) { this.view=view; this.model=model; } public void onCreate() { view.setPresenter(this); model.setPresenter(this); } public void sendEmailPresenter(String url, String email) { model.sendEmailPrsenter(url,email); } public void resultEmailPresenter(String result) { view.resultEmailView(result); } } <file_sep>package com.example.kamal.saatzanhamrah.VisitEmployeeToEmployer; import android.app.Activity; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; import com.example.kamal.saatzanhamrah.MainPackage.MainActivity; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.Share; import java.util.List; public class VisitEmployeeToEmployerFragment extends Fragment implements MainActivity.PassData{ VisitEmployeePresenter presenter; Activity activity; private VisitEmployeeAdapter adapter; private RecyclerView recyclerView; private String url="http://kamalroid.ir/get_employee_to_employer1.php"; private String user; private ProgressBar progressbar; private String userUpdate; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); presenter=new VisitEmployeePresenter(this); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.fragment_visit_employee_to_employer,container,false); recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView_vistEmployee_listEmployee); progressbar= (ProgressBar) view.findViewById(R.id.progressBar_visitEmployeeToEmployer_loading); if(Share.check(getContext())) { progressbar.setVisibility(View.VISIBLE); presenter.visitEmployeeToEmployer(url, user,progressbar); } else{ Toast.makeText(getActivity(), getResources().getString(R.string.noInternet), Toast.LENGTH_SHORT).show(); } return view; } public void passListVisitEmployeeView(List<VisitEmployee> list) { adapter = new VisitEmployeeAdapter(getActivity(), list); recyclerView.setLayoutManager(new LinearLayoutManager(activity)); recyclerView.setAdapter(adapter); } @Override public void sendData(String user, String kind,String userUpdate) { this.user=user; this.userUpdate=userUpdate; } } <file_sep>package com.example.kamal.saatzanhamrah.LoginEmploy; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.android.volley.RequestQueue; import com.example.kamal.saatzanhamrah.MySingleton; import com.example.kamal.saatzanhamrah.Share; public class LoginActivity extends AppCompatActivity { LoginView view; LoginPresenter presenter; LoginModel model; RequestQueue myrequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); view=new LoginView(this); setContentView(view); model=new LoginModel(this); presenter=new LoginPresenter(model,view); presenter.onCreate(); } @Override protected void onStop() { super.onStop(); if ( MySingleton.getInstance(this).getRequestQueue()!= null) { MySingleton.getInstance(this).getRequestQueue().cancelAll(Share.TAG); } } } <file_sep>package com.example.kamal.saatzanhamrah.VisitLastDateEmployerToEmployee; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.FragmentActivity; import android.widget.ProgressBar; import android.widget.TextView; import java.util.List; /** * Created by kamal on 12/18/2017. */ public class VisitLastDateEmployerToEmployeePresenter { VisitLastDateEmployerToEmployeeFragment view; VisitLastDateEmployerToEmployeeModel model; public VisitLastDateEmployerToEmployeePresenter(VisitLastDateEmployerToEmployeeFragment view) { this.view=view; model=new VisitLastDateEmployerToEmployeeModel(this,view.getActivity()); } public void getLastDatePresenter(String url, String start, String end, String user, String kind, int row_start, ProgressBar progressbar, FloatingActionButton floatingActionButton, String userUpdate) { model.getLastDateModel(url,start,end,user,kind,row_start,progressbar,floatingActionButton); } public void passListPresenter(List<LastTimeConfirm> lastTimeList) { view.passListView(lastTimeList); } public void passListPresenterMore(List<LastTimeConfirm> lastTimeList) { view.passListViewMore(lastTimeList); } public void dataCheckPresenter(String url, VisitLastDateEmployerToEmployeeAdapter adapter, String startDateDelete, String startTimeDelete, FragmentActivity visitLastDateFragment, String user, String kind, ProgressBar progressbar, int check) { model.dataCheckModel(url,adapter,startDateDelete,startTimeDelete,visitLastDateFragment,progressbar,check); } public void MessageConfirmPresenter(String result) { view.messageConfirm(result); } public void getLastDatePresenterMore(String url, String start, String end, String user, String kind, int start_row, ProgressBar progressbar, FloatingActionButton floatingActionButton) { model.getLastDateModelMore(url,start,end,start_row,progressbar,floatingActionButton); } public void buildPdfPresenter(String url, String start, String end, String user, String kind, ProgressBar progressbar, TextView textSum, String userUpdate) { model.buildPdf(url,start,end,user,kind,progressbar,textSum,userUpdate); } public void sumPresenter(String url, String start, String end, String user, String kind, ProgressBar progressbar) { model.sumModel(url,start,end,user,kind,progressbar); } public void buildExcelPresenter(String url, String start, String end, String user, String kind, ProgressBar progressbar, CoordinatorLayout coordinatorLayout, TextView textSum, String userUpdate) { model.buildExcel(url,start,end,user,kind,progressbar,coordinatorLayout,textSum,userUpdate); } public void resulSumPresenter(String result) { view.resultSumView(result); } } <file_sep>package com.example.kamal.saatzanhamrah.MainPackage; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import co.ronash.pushe.Pushe; import com.android.volley.Request; import com.example.kamal.saatzanhamrah.AboutUsFragment; import com.example.kamal.saatzanhamrah.AddEmployeeToEmployer.AddEmployeeToEmployerFragment; import com.example.kamal.saatzanhamrah.LoginEmploy.LoginActivity; import com.example.kamal.saatzanhamrah.MySingleton; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.Share; import com.example.kamal.saatzanhamrah.TimeEmploy.AutoDateFragment; import com.example.kamal.saatzanhamrah.TimeEmploy.HandDateFragment; import com.example.kamal.saatzanhamrah.VacationDate.VacationDateFragment; import com.example.kamal.saatzanhamrah.VacationHour.VacationFragment; import com.example.kamal.saatzanhamrah.VisitEmployeeToEmployer.VisitEmployee; import com.example.kamal.saatzanhamrah.VisitEmployeeToEmployer.VisitEmployeeToEmployerFragment; import com.example.kamal.saatzanhamrah.VisitEmployerToEmployee.VisitEmployerToEmployeeFragment; import com.example.kamal.saatzanhamrah.VisitLastDate.VisitLastDateFragment; import com.example.kamal.saatzanhamrah.VisitLastVacation.VisitLastVacationFragment; import com.example.kamal.saatzanhamrah.util.IabHelper; import com.example.kamal.saatzanhamrah.util.IabResult; import com.example.kamal.saatzanhamrah.util.Inventory; import com.example.kamal.saatzanhamrah.util.Purchase; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity implements View.OnClickListener, NavigationView.OnNavigationItemSelectedListener { private PassData passData; private EnableData enableData; private Fragment autoDateFragment; private EditText explain; private String user, kind; private Toolbar toolbar; private ImageButton imageButton; private ListView listView; private DrawerLayout drawerLayout; private NavigationView navigationView; private ActionBarDrawerToggle actionBarDrawerToggle; private Fragment fragment; private Runnable runnable; private TextView userName, kindText; private PopupWindow myPopUp; private RelativeLayout relativeLayout; private EditText user_update, email_update; private String urlGetEmail = "http://kamalroid.ir/get_email.php"; private String urlGetUpdate = "http://kamalroid.ir/update_user_name.php"; private String urlConfirm = "http://kamalroid.ir/get_key.php"; private ProgressBar progressBar; private Button buttonSettings, buttonExitUpdate; private String userUpdate; private FrameLayout frameLayout; private MainPresenter presenter; private TextView title; private String flagVacationHour="vacation_hour"; static final String TAG = "tag"; // SKUs for our products: the premium upgrade (non-consumable) static final String SKU_PREMIUM = "2018saatzan"; // Does the user have the premium upgrade? boolean mIsPremium = true; boolean statusEnable = false; // (arbitrary) request code for the purchase flow static final int RC_REQUEST = 1372; // The helper object IabHelper mHelper; ProgressDialog pd; IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener; IabHelper.QueryInventoryFinishedListener mGotInventoryListener; @Override protected void onStop() { super.onStop(); if (MySingleton.getInstance(this).getRequestQueue() != null) { MySingleton.getInstance(this).getRequestQueue().cancelAll(Share.TAG); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Pushe.initialize(this, true); setContentView(R.layout.navigation_drawer); toolbar = (Toolbar) findViewById(R.id.toolbar); frameLayout = findViewById(R.id.frameLayout_main_containerFragment); title = findViewById(R.id.textView_toolbar_title); relativeLayout = findViewById(R.id.main_layout); userUpdate = Share.loadPref(MainActivity.this, "userKeyUpdate"); setSupportActionBar(toolbar); if (Share.loadPref(this, "count").equals("")) { Share.saveSharePref(this, "count", "1"); } if (Share.loadPref(this, "my_key").equals("")) { if (Share.check(this)) { presenter = new MainPresenter(); presenter.BuyPresenter(this, urlConfirm); } } else { confirm(Share.loadPref(this, "my_key")); } getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); Intent intent = getIntent(); user = intent.getStringExtra("user"); kind = intent.getStringExtra("kind"); if (Share.loadPref(this, "start" + user).equals(false)) { toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.yellow)); } else if (Share.loadPref(this, "end" + user).equals(false)) { toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.green_500)); } autoDateFragment = new AutoDateFragment(); passData = (PassData) autoDateFragment; passData.sendData(user, kind, userUpdate); getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout_main_containerFragment, autoDateFragment).commit(); fragment=autoDateFragment; setupNavigationDrawer(); } @Override public void onClick(View v) { mHelper.launchPurchaseFlow(this, SKU_PREMIUM, RC_REQUEST, mPurchaseFinishedListener, "payload-string"); } @Override public boolean onNavigationItemSelected(@NonNull final MenuItem menuItem) { fragment = null; int id = menuItem.getItemId(); switch (id) { case R.id.item_menuItems_enable: mHelper.launchPurchaseFlow(MainActivity.this, SKU_PREMIUM, RC_REQUEST, mPurchaseFinishedListener, "payload-string"); break; case R.id.item_menuItems_visitDateMyWork: fragment = new VisitLastDateFragment(); passData = (PassData) fragment; passData.sendData(user, kind, userUpdate); break; case R.id.item_menuItems_visit_vacation: fragment = new VisitLastVacationFragment(); passData = (PassData) fragment; passData.sendData(user, kind, userUpdate); break; case R.id.item_menuItems_addEmployeeToEmployer: fragment = new AddEmployeeToEmployerFragment(); passData = (PassData) fragment; passData.sendData(user, kind, userUpdate); break; case R.id.item_menuItems_visitWorkEmployee: fragment = new VisitEmployeeToEmployerFragment(); passData = (PassData) fragment; passData.sendData(user, kind, userUpdate); break; case R.id.item_menuItems_registerAutoTime: fragment = new AutoDateFragment(); passData = (PassData) fragment; passData.sendData(user, kind, userUpdate); break; case R.id.item_menuItems_settings: AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); LayoutInflater inflater = MainActivity.this.getLayoutInflater(); View custumView = inflater.inflate(R.layout.pop_up_settings, null); builder.setView(custumView); builder.setCancelable(false); AlertDialog alert = builder.create(); alert.show(); email_update = custumView.findViewById(R.id.editText_update_email); progressBar = custumView.findViewById(R.id.progressBar_settings); buttonSettings = custumView.findViewById(R.id.Button_settings); buttonExitUpdate = custumView.findViewById(R.id.button_exit_update); getInfo(user, email_update, progressBar, buttonSettings, alert); break; case R.id.item_menuItems_registerHandTime: if (Share.loadPref(MainActivity.this, "start" + user).equals("true")) { fragment = new HandDateFragment(); enableData = (EnableData) fragment; enableData.sendEnable(mIsPremium,user, kind); break; } else { Toast.makeText(MainActivity.this, getString(R.string.messageErrorHandDate), Toast.LENGTH_LONG).show(); break; } case R.id.item_menuItems_vacationHour: fragment = new VacationFragment(); enableData = (EnableData) fragment; enableData.sendEnable(mIsPremium,user,kind); break; case R.id.item_menuItems_vacationDate: fragment = new VacationDateFragment(); enableData = (EnableData) fragment; enableData.sendEnable(mIsPremium,user,kind); break; case R.id.item_menuItems_visitEmployer: fragment = new VisitEmployerToEmployeeFragment(); passData = (PassData) fragment; passData.sendData(user, kind, userUpdate); break; case R.id.item_menuItems_exit: Share.saveSharePref(MainActivity.this, "userKeyUpdate", ""); Share.saveSharePref(MainActivity.this, "userKey", ""); Share.saveSharePref(MainActivity.this, "passKey", ""); Share.saveSharePref(MainActivity.this, "kindKey", ""); Intent intent = new Intent(MainActivity.this, LoginActivity.class); startActivity(intent); finish(); break; case R.id.item_menuItems_aboutUs: fragment = new AboutUsFragment(); break; } drawerLayout.closeDrawer(Gravity.START); return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data); // Pass on the activity result to the helper for handling if (!mHelper.handleActivityResult(requestCode, resultCode, data)) { super.onActivityResult(requestCode, resultCode, data); } else { Log.d(TAG, "onActivityResult handled by IABUtil."); } } @Override public void onDestroy() { //از سرویس در زمان اتمام عمر activity قطع شوید super.onDestroy(); if (mHelper != null) mHelper.dispose(); mHelper = null; } private void setupNavigationDrawer() { navigationView = findViewById(R.id.navigation_view); drawerLayout = findViewById(R.id.navigation_layout); kindText = navigationView.getHeaderView(0).findViewById(R.id.kind); userName = navigationView.getHeaderView(0).findViewById(R.id.userName); if (kind.equals("employee")) kindText.setText("کارمند/کارگر"); else if (kind.equals("employer")) kindText.setText("کارفرما"); userName.setText(userUpdate); navigationView.setNavigationItemSelectedListener(this); actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer) { @Override public void onDrawerClosed(View drawerView) { if (fragment != null) { getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout_main_containerFragment, fragment).commit(); } super.onDrawerClosed(drawerView); invalidateOptionsMenu(); } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); invalidateOptionsMenu(); new Handler().postDelayed(new Runnable() { @Override public void run() { if (autoDateFragment != null) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(frameLayout.getWindowToken(), 0); } } }, 100); } @Override public void onDrawerStateChanged(int newState) { super.onDrawerStateChanged(newState); } }; drawerLayout.addDrawerListener(actionBarDrawerToggle); drawerLayout.post(new Runnable() { @Override public void run() { actionBarDrawerToggle.syncState(); } }); Menu menuNav = navigationView.getMenu(); if (Share.loadPref(MainActivity.this, "mIsPremium").equals("true")) { MenuItem item = menuNav.findItem(R.id.item_menuItems_enable); item.setVisible(false); } if (kind.equals("employee")) { MenuItem item = menuNav.findItem(R.id.item_menuItems_visitWorkEmployee); item.setVisible(false); } else if (kind.equals("employer")) { MenuItem item1 = menuNav.findItem(R.id.item_menuItems_addEmployeeToEmployer); item1.setVisible(false); MenuItem item2 = menuNav.findItem(R.id.item_menuItems_visitEmployer); item2.setVisible(false); } } public interface EnableData { public void sendEnable(boolean mIsPremium,String user, String kind); } public interface PassData { public void sendData(String user, String kind, String userUpdate); } public void getInfo(final String user_update, final EditText email_update, final ProgressBar progressBar, final Button buttonSettings, final AlertDialog alert) { progressBar.setVisibility(View.VISIBLE); Share.getStringResponse(this, Request.Method.POST, urlGetEmail, null, new Share.StringVolleyCallBack() { @Override public void onSuccessResponse(String result) { try { JSONObject jsonObject = new JSONObject(result); JSONArray jsonArray = jsonObject.getJSONArray("result1"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject1 = jsonArray.getJSONObject(i); String userNameInfo = jsonObject1.getString("username"); String emailInfo = jsonObject1.getString("email"); if (emailInfo.equals("null")) { email_update.setHint(""); } else { email_update.setText(emailInfo); } progressBar.setVisibility(View.GONE); } } catch (JSONException e) { List<VisitEmployee> list = new ArrayList<VisitEmployee>(); e.printStackTrace(); progressBar.setVisibility(View.GONE); } } @Override public void onError(String error) { Toast.makeText(MainActivity.this, getResources().getString(R.string.error), Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.GONE); } @Override public Map onMapPost() { Map<String, String> Params = new HashMap<>(); Params.put("user", user); Params.put("kind", kind); Params.put("key_text_android", "ktaa"); return Params; } }); buttonSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String user_update1 = Share.loadPref(MainActivity.this,"userKeyUpdate"); final String email_update1 = email_update.getText().toString().trim(); if (email_update1.equals("")) { Toast.makeText(MainActivity.this, "ایمیل را وارد کنید.", Toast.LENGTH_SHORT).show(); } else { Share.getStringResponse(MainActivity.this, Request.Method.POST, urlGetUpdate, null, new Share.StringVolleyCallBack() { @Override public void onSuccessResponse(String result) { if (result.equals("done")) { Toast.makeText(MainActivity.this, "ویرایش شد.", Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); } else if (result.equals("this user there is")) { Toast.makeText(MainActivity.this, getResources().getString(R.string.repeatUser), Toast.LENGTH_LONG).show(); } else if (result.equals("noDone")) { Toast.makeText(MainActivity.this, "تغییری ایجاد نشد.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, getResources().getString(R.string.error), Toast.LENGTH_LONG).show(); } alert.cancel(); } @Override public void onError(String error) { Toast.makeText(MainActivity.this, getResources().getString(R.string.error), Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.GONE); } @Override public Map onMapPost() { Map<String, String> Params = new HashMap<>(); Params.put("user", user); Params.put("kind", kind); Params.put("update_user", user_update1); Params.put("update_email", email_update1); Params.put("key_text_android", "ktaa"); return Params; } }); } } }); buttonExitUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alert.cancel(); } }); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(Gravity.START)) { drawerLayout.closeDrawer(Gravity.START); } else if(fragment!=autoDateFragment) { fragment = new AutoDateFragment(); passData = (PassData) fragment; passData.sendData(user, kind, userUpdate); getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout_main_containerFragment, fragment).commit(); navigationView.setCheckedItem(R.id.item_menuItems_registerAutoTime); fragment=autoDateFragment; }else{ super.onBackPressed(); } } public void confirm(String my_buy) { mHelper = new IabHelper(MainActivity.this, my_buy); try { mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Log.d(TAG, "Query inventory finished."); if (result.isFailure()) { Log.d(TAG, "Failed to query inventory: " + result); return; } else { Log.d(TAG, "Query inventory was successful."); mIsPremium = inventory.hasPurchase(SKU_PREMIUM); if (mIsPremium) { navigationView.getMenu().findItem(com.example.kamal.saatzanhamrah.R.id.item_menuItems_enable).setVisible(false); Share.saveSharePref(MainActivity.this, "count", "1"); Share.saveSharePref(MainActivity.this, "mIsPremium", "true"); enableData = (EnableData) autoDateFragment; enableData.sendEnable(mIsPremium,user,kind); } else { if (Share.loadPref(MainActivity.this, "count").equals("1")) { navigationView.getMenu().findItem(com.example.kamal.saatzanhamrah.R.id.item_menuItems_enable).setVisible(true); Share.saveSharePref(MainActivity.this, "count", "1"); Share.saveSharePref(MainActivity.this, "mIsPremium", "false"); enableData = (EnableData) autoDateFragment; enableData.sendEnable(mIsPremium,user,kind); } } Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM")); } Log.d(TAG, "Initial inventory query finished; enabling main UI."); } }; } catch (Exception e) { progressBar.setVisibility(View.VISIBLE); Toast.makeText(this, "خارج شدید.", Toast.LENGTH_SHORT).show(); } mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { public void onIabPurchaseFinished(IabResult result, Purchase purchase) { if (result.isFailure()) { Log.d(TAG, "Error purchasing: " + result); return; } else if (purchase.getSku().equals(SKU_PREMIUM)) { // give user access to premium content and update the UI Toast.makeText(MainActivity.this, "خرید موفق", Toast.LENGTH_LONG).show(); Share.saveSharePref(MainActivity.this, "mIsPremium", "true"); mIsPremium = true; enableData = (EnableData) autoDateFragment; enableData.sendEnable(mIsPremium,user,kind); navigationView.getMenu().findItem(com.example.kamal.saatzanhamrah.R.id.item_menuItems_enable).setVisible(false); Share.saveSharePref(MainActivity.this, "count", "1"); Share.saveSharePref(MainActivity.this, "mIsPremium", "true"); } } }; Log.d(TAG, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Log.d(TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. Log.d(TAG, "Problem setting up In-app Billing: " + result); } // Hooray, IAB is fully set up! mHelper.queryInventoryAsync(mGotInventoryListener); } }); } } <file_sep>package com.example.kamal.saatzanhamrah; import android.content.Context; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.kamal.saatzanhamrah.TimeEmploy.HandDateFragment; import java.util.Map; public class VerifyFragment extends Fragment implements HandDateFragment.Info_hand_date { private Map<String, String> params; private String sumTime ; private TextView verifyHandStart, verifyHandEnd, verifyHandSum; private String mHour,mMinute,mSecond; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_verify, container, false); verifyHandStart = view.findViewById(R.id.verify_startHand); verifyHandEnd = view.findViewById(R.id.verify_endHand); verifyHandSum = view.findViewById(R.id.verify_sumHand); verifyHandStart.setTextColor(Color.BLUE); verifyHandEnd.setTextColor(Color.RED); verifyHandStart.setText(params.get("timeStart")+" "+params.get("dateStart")); verifyHandEnd.setText(params.get("timeEnd")+" "+params.get("dateEnd")); verifyHandSum.setText(sumTime); return view; } @Override public void sendInfoHand(Map<String, String> params, String _workTime) { this.params = params; int workTime = Integer.parseInt(_workTime); sumTime = Share.changeTime(workTime); } } <file_sep>package com.example.kamal.saatzanhamrah.VisitEmployeeToEmployer; /** * Created by kamal on 12/24/2017. */ public class VisitEmployee { private String userNameEmployee; private String userNameEmployeeMain; public String getUserNameEmployee() { return userNameEmployee; } public void setUserNameEmployee(String userNameEmployee) { this.userNameEmployee = userNameEmployee; } public String getUserNameEmployeeMain() { return userNameEmployeeMain; } public void setUserNameEmployeeMain(String userNameEmployeeMain) { this.userNameEmployeeMain = userNameEmployeeMain; } } <file_sep>package com.example.kamal.saatzanhamrah.VisitLastDate; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.FragmentActivity; import android.widget.ProgressBar; import android.widget.TextView; import java.util.List; /** * Created by kamal on 12/18/2017. */ public class VisitLastDatePresenter{ VisitLastDateFragment view; VisitLastDateModel model; public VisitLastDatePresenter(VisitLastDateFragment view) { this.view=view; model=new VisitLastDateModel(this,view.getActivity()); } public void getLastDatePresenter(String url, String start, String end, String user, String kind, int row_start, ProgressBar progressbar, FloatingActionButton floatingActionButton) { model.getLastDateModel(url,start,end,user,kind,row_start,progressbar,floatingActionButton); } public void getLastDateAfterDeletePresenter(String url) { // model.getLastDateAfterdeleteModel(url,start,end,user,kind); } public void passListPresenter(List<LastTime> lastTimeList) { view.passListView(lastTimeList); } public void passListPresenterMore(List<LastTime> lastTimeList) { view.passListViewMore(lastTimeList); } public void dataDeletePresenter(String url, LastTimeAdapter adapter, String startDateDelete, String startTimeDelete, FragmentActivity visitLastDateFragment, String user, String kind, ProgressBar progressbar) { model.dataDeleteModel(url,adapter,startDateDelete,startTimeDelete,visitLastDateFragment,progressbar); } public void deleteMessagePresenter(String result) { view.messageDeleteView(result); } public void getLastDatePresenterMore(String url, String start, String end, String user, String kind, int start_row, ProgressBar progressbar, FloatingActionButton floatingActionButton) { model.getLastDateModelMore(url,start,end,start_row,progressbar,floatingActionButton); } public void buildPdfPresenter(String url, String start, String end, String user, String kind, ProgressBar progressbar, CoordinatorLayout coordinatorLayout, TextView textSum) { model.buildPdf(url,start,end,user,kind,progressbar,coordinatorLayout,textSum); } public void sumPresenter(String url, String start, String end, String user, String kind, ProgressBar progressbar) { model.sumModel(url,start,end,user,kind,progressbar); } public void resulSumPresenter(String result) { view.resultSumView(result); } public void buildExcelPresenter(String url, String start, String end, String user, String kind, ProgressBar progressbar, CoordinatorLayout coordinatorLayout, TextView textSum) { model.buildExcel(url,start,end,user,kind,progressbar,coordinatorLayout,textSum); } } <file_sep>package com.example.kamal.saatzanhamrah.LoginEmploy; import android.content.Intent; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Toast; import com.android.volley.Request; import com.example.kamal.saatzanhamrah.ForgotPackage.ForgotActivity; import com.example.kamal.saatzanhamrah.MainPackage.MainActivity; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.RegisterEmploy.RegisterActivity; import com.example.kamal.saatzanhamrah.Share; import com.example.kamal.saatzanhamrah.VisitEmployeeToEmployer.VisitEmployee; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by kamal on 12/9/2017. */ public class LoginModel { LoginActivity activity; LoginPresenter presenter; String userNameMain,success; public LoginModel(LoginActivity loginActivity) { this.activity = loginActivity; } public void setPresenter(LoginPresenter loginPresenter) { this.presenter = loginPresenter; } public void registerModel() { Intent intent = new Intent(activity, RegisterActivity.class); activity.startActivity(intent); } public void loginModel(final String user, final String pass, final String kind, String url, final ProgressBar progressBar, final Button btnLogin) { if (user.equals("") || pass.equals("")) { Toast.makeText(activity, "لطفا نام کاربری و رمز عبور را وارد کنید.", Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); btnLogin.setEnabled(true); return; } Share.getStringResponse(activity, Request.Method.POST, url, null, new Share.StringVolleyCallBack() { @Override public void onSuccessResponse(String result) { try { JSONObject jsonObject = new JSONObject(result); JSONArray jsonArray = jsonObject.getJSONArray("result1"); List<VisitEmployee> list = new ArrayList<VisitEmployee>(); JSONObject jsonObject1 = jsonArray.getJSONObject(0); userNameMain = jsonObject1.getString("username"); success = jsonObject1.getString("success"); if (success.equals("find")) { Share.saveSharePref(activity, "userKey", userNameMain); Share.saveSharePref(activity, "userKeyUpdate", user); Share.saveSharePref(activity, "passKey", pass); Share.saveSharePref(activity, "kindKey", kind); Intent intent = new Intent(activity, MainActivity.class); intent.putExtra("user", userNameMain); intent.putExtra("kind", kind); activity.startActivity(intent); activity.finish(); progressBar.setVisibility(View.GONE); btnLogin.setEnabled(true); }else if(success.equals("noFind")){ Toast.makeText(activity, "لطفا ثبت نام نمایید و نوع شغل هم درست انتخاب کرده باشید.", Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); btnLogin.setEnabled(true); }else if (success.equals("noConnect")) { Toast.makeText(activity, activity.getString(R.string.registerError), Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); btnLogin.setEnabled(true); } else { Toast.makeText(activity, "خطا", Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); btnLogin.setEnabled(true); } } catch (JSONException e) { e.printStackTrace(); progressBar.setVisibility(View.GONE); } } @Override public void onError(String error) { Toast.makeText(activity, activity.getString(R.string.registerError), Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); btnLogin.setEnabled(true); } @Override public Map onMapPost() { Map<String, String> loginparams = new HashMap<>(); loginparams.put("user", user); loginparams.put("pass", <PASSWORD>); loginparams.put("kind", kind); loginparams.put("key_text_android", "ktaa"); return loginparams; } }); } public void forgotModel() { Intent intent = new Intent(activity, ForgotActivity.class); activity.startActivity(intent); } } <file_sep>package com.example.kamal.saatzanhamrah.RegisterEmploy; import android.content.Intent; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Toast; import com.android.volley.Request; import com.example.kamal.saatzanhamrah.MainPackage.MainActivity; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.Share; import java.util.HashMap; import java.util.Map; /** * Created by kamal on 12/6/2017. */ public class RegisterModel { RegisterActivity activity; RegisterPresenter presenter; public RegisterModel(RegisterActivity registerActivity) { activity = registerActivity; } public void employPostParams(final Map<String, String> params, String url, final ProgressBar progressBar, final Button registerButton) { final String username = params.get("username"); final String password = params.get("password"); final String kind = params.get("kind"); final String email = params.get("email"); if (username.equals("") || password.equals("") || kind.equals("")) { Toast.makeText(activity, "لطفا اطلاعات را تکمیل فرمایید.", Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.GONE); return; } Share.getStringResponse(activity, Request.Method.POST, url, null, new Share.StringVolleyCallBack() { @Override public void onSuccessResponse(String result) { switch (result) { case "done": Toast.makeText(activity, activity.getResources().getString(R.string.registerSuccessfully), Toast.LENGTH_LONG).show(); Share.saveSharePref(activity, "userKey", username); Share.saveSharePref(activity, "userKeyUpdate", username); Share.saveSharePref(activity, "passKey", password); Share.saveSharePref(activity, "kindKey", kind); Intent intent = new Intent(activity, MainActivity.class); intent.putExtra("user", username); intent.putExtra("kind", kind); activity.startActivity(intent); activity.finish(); progressBar.setVisibility(View.GONE); activity.startActivity(intent); activity.finish(); break; case "fillfield": Toast.makeText(activity, activity.getResources().getString(R.string.fillField), Toast.LENGTH_LONG).show(); registerButton.setEnabled(true); break; case "this user there is": Toast.makeText(activity, activity.getResources().getString(R.string.repeatUser), Toast.LENGTH_LONG).show(); registerButton.setEnabled(true); break; case "failer_interesting_database": Toast.makeText(activity, activity.getResources().getString(R.string.registerNull), Toast.LENGTH_LONG).show(); registerButton.setEnabled(true); break; case "failure_post": Toast.makeText(activity, activity.getResources().getString(R.string.registerError), Toast.LENGTH_LONG).show(); registerButton.setEnabled(true); break; default: Toast.makeText(activity, activity.getResources().getString(R.string.registerError), Toast.LENGTH_LONG).show(); registerButton.setEnabled(true); break; } progressBar.setVisibility(View.GONE); } @Override public void onError(String error) { Toast.makeText(activity, activity.getString(R.string.registerError), Toast.LENGTH_SHORT).show(); registerButton.setEnabled(true); progressBar.setVisibility(View.GONE); } @Override public Map onMapPost() { Map<String, String> serverParams = new HashMap<>(); serverParams.put("user", username); serverParams.put("pass", <PASSWORD>); serverParams.put("kind", kind); serverParams.put("email", email); serverParams.put("key_text_android", "ktaa"); return serverParams; } }); } public void setPresenter(RegisterPresenter registerPresenter) { this.presenter = registerPresenter; } } <file_sep>package com.example.kamal.saatzanhamrah.AddEmployeeToEmployer; /** * Created by kamal on 12/29/2017. */ public class AddEmployeeToEmployerPresenter { AddEmployeeToEmployerModel model; AddEmployeeToEmployerFragment view; public AddEmployeeToEmployerPresenter(AddEmployeeToEmployerFragment view){ this.view=view; model=new AddEmployeeToEmployerModel(this,view.getActivity()); } public void presenterAddEmployee(String editTextAddEmployeeToEmployer,String addEmployeeUrl,String user) { model.addEmployee(editTextAddEmployeeToEmployer,addEmployeeUrl,user); } public void resultAddEmployeePresenter(String result) { view.resultAddEmployeeView(result); } } <file_sep>package com.example.kamal.saatzanhamrah.VisitEmployerToEmployee; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.example.kamal.saatzanhamrah.MainPackage.MainActivity; import com.example.kamal.saatzanhamrah.R; import com.example.kamal.saatzanhamrah.Share; import java.util.List; public class VisitEmployerToEmployeeFragment extends Fragment implements MainActivity.PassData { VisitEmployerPresenter presenter; Activity activity; private VisitEmployerAdapter adapter; private RecyclerView recyclerView; private String url="http://kamalroid.ir/get_employer_to_employee1.php"; private String user; private TextView textTitle; private ProgressBar progressbar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); presenter=new VisitEmployerPresenter(this); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.fragment_visit_employer_to_employee,container,false); recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView_visitEmployerToEmployee_listEmployer); progressbar= (ProgressBar) view.findViewById(R.id.progressBar_visitEmployerToEmployee_loading); textTitle=(TextView)getActivity().findViewById(R.id.textView_toolbar_title); textTitle.setText(getString(R.string.visitEmployer)); if(Share.check(getContext())) { progressbar.setVisibility(View.VISIBLE); presenter.visitEmployerToEmployee(url, user,progressbar); } else{ Toast.makeText(getActivity(), getResources().getString(R.string.noInternet), Toast.LENGTH_SHORT).show(); } return view; } public void passListVisitEmployerView(List<VisitEmployer> list) { adapter = new VisitEmployerAdapter(getActivity(), list); recyclerView.setLayoutManager(new LinearLayoutManager(activity)); recyclerView.setAdapter(adapter); } @Override public void sendData(String user, String kind,String userUpdate) { this.user=user; } }
6ff5c53c94079209b685f57e37222f41be0a5e86
[ "Java" ]
26
Java
sayedkamalhoseini/MyApplicationwork
5a8af6c6ee963fa3daa94defe29acec67181b21d
bac36ddcc1310aa354d8fe839474e48c74b58062
refs/heads/master
<repo_name>gedarufi/gcfglobal-front<file_sep>/src/app/@shared/course-item/course-item.component.ts import { Component, Input, OnInit } from '@angular/core'; import { CourseEnrollment } from '../course'; @Component({ selector: 'course-item', templateUrl: './course-item.component.html', styleUrls: ['./course-item.component.scss'] }) export class CourseItemComponent implements OnInit { @Input() course!: CourseEnrollment; constructor() { } ngOnInit(): void { } get status(): string { const status = { 'passed': 'Aprobado', 'failed': 'Desaprobado', 'in-progress': 'En progreso', }; return status[this.course.status]; } } <file_sep>/src/app/@shared/course.ts export interface Course { id: string; name: string; description: string; pages: Page[]; } export interface Page { id: number; course: string; content: string; } export interface CourseEnrollment { course: Course; status: "passed" | "failed" | "in-progress"; }; <file_sep>/src/app/user/login/login.component.spec.ts import { CommonModule } from '@angular/common'; import { HttpClientModule } from '@angular/common/http'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { AuthService } from 'src/app/auth.service'; import { LoginComponent } from './login.component'; describe('LoginComponent', () => { let component: LoginComponent; let fixture: ComponentFixture<LoginComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ LoginComponent ], imports: [ CommonModule, FormsModule, HttpClientModule, ReactiveFormsModule, RouterModule.forRoot([]), ], providers: [ AuthService ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(LoginComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should be disabled the login button', () => { const compiled = fixture.nativeElement as HTMLElement; const inpEmail = compiled.querySelector('input[type="email"]') as HTMLFormElement; const inpPassword = compiled.querySelector('input[type="password"]') as HTMLFormElement; expect(inpEmail).toBeDefined(); expect(inpPassword).toBeDefined(); expect(component.form.valid).toBeFalse(); inpEmail.value = 'gedarufi'; inpPassword.value = '<PASSWORD>'; fixture.detectChanges(); expect(component.form.valid).toBeFalse(); }); }); <file_sep>/src/app/home/home/home.service.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { environment } from './../../../environments/environment'; import { CourseEnrollment } from '../../@shared/course'; @Injectable() export class HomeService { constructor(protected http: HttpClient) {} getCoursesByEnrollments(userId: number): Observable<CourseEnrollment[]> { return this.http.get<CourseEnrollment[]>( `${environment.ApiUrl}/users/${userId}/courses` ); } } <file_sep>/src/app/layout/header/header.component.spec.ts import { AuthService } from './../../auth.service'; import { CommonModule } from '@angular/common'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterModule } from '@angular/router'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { HeaderComponent } from './header.component'; import { HttpClientModule } from '@angular/common/http'; describe('HeaderComponent', () => { let component: HeaderComponent; let fixture: ComponentFixture<HeaderComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ HeaderComponent ], imports: [ CommonModule, NgbModule, HttpClientModule, RouterModule.forRoot([]), ], providers: [ AuthService ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(HeaderComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should contain the navbar', () => { const compiled = fixture.nativeElement as HTMLElement; expect(compiled.querySelector('header nav.navbar')).toBeDefined(); }); it('should contain 4 items in the navbar', () => { const compiled = fixture.nativeElement as HTMLElement; expect( compiled.querySelectorAll('header nav.navbar ul.navbar-nav li.nav-item')?.length ).toBe(3); }); }); <file_sep>/src/app/home/home/home.component.spec.ts import { AuthService } from './../../auth.service'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { HomeComponent } from './home.component'; import { HomeService } from './home.service'; import { HttpClientModule } from '@angular/common/http'; describe('HomeComponent', () => { let component: HomeComponent; let fixture: ComponentFixture<HomeComponent>; const mockAuthSrv = jasmine.createSpyObj( 'AuthService', ['getPayload'] ); beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ HttpClientModule ], declarations: [ HomeComponent ], providers: [ HomeService, { provide: AuthService, useValue: mockAuthSrv } ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(HomeComponent); mockAuthSrv.getPayload.and.returnValue({ "id": 326, "email": "<EMAIL>", "fullName": "<NAME>", "iat": 1630345630335, "exp": 1630360030335 }); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/src/app/user/login/login.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { AuthService } from 'src/app/auth.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent { form: FormGroup; returnUrl: string | boolean = false; constructor( fb: FormBuilder, route: ActivatedRoute, protected authSrv: AuthService, protected router: Router, ) { this.form = fb.group({ email: ['', [Validators.required, Validators.email]], password: ['', [Validators.required, Validators.minLength(4)]], }); route.queryParams.subscribe(query => { if (!!query.returnUrl) { this.returnUrl = query.returnUrl; } }); } login() { if (!this.form.valid) { return; } this.authSrv.login(this.form.value).subscribe( token => this.router.navigateByUrl( this.returnUrl ? this.returnUrl.toString() : '/home' ) ); } } <file_sep>/src/app/content/course-list/course-list.component.ts import { Component, OnInit } from '@angular/core'; import { CourseListService } from './course-list.service'; import { Course } from '../../@shared/course'; import { Observable } from 'rxjs'; @Component({ selector: 'app-course-list', templateUrl: './course-list.component.html', styleUrls: ['./course-list.component.scss'] }) export class CourseListComponent implements OnInit { courses!: Observable<Course[]>; constructor( protected courseListSrv: CourseListService ) { } ngOnInit(): void { this.loadCourses(); } loadCourses() { this.courses = this.courseListSrv.getCourses(); } } <file_sep>/src/app/home/home/home.component.ts import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { AuthService, JwtPayload } from 'src/app/auth.service'; import { HomeService } from './home.service'; import { CourseEnrollment } from '../../@shared/course'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { courseList: Observable<CourseEnrollment[]> = new Observable<CourseEnrollment[]>(); constructor( protected authSrv: AuthService, protected homeSrv: HomeService, ) { } ngOnInit(): void { this.LoadUserInfo(); } LoadUserInfo() { const user = this.authSrv.getPayload() as JwtPayload; this.courseList = this.homeSrv.getCoursesByEnrollments(user.id); } } <file_sep>/src/app/auth.service.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { environment } from './../environments/environment'; export interface IJwtToken { token: string; } export interface JwtPayload { id: number; email: string; password?: string; fullName?: string; iat?: number; exp?: number; } @Injectable() export class AuthService { constructor(protected http: HttpClient) {} public get isLogued(): boolean { return !!this.getToken(); } getToken(): string | null { return localStorage.getItem(environment.Auth.tokenName); } getPayload(): JwtPayload | null { if (!this.isLogued) { return null; } const token = this.getToken() as string; const jwtParts = token.split('.'); const payload = decodeURIComponent( atob(jwtParts[1]).split('').map( c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) ).join('') ); return JSON.parse(payload); } login(payload: any): Observable<IJwtToken> { return new Observable(subscribe => { this.http.post( environment.Auth.loginUrl, payload, ).subscribe( (token: any) => { localStorage.setItem(environment.Auth.tokenName, token.token) subscribe.next(token as IJwtToken); }, error => subscribe.error(error) ); }); } logout() { localStorage.removeItem(environment.Auth.tokenName); } } <file_sep>/src/app/@shared/course-available/course-available.component.spec.ts import { ComponentFixture, TestBed } from '@angular/core/testing'; import { CourseAvailableComponent } from './course-available.component'; describe('CourseAvailableComponent', () => { let component: CourseAvailableComponent; let fixture: ComponentFixture<CourseAvailableComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ CourseAvailableComponent ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(CourseAvailableComponent); component = fixture.componentInstance; component.course = { id: 'A1', name: 'Inglés Básico', description: 'En este nivel aprenderás el vocabulario básico para dar tus primeros pasos en inglés. También descubrirás palabras y nuevas formas de expresarte en este idioma.', pages: [], }; fixture.detectChanges(); }); it('should create and render the course information', () => { expect(component).toBeTruthy(); }); }); <file_sep>/src/app/content/course/course.component.ts import { Course } from './../../@shared/course'; import { ChangeDetectionStrategy, Component } from '@angular/core'; import { ActivatedRoute, ParamMap, Params } from '@angular/router'; import { CourseService } from './course.service'; import { Observable } from 'rxjs'; @Component({ selector: 'app-course', templateUrl: './course.component.html', styleUrls: ['./course.component.scss'] }) export class CourseComponent { course$!: Observable<Course>; constructor( route: ActivatedRoute, protected courseSrv: CourseService, ) { route.paramMap.subscribe(params => this.loadCourse(params.get('id') as string)); } loadCourse(id: string): void { this.course$ = this.courseSrv.getCourse(id); } } <file_sep>/src/app/@shared/course-available/course-available.component.ts import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'; import { Course } from '../course'; @Component({ selector: 'course-available', templateUrl: './course-available.component.html', styleUrls: ['./course-available.component.scss'] }) export class CourseAvailableComponent implements OnInit { @Input() course!: Course; constructor() { } ngOnInit(): void { } } <file_sep>/src/app/content/course-list/course-list.service.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { environment } from './../../../environments/environment'; import { Course } from '../../@shared/course'; @Injectable() export class CourseListService { constructor(protected http: HttpClient) {} getCourses(): Observable<Course[]> { return this.http.get<Course[]>( `${environment.ApiUrl}/courses` ); } } <file_sep>/src/app/layout/header/header.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { AuthService } from 'src/app/auth.service'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.scss'] }) export class HeaderComponent implements OnInit { isMenuCollapsed = true; isProfileMenuCollapsed = true; isLogued = false; user: any; constructor( protected route: ActivatedRoute, protected router: Router, protected authSrv: AuthService, ) { } ngOnInit(): void { this.InitHeader(); } InitHeader() { this.isLogued = this.authSrv.isLogued; this.isProfileMenuCollapsed = true; if (this.isLogued) { this.user = this.authSrv.getPayload(); } } signOut() { this.authSrv.logout(); this.InitHeader(); this.router.navigateByUrl('/content'); } } <file_sep>/src/environments/environment.prod.ts export const environment = { production: true, ApiUrl: 'https://api-gcf.inger.co/api/v1', PublicUrl: 'https://api-gcf.inger.co', Auth: { tokenName: '<PASSWORD>', loginUrl: 'https://api-gcf.inger.co/api/v1/login' } }; <file_sep>/src/app/@shared/shared.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CourseItemComponent } from './course-item/course-item.component'; import { CourseAvailableComponent } from './course-available/course-available.component'; import { RouterModule } from '@angular/router'; @NgModule({ declarations: [ CourseItemComponent, CourseAvailableComponent, ], imports: [ CommonModule, RouterModule, ], exports: [ CourseItemComponent, CourseAvailableComponent, ] }) export class SharedModule { } <file_sep>/src/app/content/content.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CourseComponent } from './course/course.component'; import { ContentRoutingModule } from './content-routing.module'; import { CourseListComponent } from './course-list/course-list.component'; import { SharedModule } from '../@shared/shared.module'; import { CourseService } from './course/course.service'; import { CourseListService } from './course-list/course-list.service'; @NgModule({ declarations: [ CourseComponent, CourseListComponent ], imports: [ CommonModule, ContentRoutingModule, SharedModule, ], providers: [ CourseService, CourseListService ] }) export class ContentModule { } <file_sep>/src/app/content/course/course.service.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { environment } from './../../../environments/environment'; import { Course } from '../../@shared/course'; @Injectable() export class CourseService { constructor(protected http: HttpClient) {} getCourse(id: string): Observable<Course> { return this.http.get<Course>( `${environment.ApiUrl}/courses/${id}` ).pipe( map((c: Course) => { c.pages = c.pages.map(p => { p.content = p.content.split('src="/recursos/').join(`src="${environment.PublicUrl}/recursos/`); return p; }); return c; }) ); } }
9557e878216879c00b7ad26fb2228c1a6b7010fb
[ "TypeScript" ]
19
TypeScript
gedarufi/gcfglobal-front
c69d63356aa6b9216be83a90b2a5e76b5df7a01a
a6bbf7eb4cc9baf2befda5e8eef8ab5aef5e428b
refs/heads/master
<repo_name>zakharovre/JavaHomework<file_sep>/src/homework11/Task1.java package homework11; import java.util.ArrayList; import java.util.Arrays; public class Task1 { public static void main(String[] args) { String[] words = {"cat", "pet", "job", "dog", "cat", "dog", "sun", "dog", "top", "mad", "mug", "sit", "pet", "sun", "top"}; System.out.println("Uniq words: " + uniq(words)); count(words); } private static void count(String[] arr) { ArrayList<String> list = new ArrayList<>(Arrays.asList(arr)); ArrayList<String> checked = new ArrayList<>(); for (String word : list) { int count = 0; if (!checked.contains(word)) { System.out.print(word + " : "); for (String s : list) { if (word.equals(s)) count++; } checked.add(word); System.out.println(count); } } } private static ArrayList<String> uniq(String[] arr) { ArrayList<String> list = new ArrayList<>(Arrays.asList(arr)); ArrayList<String> uniq = new ArrayList<>(); for (String s : list) { if (list.indexOf(s) == list.lastIndexOf(s)) uniq.add(s); } return uniq; } } <file_sep>/src/homework2/Task6.java package homework2; public class Task6 { public static void main(String[] args) { int[] m = {1,0,1,1,2,3,0,2,1,2,3}; System.out.println(checkBalance(m)); } public static boolean checkBalance(int[] m){ for(int j = 0; j < m.length; j++){ int sumL = 0, sumR = 0; for(int i=0; i<=j; i++) sumL+=m[i]; for(int i = j+1; i< m.length; i++) sumR+=m[i]; if(sumL==sumR) return true; } return false; } } <file_sep>/src/homework11/PhoneBook.java package homework11; import java.util.HashMap; public class PhoneBook { private HashMap<String, String> map = new HashMap<>(); public void add(String name, String number) { if (map.containsKey(name)) map.put(name, map.get(name) + " , " + number); else map.put(name, number); } public void get(String name){ System.out.printf("Имя : %s; Номер телефона : %s%n",name,map.get(name)); } } <file_sep>/src/homework1/Task1.java package homework1; public class Task1 { public static void main(String[] args) { //System.out.println(Task3.doSome(2,3,5,3)); //System.out.println(Task4.sumLimit(5,5)); //System.out.println(Task5.positive(-312)); //System.out.println(Task6.negative(-1)); //System.out.println(Task7.greetings("Олег")); //System.out.println(Task8.leap(800)); } } <file_sep>/src/homework6/Animal.java package homework6; public abstract class Animal { protected int runLimit; protected float jumpHeight; public int getRunLimit() { return runLimit; } public void setRunLimit(int runLimit) { this.runLimit = runLimit; } public float getJumpHeight() { return jumpHeight; } public void setJumpHeight(int jumpHeight) { this.jumpHeight = jumpHeight; } public abstract void run(int distance); public abstract void jump(float height); } <file_sep>/src/homework2/Task4.java package homework2; import java.util.Arrays; public class Task4 { public static void main(String[] args) { int[][] m = new int[10][10]; for(int i = 0; i<10; i++){ for(int j = 0; j<10; j++){ m[i][j] = 0; } } for(int i = 0; i< m.length; i++){ for(int j=0; j<m[i].length; j++){ if(i==j || i==(9-j)){ m[i][j] = 1; } System.out.print(m[i][j] + " "); } System.out.println(); } } } <file_sep>/src/homework2/Task2.java package homework2; import java.util.Arrays; public class Task2 { public static void main(String[] args) { int[] m = new int[8]; for(int i=0; i< m.length; i++) m[i]=i*3; System.out.println(Arrays.toString(m)); } } <file_sep>/src/homework14/Server.java package homework14; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Server { public static void main(String[] args) { try (ServerSocket server = new ServerSocket(5555)) { System.out.println("Waiting for connection..."); Socket serverSocket = server.accept(); System.out.println("Client has been connected. Type '/end' to stop connection."); DataInputStream in = new DataInputStream(serverSocket.getInputStream()); DataOutputStream out = new DataOutputStream(serverSocket.getOutputStream()); Thread thread1 = new Thread(() -> { while (true){ try { System.out.println("Client: " + in.readUTF()); } catch (IOException e) { System.exit(0); } } }); thread1.setDaemon(true); thread1.start(); while (true){ Scanner scanner = new Scanner(System.in); String message = scanner.nextLine(); if(message.equals("/end")) break; out.writeUTF(message); } } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/src/homework10/Task.java package homework10; public class Task { public static void main(String[] args) { String[][] someArr = {{"1", "2", "3", "1"}, {"4", "2", "4", "2"}, {"3", "2", "2", "1"}, {"4", "4", "2", "5"}}; try { System.out.println(getSumFromArray(someArr)); } catch (MyArraySizeException | MyArrayDataException e) { System.out.println(e.getMessage()); } } public static int getSumFromArray(String[][] arr) throws MyArrayDataException, MyArraySizeException { if (arr.length != 4 || arr[0].length != 4) throw new MyArraySizeException(); int sum = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { try { sum += Integer.parseInt(arr[i][j]); } catch (NumberFormatException e) { throw new MyArrayDataException(i, j); } } } return sum; } } <file_sep>/src/homework1/Task4.java package homework1; public class Task4 { public static boolean sumLimit(int a, int b){ return 10<=a+b && a+b<=20; } } <file_sep>/src/homework12/Controller.java package homework12; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.scene.control.*; import java.text.SimpleDateFormat; import java.util.Date; public class Controller { @FXML private ListView<String> ContactList; @FXML private TextArea MessagesArea; @FXML private TextField TextInput; @FXML private Button SendButton; @FXML void initialize(){ ContactList.setItems(FXCollections.observableList(Main.Contacts)); SendButton.setOnAction(event -> sendMessage()); TextInput.setOnAction(event -> sendMessage()); } void sendMessage(){ MessagesArea.appendText(new SimpleDateFormat("[HH:mm:ss] ").format(new Date())); MessagesArea.appendText(Main.userName + ": "); MessagesArea.appendText(TextInput.getText()); MessagesArea.appendText(System.lineSeparator()); TextInput.clear(); } } <file_sep>/src/homework10/MyArrayDataException.java package homework10; public class MyArrayDataException extends NumberFormatException { public MyArrayDataException(int a, int b) { super("Данные в ячейке arr[" + a + "][" + b + "] не привести к типу int"); } } <file_sep>/src/homework1/Task7.java package homework1; public class Task7 { public static String greetings(String name){ return "Привет, " + name + "!"; } } <file_sep>/src/homework6/Cat.java package homework6; public class Cat extends Animal { public Cat() { runLimit = (int) (Math.random() * 200) + 100; jumpHeight = ((int) (Math.random() * 10) + 15) / 10.0f; } @Override public void run(int distance) { System.out.println("Кот сможет пробежать " + getRunLimit() + " метров."); System.out.println("Дистанция забега: " + distance + " метров."); if (distance > getRunLimit()) System.out.println("Провал"); else System.out.println("Успех"); } @Override public void jump(float height) { System.out.println("Кот сможет перепрыгнуть " + getJumpHeight() + " метров."); System.out.println("Высота препятствия: " + height + " метров."); if (height > getJumpHeight()) System.out.println("Провал"); else System.out.println("Успех"); } } <file_sep>/src/homework10/MyArraySizeException.java package homework10; public class MyArraySizeException extends Exception { public MyArraySizeException() { super("Размер массива должен быть 4х4"); } } <file_sep>/src/homework2/Task5.java package homework2; import java.util.Arrays; public class Task5 { public static void main(String[] args) { int[] m = new int[15]; for(int i=0; i<m.length; i++) m[i] = (int)(Math.random()*200 - 100); System.out.println(Arrays.toString(m)); Arrays.sort(m); System.out.println("max = " + m[m.length-1]); System.out.println("min = " + m[0]); } }
81c09a62f2342a2badbb6de0e8c5d5a0c9178926
[ "Java" ]
16
Java
zakharovre/JavaHomework
2f2a531e323f4bd547611d0226aa5dbde43bdb04
974f4b3d7244a9c33caf6d8e53931d8fbcaaa894
refs/heads/master
<file_sep>#!/bin/ python3.8 #Projet numéro 2 #Read Definition for more medical description. #Read Readme for more sources. # DataFrame : CSV - UTF 8 import pandas as pd # Windows : #data = pd.read_csv("DATA/heart.csv", encoding ="utf8") # Ubuntu : data = pd.read_csv('/media/jhy/JHY/Etudes/Projets/Work in progress/Projets 2/DATA/heart.csv', encoding = "utf8") #Import graph import matplotlib.pyplot as plt # Disable chain limit pd.options.mode.chained_assignment = None # Shortcut for DataFrame age,sex = data['age'],data['sex'] chest_pain, blood_pressure = data['cp'], data['trestbps'] cholesterol ,fast_sugars = data['chol'],data['fbs'] rest_cardiogram,maximun_heartrate = data['restecg'],data['thalach'] pain_exercice, depression_rest = data['exang'],data['oldpeak'] slope, big_vessel = data['slope'],data['ca'] diag, heart_faillure = data['thal'],data['target'] #correction : target was swap 0 mean heart attack, 1 mean no trouble heart_faillure[heart_faillure == 0] = "Accident" heart_faillure[heart_faillure == 1] = "Nothing" #ajustement sex[sex == 1] = "Male" sex[sex == 0] = "Female" #Age to target def hp_faillure(): cpt = 0 cpt_tot = 0 for x in heart_faillure: if x is True : cpt +=1 else : cpt_tot +=1 total = cpt + cpt_tot percent = round((cpt / total)*100,2) return percent age_target = round(age.mean()),hp_faillure() #print(parite_HF) ############################################################################################################################ ###################################### DATA TRENDS ####################################################### ############################################################################################################################ # Parity men = 0 women = 0 for x in sex : if x == "Male" : men += 1 elif x == "Female" : women += 1 else : print('check database') pass men_target = sex[sex == 'Male'][heart_faillure =="Accident"].count() women_target = sex[sex == 'Female'][heart_faillure =="Accident"].count() parite_HF = round(women / (women+men)*100,2) age_man_target = age[sex=="Male"][heart_faillure=="Accident"] age_man_untarget = age[sex=="Male"][heart_faillure=="Nothing"] age_woman_target = age[sex=="Female"][heart_faillure=="Accident"] age_woman_untarget = age[sex=="Female"][heart_faillure=="Nothing"] # Cholesterols avg_cholesterol = round(cholesterol.mean(),2) #Target cholesterol_male_target = cholesterol[sex=="Male"][heart_faillure=="Accident"] cholesterol_female_target = cholesterol[sex=="Female"][heart_faillure=="Accident"] #Untarget cholesterol_male_untarget = cholesterol[sex=="Male"][heart_faillure=="Nothing"] cholesterol_female_untarget = cholesterol[sex=="Female"][heart_faillure=="Nothing"] #Diabetes # > 125mg = True = Diabetes #target diab_male_target = fast_sugars[sex=="Male"][heart_faillure=="Accident"][fast_sugars ==1] diab_female_target = fast_sugars[sex=="Female"][heart_faillure=="Accident"][fast_sugars ==1] #untarget diab_male_untarget = fast_sugars[sex=="Male"][heart_faillure=="Nothing"] diab_female_untarget = fast_sugars[sex=="Female"][heart_faillure=="Nothing"] #Resting blood pressure avg_bloodpress = round(blood_pressure.mean(),2) # > 90 risk trouble health #target bloodpress_male_target = blood_pressure[sex=='Male'][heart_faillure=='Accident'] bloodpress_female_target = blood_pressure[sex=='Female'][heart_faillure=='Accident'] #untarget bloodpress_male_untarget = blood_pressure[sex=='Male'][heart_faillure=='Nothing'] bloodpress_female_untarget = blood_pressure[sex=='Female'][heart_faillure=='Nothing'] #chest pain # 1: typical angina, 2: atypical angina, 3: non-anginal pain, 4: asymptomatic #Male #Target chest_type1_men_target = chest_pain[sex=='Male'][heart_faillure=='Accident'][chest_pain == 1] chest_type2_men_target = chest_pain[sex=='Male'][heart_faillure=='Accident'][chest_pain == 2] chest_type3_men_target = chest_pain[sex=='Male'][heart_faillure=='Accident'][chest_pain == 3] chest_type4_men_target = chest_pain[sex=='Male'][heart_faillure=='Accident'][chest_pain == 4] #Untarget chest_type1_men_untarget = chest_pain[sex=='Male'][heart_faillure=='Nothing'][chest_pain == 1] chest_type2_men_untarget = chest_pain[sex=='Male'][heart_faillure=='Nothing'][chest_pain == 2] chest_type3_men_untarget = chest_pain[sex=='Male'][heart_faillure=='Nothing'][chest_pain == 3] chest_type4_men_untarget = chest_pain[sex=='Male'][heart_faillure=='Nothing'][chest_pain == 4] #Female #Target chest_type1_women_target = chest_pain[sex=='Female'][heart_faillure=='Accident'][chest_pain == 1] chest_type2_women_target = chest_pain[sex=='Female'][heart_faillure=='Accident'][chest_pain == 2] chest_type3_women_target = chest_pain[sex=='Female'][heart_faillure=='Accident'][chest_pain == 3] chest_type4_women_target = chest_pain[sex=='Female'][heart_faillure=='Accident'][chest_pain == 4] #Untarget chest_type1_women_untarget = chest_pain[sex=='Female'][heart_faillure=='Nothing'][chest_pain == 1] chest_type2_women_untarget = chest_pain[sex=='Female'][heart_faillure=='Nothing'][chest_pain == 2] chest_type3_women_untarget = chest_pain[sex=='Female'][heart_faillure=='Nothing'][chest_pain == 3] chest_type4_women_untarget = chest_pain[sex=='Female'][heart_faillure=='Nothing'][chest_pain == 4] ############################################################################################################################# #---------------------------------------------------Graphique---------------------------------------------------------------- # Disparité cholesterol plt.scatter(age,cholesterol,c ='Yellow', linewidths= 5) plt.scatter(age_man_target, cholesterol_male_target, c ='Blue') plt.scatter(age_woman_target,cholesterol_female_target, c = 'Pink') plt.ylabel("CHOLESTEROLS RATES") plt.xlabel("AGES") plt.title("DATA FROM 300 PATIENTS : HEART ATTACK CORRELATION BETWEEN CHOLESTEROLS") legends_chol=["Health","Male Heart Attack","Female Heart Attack"] plt.legend(legends_chol,bbox_to_anchor = (1,1)) plt.ylim(0,600) plt.xlim(0,90) plt.show() #disparité diabetes #can only be use in scoring #Resting blood pressure plt.scatter(age,blood_pressure,c ='Yellow', linewidths= 5) plt.scatter(age_man_target, bloodpress_male_target, c ='Blue') plt.scatter(age_woman_target,bloodpress_female_target,c = 'Pink') plt.ylabel("BLOOD PRESSURES") plt.xlabel("AGES") plt.title("DATA FROM 300 PATIENTS : HEART ATTACK CORRELATION BETWEEN BLOOD PRESSURES") plt.legend(legends_chol,bbox_to_anchor = (1,1)) plt.ylim(0,250) plt.xlim(0,90) plt.show() # chest
ac889d59b88870f389ba75cfdfaba8c02adf42c7
[ "Python" ]
1
Python
Jhy-Red/heart
a53d36f33445a068f395f8e8a59a775f1bcc59b3
009f7d12dd77f7271f121a30640890ef7c73e431
refs/heads/main
<repo_name>littlejo/python-rabbitmq-client<file_sep>/settings.py protocol = 'amqps' #amqps or amqp user = 'user' password = '<PASSWORD>' host = 'hostname' port = '5671' #default port for amqps (5672 for amqp) raw_url = f'{protocol}://{user}:{password}@{host}:{port}' <file_sep>/Dockerfile FROM python:3.9.0-alpine3.12 RUN pip install pika ADD *.py /app/ WORKDIR /app ENTRYPOINT ["python"] CMD ["publisher.py"]
5fc22e0fd01b87893996a6361fec9da2c6f8496a
[ "Python", "Dockerfile" ]
2
Python
littlejo/python-rabbitmq-client
f93ff9bba9ad3e00cd78de6b2e80f746c3966a1a
97b943825b0e973e2890e753266913960c64fc61
refs/heads/main
<file_sep>export default class Pixabay { static async makePixabayApiCall(userSearchInput) { try { const response = await fetch(`https://pixabay.com/api/?key=${process.env.API_KEY}&q=${userSearchInput}&image_type=photo`); if (!response.ok) { throw Error(response.statusText); } return response.json(); } catch(error) { return error.message; } } }<file_sep>/*eslint-disable*/ import $ from 'jquery'; /*eslint-disable*/ import 'bootstrap'; import 'bootstrap/dist/css/bootstrap.min.css'; import './css/styles.css'; import EpicEarth from './js/services/epic-earth.js'; import Pixabay from './js/services/pixabay.js' function randomImage(length) { return Math.floor(Math.random() * length); } $(document).ready(function() { $('#dateForm').submit(function(event) { event.preventDefault(); const userDateInput = $('#date-input').val(); const dateSlash = userDateInput.replace(/-/g, "/"); (async function() { const earthResponse = await EpicEarth.makeEpicApiCall(userDateInput); if (earthResponse.length === 0) { $('#image').html("<h1>please select another date</h1>"); } else { console.log(earthResponse); const imageNumber = randomImage(earthResponse.length); const imageFile = earthResponse[imageNumber].image; $('#image').html(`<img src="https://epic.gsfc.nasa.gov/archive/enhanced/${dateSlash}/png/${imageFile}.png" alt="EPIC Image">`); } })(); }) $('#imageForm').submit(function(event) { event.preventDefault(); const userSearchInput = $('#image-input').val(); (async function () { const imageResponse = await Pixabay.makePixabayApiCall(userSearchInput); if (imageResponse.total === 0) { $('#pixaImage').html("<p>No results found. Please enter a different input.</p>"); } else { const pixaImageNumber = randomImage(imageResponse.hits.length); const pixaImageUrl = imageResponse.hits[pixaImageNumber].largeImageURL; const pixaTags = imageResponse.hits[pixaImageNumber].tags; $('#pixaImage').html(`<img src="${pixaImageUrl}" alt="${pixaTags}">`) } console.log(imageResponse); })(); }) })<file_sep># _Project Name_ #### _Brief Description_ #### By _**<NAME>**_ ## Technologies Used * Babel/core 7.6.4 * Babel/plugin-transform-modules-commonjs 7.6.0 * Bootstrap 4.6.0 * clean-webpack-plugin 3.0.0 * CSS * css-loader 3.2.0 * eslint 6.3.0 * eslint-loader 3.0.0 * HTML5 * html-webpack-plugin 3.2.0 * JavaScript * Jest 24.9.0 * jQuery 3.5.1 * Node Package Manager 6.14.9 * popper.js 1.16.1 * style-loader 1.0.0 * webpack 4.39.3 * webpack-cli 3.3.8 * webpack-dev-server 3.11.2 ## Description _In depth description_<br><br> _View project on GH Pages: [gh-pages](https://chloeloveall.github.io/project-name/)_<br><br> ## Setup/Installation Requirements 1. Clone the repository with the following git command: >$ git clone https://github.com/chloeloveall/project-name.git 2. Open the project directory in your terminal 3. Recreate the project environment by running the terminal command $ npm install 4. Create the production environment by running the terminal command $ npm run build 5. Open the project in the browser of your choice with the terminal command $ npm run start 6. Run tests in Jest with the terminal command $ npm test ## Known Bugs * None ## License [MIT](LICENSE.md) ## Contact Information _<NAME> <<EMAIL>>_
20cdc710e870380b6a1e3b993f7d0cceb0d599a9
[ "JavaScript", "Markdown" ]
3
JavaScript
Pingel88/space-api
97c4b315be2ad797f392d58ceee36c49124e4f63
c18dca30810686c7293b3a46d2208a5ec4f7a3bc
refs/heads/main
<file_sep># kanban Kanban board
510d9f055b88dc83072f21392ac1d26a0babea06
[ "Markdown" ]
1
Markdown
antoniokelvin/kanban
e0792c07b935690f8946e563f93919e96ace282a
a9d0684d2689f8965ab3ffe079e538164daba163
refs/heads/master
<repo_name>CoyoteNET/CoyoteNET-frontend<file_sep>/CoyoteFrontend/FakeLocalStorage.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CoyoteFrontend { public static class FakeLocalStorage { // temporary work around to hold JWT somewhere public static string Username { get; set; } public static string Token { get; set; } public static DateTime ExpiresAt { get; set; } } } <file_sep>/CoyoteFrontend/Data/Service.cs using System; using Newtonsoft.Json; using System.Net.Http; using System.Threading.Tasks; using System.Text; using Microsoft.Extensions.Configuration; using CoyoteNETCore.Shared.ResultHandling; using System.Net.Http.Headers; namespace CoyoteFrontend.Data { public class Service { private readonly IConfiguration _configuration; public Service(IConfiguration configuration) { _configuration = configuration; } public async Task<Result<U>> TryPOST<T, U>(T command, string endpoint, string bearer_token = "") { using (var client = new HttpClient()) { var json = JsonConvert.SerializeObject(command); var request = new HttpRequestMessage(HttpMethod.Post, _configuration["Backend:Host"] + endpoint) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; if (!string.IsNullOrEmpty(bearer_token)) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token); } var response = await client.SendAsync(request); var responseString = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { Console.Clear(); Console.WriteLine(responseString); Console.WriteLine(typeof(U)); var t = JsonConvert.DeserializeObject<U>(responseString); return new Result<U>(t); } return new Result<U>(ErrorType.BadRequest, responseString); } } public async Task<Result<U>> TryGET<U>(string endpoint, string bearer_token = "") { using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Get, _configuration["Backend:Host"] + endpoint) { }; if (!string.IsNullOrEmpty(bearer_token)) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token); } var response = await client.SendAsync(request); var responseString = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { var t = JsonConvert.DeserializeObject<U>(responseString, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); return new Result<U>(t); } return new Result<U>(ErrorType.BadRequest, responseString); } } } }
ba2a249429c5b333c17d549fc2dc2f50120ab92c
[ "C#" ]
2
C#
CoyoteNET/CoyoteNET-frontend
40e59a27a88f0005f9125295994428c4d50ef9a8
986eb82247f203b81260590dc0a4c07ae8a203cf
refs/heads/master
<repo_name>SneakyG/kits<file_sep>/CalculatorEx/src/exercise/CalculatorEx.java package exercise; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class CalculatorEx { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { System.out.print("First number: "); int n1 = sc.nextInt(); List<String> operators = new ArrayList<String>(); operators.add("+"); operators.add("-"); operators.add("*"); operators.add("/"); String operator = ""; boolean flag = true; while (flag) { operator = sc.next(); for (int i = 0; i < operators.size();i++) { if (operator.equals(operators.get(i))) { flag = false; break; } } if(flag) System.out.println("not operator!"); } System.out.println("Operator: " + operator); System.out.print("Second number: "); int n2 = sc.nextInt(); String equal; while (true) { equal = sc.next(); if (equal.equals("=")) break; System.out.println("not valid"); } result(n1, n2, operator); sc.close(); } public static void result(int n1, int n2, String operator) { switch (operator) { case "+": System.out.println("Result: " + n1 + " + " + n2 + " = " + (n1 + n2)); break; case "-": System.out.println("Result: " + n1 + " - " + n2 + " = " + (n1 - n2)); break; case "*": System.out.println("Result: " + n1 + " * " + n2 + " = " + (n1 * n2)); break; case "/": if (n2 == 0) { System.out.println("Not divide by zero"); } else { System.out.println("Result: " + n1 + " / " + n2 + " = " + (n1 / n2)); } break; default: break; } } }
4c46d91d7f4a865b6058cfb16306c8cec64a3da7
[ "Java" ]
1
Java
SneakyG/kits
40fc80efd643d9e4d524ceed46b675e10fec0150
14b0cce73b0cffcbbd805618c853dbdc2f3b3cb4
refs/heads/master
<file_sep>{ 'name': 'Customize login page', 'version': '1.0', 'description': "This module will change the display of login page", 'category': 'web', 'complexity': "easy", 'description': """ This module will change this login page. ================= Change login homepage, logo and some CSS properties. """, 'author': 'ERPTalk.net', 'website': 'http://erptalk.net', 'installable': True, 'active': False, 'depends': ['web'], 'qweb' : [ "static/src/base.xml", ], 'css': [ "static/src/css/login.css", ], }
e2fc295e0cc3b312a72d4bff63c5a4d849a93451
[ "Python" ]
1
Python
sadana/customize_login
5e96b214ba75441d361fb372fda80fab86c71aef
354fd9759d31f9ea2d867ccc2082117106c989fb
refs/heads/master
<repo_name>xohail/TRM---Test<file_sep>/tests/MyTest.php <?php use TheRMTest\StringCalculator; use PHPUnit\Framework\TestCase; class MyTest extends TestCase { protected StringCalculator $string_calculator; public function __construct(?string $name = null, array $data = [], $dataName = '') { parent::__construct($name, $data, $dataName); $this->string_calculator = new StringCalculator(); } /** * Test if the StringCalculator class exists */ public function testSetup(): void { $this->assertTrue($this->string_calculator instanceof StringCalculator); } /** * Test returns 0 if empty string is provided */ public function testEmptyString(): void { $sum = $this->string_calculator->intAdd(""); $this->assertSame(0, $sum); } /** * Test returns same digit passed in string */ public function testSingleDigitString(): void { $sum = $this->string_calculator->intAdd('1'); $this->assertSame(1, $sum); } /** * Test returns sum of the 2 digits passed in string */ public function testTwoDigitString(): void { $sum = $this->string_calculator->intAdd('1,2'); $this->assertEquals(3, $sum); } /** * Test returns sum of unknown length of digits passed in the string */ public function testUnknownDigitLengthString(): void { $sum = $this->string_calculator->intAdd('1,2,3,4,5,6'); $this->assertEquals(21, $sum); } /** * Test returns sum of digit with \n in it */ public function testHandleNewLineInString(): void { $sum = $this->string_calculator->intAdd('1\n2,3'); $this->assertEquals(6, $sum); } /** * Test returns sum of digit with \n at start */ public function testHandleNewLineInStartOfString(): void { $sum = $this->string_calculator->intAdd('\n1\n2,3'); $this->assertEquals(6, $sum); } /** * Test returns sum of digit with \n at end */ public function testHandleNewLineInEndOfString(): void { $sum = $this->string_calculator->intAdd('1\n2,3\n'); $this->assertEquals(6, $sum); } /** * Test returns sum of digit with \n at both start and end */ public function testHandleNewLineInStartAndEndOfString(): void { $sum = $this->string_calculator->intAdd('\n1\n2,3\n'); $this->assertEquals(6, $sum); } /** * Test returns if the string has new delimiter */ public function testIdentifyStringWithNewDelimiter(): void { $this->assertTrue($this->string_calculator->checkNewDelimiter('//;\n1;2')); } /** * Test returns if the delimiter successfully replace the existing delimiter */ public function testReplaceCommaWithNewDelimiter(): void { $string = '//;\n1;2'; $this->assertSame(';', $this->string_calculator->addNewDelimiter($string)); } /** * Test returns if the correct string retrieved after finding new delimiter */ public function testRetrieveStringAfterNewDelimiter(): void { $string = '//;\n1;2'; if ($this->string_calculator->checkNewDelimiter($string)) { $this->assertSame('1;2', $this->string_calculator->retrieveString($string)); } } /** * Test returns if the sum is working with the new delimiter */ public function testSumWithNewDelimiter(): void { $sum = $this->string_calculator->intAdd('//;\n1;2'); $this->assertEquals(3, $sum); } /** * Test returns if the correct is retrieved from the string */ public function testRetrieveArray(): void { $array = $this->string_calculator->retrieveArray('1;2', ';'); $this->assertEquals([1, 2], $array); } /** * Test if there is a negative value in the string */ public function testNegativeValueInString(): void { $this->assertTrue($this->string_calculator->checkNegative([1, -2])); } /** * Test if the exception is thrown when negative value is added to the string */ public function testGetNegativeValue(): void { $this->assertSame(-2, $this->string_calculator->getNegativeValue([1, -2])); $this->expectException("Exception"); $this->expectExceptionMessage("Negatives not allowed -2"); } /** * Test if the exception is thrown when negative values are added to the string */ public function testGetMultipleNegativeNumbers(): void { $this->assertSame('-2 -1', $this->string_calculator->GetMultipleNegativeNumbers([-2, -1, 3])); $this->expectException("Exception"); if ($this->getExpectedException() == 'Exception') { $this->assertTrue(true); } $this->expectExceptionMessage("Negatives not allowed -2 -1"); if ($this->getExpectedExceptionMessage() == 'Negatives not allowed -2 -1') { $this->assertTrue(true); } } /** * Test if the number of times the intAdd is called is returned correct * * @throws Exception */ public function testAddMethodCount(): void { $this->string_calculator::$count = 0; $this->string_calculator->intAdd('\n1\n2,3\n'); $this->string_calculator->intAdd('\n1\n2,3\n'); try { $this->string_calculator->intAdd('\n1\n2,-3\n'); } catch (Exception $exception) { $exception->getMessage(); } $this->assertSame(3, $this->string_calculator->getCalledCount()); } /** * Check if the number greater than 1000 is ignored * * @throws Exception */ public function testCheckIfNumberGreaterThan1000IsIgnored(): void { $this->assertEquals([1, 23], $this->string_calculator->unsetLargerValues([1, 2000, 23])); $this->assertEquals(24, $this->string_calculator->intAdd('1,23')); } /** * Check if correct position of new line is retrieved */ public function testCheckFirstNewLineOccurrencePosition(): void { $this->assertSame(5, $this->string_calculator->getNewLinePosition('//***\n1***2***3')); } /** * Check if the delimiter is a compound one or a single or multiple unique ones */ public function testCheckAllCharactersInTheStringAreSame(): void { $this->assertTrue($this->string_calculator->CheckAllCharactersInTheStringAreSame('****')); $this->assertFalse($this->string_calculator->CheckAllCharactersInTheStringAreSame('%*%*')); } /** * Get unique characters from a string */ public function testCheckRetrieveUniqueCharactersFromString(): void { $this->assertSame(['%', '*'], $this->string_calculator->RetrieveUniqueCharactersFromString('%*%*')); } /** * Check if the converted string with multiple delimiters is correct */ public function testCheckIfTheStringIsCorrectlyConvertedWithUnifiedDelimiter(): void { // Check if the correct string is formulated after conversion $this->assertSame('1,2,2,', $this->string_calculator->ConvertUniqueDelimitersIntoUnifiedDelimiterAndExtractString('1#2$2#', ['#', '$'])); } }<file_sep>/README.md # TRM---Test Repository for the TRM technical test ## Steps to configure on local system * Open CLI * Make sure Docker and Docker-compose is installed on the system * Check by typing $`docker` and $`docker-compose` in the CLI * Create directory and change directory to it * $`mkdir TRM` * $`cd TRM` * $`git clone <EMAIL>:xohail/TRM.git .` * $`alias dcr='docker-compose run'` // for shorthand * $`dcr composer require --dev phpunit/phpunit` * $`docker-compose up -d fpm nginx` * Website should be up on http://localhost:8080 * If not please configure to the available port in **docker-compose.yml** for nginx * $`dcr php-unit --debug` // for tests * Update `index.php` to check specific case and output will be printed on http://localhost:8080 <file_sep>/src/StringCalculator.php <?php declare(strict_types=1); namespace TheRMTest; class StringCalculator { public static int $count = 0; public const DELIMITER = ','; /** * Return sum of digits passed in the string * * @param $string * @return int * @throws \Exception */ public function intAdd($string): int { self::$count++; // Increment each time the method is called // Empty string case if (empty($string)) { return 0; } // If new delimiter is added to the string; retrieve and process $delimiter = self::DELIMITER; if ($this->checkNewDelimiter($string)) { $delimiter = $this->addNewDelimiter($string); if (!$this->CheckAllCharactersInTheStringAreSame($delimiter)) { $delimiter = self::DELIMITER; // Since we are using this as default for the multiple delimiters $delimiter_array = $this->RetrieveUniqueCharactersFromString($delimiter); $string = $this->ConvertUniqueDelimitersIntoUnifiedDelimiterAndExtractString($string, $delimiter_array); } $string = $this->retrieveString($string); } // Sanitize & retrieve input $array = $this->retrieveArray($string, $delimiter); $array = $this->unsetLargerValues($array); // Check negative value if ($this->checkNegative($array)) { $negative_string = $this->GetMultipleNegativeNumbers($array); throw new \Exception("Negatives not allowed " . $negative_string); } // For single digit string if (count($array) == 1) { return (int) $array[0]; } elseif (count($array) == 1) { // For two digits string return (int) $array[0]+$array[1]; } else { // Sum all digits in the string return (int) array_sum($array); } } /** * Check if new delimiter is added to the string * * @param $string * @return bool */ public function checkNewDelimiter($string): bool { return substr($string, 0, 2) == '//'; } /** * Replace comma with new delimiter * * @param $string * @return string */ public function addNewDelimiter($string): string { return substr($string, 2, $this->getNewLinePosition($string) - 2); } /** * Checks if the extracted delimiter is comprised of same characters or unique * * @param $string * @return bool */ public function CheckAllCharactersInTheStringAreSame($string): bool { return count(array_count_values(str_split($string))) == 1; } /** * Get array of unique delimiters from delimiter string * * @param $string * @return array */ public function RetrieveUniqueCharactersFromString($string): array { return array_unique(str_split($string)); } /** * Get the string to perform addition after replace comma with new delimiters * * @param $string * @param $delimiter_array * @return string */ public function ConvertUniqueDelimitersIntoUnifiedDelimiterAndExtractString($string, $delimiter_array): string { foreach ($delimiter_array as $delimiter) { $string = str_replace($delimiter, ',', $string); } return $string; } /** * Get position in the string of the new line '\n' * * @param $string * @return int */ public function getNewLinePosition($string): int { return strpos($string, '\n'); } /** * Retrieve string to sum after the new delimiter * * @param $string * @return string */ public function retrieveString($string): string { return substr($string, $this->getNewLinePosition($string) + 2); } /** * Retrieve array from the string * * @param $string * @param $delimiter * @return array */ public function retrieveArray($string, $delimiter): array { $string = str_replace('\n', $delimiter, $string); return explode($delimiter, $string); // Explode string to array } /** * Check if array has a negative value * * @param $array * @return bool */ public function checkNegative($array): bool { return min($array) < 0; } /** * Get the negative value from array * * @param $array * @return int */ public function getNegativeValue($array): int { return (int) min($array); } /** * Get string of negative numbers from the array * * @param $array * @return string */ public function GetMultipleNegativeNumbers($array): string { $neg = array_filter($array, function($x) { return $x < 0; }); return implode(" ", $neg); } /** * Return count of times the intAdd method is called * * @return int */ public function getCalledCount(): int { return self::$count; } /** * Filter numbers greater than 1000 * * @param $array * @return array */ public function unsetLargerValues($array): array { $filter = array_filter($array, function($x) { return $x <= 1000; }); $res = array(); foreach ($filter as $key => $value) { if (!empty($value)) { $res[] = $value; } } if (!empty($res)) { $filter = $res; } return $filter; } }<file_sep>/public/index.php <?php require_once __DIR__ . '/../vendor/autoload.php'; use TheRMTest\StringCalculator; $sc = new StringCalculator(); echo "Empty case: " . $sc->intAdd(''); // Add input here to check explicit input result echo "<br>"; echo "Single digit case: " . $sc->intAdd('1'); // Add input here to check explicit input result echo "<br>"; echo "Two digits case: " . $sc->intAdd('1,2'); // Add input here to check explicit input result echo "<br>"; echo "Multiple numbers case: " . $sc->intAdd('1,2,3,4,5,6'); // Add input here to check explicit input result echo "<br>"; echo "New line case: " . $sc->intAdd('1\n2,3'); // Add input here to check explicit input result echo "<br>"; echo "New delimiter case: " . $sc->intAdd('//:\n1:2'); // Add input here to check explicit input result echo "<br>"; try { $sc->intAdd('//:\n1:-2'); // Add input here to check explicit input result } catch (Exception $exception) { echo "Single negative digit case: " . $exception->getMessage(); } echo "<br>"; try { $sc->intAdd('//:\n1:-2:-3'); // Add input here to check explicit input result } catch (Exception $exception) { echo "Multiple negative digits case: " . $exception->getMessage(); } echo "<br>"; echo "Number greater than 1000 case: " . $sc->intAdd('//:\n1:2000:4'); // Add input here to check explicit input result echo "<br>"; echo "Compound delimiter case: " . $sc->intAdd('//***\n1***2***3'); // Add input here to check explicit input result echo "<br>"; echo "Multiple delimiters case: " . $sc->intAdd('//*%\n1*2%3'); // Add input here to check explicit input result echo "<br>"; echo "Compound multiple delimiters case: " . $sc->intAdd('//**%%\n1**2%%3'); // Add input here to check explicit input result echo "<br>"; echo "<br>"; echo "Total number of time intAdd is called: " . $sc->getCalledCount(); // Times the count function is called
143c076e0ad704932648a85e79be1b691046bb6f
[ "Markdown", "PHP" ]
4
PHP
xohail/TRM---Test
cd23baa581219083f3a8238e7b737bdc63bca2d6
b58c32f272cf9f16e7af0fb6638a76ceb3d38d71