branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>cryptobuks/BlockGamez<file_sep>/BlockGamez-Solutions/Bitcoin/GenerateAddresses/src/BitCoinWalletGenerate.java /** * Created by arjun on 1/14/17. */ public class BitCoinWalletGenerate implements WalletGenerateInterface { @Override public String privateToWif(byte[] privateKey) { byte[] newValue80Front = ByteUtil.Add80Byte(privateKey); //System.out.println("Add Byte 80 " + ByteUtil.byteArrayToHexString(newValue80Front)); byte[] newValue256 = ByteUtil.SHA256hash(newValue80Front); //System.out.println("SHA256 " + ByteUtil.byteArrayToHexString(newValue256)); byte[] newValue256Again = ByteUtil.SHA256hash(newValue256); //System.out.println("SHA256 Again " + ByteUtil.byteArrayToHexString(newValue256Again)); byte[] grabFourBytes = ByteUtil.GrabFirstFourBytes(newValue256Again); //System.out.println("GrabFirstFour " + ByteUtil.byteArrayToHexString(grabFourBytes)); byte[] keyAndCheckSum = ByteUtil.AddChecksumEndOfKey(newValue80Front,grabFourBytes); //System.out.println("Add Checksum " + ByteUtil.byteArrayToHexString(keyAndCheckSum)); String WIF = Base58.encode(keyAndCheckSum); System.out.println("Private Key WIF: " + WIF+"\n"); return WIF; } @Override public String publicToWif(byte[] publicKey) { byte[] newValue256 = ByteUtil.SHA256hash(publicKey); //System.out.println("SHA256 " + ByteUtil.byteArrayToHexString(newValue256)); byte[] newValue160 = ByteUtil.RIPEMD160(newValue256); //System.out.println("RIPEMD160 " + ByteUtil.byteArrayToHexString(newValue160)); byte[] newValueNetwork = ByteUtil.AddNetworkBytes(newValue160); //System.out.println("ADDBYTES " + ByteUtil.byteArrayToHexString(newValueNetwork)); byte[] re_SHA256_First = ByteUtil.SHA256hash(newValueNetwork); //System.out.println("SHA256Again " + ByteUtil.byteArrayToHexString(re_SHA256_First)); byte[] re_SHA256_Second = ByteUtil.SHA256hash(re_SHA256_First); //System.out.println("SHA256AgainSecondTime " + ByteUtil.byteArrayToHexString(re_SHA256_Second)); byte[] grabFourBytes = ByteUtil.GrabFirstFourBytes(re_SHA256_Second); //System.out.println("GrabFirstFour " + ByteUtil.byteArrayToHexString(grabFourBytes)); byte[] AddSeven = ByteUtil.AddSevenEndOfNetworkByte(grabFourBytes, newValueNetwork); //System.out.println("AddFourBytesToNetwork " + ByteUtil.byteArrayToHexString(AddSeven)); String WIF = Base58.encode(AddSeven); System.out.println("Public Key WIF " + WIF + "\n"); return WIF; } @Override public String WifToPrivate(String privateWIF) { byte[] privateByte = Base58.decode(privateWIF); byte[] trimmedByte = ByteUtil.RemoveLastFourBytes(privateByte); byte[] privateKey = ByteUtil.RemoveFirstByte(trimmedByte); return ByteUtil.byteArrayToHexString(privateKey); } @Override public String WifToPublic(String publicWIF) { byte[] publicByte = Base58.decode(publicWIF); return ByteUtil.byteArrayToHexString(publicByte); } } <file_sep>/BlockGamez-Android/BlockGamezAndroid/app/src/main/java/com/example/tief/blockgamezandroid/Address_Fragment.java package com.example.tief.blockgamezandroid; import android.content.Context; import android.net.Uri; import android.os.Bundle; 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.TextView; import org.spongycastle.asn1.sec.SECNamedCurves; import org.spongycastle.asn1.x9.X9ECParameters; import org.spongycastle.crypto.AsymmetricCipherKeyPair; import org.spongycastle.crypto.digests.RIPEMD160Digest; import org.spongycastle.crypto.digests.SHA256Digest; import org.spongycastle.crypto.generators.ECKeyPairGenerator; import org.spongycastle.crypto.params.ECDomainParameters; import org.spongycastle.crypto.params.ECKeyGenerationParameters; import org.spongycastle.crypto.params.ECPrivateKeyParameters; import org.spongycastle.crypto.params.ECPublicKeyParameters; import org.spongycastle.math.ec.ECFieldElement; import org.spongycastle.math.ec.ECPoint; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link Address_Fragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link Address_Fragment#newInstance} factory method to * create an instance of this fragment. */ public class Address_Fragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public Address_Fragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment Address_Fragment. */ // TODO: Rename and change types and number of parameters public static Address_Fragment newInstance(String param1, String param2) { Address_Fragment fragment = new Address_Fragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_transactions_, container, false); TextView test = (TextView)rootView.findViewById(R.id.test); try { test.setText(generatePubPriv()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return rootView; } public static String generatePubPriv() throws NoSuchAlgorithmException, IOException { X9ECParameters ecp = SECNamedCurves.getByName("secp256k1"); ECDomainParameters domainParams = new ECDomainParameters(ecp.getCurve(), ecp.getG(), ecp.getN(), ecp.getH(), ecp.getSeed()); // Generate a private key and a public key AsymmetricCipherKeyPair keyPair; ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(domainParams, new SecureRandom()); ECKeyPairGenerator generator = new ECKeyPairGenerator(); generator.init(keyGenParams); keyPair = generator.generateKeyPair(); ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.getPublic(); byte[] privateKeyBytes = privateKey.getD().toByteArray(); ECFieldElement getFirst = publicKey.getQ().getX(); ECFieldElement getSecond = publicKey.getQ().getY(); String finalPublic = "04" + getFirst.toString() + getSecond.toString(); System.out.println(""); // First print our generated private key and public key System.out.println("Private key: " + toHex(privateKeyBytes)); System.out.println("Public key: " + finalPublic); System.out.println(""); ECPoint dd = ecp.getG().multiply(privateKey.getD()); byte[] publickey=new byte[65]; System.arraycopy(dd.getY().toBigInteger().toByteArray(), 0, publickey, 64-dd.getY().toBigInteger().toByteArray().length+1, dd.getY().toBigInteger().toByteArray().length); System.arraycopy(dd.getX().toBigInteger().toByteArray(), 0, publickey, 32-dd.getX().toBigInteger().toByteArray().length+1, dd.getX().toBigInteger().toByteArray().length); publickey[0]=4; byte[] newValue256 = SHA256hash(publickey); System.out.println("SHA256 " + toHex(newValue256)); byte[] newValue160 = RIPEMD160(newValue256); System.out.println("RIPEMD160 " + toHex(newValue160)); byte[] newValueNetwork = AddNetworkBytes(newValue160); System.out.println("ADDBYTES " + toHex(newValueNetwork)); byte[] re_SHA256_First = SHA256hash(newValueNetwork); System.out.println("SHA256Again " + toHex(re_SHA256_First)); byte[] re_SHA256_Second = SHA256hash(re_SHA256_First); System.out.println("SHA256AgainSecondTime " + toHex(re_SHA256_Second)); byte[] grabFourBytes = GrabFirstFourBytes(re_SHA256_Second); System.out.println("GrabFirstFour " + toHex(grabFourBytes)); byte[] AddSeven = AddSevenEndOfNetworkByte(grabFourBytes, newValueNetwork); System.out.println("AddFourBytesToNetwork " + toHex(AddSeven)); String WIF = Base58.encode(AddSeven); System.out.println("Bitcoin Address " + WIF); return WIF; } public static String toHex(byte[] data) { StringBuilder sb = new StringBuilder(); for (byte b: data) { sb.append(String.format("%02x", b&0xff)); } return sb.toString(); } private static byte[] SHA256hash(byte[] enterKey){ SHA256Digest digester=new SHA256Digest(); byte[] retValue=new byte[digester.getDigestSize()]; digester.update(enterKey, 0, enterKey.length); digester.doFinal(retValue, 0); return retValue; } private static byte[] RIPEMD160(byte[] enterKey){ RIPEMD160Digest digester = new RIPEMD160Digest(); byte[] retValue=new byte[digester.getDigestSize()]; digester.update(enterKey, 0, enterKey.length); digester.doFinal(retValue, 0); return retValue; } private static byte[] AddNetworkBytes(byte[] enterKey){ byte[] networkByte = {(byte) 0x0 }; byte[] newByteArray = new byte[networkByte.length + enterKey.length]; System.arraycopy(networkByte, 0, newByteArray, 0, networkByte.length); System.arraycopy(enterKey, 0, newByteArray, networkByte.length, enterKey.length); return newByteArray; } private static byte[] GrabFirstFourBytes(byte[] enterKey){ byte[] firstFourBytes = new byte[4]; for(int i = 0; i < firstFourBytes.length; i++){ firstFourBytes[i] = enterKey[i]; } return firstFourBytes; } private static byte[] AddSevenEndOfNetworkByte(byte[] firstFour, byte[] NetworkByteArray){ byte[] newByteArray = new byte[NetworkByteArray.length + firstFour.length]; System.arraycopy(NetworkByteArray, 0, newByteArray, 0, NetworkByteArray.length); System.arraycopy(firstFour, 0, newByteArray, NetworkByteArray.length, firstFour.length); return newByteArray; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } } <file_sep>/BlockGamez-Solutions/Bitcoin/GenerateAddresses/test/GenerateTest.java import org.junit.jupiter.api.Test; import javax.xml.bind.DatatypeConverter; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import static org.junit.jupiter.api.Assertions.*; /** * Created by arjun on 12/17/16. */ class GenerateTest { @Test public void testGeneratePubPriv() throws NoSuchAlgorithmException, IOException, InvalidAlgorithmParameterException, NoSuchProviderException { Generate gen = new Generate(); gen.generatePubPriv("hello"); } @Test public void testPrivateWIFGenerate_1() throws NoSuchAlgorithmException, IOException { String sPrivateKey = "0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D"; byte[] bPrivateKey = DatatypeConverter.parseHexBinary(sPrivateKey); Generate test = new Generate(); String expectedWIF = "5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ"; String actualWif = test.privateToWif(bPrivateKey); assertEquals(expectedWIF,actualWif); } @Test public void testPublicWIFGenerate_1() { String sPublicKey = "<KEY>"; byte[] bPrivateKey = DatatypeConverter.parseHexBinary(sPublicKey); Generate test = new Generate(); String expectedWif = "1GAehh7TsJAHuUAeKZcXf5CnwuGuGgyX2S"; String actualWif = test.publicToWif(bPrivateKey); assertEquals(expectedWif,actualWif); } @Test public void testPrivateWIFGenerate_2()throws NoSuchAlgorithmException, IOException { String sPrivateKey = "<KEY>"; byte[] bPrivateKey = DatatypeConverter.parseHexBinary(sPrivateKey); Generate test = new Generate(); String expectedWIF = "5Kfzs14jFfRcAnLDitmzo61TZwFFxMXx3htdk8xzVTu7sjn7siW"; String actualWif = test.privateToWif(bPrivateKey); assertEquals(expectedWIF,actualWif); } @Test public void testPublicWIFGenerate_2() { String sPublicKey = "0406D851FDE3F8E78605D56C28D3F2184223FA1608B72F567275836EA798DC054D6DF314769A0CB73E508F9D76D88FDFD389D728FE3CAA905D92FF34AACC77369B"; byte[] bPrivateKey = DatatypeConverter.parseHexBinary(sPublicKey); Generate test = new Generate(); String expectedWif = "1PrDBFmTJWGGxWvf1LnnsgeUC7VsSQhPLW"; String actualWif = test.publicToWif(bPrivateKey); assertEquals(expectedWif,actualWif); } }<file_sep>/BlockGamez-Solutions/Bitcoin/SignedTransactions/README.txt This folder supplies solutions to Bitcoin & Ethereum Transaction Creation/Signing. Needed Dependencies to Run (~/BlockGamez/BlockGamez-Solutions/Dependencies): 1. Bouncy Castle: bcprov-ext-jdk15on-155.jar 2. Google Gson: gson-2.2.2.jar 3. BitcoinJ: bitcoinj-core-0.14.4-bundled.jar 4. junit-4.12.jar 5. junit-jupiter-api-5.0.0-M3.jar 6. opentest4j-1.0.0-M1.jar <file_sep>/BlockGamez-Solutions/Bitcoin/UnsignedTransactions/README.txt This project solution is to demostrate a simple transaction that is not signed, with just packing data into binary. <file_sep>/BlockGamez-Solutions/Ethereum/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.web3j</groupId> <artifactId>core</artifactId> <version>2.1.0</version> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <dependencies> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.5</version> </dependency> <!-- https://mvnrepository.com/artifact/com.github.jnr/jnr-unixsocket --> <dependency> <groupId>com.github.jnr</groupId> <artifactId>jnr-unixsocket</artifactId> <version>0.15</version> </dependency> <!-- https://mvnrepository.com/artifact/com.lambdaworks/scrypt --> <dependency> <groupId>com.lambdaworks</groupId> <artifactId>scrypt</artifactId> <version>1.4.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.squareup/javapoet --> <dependency> <groupId>com.squareup</groupId> <artifactId>javapoet</artifactId> <version>1.7.0</version> </dependency> <!-- https://mvnrepository.com/artifact/io.reactivex/rxjava --> <dependency> <groupId>io.reactivex</groupId> <artifactId>rxjava</artifactId> <version>1.2.4</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on --> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.54</version> </dependency> </dependencies> </project><file_sep>/BlockGamez-Solutions/Bitcoin/GenerateAddresses/README.txt This project solution is for generating Bitcoin private and public keys, as well as WIF. Included is Ethereum Address Generation as well. Needed Dependencies to Run (~/BlockGamez/BlockGamez-Solutions/Dependencies): 1. Bouncy Castle: bcprov-ext-jdk15on-155.jar 2. junit-4.12.jar 3. junit-jupiter-api-5.0.0-M3.jar 4. opentest4j-1.0.0-M1.jar
29414a387c96bda3d2ca901e9e3b2ba0304a3983
[ "Java", "Text", "Maven POM" ]
7
Java
cryptobuks/BlockGamez
96ef413f1c6cb4ce6edc115892b41485d0b9e406
9e90a31697698d1d1e3267c9606508a30ce55dc7
refs/heads/master
<repo_name>salinatservantez/Closest-Point<file_sep>/src/ClosestPoints.java /** * Description: This program finds the closest pair of points in a set Q of points using divide, conquer, and combine. * * @author <NAME> * @edu.uwp.cs.340.section001 * * @edu.uwp.cs.340.assignment4-ClosestPoints * * @bugs none */ import java.io.File; import java.util.ArrayList; import java.util.Scanner; public class ClosestPoints { public static class Point{ private double x; private double y; /** * Constructor for a 2d point * @param x * @param y */ private Point(double x, double y){ this.x = x; this.y = y; } @Override public String toString(){ return "(" + x + ")" + "'" + "(" + y + ")"; } } /** * Main Method that prompts user for a file to be read, putting x and y as doubles * @param args * @throws Exception */ public static void main(String [] args) throws Exception{ // User input for the filename Scanner input = new Scanner(System.in); System.out.print("Enter the file to be read: "); String filename = input.next(); Scanner fileIn = new Scanner(new File(filename)); ArrayList<Point> xPoints = new ArrayList<>(); ArrayList<Point> yPoints = new ArrayList<>(); // Read in each point from the file while(fileIn.hasNextLine()){ // Read in as a string String line = fileIn.nextLine(); // Split the string into the x and y value String[] numbers = line.split(" "); double x = Double.parseDouble(numbers[0]); double y = Double.parseDouble(numbers[1]); // Create the point and add it to both lists Point p = new Point(x, y); xPoints.add(p); yPoints.add(p); } // Sort each list into ascending order by both x values and y values sortX(xPoints); sortY(yPoints); // If there is only one point if(xPoints.size() <= 1) { System.out.println("Not enough points to calculate distance"); } // If there is less than 3 points use the brute force method else if (xPoints.size() <= 3){ // Find the closest points Point[] pPair = bruteForce(xPoints); // Print out the points and the distance between them System.out.println("Closest Point"); System.out.println(pPair[0]); System.out.println(pPair[1]); System.out.println("Distance between them is: " + dist(pPair[0], pPair[1])); } else { // Find the closest points using the recursive method Point[] pPair = closest(xPoints, yPoints); System.out.println("Closest Point"); System.out.println(pPair[0]); System.out.println(pPair[1]); System.out.println("Distance between them is: " + dist(pPair[0], pPair[1])); } } /** * the bruteForce method looks at all the possible pairs of points. Since there are Θ (n2) pairs, the brute algorithm is Θ (n2) . * Here we describe a divide and conquer algorithm that is Θ (n lg n)If X contains 3 or fewer elements, it calculates the distance * between all pairs and return the pair that has the smallest distance. * @param points * @return */ public static Point [] bruteForce(ArrayList<Point> points){ Point[] pPair = new Point[2]; // Default the smallest distance to the max value so the first iteration has something to compare to double smallDist = Double.MAX_VALUE; // Grab the first point for(Point p: points){ // Compare to a second point for(Point p2: points){ if(!(p.x == p2.x)){ //If the new distance is smaller make it the new smallest double distance = dist(p, p2); if(smallDist > distance){ pPair[0] = p; pPair[1] = p2; smallDist = distance; } } } } return pPair; } /** * Find the distance between 2 points * @param p1 * @param p2 * @return */ public static double dist(Point p1, Point p2){ return Math.sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y)); } /** * Sort an array of points in ascending x order * @param points */ public static void sortX(ArrayList<Point> points){ points.sort((Point p1, Point p2) -> { if(p1.x < p2.x) return -1; else if (p1.x > p2.x) return 1; else return 0; }); } /** * Sort an array into ascending y order * @param points */ public static void sortY(ArrayList<Point> points) { points.sort((Point p1, Point p2) -> { if (p1.y < p2.y) return -1; else if (p1.y > p2.y) return 1; else return 0; }); } /** * This method splits points into arraylists and recursively calls the method, finds closest point to eachother even along the line * @param xPoints * @param yPoints * @return */ public static Point[] closest(ArrayList<Point> xPoints, ArrayList<Point> yPoints){ // If there are less than 3 points brute force the answer if(xPoints.size() <= 3){ return bruteForce(xPoints); } // Find the midpoint and split x into two arraylists int midIndex = xPoints.size()/2; Point midPoint = xPoints.get(xPoints.size()/2); ArrayList<Point> xlPoints = new ArrayList<>(xPoints.subList(0,midIndex)); ArrayList<Point> xrPoints = new ArrayList<>(xPoints.subList(midIndex, xPoints.size())); ArrayList<Point> ylPoints = new ArrayList<>(); ArrayList<Point> yrPoints = new ArrayList<>(); // Split the y arraylist into two arraylists for(Point p : yPoints){ if(p.x < midPoint.x) ylPoints.add(p); else yrPoints.add(p); } // Recursively call the method Point[] pPair1 = closest(xlPoints, ylPoints); Point[] pPair2 = closest(xrPoints, yrPoints); Point[] pClose; // See what the smaller distance between each half is and make it the smallest distance set of points double dist = min(dist(pPair1[0], pPair1[1]), dist(pPair2[0], pPair2[1])); if (dist(pPair1[0], pPair1[1]) == dist){ pClose = pPair1; } else { pClose = pPair2; } // Add all points that are less than the distance from the midpoint to an arraylist ArrayList<Point> linePoints = new ArrayList<>(); for (Point p: yPoints){ if (Math.abs(p.x - midPoint.x) < dist) linePoints.add(p); } // Compare points on each side of the line for(int i = 0; i < linePoints.size(); ++i) for (int j = i+1; j < linePoints.size() && (j - i) <= 5; ++j) if (dist(linePoints.get(i),linePoints.get(j)) < dist) { dist = dist(linePoints.get(j), linePoints.get(i)); pClose[0] = linePoints.get(j); pClose[1] = linePoints.get(i); } return pClose; } /** * Find the min between 2 numbers * @param x * @param y * @return */ public static double min(double x, double y){ if(x<y) return x; else return y; } }
2b34088a3145c9b52d9193f0e4b81ccda408cd9b
[ "Java" ]
1
Java
salinatservantez/Closest-Point
c0e9a0703d85490964acb1a45e643f0e346a87da
a0676a56c97f78a60fe37f6ba1d7ea02ad2b34dd
refs/heads/master
<file_sep># Voices Name Correspondence List Extractor # comes with ABSOLUTELY NO WARRANTY. # Copyright (C) 2016 Hintay <<EMAIL>> # FSN support by Quibi # # 提取语音名称与角色对应的列表 import os import sys import codecs import argparse route_list = { # Fate/stay night 'プロローグ1日目': 'prg01', 'プロローグ2日目': 'prg02', 'プロローグ3日目': 'prg03', 'セイバーエピローグ': 'savep', '凛エピローグ': 'rinep', '凛エピローグ2': 'rinep2', '桜エピローグ': 'sakep', '桜エピローグ2': 'sakep2', 'タイガー道場すぺしゃる': 'tigsp', 'ラストエピソード': 'lstep', # Fate/hollow ataraxia 'カレン': 'KAREN', '合宿編': 'CAMPH', '夜編1': 'NGH01', '夜編2': 'NGH02', '学校・1日目': 'SCH01', '学校・2日目': 'SCH02', '学校・3日目': 'SCH03', '学校・4日目': 'SCH04', '柳洞寺・1日目': 'RUY01', '柳洞寺・2日目': 'RUY02', '柳洞寺・3日目': 'RUY03', '柳洞寺・4日目': 'RUY04', '真・冒頭': 'SNPLG', 'ランサー港': 'LANCR', '街・特別編': 'CTYEH', '街編・1日目': 'CTY01', '街編・2日目': 'CTY02', '街編・3日目': 'CTY03', '街編・4日目': 'CTY04', '衛宮邸・1日目': 'EMI01', '衛宮邸・2日目': 'EMI02', '衛宮邸・3日目': 'EMI03', '衛宮邸・4日目': 'EMI04', '衛宮邸・夜マップ': 'EMIMP', '衛宮邸・夜開始': 'EMING', '裏マップ': 'MAPEC', '魔境編': 'MAKYO' } # Fate/stay night fsn_routes = ['セイバー', '凛', '桜'] routes_to_days = {'セイバー': 15, '凛': 14, '桜': 16} routes_to_names = {'セイバー': 'sav', '凛': 'rin', '桜': 'sak'} days = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六'] for fsn_route in fsn_routes: days_count = routes_to_days[fsn_route] for i, day in enumerate(days[:days_count]): route_list[f'{fsn_route}ルート{day}日目'] = f'{routes_to_names[fsn_route]}{i+1:02}' class VoiceFile: def __init__(self): self.voice_filename = {} def loop_file(self, filename): basename = os.path.splitext(filename)[0] basename_split = basename.split('-') if len(basename_split) < 2: route_with_day = basename scene_number = '' else: route_with_day = basename_split[0] scene_number = basename_split[1] fs = open(filename, 'rb') text = fs.read() lines = text.split(b';') for line in lines: if line[:5] == b'_VPLY': voices = line[6:].decode().split(',') character = voices[0] voice_number = voices[1] if voice_number in self.voice_filename: continue self.voice_filename[voice_number] = [route_list[route_with_day], scene_number, character] fs.close() def output_file(self): fs = codecs.open('voices.py', 'w', 'utf-8') # 文本方式打开 sorted_filename = sorted(self.voice_filename.items(), key=lambda d: d[0], reverse=False) new_filename = '{\n' for item in sorted_filename: new_filename += "\t'" + item[0] + "': " + str(item[1]) + ",\n" new_filename += '}' fs.write(new_filename) # fs.write(repr(self.voice_filename)) fs.close() def parse_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('input', metavar='input', help='input .ini file or folder') return parser, parser.parse_args() def extract_verb(args): if not os.path.exists(args.input): parser.print_usage() print('Error: the following file or folder does not exist: ' + args.input) sys.exit(20) voices = VoiceFile() os.chdir(args.input) for file in os.listdir('.'): if file.endswith('ini'): voices.loop_file(file) voices.output_file() if __name__ == '__main__': parser, args = parse_args() if args.input is not None: extract_verb(args) else: parser.print_usage() sys.exit(20) sys.exit(0) <file_sep># Voice File Names Renamer # comes with ABSOLUTELY NO WARRANTY. # Copyright (C) 2016-2018 Hintay <<EMAIL>> # # 批量修改语音文件名 from extra.voices_character import * import sys import logging from pathlib import Path BASE_PATH = Path('.') VOICE_PATH = (BASE_PATH.joinpath('voice1'), BASE_PATH.joinpath('voice2')) VOICES_SUFFIX = '.at9' hex_files = {'voice1': Path('03e5a'), 'voice2': Path('04e21')} old_special_files = {'voice1': Path('KARE-000002'), 'voice2': Path('MAKY-0002')} # Config Logger logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') logger = logging.getLogger('VOICE_RENAME') fileLog = logging.FileHandler('rename.log', 'w', 'utf-8') formatter = logging.Formatter('%(levelname)s: %(message)s') fileLog.setFormatter(formatter) logger.addHandler(fileLog) class ChangeVoiceName: def __init__(self, folder): logger.info("Processing directory %s" % folder) self.folder = folder self.hex_mod = folder.joinpath(hex_files[folder.stem]).with_suffix(VOICES_SUFFIX).exists() self.need_shrine_fix = folder.joinpath(Path('EMA_01_ARC_0000')).with_suffix(VOICES_SUFFIX).exists() is_from_old_extractor = folder.joinpath(old_special_files[folder.stem]).with_suffix(VOICES_SUFFIX).exists() self.special_name = special_name_old if is_from_old_extractor else special_name self.rename_files() def rename_files(self): for file in self.folder.glob('**/*{ext}'.format(ext=VOICES_SUFFIX)): if self.need_shrine_fix: if self.shrine_fix(file): continue voice_number = self.match_number(file.stem) try: if self.hex_mod: if len(voice_number) == 4: continue # 四位数则跳过(0000、0010这种) voice_number = int(voice_number, 16) else: voice_number = int(voice_number) if self.folder.stem == 'voice2': voice_number += 20000 hex_number = '%05x' % voice_number self.rename_file(file, hex_number) except ValueError: # 字母等 continue @staticmethod def rename_file(file, hex_number): voice_name = voices_list.get(hex_number, '') if voice_name: if len(voice_name) == 4: if voice_name[0] == '': new_name = '%s_%s' % (voice_name[2], voice_name[3]) elif voice_name[0] == 'EMA_' or voice_name[0] == 'KUJI': new_name = '%s_%s_%s_%s' % (voice_name[0], voice_name[1], voice_name[2], voice_name[3]) else: new_name = '%s%s_%s_%s' % (voice_name[0], voice_name[1], voice_name[2], voice_name[3]) else: new_name = '%s%s_%s_%s' % (voice_name[0], voice_name[1], voice_name[2], hex_number) # new_name = '%s_%s' % (voice_name[2], hex_number) else: new_name = hex_number new_file = file.with_name(new_name).with_suffix(VOICES_SUFFIX) if file == new_file: return try: logger.info('>> Rename %s to %s' % (file.name, new_file.name)) file.rename(new_file) except WindowsError: logger.error(' Rename FAILED!') # 用于修复前期脚本所导致的问题文件名 @staticmethod def shrine_fix(file): if (file.name.startswith('EMA_') and file.name[4] != '_') or ( file.name.startswith('KUJI') and (file.name[4] != '_' and file.name[4] != 'F')): new_name = file.name[:4] + '_' + file.name[4:] new_file = file.with_name(new_name).with_suffix(VOICES_SUFFIX) try: logger.info('>> [Shrine Fix] Rename %s to %s' % (file.name, new_file.name)) file.rename(new_file) except WindowsError: logger.error(' Rename FAILED!') return True else: return False def match_number(self, file_name): if self.hex_mod: name_split = file_name.split('_') else: name_split = file_name.split('-') if len(name_split) > 1: voice_number = name_split[-1] else: voice_number = self.special_name[self.folder.stem].get(file_name, file_name) return voice_number if __name__ == '__main__': for voice_path in VOICE_PATH: if not voice_path.exists(): logger.error('please change BASE_PATH to the outer layer of the voice and voice2 folder.') sys.exit(20) for voice_path in VOICE_PATH: ChangeVoiceName(voice_path) logger.info("DONE!") <file_sep># Vita Scenarios Tools Vita scenarios converter and tools for "HuneX" game engine. Test for FHA and FSN in Vita. # Usage ## Vita Scenarios Converter comes with ABSOLUTELY NO WARRANTY. ``` usage: psvstool.py [-h] input positional arguments: input input .ini file or folder optional arguments: -h, --help show this help message and exit ``` ## Voices Name Correspondence List Extractor comes with ABSOLUTELY NO WARRANTY. *Only for FSN and FHA in Vita.* ``` usage: extract_voices_list.py [-h] input positional arguments: input input .ini file or folder optional arguments: -h, --help show this help message and exit ``` ## Voice Filenames List from Ema Scene Extractor comes with ABSOLUTELY NO WARRANTY. *This script is only for Vita FHA.* ``` usage: extract_voices_list_from_ema.py [-h] input positional arguments: input input .ini file or folder optional arguments: -h, --help show this help message and exit ``` ## Voice Filenames Renamer comes with ABSOLUTELY NO WARRANTY. Rename indexed filenames for voices from Vita to regular. Please change `BASE_PATH` to your voices folder path that include `voice` and `voice2` folder. ## TROPHY.TRP Extractor comes with ABSOLUTELY NO WARRANTY. Python version for TROPHY.TRP Extractor, the original C version code by Red Squirrel. ``` usage: trpex.py [-h] input_file output_folder positional arguments: input_file path of your TROPHY.TRP. output_folder output folder. optional arguments: -h, --help show this help message and exit ```
1c0f55774190551cd33267a5628da792c7d11209
[ "Markdown", "Python" ]
3
Python
Ultimate-Moon/VitaScenariosTool
3d6731471a0c104d12bd4ce05416545b6cb6a896
3136193c119344646070fd2c29f5a78a622a36d4
refs/heads/main
<repo_name>vvpn9/Machine-Learning-Basics<file_sep>/Spam Filter/Naive Bayesian Model.py import os def fileWalker(path): fileArray = [] for roots, dirs, files in os.walk(path): for fn in files: eachpath = str(roots + '/' + fn) fileArray.append(eachpath) # print(fileArray) return fileArray # fileWalker('/Users/zw/Desktop/Data Learning/Machine Learning Basics/Spam Filter') def readText(path, encoding): with open(path, 'r', encoding=encoding) as f: lines = f.readlines() # print(lines) return lines # readText('/Users/zw/Desktop/Data Learning/Machine Learning Basics/Spam Filter/ham/1.txt', # encoding='utf-8') def email_parser(email_path): punctuations = """,.<>()*&^%$#@!'";~`[]{}|、\\/~+_-=?""" content_list = readText(email_path, 'utf-8') content = (' '.join(content_list)).replace('\r\n', ' ').replace('\t', ' ') # LF, CR, HT clean_word = [] for punctuation in punctuations: content = (' '.join(content.split(punctuation))).replace(' ', ' ') clean_word = [word.lower for word in content.split(' ') if len(word) >= 2] # print(clean_word) return clean_word # email_parser('/Users/zw/Desktop/Data Learning/Machine Learning Basics/Spam Filter/ham/1.txt') def get_word(email_file): word_list = [] word_set = [] email_paths = fileWalker(email_file) for each_email_path in email_paths: clean_word = email_parser(each_email_path) word_list.append(clean_word) word_set.extend(clean_word) return word_list, set(word_set) get_word('/Users/zw/Desktop/Data Learning/Machine Learning Basics/Spam Filter/ham/1.txt')<file_sep>/Titanic Test/Titanic_Test2.py #!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd # In[2]: from sklearn.linear_model import LogisticRegression # In[3]: from sklearn.model_selection import train_test_split # In[4]: from sklearn.metrics import classification_report # In[5]: titanic_df = pd.read_csv('train.csv') # In[6]: titanic_df = titanic_df.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1) # In[7]: titanic_df.info() # In[8]: titanic_df.head(10) # In[9]: titanic_df['AgeIsMissing'] = 0 # In[10]: titanic_df.loc[titanic_df.Age.isnull(), 'AgeIsMissing'] = 1 # In[11]: titanic_df.head(10) # In[12]: age_mean = round(titanic_df['Age'].mean()) # In[13]: age_mean # In[14]: titanic_df.Age.fillna(age_mean, inplace=True) # In[15]: titanic_df.info() # In[16]: titanic_df.Embarked.fillna('S', inplace=True) # In[17]: titanic_df.info() # In[18]: cut_points = [0,18,25,40,60,100] # In[19]: titanic_df['Age_bin'] = pd.cut(titanic_df.Age, bins=cut_points) # In[20]: titanic_df.head() # In[21]: titanic_df['Fare_bin'] = pd.qcut(titanic_df.Fare, 5) # In[22]: titanic_df.Fare_bin.unique() # In[23]: titanic_df.head() # In[24]: titanic_df['FamilySize'] = titanic_df['SibSp'] + titanic_df['Parch'] + 1 # In[25]: titanic_df.head() # In[26]: titanic_df['IsAlone'] = 0 # In[27]: titanic_df.loc[titanic_df['FamilySize'] == 1, 'IsAlone'] = 1 # In[28]: titanic_df.head() # In[29]: pd.crosstab(titanic_df.Survived,titanic_df.IsAlone).apply(lambda a:a/a.sum(),axis=0) # In[30]: titanic_df['IsMother'] = 0 # In[31]: titanic_df.loc[(titanic_df['Sex']=='female') & (titanic_df['Parch']>0) & (titanic_df['Age']>20), 'IsMother'] = 1 # In[32]: titanic_df.head() # In[33]: pd.crosstab(titanic_df.Survived,titanic_df.IsMother).apply(lambda a:a/a.sum(),axis=0) # In[34]: titanic_df['SexAge_Combo'] = titanic_df['Sex'] + "_" + titanic_df['Age_bin'].astype(str) # In[35]: titanic_df.head() # In[36]: titanic_df.info() # In[37]: Pclass = pd.get_dummies(titanic_df.Pclass,prefix='Pclass') # In[38]: Sex = pd.get_dummies(titanic_df.Sex,prefix='Sex') # In[39]: Embarked = pd.get_dummies(titanic_df.Embarked,prefix='Embarked') # In[40]: Age_bin = pd.get_dummies(titanic_df.Age_bin,prefix='Age_bin') # In[41]: Fare_bin = pd.get_dummies(titanic_df.Fare_bin,prefix='Fare_bin') # In[42]: FamilySize = pd.get_dummies(titanic_df.FamilySize,prefix='FamilySize') # In[43]: SexAge_Combo = pd.get_dummies(titanic_df.SexAge_Combo,prefix='SexAge_Combo') # In[44]: TrainData=pd.concat([titanic_df[['Survived','AgeIsMissing','IsAlone','IsMother']],Pclass,Sex,Embarked,Age_bin,Fare_bin,FamilySize,SexAge_Combo],axis=1) # In[45]: TrainData.head(10) # In[46]: TrainData.info() # In[47]: # as such we prepare the data for training # In[48]: TrainData_X = TrainData.drop(['Survived'], axis=1) # In[49]: TrainData_X.head() # In[50]: TrainData_y = TrainData.Survived # In[51]: TrainData_y # In[52]: X_train, X_test, y_train, y_test = train_test_split(TrainData_X, TrainData_y, test_size = 0.3, random_state=123456) # In[53]: lr = LogisticRegression(solver='liblinear') # In[54]: lr.fit(X_train, y_train) # In[55]: y_test_pred = lr.predict(X_test) # In[56]: print(classification_report(y_test, y_test_pred)) # In[57]: # Now we already have a model to predict <file_sep>/first forecasting model.md from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report ## 数据预处理 # 1. 读取原始数据 X容易获得,但是y(标注的数据)难以获得。 数据的实时产生,针对批量数据建模就是批量学习,针对实时数据建模就叫在线学习,一般情况下都用增量数据进行模型训练, 故又叫增量学习。 # 2. 各种数据预处理 数据清洗:例如缺失值的处理 特征构造:从原始数据中加工提取出有用的特征变量 特征转换:标准化,归一化,独热编码 特征筛选:丢弃掉一些不要的特征变量,数据预处理对模型的性能影响巨大,它决定了模型性能的上限,算法只是逼近这个上限。 # 3. 构造一张集成好的数据大宽表 ## 模型训练 不存在一招鲜吃遍天,不同场合运用不同算法模型 # 1. 数据格式 X_train是一个二维矩阵,存放m行样本,拥有n行特征 y_train是一个长度为m的一维数组 X_train和y_train的长度必须一致 # 2. 数据集拆分 训练模型用X_train和y_train,评估模型用X_test和y_test。 train和test是通过数据集的随机拆分完成的 —> test_size = (0 < something < 1) # 3. 模型的评估 方法:交叉验证(一部分数据集来训练,一部分数据集来做测试) 性能需要被评估,但模型评估不能使用训练集,必须在绝对没有参与模型训练的测试集上进行评估测试。 最常用的评估指标是正确率,但有时候只看正确率无法对模型进行全面评估。还有诸如以下的评估标准: 1. 误分类矩阵 2. 准确率,召回率,F1 Score等 3. ROC曲线,AUC值 4. Lorenz曲线 5. KS曲线,KS值 ## 对新数据做出预测(模型上线) 分为:离线训练和在线预测 模型一般都是在离线模式下完成的。 模型训练是一个不断迭代的过程,需要训练到满意位置,一旦确认模型准备完成则称为模型上线或者模型部署。 模型预测往往应用的时候都是在线的。 1. 对新数据进行同样的数据预处理工作 2. 利用训练好的模型对新数据进行预测 3. 预测结果保存为文件<file_sep>/Customer Loss/Possible use of model(s).md After the model is built locally, the model is ready for further uses. Here are some examples: 1. Offline training and test online. 2. Warp the model as a function and provides api(s). 3. Encapsulate the model as a Jar 4. C/S 5. model-based RL or model-free RL<file_sep>/Customer Loss/Customer_Loss1.py #!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt df = pd.read_csv('churn.csv') col_names = df.columns.tolist() print('Column names:') print(col_names) print(df.shape) # In[2]: df.head() # In[3]: df.info() # In[4]: df.describe() # In[5]: df['Churn?'].value_counts() # In[6]: df['CustServ Calls'].value_counts() # In[7]: get_ipython().run_line_magic('matplotlib', 'inline') fig = plt.figure() fig.set(alpha=0.2) plt.subplot2grid((2,3),(0,0)) df['Churn?'].value_counts().plot(kind='bar') plt.title('Customer Loss Percent') plt.ylabel('Number') plt.xlabel('Whether loss or not') plt.subplot2grid((2,3),(0,2)) df['CustServ Calls'].value_counts().plot(kind='bar') plt.title('Customer Service Call Statistics') plt.ylabel('Call Numbers') plt.xlabel('Frequency') plt.show() # In[8]: plt.subplot2grid((2,5),(0,0)) df['Day Mins'].plot(kind='kde') plt.xlabel('Mins') plt.ylabel('Density') plt.title('Dis for day mins') plt.subplot2grid((2,5),(0,2)) df['Day Calls'].plot(kind='kde') plt.xlabel("Call") plt.ylabel("Density") plt.title("Dis for day calls") plt.subplot2grid((2,5),(0,4)) df['Day Charge'].plot(kind='kde') plt.xlabel("Charge") plt.ylabel("density") plt.title("dis for day charge") plt.show() # In[9]: # We can see that, all plots above show the shape of normal distribution. # Here, kde stands for kernel density estimation # In[10]: # Here, we wanna discover the relationship between the Int'I Plan and Churn? # In[11]: int_yes = df['Churn?'][df['Int\'l Plan'] == 'yes'].value_counts() int_yes # In[12]: int_no = df['Churn?'][df['Int\'l Plan'] == 'no'].value_counts() int_no # In[13]: type(int_yes) # In[14]: df_int=pd.DataFrame({u'int plan':int_yes, u'no int plan':int_no}) df_int # In[15]: # Then, if we want to visualize the crosstale above df_int.plot(kind='bar', stacked=True) plt.title('International Long Distance Plan Whether Lost or Not') plt.xlabel('Int or not') plt.ylabel('Number') plt.show() # In[16]: cus_0 = df['CustServ Calls'][df['Churn?'] == 'False.'].value_counts() cus_1 = df['CustServ Calls'][df['Churn?'] == 'True.'].value_counts() df_cus=pd.DataFrame({u'churn':cus_1,u'retain':cus_0}) df_cus # In[17]: df_cus.plot(kind='bar',stacked=True) plt.title('Relationship between Customer Service Complaint Phone Number and' 'Customer Churn Rate') plt.xlabel('Call Service') plt.ylabel('Num') plt.show() # In[18]: # So data is not suitable for further analysis, so we need to tranform # them into 0/1 type ds_result = df['Churn?'] y = np.where(ds_result == 'True.',1,0) # here not 1.0, but 1, 0 dummies_int = pd.get_dummies(df["Int\'l Plan"], prefix="_Int\' Plan") dummies_voice = pd.get_dummies(df['VMail Plan'], prefix='VMail') ds_tmp=pd.concat([df, dummies_int, dummies_voice], axis=1) ds_tmp.head() # In[19]: y # In[20]: to_drop = ['State','Area Code','Phone','Churn?', 'Int\'l Plan', 'VMail Plan'] df = ds_tmp.drop(to_drop,axis=1) # In[21]: print("after trans: ") df.head(5) # In[22]: X = df.values.astype(np.float) X # In[23]: scaler = StandardScaler() X = scaler.fit_transform(X) X # In[24]: X.shape # In[25]: print("Feature space holds %d observations and %d features" % X.shape) # In[27]: print("Unique target labels:", np.unique(y)) # In[28]: print(X[0]) # In[34]: y[0] # In[ ]: <file_sep>/README.md # Machine-Learning-Basics A path to get a rough view of ML based on macOS Version 11.2.1 (20D74) M1 chip <file_sep>/first glance at sklearn.py from sklearn import datasets print(datasets.load_iris)
72efb0a7759994b079a4140eabe48669136c5458
[ "Markdown", "Python" ]
7
Python
vvpn9/Machine-Learning-Basics
c799cabd695ee0980b27d6bb5279c7fbff282077
aab3585a452e6aa83c22f2c95e2feac0ffdb79b3
refs/heads/master
<repo_name>rca/sbonrails<file_sep>/config/routes.rb ActionController::Routing::Routes.draw do |map| map.resources :events map.presentation_ideas "/presentations/ideas", :controller => 'presentations', :action => 'ideas' map.upcoming_presentations "/presentations/upcomng", :controller => 'presentations', :action => 'upcoming' map.past_presentations "/presentations/past", :controller => 'presentations', :action => 'past' map.resources :presentations map.resources :likes map.resource :session map.resources :events map.sign_up 'sign_up', :controller => 'users', :action => 'new' map.sign_in 'sign_in', :controller => 'sessions', :action => 'new' map.sign_out 'sign_out', :controller => 'sessions', :action => 'destroy', :method => :delete Clearance::Routes.draw(map) map.root :controller => 'home' map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end <file_sep>/app/helpers/application_helper.rb # Methods added to this helper will be available to all templates in the application. module ApplicationHelper def render_flash html = "<div id='flash'>" flash.each do |key, value| html += "<div id='flash_#{key}'> #{value} </div>" end html += "</div>" end end <file_sep>/public/javascripts/behaviors.js $(document).ready(function() { /* ------------------------ FOR LIKING A PRESENTATION IDEA ---------------------------*/ $('.like').click( function(e) { var obj = $(this); var id = obj.extract_id(); data = "like[presentation_id]=" + id; $.post('/likes/create',data, function(data) { if (data === "success") { var span = obj.next('span.num-likes') var insert = parseInt( span.html() ) + 1; obj.addClass('already-liked'); obj.removeClass('like'); span.html(insert); } }); return false; }); //$('.already-liked').click( function(e) { return false; } ); /* ------------------------ FADING FORM LABELS -----------------------*/ $('.special-labels input').each( function() { var obj = $(this); var label = obj.prev('label'); if ( obj.val().length > 0) { label.hide(); } }); $('.special-labels input').focus(function () { $(this).prev('label').addClass('faded'); }); $('.special-labels input').blur(function () { $(this).prev('label').removeClass('faded'); }); $('.special-labels input').keyup(function (e) { var obj = $(this); var label = obj.prev('label'); if ( obj.val().length == 0 && !label.is(":visible") ) { label.show(); } else if ( obj.val().length > 0 && label.is (":visible") ) { label.hide(); } }); $('.special-labels textarea').each( function() { var obj = $(this); var label = obj.prev('label'); if ( obj.val().length > 0) { label.hide(); } }); $('.special-labels textarea').focus(function () { $(this).prev('label').addClass('faded'); }); $('.special-labels textarea').blur(function () { $(this).prev('label').removeClass('faded'); }); $('.special-labels textarea').keyup(function (e) { var obj = $(this); var label = obj.prev('label'); if ( obj.val().length == 0 && !label.is(":visible") ) { label.show(); } else if ( obj.val().length > 0 && label.is (":visible") ) { label.hide(); } }); }); <file_sep>/features/step_definitions/like_steps.rb Given /^"(.+)" has (.+) likes$/ do |title,num_likes| presentation = Presentation.find_by_title(title) num_likes.to_i.times do |i| Like.create(:user_id => i, :presentation_id => presentation.id) end presentation.num_likes num_likes.to_i assert_equal presentation.num_likes, num_likes.to_i end <file_sep>/config/environment.rb RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| config.gem 'compass', :version => '>= 0.8.17' config.gem 'haml', :version => '>=2.2.16' config.gem "clearance" config.time_zone = 'UTC' end ActionMailer::Base.smtp_settings = { :enable_starttls_auto => true, :address => "smtp.gmail.com", :port => "587", :domain => "gmail.com", :authentication => :plain, :user_name => "santabarbara.railsgroup", :password => "<PASSWORD>" } <file_sep>/test/unit/user_test.rb require 'test_helper' class UserTest < ActiveSupport::TestCase should_have_many :presentations, :created_presentations, :likes, :liked_presentation_ideas context "users who like some presentations" do setup do @user1 = Factory(:email_confirmed_user, :email => '<EMAIL>') @user2 = Factory(:email_confirmed_user, :email => '<EMAIL>') @user3 = Factory(:email_confirmed_user, :email => '<EMAIL>') @presentation_idea1 = Factory(:presentation_idea) @presentation_idea2 = Factory(:presentation_idea) @presentation_idea3 = Factory(:presentation_idea) end # .likes?(presentation) should "return false when user doesnt like presentation" do assert [email protected]?(@presentation_idea1) end should "return true when user does like presentation" do Like.create(:user => @user1, :presentation => @presentation_idea1 ) assert @user1.likes?(@presentation_idea1) end end end <file_sep>/app/controllers/home_controller.rb class HomeController < ApplicationController def index @presentation_ideas = Presentation.sorted_by_likes_slow(:limit => 5) @liked_ideas = current_user.liked_presentation_ideas if current_user @events = Event.all end end <file_sep>/README.markdown # SBonRails This is the source code for the Santa Barbara Rails Group website, [sbonrails.com](http://sbonrails.com). ## Getting up and running ### Requirements sbonrails is built and managed primarily the following: * Ruby 1.8.x * Rubygems 1.3.5 * Ruby on Rails 2.3.5 * MySQL * git ### Gem Requirements * compass * haml * thoughtbot-shoulda * factory_girl * clearance * cucumber-rails * database_cleaner * webrat ### Initial setup Before anything else, change into the newly created `sbonrails` directory. cd sbonrails We need to make sure all the gem dependencies are installed: rake gems:install rake gems:install RAILS_ENV=test Now we need to create an initial database. We currently assume you have MySQL installed, and that you can login as 'root' without a password. rake db:create Next migrate the database to the latest version: rake db:migrate At last, we can run the server: script/server This will keep running until you hit Control-C, but now you can open a browser and go to http://localhost:3000 to see the app running. ## Testing We are using shoulda & cucumber for our testing. Before running them, you need to run the following to create the test database: rake db:create RAILS_ENV=test At this point, you can run them with: rake test We are also using cucumber for user stories / integration testing. You can run them with: rake features ## Contributing You should go through the steps lined out in 'Getting up and running'. To contribute, you should fork on GitHub, make your changes, and then either comment on an existing issue pointing at your changes, or create a new issue if it's a new bug or feature. ## Contributors Design by <NAME>. <file_sep>/test/unit/presentation_test.rb require 'test_helper' class PresentationTest < ActiveSupport::TestCase should_belong_to :presenter, :owner should_have_many :likes, :users_who_like_this should_validate_presence_of :title, :owner_id context "users who like some presentations" do setup do @user1 = Factory(:email_confirmed_user, :email => '<EMAIL>') @user2 = Factory(:email_confirmed_user, :email => '<EMAIL>') @user3 = Factory(:email_confirmed_user, :email => '<EMAIL>') @user4 = Factory(:email_confirmed_user, :email => '<EMAIL>') @user5 = Factory(:email_confirmed_user, :email => '<EMAIL>') @user6 = Factory(:email_confirmed_user, :email => '<EMAIL>') @presentation_idea1 = Factory(:presentation_idea, :created_at => Time.now - 1.year ) @presentation_idea2 = Factory(:presentation_idea, :created_at => Time.now - 2.months ) @presentation_idea3 = Factory(:presentation_idea, :created_at => Time.now - 3.months ) @presentation_idea4 = Factory(:presentation_idea) @presentation_idea5 = Factory(:presentation_idea) Like.create(:user => @user1, :presentation => @presentation_idea1) Like.create(:user => @user2, :presentation => @presentation_idea1) Like.create(:user => @user3, :presentation => @presentation_idea1) Like.create(:user => @user2, :presentation => @presentation_idea2) Like.create(:user => @user3, :presentation => @presentation_idea2) Like.create(:user => @user3, :presentation => @presentation_idea3) Like.create(:user => @user1, :presentation => @presentation_idea4) Like.create(:user => @user2, :presentation => @presentation_idea4) Like.create(:user => @user3, :presentation => @presentation_idea4) Like.create(:user => @user4, :presentation => @presentation_idea4) Like.create(:user => @user5, :presentation => @presentation_idea4) Like.create(:user => @user6, :presentation => @presentation_idea4) end should "have method for number of likes" do assert_equal @presentation_idea1.num_likes, 3 assert_equal @presentation_idea2.num_likes, 2 assert_equal @presentation_idea3.num_likes, 1 assert_equal @presentation_idea4.num_likes, 6 end should "have way to limit resutls for popular ideas" do assert_equal Presentation.sorted_by_likes.all(:limit => 1), [@presentation_idea4] end # Temp method to circumvent - named_scope issues between mysql & psql should "have method for popular ideas (sorted by likes_slow)" do assert_equal Presentation.sorted_by_likes_slow, [ @presentation_idea4, @presentation_idea1, @presentation_idea2, @presentation_idea3, @presentation_idea5 ] end should "have way to limit resutls for popular ideas (slower method)" do assert_equal Presentation.sorted_by_likes_slow(:limit => 1), [@presentation_idea4] end end end <file_sep>/app/controllers/presentations_controller.rb class PresentationsController < ApplicationController def index end def ideas @presentations = Presentation.ideas.all end def past @presentations = Presentation.past.all end def upcoming @presentations = Presentation.upcoming.all end def show @presentation = Presentation.find(params[:id]) end def new @presentation = Presentation.new end def create @presentation = Presentation.new(params[:presentation]) if @presentation.save flash[:success] = "Presentation was saved successfully" redirect_to root_url else flash[:error] = "There was an error saving your presentation" render :action => 'new' end end def edit end def update end def destroy end end <file_sep>/app/helpers/home_helper.rb module HomeHelper def render_like_link(idea) if current_user return link_to "Like This","/likes/new/#{idea.id}", {:class => "#{ @liked_ideas.include?(idea)? 'already-liked': 'like' }", :id => "presentation_#{idea.id}"} end return "<span class='like-icon'>Like This</span>" end def google_maps_appfolio_url <<-url http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=55+Castilian+Dr.+Goleta,+CA+93117&sll=37.0625,-95.677068&sspn=49.176833,114.169922&ie=UTF8&hq=&hnear=55+Castilian+Dr,+Goleta,+Santa+Barbara,+California+93117&z=17&iwloc=A url end end <file_sep>/test/factories/presentation.rb Factory.define :presentation do |pres| pres.title { "Some talk" } pres.description { "some description" } pres.owner { Factory(:email_confirmed_user) } end Factory.define :presentation_idea, :parent => :presentation do |pres| pres.state { "idea" } end <file_sep>/app/controllers/likes_controller.rb class LikesController < ApplicationController def new # Messy but hack to make for when js is disabled in browser params[:like] = {:presentation_id => params[:id] } create end def create @like = Like.new(params[:like]) @like.user = current_user if @like.save respond_to do |format| format.js { render :text => 'success' } format.html { flash[:success] = "Your liking of this presentation has been recorded" redirect_to root_url } end else flash[:error] = "could not save like" respond_to do |format| format.js { render :text => 'failure' } format.html { flash[:error] = "Your liking of this presentation could not be recorded" redirect_to root_url } end end end end <file_sep>/features/step_definitions/presentation_steps.rb Given /^presentation ideas (.+)$/ do |presentations| presentations.split(',').each do |title| Factory(:presentation, :title => title) end end <file_sep>/app/models/presentation.rb class Presentation < ActiveRecord::Base validates_presence_of :title, :owner_id belongs_to :presenter, :class_name => "User" belongs_to :owner, :class_name => "User" has_many :likes has_many :users_who_like_this, :through => :likes, :source => :user named_scope :archived, :conditions => { :state => 'archived' }, :order => 'date DESC' named_scope :ideas, :conditions => {:state => 'idea' }, :order => 'created_at DESC' named_scope :upcoming, :conditions => {:state => 'upcoming' }, :order => 'date ASC' named_scope :sorted_by_likes, :joins => 'left outer join likes on likes.presentation_id = presentations.id', :group => "presentations.id", :order => 'COUNT(likes.id) DESC' def self.sorted_by_likes_slow(options = nil) Presentation.ideas.all(options).sort {|a,b| b.num_likes <=> a.num_likes } end def num_likes likes.count end end <file_sep>/app/models/user.rb class User < ActiveRecord::Base has_many :presentations, :class_name => "Presentation", :foreign_key => "presenter_id" has_many :created_presentations, :class_name => "Presentation", :foreign_key => 'owner_id' has_many :likes has_many :liked_presentation_ideas, :through => :likes, :source => :presentation def likes?(presentation) liked_presentation_ideas.map(&:id).include? presentation.id end include Clearance::User end <file_sep>/test/unit/like_test.rb require 'test_helper' class LikeTest < ActiveSupport::TestCase should_validate_presence_of :user_id, :presentation_id context "users who like some presentations" do setup do @user1 = Factory(:email_confirmed_user, :email => '<EMAIL>') @user2 = Factory(:email_confirmed_user, :email => '<EMAIL>') @user3 = Factory(:email_confirmed_user, :email => '<EMAIL>') @presentation_idea1 = Factory(:presentation_idea) @presentation_idea2 = Factory(:presentation_idea) @presentation_idea3 = Factory(:presentation_idea) end should "form a join model between presentations and users" do Like.create(:user => @user1, :presentation => @presentation_idea1 ) assert_equal @presentation_idea1, @user1.liked_presentation_ideas.first assert_equal @user1, @presentation_idea1.users_who_like_this.first end should "not allow users to like presentation multiple times" do like1 = Like.new(:user => @user1, :presentation => @presentation_idea1 ) assert like1.valid? assert like1.save like2 = Like.new(:user => @user1, :presentation => @presentation_idea1 ) assert !like2.valid? end end end <file_sep>/public/javascripts/utilities.js jQuery.fn.extract_id = function() { return $(this).attr('id').match(/[0-9].*/)[0]; } <file_sep>/app/controllers/events_controller.rb class EventsController < ApplicationController skip_before_filter :login_required def index @events = Event.all end def new @event = Event.new end def create @event = Event.new(params[:event]) if @event.save flash[:success] = "saved successfully" redirect_to root_url else flash[:error] = "could not save the event" redirect_to root_url end end end <file_sep>/app/models/like.rb class Like < ActiveRecord::Base belongs_to :user belongs_to :presentation validates_presence_of :user_id,:presentation_id validate :user_cant_like_presentation_twice def user_cant_like_presentation_twice errors.add_to_base("user already likes this presentation!") if already_liked? end def already_liked? !Like.find(:all, :conditions => { :user_id => user_id, :presentation_id => presentation_id }).empty? end end
834c75072a60ba95a2d8299ad9499d16085c020b
[ "JavaScript", "Ruby", "Markdown" ]
20
Ruby
rca/sbonrails
d5504d3623fc34a52181c0ad8a5fd907e24214de
4dac67f108444905d2a69bfa9bf5a8894c09b76d
refs/heads/master
<repo_name>lbxl2345/learnDECAF<file_sep>/LearnDECAF.md # DECAF *** ### 应关注的文件 *** + callbacktests.c + DECAF_types.h + DECAF_main.h + DECAF_callback.h + DECAF_callback_common.h + DECAF_target.h + hookapi.h + monitor.h + qdict.h + qemu-common.h + qobject.h + vmi_callback.h + vmi_c_wrapper.h + vmi_callback.h + utils/Output.h ### callbacktests.c *** //init plugin plugin_interface_t* init_plugin(void) { //init mon_cmds callbacktests_interface.mon_cmds = callbacktests_term_cmds; //init cleanup callbacktests_interface.plugin_cleanup = &callbacktests_cleanup; callbacktest_init(); return (&callbacktests_interface); } ### DECAF_types.h *** typedef uintptr_t DECAF_Handle;//uintptr_t hold any pointer #define DECAF_NULL_HANDLE ((uintptr_t)NULL) ### DECAF_main.h *** 1.interface struct typedef struct _plugin_interface{ const mon_cmd_t *mom_cmds;//array of moniter commands const mon_cmd_t *info_cmds;//array of informational commands void (*plugin_cleanup)(void); void (*after_loadvm)(const char *param); union { uint32_t monitored_cr3; uint32_t monitored_pgd; }; }plugin_interface_t; 2.plugin load void do_load_plugin_internal(Monitor *mon, const char *plugin_path); int do_load_plugin(Monitor *mon, const QDict *qdict, QObject **ret_data); int do_unload_plugin(Monitor *mon, const QDict *qdict, QObject **ret_data); 3.DECAF init void DECAF_init(void) { DECAF_callback_init(); tainting_init(); DECAF_virtdev_init(); register_savevm(NULL,"DECAF",0,1,DECAF_save,DECAF_load,NULL); DECAF_vm_compress_init(); function_map_init(); init_hookapi(); } ### DECAF_callback.h *** ### DECAF_callback_common.h *** ocb_t:optimized callback type DECAF_callback_type_t:DECAF callback type ### DECAF_target.h *** ### hookapi.h *** ### monitor.h *** typedef struct mon_cmd_t { const char *name; const char *args_type; const char *params; const char *help; void (*user_print)(Monitor *mon, const QObject *data); union { void (*info)(Monitor *mon); void (*cmd)(Monitor *mon, const QDict *qdict); int (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data); int (*cmd_async)(Monitor *mon, const QDict *params, MonitorCompletion *cb, void *opaque); }mhandler; bool qapi; int flags; }mon_cmd_t; ### qdict.h *** typedef struct QDictEntry { char *key; QObject *value; QLIST_ENTRY(QDictEntry) next; }QDictEntry; typedef struct QDict { QObject_HEAD; size_t size; QLIST_HEAD(,QDictEntry) table[QDICT_BUCKET_MAX]; }QDict; ### qemu-common.h *** //null struct Monitor struct Monitor; typedef struct Monitor Monitor; ### qobject.h *** typedef enum qtype_code //qemu object model typedef struct QType { qtype_code code; void (*destroy)(struct QObject *); }QType; typedef struct QObject { const QType *type; size_t refcnt; }QObject; ### vmi_callback.h *** <file_sep>/datatracer/datatracer/datatracer.cpp // // datatracer.c // datatracer // // Created by 刘本熙 on 15/3/15. // // #include <stdio.h> #include <time.h> #include "DECAF_types.h" #include "DECAF_main.h" #include "DECAF_target.h" #include "hookapi.h" #include "DECAF_callback.h" #include "utils/Output.h" #include "function_map.h" #include "vmi_callback.h" #include "vmi_c_wrapper.h" #include "vmi.h" #define STACK_SIZE 10000 char modname_t[512]; char funcname_t[512]; static plugin_interface_t datatracer_interface; static DECAF_Handle create_process_handle = DECAF_NULL_HANDLE; static DECAF_Handle remove_process_handle = DECAF_NULL_HANDLE; static DECAF_Handle write_taint_handle = DECAF_NULL_HANDLE; static DECAF_Handle read_taint_handle = DECAF_NULL_HANDLE; static DECAF_Handle block_end_handle = DECAF_NULL_HANDLE; static DECAF_Handle key_stroke_handle = DECAF_NULL_HANDLE; static time_t ks_time; static uint32_t source_pid; static uint32_t source_cr3; static uint32_t pc_stack[STACK_SIZE]; static uint32_t fun_stack[STACK_SIZE]; static uint32_t cr3_stack[STACK_SIZE]; static uint32_t ptr_stack = 0; static char source_name[512]; FILE *tracelog = NULL; void do_create_proc(VMI_Callback_Params *param) { char procname[64]; uint32_t pid; if(param == NULL){ return; } //通过param获取当前的进程pid以及进程名 VMI_find_process_by_cr3_c(param->cp.cr3, procname, 64, &pid); if (pid == (uint32_t)(-1)) { return; } if (strcmp(source_name, procname) == 0) { source_pid = pid; source_cr3 = param->cp.cr3; } DECAF_printf("Process name:%s\t pid:%d\t cr3:%u was created\n", procname, pid, param->cp.cr3); } void handle_call(DECAF_Callback_Params *param) { if (ptr_stack == STACK_SIZE) { memcpy(pc_stack,&pc_stack[STACK_SIZE/10],STACK_SIZE-STACK_SIZE/10); memcpy(cr3_stack, &cr3_stack[STACK_SIZE/10], STACK_SIZE-STACK_SIZE/10); memcpy(fun_stack, &fun_stack, STACK_SIZE-STACK_SIZE/10); return; } CPUState *env = param->be.env; //调用call时,下一条pc即所调用代码块的入口 target_ulong next_pc = param->be.next_pc; target_ulong cr3 = DECAF_getPGD(env); //在当前进程空间中获取这个call指令所调用函数的函数名和模块名 if (funcmap_get_name_c(next_pc, cr3, modname_t, funcname_t)) { //ESP:栈指针寄存器,其内存放着一个指针,该指针永远指向帧栈的栈顶,这里也就是指向call调用完成后所执行的下一条指令 DECAF_read_mem(env, env->regs[R_ESP], 4, &pc_stack[ptr_stack]); fun_stack[ptr_stack] = next_pc; cr3_stack[ptr_stack] = cr3; ptr_stack++; } } void handle_ret(DECAF_Callback_Params *param) { if (!ptr_stack) { return; } if (param->be.next_pc == pc_stack[ptr_stack]) { ptr_stack--; } } void do_remove_proc(VMI_Callback_Params *param) { process proc; } void do_write_taint_mem(DECAF_Callback_Params *param) { uint32_t eip = DECAF_getPC(cpu_single_env); uint32_t cr3 = DECAF_getPGD(cpu_single_env); tmodinfo_t mod_info_t; time_t wt_t; vmi_ if (ptr_stack) { if (cr3 == cr3_stack[ptr_stack-1]) { funcmap_get_name_c(pc_stack[pc_stack-1], cr3, modname_t, funcname_t); } else{ memset(modname_t, 0, 512); memset(funcname_t, 0, 512); } } else{ memset(modname_t, 0, 512); memset(funcname_t, 0, 512); } } void do_read_taint_mem(DECAF_Callback_Params *param) { uint32_t eip = DECAF_getPC(cpu_single_env); uint32_t cr3 = DECAF_getPGD(cpu_single_env); tmodinfo_t mod_info_t; time_t wr_t; if (ptr_stack) { if (cr3 == cr3_stack[ptr_stack-1]) { funcmap_get_name_c(pc_stack[pc_stack-1], cr3, modname_t, funcname_t); } else{ memset(modname_t, 0, 512); memset(funcname_t, 0, 512); } } else{ memset(modname_t, 0, 512); memset(funcname_t, 0, 512); } } void do_block_end(DECAF_Callback_Params *param) { uint8_t ins_buf[2]; int call_flag = 0, ret_flag = 0; int b; DECAF_read_mem(param->be.env, param->be.cur_pc, 2 * sizeof(char),ins_buf); switch (ins_buf[0]) { case 0x9a: case 0x38: call_flag = 1; break; case 0xff: b = (ins_buf[1]>>3) & 7; if (b == 2 || b == 3) call_flag = 1; break; case 0xc2: case 0xc3: case 0xca: case 0xcb: ret_flag = 1; break; default: break; } if (call_flag) { } } void do_analysis(Monitor *mon, const QDict *qdict) { } void tracing_send_key(DECAF_Callback_Params *params) { int keycode = params->ks.keycode; uint32_t *taint_mark = params->ks.taint_mark; *taint_mark = taint_key_enabled; taint_key_enabled = 0; printf("taint keystroke %d \n", keycode); } void do_taint_sendkey(Monitor *mon, const QDict *qdict) { if (qdict_haskey(qdict, "key")) { if (!key_stroke_handle) { key_stroke_handle = DECAF_register_callback(DECAF_KEYSTROKE_CB, tracing_send_key, NULL); } do_send_key(qdict_get_str(qdict, "key")); } else ; } void do_enable_data_trace(Monitor *mon, const QDict *qdict) { DECAF_printf("******enable data trace******\n"); //delete here if ((qdict != NULL)&&(qdict_haskey(qdict,"procname"))) { strncpy(source_name, qdict_get_str(qdict,"procname"), 512); } else { DECAF_printf("A program name was not specified.\n"); return; } const char *tracefile_t = qdict_get_str(qdict, "tracefile"); tracelog = fopen(tracefile_t, "w"); if (!tracelog) { DECAF_printf("the %s can not be open or created.\n", tracefile_t); return; } //注册进程开始和结束的回调 if (create_process_handle != DECAF_NULL_HANDLE) { create_process_handle = VMI_register_callback(VMI_CREATEPROC_CB, do_create_proc, NULL); } if (remove_process_handle != DECAF_NULL_HANDLE) { remove_process_handle = VMI_register_callback(VMI_REMOVEPROC_CB, do_remove_proc, NULL); } //注册污点内存读写的回调 if(read_taint_handle != DECAF_NULL_HANDLE){ read_taint_handle = DECAF_register_callback(DECAF_READ_TAINTMEM_CB, do_write_taint_mem, NULL); } if(write_taint_handle != DECAF_NULL_HANDLE){ write_taint_handle = DECAF_register_callback(DECAF_WRITE_TAINTMEM_CB, do_read_taint_mem, NULL); } //注册基本块结束的回调 if(block_end_handle != DECAF_NULL_HANDLE){ block_end_handle = DECAF_registerOptimizedBlockEndCallback(do_block_end, NULL, INV_ADDR, INV_ADDR); } } void do_disable_data_trace(Monitor *mon, const QDict *qdict) { } static void do_select_source_process(Monitor *mon, const QDict *qdict) { } static void datatracer_init(void) { DECAF_printf("******datatracer initializing******\n"); //输入源程序相关信息初始化 source_name[0] = '\0'; source_cr3 = 0; source_pid = (uint32_t)(-1); } static void datatracer_cleanup(void) { //注销所有的回调函数 if (create_process_handle != DECAF_NULL_HANDLE) { VMI_unregister_callback(VMI_CREATEPROC_CB, create_process_handle); create_process_handle = DECAF_NULL_HANDLE; } if(remove_process_handle != DECAF_NULL_HANDLE){ VMI_unregister_callback(VMI_REMOVEMODULE_CB, remove_process_handle); remove_process_handle = DECAF_NULL_HANDLE; } if (read_taint_handle != DECAF_NULL_HANDLE) { DECAF_unregister_callback(DECAF_READ_TAINTMEM_CB,read_taint_handle); read_taint_handle = DECAF_NULL_HANDLE; } if (write_taint_handle != DECAF_NULL_HANDLE) { DECAF_unregister_callback(DECAF_WRITE_TAINTMEM_CB, write_taint_handle); write_taint_handle = DECAF_NULL_HANDLE; } if (block_end_handle != DECAF_NULL_HANDLE) { DECAF_unregisterOptimizedBlockEndCallback(block_end_handle); block_end_handle = DECAF_NULL_HANDLE; } DECAF_printf("datatracer terminate\n"); } static mon_cmd_t datatracer_term_cmds[] = { #include "plugin_cmds.h" { NULL, NULL, }, }; plugin_interface_t* init_plugin(void) { datatracer_interface.mon_cmds = datatracer_term_cmds; datatracer_interface.plugin_cleanup = &datatracer_cleanup; //初始化插件 datatracer_init(); return &(datatracer_interface); } <file_sep>/DECAF插件编写.md #DECAF插件编写 ##插件加载 *** DECAF插件的加载在DECAF_main.c内实现 分别是 do_load_plugin_internal() do_load_plugin() qemu所提供的插件借口位于vl.c中 DECAF插件的本质是一个一个动态链接库,它在加载的时候要通过以下的mon_cmd_t来完成 { .name = "load_plugin", .args_type = "filename:F", .params = "filename", .help = "Load a DECAF plugin", .mhandler.cmd_new = do_load_plugin, }, 也就是说,加载插件的过程是由DECAF和QEMU共同实现的 我们在使用插件的时候,只用输入相应的命令:load_plugin plugin_path 其实也就是动态加载了一个库,但是加载的时候DECAF会默认执行初始化函数 init_plugin,因为load_plugin的时候实际上通过符号的方式绑定了初始化函数 plugin_interface_t *(*init_plugin)(void); plugin_handle = dlopen(plugin_path, RTLD_NOW); init_plugin = dlsym(plugin_handle,"init_plugin"); 因此要在init_plugin中实现插件的初始化,这个函数要返回一个plugin_interface_t*指针,这个指针也就相当于给了DECAF_main.c中的 plugin_interface_t *decaf_plugin = NULL; decaf_plugin = init_plugin(); 此处就相当于执行了init_plugin()中的所有代码。在callbacktests.c这个例子中,init_plugin()调用了callbacktests_init()这个函数进行初始化。在这个函数中,插件完成了回调事件的注册,并且进行了某些参数的初始化。这里关注一下回调注册的方法:此处是注册了进程开始和结束的回调 DECAF中回调可以分成两个种类,VMI回调和DECAF回调。 VMI和DECAF分别自己的注册/注销函数。例如VMI: DECAF_Handle VMI_register_callback( VMI_callback_type_t cb_type, VMI_callback_func_t cb_func, int *cb_cond ) { if ((cb_type > VMI_LAST_CB) || (cb_type < 0)) { return (DECAF_NULL_HANDLE); return (SimpleCallback_register(&VMI_callbacks[cb_type], (SimpleCallback_func_t)cb_func, cb_cond)); }   processbegin_handle = VMI_register_callback(VMI_CREATEPROC_CB, &callbacktests_loadmainmodule_callback, NULL); removeproc_handle = VMI_register_callback(VMI_REMOVEPROC_CB, &callbacktests_removeproc_callback, NULL); VMI回调注册的相关说明,也即将回调函数和对应的回调类型注册。 DECAF_register_callback(VMI_callback_type_t cb_type,VMI_callback_func_t cb_func, int *cb_cond) 在callbacktests中,策略在于利用VMI回调发现进程的创建,在创建的回调中实现DECAF回调的注册。 <file_sep>/datatracer/datatracer/datatracer.c // // datatracer.c // datatracer // // Created by 刘本熙 on 15/3/24. // // #include "datatracer.h" <file_sep>/datatracer/datatracer/plugin_cmds.h // // plugin_cmds.h // datatracer // // Created by 刘本熙 on 15/3/15. // // #ifndef datatracer_plugin_cmds_h #define datatracer_plugin_cmds_h #endif
42898061812ab0968665030b7899cdf5372984c0
[ "Markdown", "C", "C++" ]
5
Markdown
lbxl2345/learnDECAF
c21450f45c932528709ff6607658615c21bbce9e
350fef9ed70ac4f2b889d1cd41b72440ee810b93
refs/heads/master
<file_sep>#include "ingress_preprocessor.h" // #include "hls_stream.h" // #include "ap_int.h" // #include "ap_axi_sdata.h" int main() { hls::stream<ap_axiu<64, 0, 0, 0> > is; ap_uint<64> tstamp0 = 0x1678cda2178bd4e5; ap_uint<16> tstamp1 = 0x8bef; ap_uint<80> time_stamp = (tstamp0, tstamp1); ap_uint<1> tstamp_valid = 1; hls::stream<ap_uint<8> > dport_is; hls::stream<demac_os> dmac_os; hls::stream<ap_axiu<64, 9, 1, 3> > os_be_rs; hls::stream<ap_axiu<64, 9, 1, 3> > os_ts; hls::stream<ap_axiu<64, 0, 0, 0> > os_ps_time; hls::stream<ap_axiu<64, 0, 0, 0> > os_ps; ap_axiu<64, 0, 0, 0> framein; ap_axiu<64, 0, 0, 0> frameout; ap_uint<40> ts_cnt = 0x1200010f11; ap_uint<40> rs_cnt = 0x107e0f1110; ap_uint<40> rts_cnt = 0x120e010f11; ap_uint<40> be_cnt = 0x120e010f11; ap_uint<64> emp0 = 0xf40123456789abcd; ap_uint<8> emp1 = 0xef; ap_uint<72> ts_emp = (emp0, emp1); ap_uint<72> rs_emp = (emp0, emp1); ap_uint<72> rts_emp = (emp0, emp1); ap_uint<72> be_emp = (emp0, emp1); //CNC ap_uint<48> demac = 0x10369f683512; ap_uint<48> semac = 0x000A3500010e; ap_uint<32> vlan = 0x81008000; ap_uint<16> ethertype = 0x0800; ap_uint<48> data0 = 0x7f9e3c2b1d0f; ap_uint<64> data1 = 0x1123456789abcdef; ap_uint<64> data2 = 0x34bd6f7c8e9a12dc; framein.data = (demac, semac(47, 32)); framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = (semac(31, 0), vlan); framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = (ethertype, data0); framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = data1; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = data2; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = data1; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = data1; framein.last = 1; framein.keep = 0x00; is.write(framein); //调用函数 ingress_preprocessor(is, time_stamp, tstamp_valid, dport_is, dmac_os, os_be_rs, os_ts, os_ps_time, os_ps, ts_cnt, rs_cnt, rts_cnt, be_cnt, ts_emp, rs_emp, rts_emp, be_emp); ap_uint<48> tdemac; ap_uint<48> tsemac; ap_uint<32> tvlan; ap_uint<16> tethertype; ap_uint<304> tdata; frameout = os_ps.read(); tdata(303, 240) = frameout.data; frameout = os_ps.read(); tdata(239, 176) = frameout.data; frameout = os_ps.read(); tdata(175, 112) = frameout.data; frameout = os_ps.read(); tdata(111, 48) = frameout.data; //frameout = os_ps.read(); //tdata(47, 0) = frameout.data(63, 16); printf("%s\n", tdata.to_string(16).c_str()); //ARP ap_uint<64> in0 = 0xffffffffffff0021; ap_uint<64> in1 = 0xccc5036a08060001; ap_uint<64> in2 = 0x0800060400010021; ap_uint<64> in3 = 0xccc5036a0a02196e; ap_uint<64> in4 = 0x0000000000000a02; ap_uint<64> in5 = 0x1921000000000000; framein.data = in0; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = in1; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = in2; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = in3; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = in4; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = in5; framein.last = 0; framein.keep = 0xc0; is.write(framein); ingress_preprocessor(is, time_stamp, tstamp_valid, dport_is, dmac_os, os_be_rs, os_ts, os_ps_time, os_ps, ts_cnt, rs_cnt, rts_cnt, be_cnt, ts_emp, rs_emp, rts_emp, be_emp); ap_uint<224> arp_data; frameout = os_ps.read(); arp_data(223, 160) = frameout.data; frameout = os_ps.read(); arp_data(159, 96) = frameout.data; frameout = os_ps.read(); arp_data(95, 32) = frameout.data; frameout = os_ps.read(); arp_data(31, 0) = frameout.data(63, 32); printf("%s\n", arp_data.to_string(16).c_str()); //PTP ap_uint<64> ptp0 = 0x0180C200000ee454; ap_uint<64> ptp1 = 0xe8deca6688f70001; ap_uint<64> ptp2 = 0x080006040001e454; ap_uint<64> ptp3 = 0xe8deca660a0219b8; ap_uint<64> ptp4 = 0x670450123000a9fe; ap_uint<64> ptp5 = 0xa9fe123456789abc; framein.data = ptp0; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = ptp1; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = ptp2; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = ptp3; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = ptp4; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = ptp5; framein.last = 1; framein.keep = 0xfe; is.write(framein); ingress_preprocessor(is, time_stamp, tstamp_valid, dport_is, dmac_os, os_be_rs, os_ts, os_ps_time, os_ps, ts_cnt, rs_cnt, rts_cnt, be_cnt, ts_emp, rs_emp, rts_emp, be_emp); ap_uint<464> ptp_data; frameout = os_ps_time.read(); ptp_data(463, 400) = frameout.data; frameout = os_ps_time.read(); ptp_data(399, 336) = frameout.data; frameout = os_ps_time.read(); ptp_data(335, 272) = frameout.data; frameout = os_ps_time.read(); ptp_data(271, 208) = frameout.data; frameout = os_ps_time.read(); ptp_data(207, 144) = frameout.data; frameout = os_ps_time.read(); ptp_data(143, 80) = frameout.data; frameout = os_ps_time.read(); ptp_data(79, 16) = frameout.data; frameout = os_ps_time.read(); ptp_data(15, 0) = frameout.data(63, 48); printf("%s\n", frameout.keep.to_string(16).c_str()); printf("%s\n", ptp_data.to_string(16).c_str()); //be ֡2360391A 06040001E454E8DECA660A0219B8670450123000A9FEA9FE123456789ABC ap_uint<64> be0 = 0x357dfe5932dbe454; ap_uint<64> be1 = 0xe8deca6681006000; ap_uint<64> be2 = 0x080006040001e454; ap_uint<64> be3 = 0xe8deca660a0219b8; ap_uint<64> be4 = 0x670450123000a9fe; ap_uint<64> be5 = 0xa9fe123456789abc; ap_axiu<64, 9, 1, 3> frameout1; ap_uint<8> dport = 0x23; dport_is.write(dport); framein.data = be0; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = be1; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = be2; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = be3; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = be4; framein.last = 0; framein.keep = 0xff; is.write(framein); framein.data = be5; framein.last = 1; framein.keep = 0xfc; is.write(framein); ingress_preprocessor(is, time_stamp, tstamp_valid, dport_is, dmac_os, os_be_rs, os_ts, os_ps_time, os_ps, ts_cnt, rs_cnt, rts_cnt, be_cnt, ts_emp, rs_emp, rts_emp, be_emp); ap_uint<272> be_data; frameout1 = os_be_rs.read(); be_data(271, 208) = frameout1.data; frameout1 = os_be_rs.read(); be_data(207, 144) = frameout1.data; frameout1 = os_be_rs.read(); be_data(143, 80) = frameout1.data; frameout1 = os_be_rs.read(); be_data(79, 16) = frameout1.data; frameout1 = os_be_rs.read(); be_data(15, 0) = frameout1.data(63, 48); printf("%s\n", be_data.to_string(16).c_str()); ap_uint<272> ts_data; frameout1 = os_ts.read(); ts_data(271, 208) = frameout1.data; frameout1 = os_ts.read(); ts_data(207, 144) = frameout1.data; frameout1 = os_ts.read(); ts_data(143, 80) = frameout1.data; frameout1 = os_ts.read(); ts_data(79, 16) = frameout1.data; frameout1 = os_ts.read(); ts_data(15, 0) = frameout1.data(63, 48); printf("%s\n", ts_data.to_string(16).c_str()); return 0; } <file_sep>#pragma once #include "hls_stream.h" #include "ap_int.h" #include "ap_axi_sdata.h" struct demac_os { ap_uint<48> dmac; ap_uint<12> vlan_id_os; }; struct cnt_is { ap_uint<5> ts[8]; ap_uint<5> rs[8]; ap_uint<5> rts[8]; ap_uint<5> be[8]; }; struct emp_is { ap_uint<9> ts[8]; ap_uint<9> rs[8]; ap_uint<9> rts[8]; ap_uint<9> be[8]; }; void ingress_preprocessor( hls::stream<ap_axiu<64, 0, 0, 0>>& is, ap_uint<80>& time_stamp, ap_uint<1>& tstamp_valid, hls::stream<ap_uint<8>>& dport_is, hls::stream<demac_os>& dmac_os, hls::stream<ap_axiu<64, 9, 1, 3>>& os_be_rs, hls::stream<ap_axiu<64, 9, 1, 3>>& os_ts, hls::stream<ap_axiu<64, 0, 0, 0>>& os_ps_time, hls::stream<ap_axiu<64, 0, 0, 0>>& os_ps, ap_uint<40>& ts_cnt, ap_uint<40>& rs_cnt, ap_uint<40>& rts_cnt, ap_uint<40>& be_cnt, ap_uint<72>& ts_emp, ap_uint<72>& rs_emp, ap_uint<72>& rts_emp, ap_uint<72>& be_emp); #pragma once <file_sep>#include "ingress_preprocessor.h" // #include "hls_stream.h" // #include "ap_axi_sdata.h" int oneNum(int x); int build(int x); template<int o_I, int o_U, int o_N, int i_I, int i_U, int i_N> int frame_output( int remain, ap_axiu<64, i_I, i_U, i_N> t2, hls::stream<ap_axiu<64, 0, 0, 0>>& is, hls::stream<ap_axiu<64, o_I, o_U, o_N>>& out_port ); ap_axiu<64, 9, 1, 3> frame_cache2[188]; void ingress_preprocessor( hls::stream<ap_axiu<64, 0, 0, 0>>& is, ap_uint<80>& time_stamp, ap_uint<1>& tstamp_valid, hls::stream<ap_uint<8>>& dport_is, hls::stream<demac_os>& dmac_os, hls::stream<ap_axiu<64, 9, 1, 3>>& os_be_rs, hls::stream<ap_axiu<64, 9, 1, 3>>& os_ts, hls::stream<ap_axiu<64, 0, 0, 0>>& os_ps_time, hls::stream<ap_axiu<64, 0, 0, 0>>& os_ps, ap_uint<40>& ts_cnt, ap_uint<40>& rs_cnt, ap_uint<40>& rts_cnt, ap_uint<40>& be_cnt, ap_uint<72>& ts_emp, ap_uint<72>& rs_emp, ap_uint<72>& rts_emp, ap_uint<72>& be_emp) { #pragma HLS interface axis port = is #pragma HLS interface axis port = os_be_rs #pragma HLS interface axis port = os_ts //#pragma HLS interface axis port = dport_is //#pragma HLS interface axis port = dmac_os #pragma HLS interface axis port = os_ps_time #pragma HLS interface axis port = os_ps ap_uint<80> tstamp = time_stamp; ap_uint<48> dmac; ap_uint<48> smac; ap_uint<32> vlan; ap_uint<16> vlan_type; ap_uint<12> vlan_id; ap_uint<16> et; ap_uint<3> vlan_pri; ap_uint<48> local_mac = 0x10369f683512; ap_uint<11> frame_count = 0; ; ap_uint<8> dport; ap_uint<32> frame_header; ap_axiu<64, 9, 1, 3> frameout; ap_axiu<64, 0, 0, 0> frameout1; cnt_is cnt; emp_is emp; ap_axiu<64, 0, 0, 0> in0 = is.read(); ap_axiu<64, 0, 0, 0> in1 = is.read(); ap_axiu<64, 0, 0, 0> t1; dmac = in0.data(63, 16); smac = (in0.data(15, 0), in1.data(63, 32)); ap_axiu<64, 0, 0, 0> t2 = is.read(); if (in1.data(31, 16) == 0x8100)//含有VLAN字段的以太网帧,需要进一步判断TS\BE\RS帧 { vlan = in1.data(31, 0); vlan_type = vlan(31, 16);//(标签协议标识符),表示数据帧类型 vlan_pri = vlan(15, 13);//表示数据帧的802.1p优先级,值越大优先级越高。 vlan_id = vlan(11, 0);//表示该数据帧所属VLAN的编号 et = t2.data(63, 48); } else { et = in1.data(31, 16); } ap_uint<8> max_cnt_ts; ap_uint<8> max_cnt_rts; ap_uint<8> max_cnt_rs; ap_uint<8> max_cnt_be; struct demac_os dmac_check; //cnt for (int i = 0; i < 8; ++i) { #pragma HLS PIPELINE II = 1 cnt.ts[i] = ts_cnt((5 * i + 4), (5 * i)); cnt.rs[i] = rs_cnt((5 * i + 4), (5 * i)); cnt.rts[i] = rts_cnt((5 * i + 4), (5 * i)); cnt.be[i] = be_cnt((5 * i + 4), (5 * i)); } //emp for (int i = 0; i < 8; ++i) { #pragma HLS PIPELINE II = 1 emp.ts[i] = ts_emp((9 * i + 8), (9 * i)); emp.rs[i] = rs_emp((9 * i + 8), (9 * i)); emp.rts[i] = rts_emp((9 * i + 8), (9 * i)); emp.be[i] = be_emp((9 * i + 8), (9 * i)); } ap_uint<1> broadcast = 0; if (dmac == 0xFFFFFFFF) broadcast = 1; else broadcast = 0; if (dmac == 0x0180C200000E && et == 0x88f7 && tstamp_valid) { frameout1.data = tstamp(79, 16); frameout1.last = 0; frameout1.keep = 0xff; frameout1.data = (tstamp(15, 0), dmac); frameout1.last = 0; frameout1.keep = 0xff; os_ps_time.write(frameout1); frameout1.data = (smac, et); frameout1.last = 0; frameout1.keep = 0xff; os_ps_time.write(frameout1); frameout1.data = (in1.data(15, 0), t2.data(63, 16)); frameout1.last = 0; frameout1.keep = 0xff; os_ps_time.write(frameout1); frame_output<0, 0, 0, 0, 0, 0>(16, t2, is, os_ps_time); } else if (dmac == local_mac) { frame_output<0, 0, 0, 0, 0, 0>(48, t2, is, os_ps); } else if (et == 0x0806) { frameout1.data = (in1.data(15, 0), t2.data(63, 16)); frameout1.last = 0; frameout1.keep = 0xff; os_ps.write(frameout1); t1 = is.read(); frameout1.data = (t2.data(15, 0), t1.data(63, 16)); frameout1.last = 0; frameout1.keep = 0xff; os_ps.write(frameout1); t2 = is.read(); frameout1.data = (t1.data(15, 0), t2.data(63, 16)); frameout1.last = 0; frameout1.keep = 0xff; os_ps.write(frameout1); t1 = is.read(); frameout1.data = (t2.data(15, 0), t1.data(63, 16)); frameout1.last = 1; frameout1.keep = 0xf0; os_ps.write(frameout1); } else if (vlan_type == 0x8100) { frame_count = frame_output<9, 1, 3, 0, 0, 0>(48, t2, is, os_ts); ap_axiu<64, 9, 1, 3> d;// be0 lost for (int i = 0; i < 10; i++) { d.data = frame_cache2[i].data; } dmac_check.dmac = dmac; dmac_check.vlan_id_os = vlan_id; dmac_os.write(dmac_check); dport = dport_is.read(); frame_header(31, 24) = dport; frame_header(23, 21) = vlan_pri; frame_header[20] = broadcast; frame_header(19, 9) = frame_count; max_cnt_ts = 0x00; max_cnt_rts = 0x00; if (vlan_pri == 0x0 || vlan_pri == 0x1 || vlan_pri == 0x2) { max_cnt_ts(7, 5) = 0; max_cnt_ts(4, 0) = cnt.ts[0]; max_cnt_rts(7, 5) = 0; max_cnt_rts(4, 0) = cnt.rts[0]; for (int j = 0; j < 7; ++j) { #pragma HLS PIPELINE II = 1 if (max_cnt_ts(4, 0) < cnt.ts[j + 1]) { max_cnt_ts(7, 5) = j + 1; max_cnt_ts(4, 0) = cnt.ts[j + 1]; } else continue; } for (int j = 0; j < 7; ++j) { #pragma HLS PIPELINE II = 1 if (max_cnt_rts(4, 0) < cnt.rts[j + 1]) { max_cnt_rts(7, 5) = j + 1; max_cnt_rts(4, 0) = cnt.rts[j + 1]; } else continue; } if (max_cnt_ts(4, 0) > max_cnt_rts(4, 0)) frame_header(8, 0) = emp.ts[max_cnt_ts(7, 5)]; else frame_header(8, 0) = emp.rts[max_cnt_rts(7, 5)]; max_cnt_ts = 0x00; max_cnt_rts = 0x00; frameout.data(63, 32) = frame_header; frameout.data(31, 0) = frame_cache2[0].data(63, 32); frameout.last = 0; frameout.keep = 0xff; os_ts.write(frameout); frame_output<9, 1, 3, 9, 1, 3>(32, frame_cache2[0], is, os_ts); } else { if (vlan_pri == 0x3 || vlan_pri == 0x4 || vlan_pri == 0x5) { max_cnt_rs(7, 5) = 0; max_cnt_rs(4, 0) = cnt.rs[0]; max_cnt_rts(7, 5) = 0; max_cnt_rts(4, 0) = cnt.rts[0]; for (int j = 0; j < 7; ++j) { #pragma HLS PIPELINE II = 1 if (max_cnt_rs(4, 0) < cnt.rs[j + 1]) { max_cnt_rs(7, 5) = j + 1; max_cnt_rs(4, 0) = cnt.rs[j + 1]; } else continue; } for (int j = 0; j < 7; ++j) { #pragma HLS PIPELINE II = 1 if (max_cnt_rts(4, 0) < cnt.rts[j + 1]) { max_cnt_rts(7, 5) = j + 1; max_cnt_rts(4, 0) = cnt.rts[j + 1]; } else continue; } if (max_cnt_rs(4, 0) > max_cnt_rts(4, 0)) frame_header(8, 0) = emp.rs[max_cnt_rs(7, 5)]; else frame_header(8, 0) = emp.rts[max_cnt_rts(7, 5)]; } else if (vlan_pri == 0x6 || vlan_pri == 0x7) { max_cnt_be(7, 5) = 0x0; max_cnt_be(4, 0) = cnt.be[0]; for (int j = 0; j < 7; ++j) { #pragma HLS PIPELINE II = 1 if (max_cnt_be(4, 0) < cnt.be[j + 1]) { max_cnt_be(7, 5) = j + 1; max_cnt_be(4, 0) = cnt.be[j + 1]; } else continue; } frame_header(8, 0) = emp.be[max_cnt_be(7, 5)]; max_cnt_be = 0x00; } frameout.data(63, 32) = frame_header; frameout.data(31, 0) = frame_cache2[0].data(63, 32); frameout.last = 0; frameout.keep = 0xff; os_be_rs.write(frameout); frame_output<9, 1, 3, 9, 1, 3>(32, frame_cache2[0], is, os_be_rs); } } } template<int o_I, int o_U, int o_N, int i_I, int i_U, int i_N> int frame_output( int remain, ap_axiu<64, i_I, i_U, i_N> t2, hls::stream<ap_axiu<64, 0, 0, 0>>& is, hls::stream<ap_axiu<64, o_I, o_U, o_N>>& out_port ) { int frame_count = 0; ap_axiu<64, o_I, o_U, o_N> frame; for (int i = 0; i < 188; i++) { #pragma HLS PIPELINE II = 1 ap_axiu<64, i_I, i_U, i_N> t1; if (i_I == 0) { ap_axiu<64, 0, 0, 0> read_data = is.read(); t1.data = read_data.data; t1.keep = read_data.keep; t1.last = read_data.last; } else { t1.data = frame_cache2[i + 1].data; t1.keep = frame_cache2[i + 1].keep; t1.last = frame_cache2[i + 1].last; } if (!t1.last) { frame.data = (t2.data(remain - 1, 0), t1.data(63, remain)); frame.last = 0; frame.keep = 0xff; frame_count += 8; if (o_I == i_I) out_port.write(frame); else { frame_cache2[i].data = frame.data; frame_cache2[i].keep = frame.keep; frame_cache2[i].last = frame.last; } t2 = t1; } else { int one = oneNum(t1.keep) * 8; if (one + remain > 64) { frame.data = (t2.data(remain - 1, 0), t1.data(63, remain)); frame.keep = 0xff; frame_count += 8; if (o_I == i_I) out_port.write(frame); else { frame_cache2[i].data = frame.data; frame_cache2[i].keep = frame.keep; frame_cache2[i].last = frame.last; } frame.data(63, 128 - remain - one) = t1.data(remain - 1, 64 - one); frame.data(127 - remain - one, 0) = 0; frame.last = 1; frame.keep = build((remain + one - 64) / 8); frame_count += (remain + one - 64) / 8; if (o_I == i_I) out_port.write(frame); else { frame_cache2[i + 1].data = frame.data; frame_cache2[i + 1].keep = frame.keep; frame_cache2[i + 1].last = frame.last; } break; } else if (one + remain < 64) { frame.data(63, 64 - remain) = t2.data(remain - 1, 0); if (one != 0) { frame.data(63 - remain, 64 - remain - one) = t1.data(63, 64 - one); } frame.last = 1; frame.keep = build((one + remain) / 8); frame_count += (one + remain) / 8; if (o_I == i_I) out_port.write(frame); else { frame_cache2[i].data = frame.data; frame_cache2[i].keep = frame.keep; frame_cache2[i].last = frame.last; } break; } else { frame.data(63, 0) = (t2.data(remain - 1, 0), t1.data(63, 64 - one)); if (o_I == i_I) out_port.write(frame); else { frame_cache2[i].data = frame.data; frame_cache2[i].keep = frame.keep; frame_cache2[i].last = frame.last; } break; } } } return frame_count; } int oneNum(int x) { int count = 0; while (x) { if (x % 2 != 0) count++; x = x / 2; } return count; } int build(int x) { int res = 0; int idx = x; for (int i = 0; i < x; i++) { res = res * 2 + 1; } for (int i = 0; i < 8 - x; i++) { res = res * 2; } return res; }
14c230c8f6ec678a66348c17542ec9abe628b3e3
[ "C", "C++" ]
3
C++
qu0224/intership_code_ingress_preprocessor
9222dab17f300b57ab1b3c098794a1c5bce55fc8
761ffcd80d67c3942c05c80e65c99c70ce03d084
refs/heads/master
<file_sep>import matplotlib.pyplot as plt import numpy as np import matplotlib.mlab as mlab import math import numpy as np import scipy.stats def nplot(dfstat, value): mu = dfstat[value]['mean'] sigma = dfstat[value]['std'] x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100) ax = plt.subplot(111) ax.plot(x, scipy.stats.norm.pdf(x, mu, sigma)) return ax def twoplot(onestat, twostat, value, legends=['target', 'reference']): ax = plt.subplot(211) one_mu = onestat[value]["mean"] two_mu = twostat[value]["mean"] one_sigma = onestat[value]["std"] two_sigma = twostat[value]["std"] mu = (one_mu + two_mu)/2 left_sigma = min(one_sigma, two_sigma) right_sigma = max(one_sigma, two_sigma) x = np.linspace(mu - 4*left_sigma, mu + 4*right_sigma, 100) ax.plot(x, scipy.stats.norm.pdf(x, one_mu, one_sigma)) #ax2 = plt.subplot(212, sharex=ax1) ax.plot(x, scipy.stats.norm.pdf(x, two_mu, two_sigma)) ax.legend(legends) return ax def histplot(numbers, bins=5, color='blue', axis = "", figsize=(30,8)): if axis == "": fig = plt.figure(figsize=figsize) ax = fig.add_subplot(121) else: ax = axis numBins = bins ax.hist(numbers,density=True,bins=numBins, color=color,alpha=0.8) return ax <file_sep># CompareCorpus_easyread I samarbeid med Sofie Mybinder: https://github.com/Yoonsen/CompareCorpus_easyread
f772ce712efc461ba073063d1cd3f83f1f91b1a6
[ "Markdown", "Python" ]
2
Python
Yoonsen/CompareCorpus_easyread
bf5bb00f5428a72b21d2e57f89a7103727d90b9c
d0312a07b82835c9c5e1421465c414cc97a36603
refs/heads/master
<file_sep>import numpy as np from nltk.corpus import stopwords from nltk import download from gensim.models import KeyedVectors from pyemd import emd from gensim.corpora.dictionary import Dictionary from collections import defaultdict import os import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s') download('stopwords') # get n-gram token for one sentence def precook(s, n=1, out=False): """ Takes a string as input and returns an object that can be given to either cook_refs or cook_test. This is optional: cook_refs and cook_test can take string arguments as well. :param s: string : sentence to be converted into ngrams :param n: int : number of ngrams for which representation is calculated :return: term frequency vector for occuring ngrams """ counts = defaultdict(int) for k in xrange(1,n+1): for i in xrange(len(s)-k+1): ngram = tuple(s[i:i+k])[0] counts[ngram] += 1 return counts class WMD: def __init__(self): self.stop_words = stopwords.words('english') if not os.path.exists('/home/renmeng/gitlab/wmd/data/GoogleNews-vectors-negative300.bin.gz'): raise ValueError("SKIP: You need to download the google news model") self.model = KeyedVectors.load_word2vec_format('/home/renmeng/gitlab/wmd/data/GoogleNews-vectors-negative300.bin.gz', binary=True) self.test = [] self.refs = [] self.ctest = [] self.crefs = [] self.document_frequency = defaultdict(float) return # tokenize for one sentence, remove stop words def preprocess(self, candidate, refs): assert (len(candidate) > 0) assert (len(refs) > 0) # split into tokens token_c = candidate.split(" ") token_c = [w for w in token_c if w not in self.stop_words] token_r = [] for reference in refs: # split into tokens token_r_tmp = reference.split(" ") token_r_tmp = [w for w in token_r_tmp if w not in self.stop_words] token_r.append(token_r_tmp) return token_c, token_r def compute_doc_freq(self): ''' Compute term frequency for reference data. This will be used to compute idf (inverse document frequency later) The term frequency is stored in the object :return: None ''' for refs in self.crefs: # refs, k ref captions of one image for ngram in set([ngram for ref in refs for (ngram, count) in ref.iteritems()]): self.document_frequency[ngram] += 1 # maxcounts[ngram] = max(maxcounts.get(ngram,0), count) def bulid_wmd(self, hypo, ref): hypo, ref = self.preprocess(hypo, ref) self.test.append(hypo) self.refs.append(ref) self.crefs.append([precook(ref_, 1) for ref_ in ref]) self.ctest.append(precook(hypo, 1, True)) def wmdistance(self, document1, document2, tf_idf1, tf_idf2, weight): document1 = [token for token in document1 if self.model.__contains__(token)] document2 = [token for token in document2 if self.model.__contains__(token)] dictionary = Dictionary(documents=[document1, document2]) vocab_len = len(dictionary) if vocab_len == 1: # Both documents are composed by a single unique token return 0.0 # Sets for faster look-up. docset1 = set(document1) docset2 = set(document2) # Compute distance matrix. distance_matrix = np.zeros((vocab_len, vocab_len), dtype=np.double) for i, t1 in dictionary.items(): for j, t2 in dictionary.items(): if t1 not in docset1 or t2 not in docset2: continue # Compute Euclidean distance between word vectors. distance_matrix[i, j] = np.sqrt(np.sum((self.model.get_vector(t1) - self.model.get_vector(t2)) ** 2)) if np.sum(distance_matrix) == 0.0: logger.info('The distance matrix is all zeros. Aborting (returning inf).') return float('inf') def _tf_idf(word_tfidf): d = np.zeros(vocab_len, dtype=np.double) for id_, term in dictionary.items(): d[id_] = word_tfidf[term] return d def nbow(document): d = np.zeros(vocab_len, dtype=np.double) nbow = dictionary.doc2bow(document) # Word frequencies. doc_len = len(document) for idx, freq in nbow: d[idx] = freq / float(doc_len) # Normalized word frequencies. return d # Compute nBOW representation of documents. if weight == 'TFIDF': d1 = _tf_idf(tf_idf1) d2 = _tf_idf(tf_idf2) elif weight == 'Norm': d1 = nbow(document1) d2 = nbow(document2) # Compute WMD. return emd(d1, d2, distance_matrix) def score_(self, weight): def counts2vec(cnts): vec = defaultdict(float) for (ngram, term_freq) in cnts.iteritems(): # give word count 1 if it doesn't appear in reference corpus df = np.log(max(1.0, self.document_frequency[ngram])) # tf (term_freq) * idf (precomputed idf) for n-grams vec[ngram] = float(term_freq) * (ref_len - df) return vec ref_len = np.log(float(len(self.crefs))) scores = [] for i in range(len(self.crefs)): test_, refs_ = self.test[i], self.refs[i] ctest_, crefs_ = self.ctest[i], self.crefs[i] vec = counts2vec(ctest_) score_ = [] for j in range(len(crefs_)): ref, ref_text = crefs_[j], refs_[j] vec_f = counts2vec(ref) score_.append(self.wmdistance(test_, ref_text, vec, vec_f, weight)) scores.append(np.min(score_)) return np.mean(scores), scores def compute_score(self, gts, res, weight='TFIDF'): """ Main function to compute CIDEr score :param hypo_for_image (dict) : dictionary with key <image> and value <tokenized hypothesis / candidate sentence> ref_for_image (dict) : dictionary with key <image> and value <tokenized reference sentence> :return: cider (float) : computed CIDEr score for the corpus """ assert(gts.keys() == res.keys()) imgIds = gts.keys() for id in imgIds: hypo = res[id] ref = gts[id] # Sanity check. assert(type(hypo) is list) assert(len(hypo) == 1) assert(type(ref) is list) assert(len(ref) > 0) self.bulid_wmd(hypo[0], ref) self.compute_doc_freq() (score, scores) = self.score_(weight) return score, scores def method(self): return "WMD" <file_sep>from pycocotools.coco import COCO from pycocoevalcap.eval import COCOEvalCap import json from json import encoder encoder.FLOAT_REPR = lambda o: format(o, '.3f') dataDir='.' dataType='val2014' algName = 'fakecap' annFile='%s/annotations/captions_%s.json'%(dataDir,dataType) subtypes=['results', 'evalImgs', 'eval'] [resFile, evalImgsFile, evalFile]= \ ['%s/results/captions_%s_%s_%s.json'%(dataDir,dataType,algName,subtype) for subtype in subtypes] # create coco object and cocoRes object coco = COCO(annFile) cocoRes = coco.loadRes(resFile) # create cocoEval object by taking coco and cocoRes cocoEval = COCOEvalCap(coco, cocoRes) # evaluate on a subset of images by setting # cocoEval.params['image_id'] = cocoRes.getImgIds() # please remove this line when evaluating the full validation set cocoEval.params['image_id'] = cocoRes.getImgIds() # evaluate results cocoEval.evaluate()
b90fa2616f0a48d8d0da94673f1834172697ab4e
[ "Python" ]
2
Python
XiaoSX/coco-caption
e37ead8b5e8952bd02c7a5c2878af12efa77641e
5051caa13a41b6117eba8c0e4ceac089f501502b
refs/heads/master
<repo_name>giulialiv/bggn213<file_sep>/class15/class15.Rmd --- title: "class15" author: "<NAME>" date: "11/15/2019" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` #The data for for hands-on session comes from GEO entry: GSE37704. #The authors report on differential analysis of lung fibroblasts in response to loss of the developmental transcription factor HOXA1. Their results and others indicate that HOXA1 is required for lung fibroblast and HeLa cell cycle progression. In particular their analysis show that "loss of HOXA1 results in significant expression level changes in thousands of individual transcripts, along with isoform switching events in key regulators of the cell cycle". For our session we have used their Sailfish gene-level estimated counts and hence are restricted to protein-coding genes only. ```{r} library(DESeq2) ``` #importing data ```{r} metaFile <- "GSE37704_metadata.csv" countFile <- "GSE37704_featurecounts.csv" ``` ```{r} colData = read.csv(metaFile, row.names=1) head(colData) ``` ```{r} countData = read.csv(countFile, row.names=1) head(countData) ``` #let's remove the first column ```{r} countData <-countData[,-1] ``` #remove genes containing zeros ```{r} countData<- countData [rowSums(countData) > 0, ] ``` ```{r} nrow(countData) ``` #Principal component analysis. the first step is usually to plot the data but here we have 15K genes. How do we plot this- PCA to the rescue! ```{r} pc<- prcomp( t(countData)) plot(pc) ``` ```{r} summary(pc) ``` #PCA plot with colors do distinguish controls and knock downs. ```{r} mycols<-c(rep("blue",3), rep ("red",3)) mycols plot(pc$x[,1:2],col=mycols) ``` #if I want to see the significance I have to plot a volcano plot ```{r} dds = DESeqDataSetFromMatrix(countData=countData, colData=colData, design=~condition) dds = DESeq(dds) ``` ```{r} dds ``` ```{r} res = results(dds) ``` ```{r} res<-results(dds) res ``` #volcano plot ```{r} plot( res$log2FoldChange, -log(res$padj) ) ``` ```{r} # Make a color vector for all genes mycols <- rep("gray", nrow(res) ) # Color red the genes with absolute fold change above 2 mycols[ abs(res$log2FoldChange) > 2 ] <- "red" ``` ```{r} # Color blue those with adjusted p-value less than 0.01 # and absolute fold change more than 2 inds <- (res$padj < 0.05) & (abs(res$log2FoldChange) > 2 ) mycols[ inds ] <- "blue" plot( res$log2FoldChange, -log(res$padj), col=mycols, xlab="Log2(FoldChange)", ylab="-Log(P-value)" ) ``` ```{r} library("AnnotationDbi") library("org.Hs.eg.db") columns(org.Hs.eg.db) ``` ```{r} res$symbol = mapIds (org.Hs.eg.db, keys=row.names(res), #gene names keytype="ENSEMBL", #format of your IDs column="SYMBOL", #what new IDs format you want? multiVals="first") res$entrez = mapIds(org.Hs.eg.db, keys=row.names(res), keytype="ENSEMBL", column="ENTREZID", multiVals="first") res$name = mapIds(org.Hs.eg.db, keys=row.names(res), keytype="ENSEMBL", column="GENENAME", multiVals="first") ``` ```{r} head(res, 10) ``` #PATHWAY ANALYSIS ```{r} ##BiocManager::install("c("pathview","gage","gageData")) if not already installed library(pathview) ``` ```{r} library(gage) ``` ```{r} library(gageData) ``` ```{r} data(kegg.sets.hs) data(sigmet.idx.hs) ``` ```{r} # Focus on signaling and metabolic pathways only kegg.sets.hs = kegg.sets.hs[sigmet.idx.hs] # Examine the first 3 pathways head(kegg.sets.hs, 3) ``` #The main gage() function requires a named vector of fold changes, where the names of the values are the Entrez gene IDs.Note that we used the mapIDs() function above to obtain Entrez gene IDs (stored in res$entrez) and we have the fold change results from DESeq2 analysis (stored in res$log2FoldChange). ```{r} foldchanges = res$log2FoldChange names(foldchanges) = res$entrez head(foldchanges) ``` #now let's ran the gage()function and get the results ```{r} keggres=gage(foldchanges, gsets = kegg.sets.hs) ``` ```{r} attributes(keggres) ``` #let's look at the down regulated pathways ```{r} head(keggres$less) ``` #Now, let's try out the pathview() function from the pathview package to make a pathway plot with our RNA-Seq expression results shown in color.To begin with lets manually supply a pathway.id (namely the first part of the "hsa04110 Cell cycle") that we could see from the print out above. ```{r} pathview(gene.data=foldchanges, pathway.id="hsa04110") ``` ![my first pathway](./hsa04110.pathview.png) <file_sep>/class12/class12.Rmd --- title: "Class12" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ## prepare protein structure for docking we want to download the 1HSG PDB structure and then produce a "protein" and ligand-only new separate PDB files. ```{r} library(bio3d) get.pdb("1hsg") ``` task: produce a "1hsg_protein.pdb" and "1hsg_ligand.pdb" file ```{r} pdb<-read.pdb("1hsg.pdb") pdb ``` ```{r} atom.select(pdb,"ligand",value=TRUE) ``` ```{r} ligand<-atom.select(pdb,"ligand",value=TRUE) write.pdb(ligand,file="1hsg_ligand.pdb") ``` ```{r} atom.select(pdb,"protein",value=TRUE) ``` ```{r} protein<-atom.select(pdb,"protein",value=TRUE) write.pdb(ligand,file="1hsg_ligand.pdb") ``` <file_sep>/class06/GiuliaLivrizziHomeworksgithub.md GiuliaLivrizziHomework ================ Giulia 10/18/2019 \#WORKING ON QUESTION 6 FOR HOMEWORK ``` r library(bio3d) ``` ``` r #this will be my input that I will apply: #pdbid <- "4AKE" (I can change this depending on the kinase) #This function will make possible to visualize B factor trends for different proteins. myfun <- function(pdbid, chain="A") { s1 <- read.pdb(pdbid) # pdbid of any protein of interest; chain A is already defined s1.chainA <- trim.pdb(s1, chain=chain, elety="CA") s1.b <- s1.chainA$atom$b #defining atoms plotb3(s1.b, sse=s1.chainA, typ="l", ylab="Bfactor") #plotting the results. } ``` ``` r myfun("1AKE") #testing if the function works again with another kinase name ``` ## Note: Accessing on-line PDB file ## PDB has ALT records, taking A only, rm.alt=TRUE ![](GiuliaLivrizziHomeworksgithub_files/figure-gfm/unnamed-chunk-3-1.png)<!-- --> \#Down here working on the other questions in class (not for homework): ``` r library(bio3d) s1 <- read.pdb("4AKE") # kinase with drug ``` ## Note: Accessing on-line PDB file ``` r s2 <- read.pdb("1AKE") # kinase no drug ``` ## Note: Accessing on-line PDB file ## Warning in get.pdb(file, path = tempdir(), verbose = FALSE): /var/folders/ ## <KEY>R<KEY>/1AKE.pdb exists. Skipping ## download ## PDB has ALT records, taking A only, rm.alt=TRUE ``` r s3 <- read.pdb("1E4Y") # kinase with drug ``` ## Note: Accessing on-line PDB file ``` r s1.chainA <- trim.pdb(s1, chain="A", elety="CA") s2.chainA <- trim.pdb(s2, chain="A", elety="CA") s3.chainA <- trim.pdb(s3, chain="A", elety="CA") s1.b <- s1.chainA$atom$b s2.b <- s2.chainA$atom$b s3.b <- s3.chainA$atom$b plotb3(s1.b, sse=s1.chainA, typ="l", ylab="Bfactor") ``` ![](GiuliaLivrizziHomeworksgithub_files/figure-gfm/unnamed-chunk-4-1.png)<!-- --> ``` r plotb3(s2.b, sse=s2.chainA, typ="l", ylab="Bfactor") ``` ![](GiuliaLivrizziHomeworksgithub_files/figure-gfm/unnamed-chunk-4-2.png)<!-- --> ``` r plotb3(s3.b, sse=s3.chainA, typ="l", ylab="Bfactor") ``` ![](GiuliaLivrizziHomeworksgithub_files/figure-gfm/unnamed-chunk-4-3.png)<!-- --> \#Q1:when we run read.pdb(nameofprotein) it searches online for the PDB file and it imports the data \#Q2: when we use trim.pdb,we can obtain a smaller subset of atoms from the large protein. In the argument you have to specify the chains and the targeted atoms and specify the element type(elety=CA). \#Q3:Troubloshooting:removing the black and grey boxes….but what are they?secondary structures forms. \#Q4:put them on the same graph plotb3(s1.b, sse=s1.chainA, typ=“l”, ylab=“Bfactor”) points(s3.b, typ=“l”, col=“blue”) points(s2.b, typ=“l”, col=“red”) \#Q5. Which proteins are more similar to each other in their B-factor trends. How could you quantify this? I corrected the mistake in the code to have s1,s2,s3 and so the more similar ones will be 1AKE and 1E4Y. \#create a function that plot them to quantify: hc \<- hclust( dist( rbind(s1.b, s2.b, s3.b) ) ) plot(hc) <file_sep>/class06/GiuliaLivrizziHomeworksgithub.Rmd --- title: "GiuliaLivrizziHomework" author: "Giulia" date: "10/18/2019" output: github_document --- #WORKING ON QUESTION 6 FOR HOMEWORK ```{r} library(bio3d) ``` ```{r} #this will be my input that I will apply: #pdbid <- "4AKE" (I can change this depending on the kinase) #This function will make possible to visualize B factor trends for different proteins. myfun <- function(pdbid, chain="A") { s1 <- read.pdb(pdbid) # pdbid of any protein of interest; chain A is already defined s1.chainA <- trim.pdb(s1, chain=chain, elety="CA") s1.b <- s1.chainA$atom$b #defining atoms plotb3(s1.b, sse=s1.chainA, typ="l", ylab="Bfactor") #plotting the results. } ``` ```{r} myfun("1AKE") #testing if the function works again with another kinase name ``` #Down here working on the other questions in class (not for homework): ```{r} library(bio3d) s1 <- read.pdb("4AKE") # kinase with drug s2 <- read.pdb("1AKE") # kinase no drug s3 <- read.pdb("1E4Y") # kinase with drug s1.chainA <- trim.pdb(s1, chain="A", elety="CA") s2.chainA <- trim.pdb(s2, chain="A", elety="CA") s3.chainA <- trim.pdb(s3, chain="A", elety="CA") s1.b <- s1.chainA$atom$b s2.b <- s2.chainA$atom$b s3.b <- s3.chainA$atom$b plotb3(s1.b, sse=s1.chainA, typ="l", ylab="Bfactor") plotb3(s2.b, sse=s2.chainA, typ="l", ylab="Bfactor") plotb3(s3.b, sse=s3.chainA, typ="l", ylab="Bfactor") ``` #Q1:when we run read.pdb(nameofprotein) it searches online for the PDB file and it imports the data #Q2: when we use trim.pdb,we can obtain a smaller subset of atoms from the large protein. In the argument you have to specify the chains and the targeted atoms and specify the element type(elety=CA). #Q3:Troubloshooting:removing the black and grey boxes....but what are they?secondary structures forms. #Q4:put them on the same graph plotb3(s1.b, sse=s1.chainA, typ="l", ylab="Bfactor") points(s3.b, typ="l", col="blue") points(s2.b, typ="l", col="red") #Q5. Which proteins are more similar to each other in their B-factor trends. How could you quantify this? I corrected the mistake in the code to have s1,s2,s3 and so the more similar ones will be 1AKE and 1E4Y. #create a function that plot them to quantify: hc <- hclust( dist( rbind(s1.b, s2.b, s3.b) ) ) plot(hc) <file_sep>/class18/class18.Rmd --- title: "class18" author: "<NAME>" date: "11/27/2019" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` <file_sep>/class14/class14.Rmd --- title: "class14" author: "<NAME>" date: "11/13/2019" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r} read.csv("airway_metadata.csv") ``` ```{r} read.csv("airway_scaledcounts.csv") ``` ```{r} counts <- read.csv("airway_scaledcounts.csv", stringsAsFactors = FALSE) metadata <- read.csv("airway_metadata.csv", stringsAsFactors = FALSE) ``` ```{r} head(counts) ``` ```{r} head(metadata) ``` #SETUP Bioconductor DESeq2 ```{r eval=FALSE} install.packages("BiocManager") BiocManager::install() BiocManager::install("DESeq2") ``` ```{r} head(metadata) ``` how many genes do we have in this data set? ```{r} nrow(counts) ``` how many experiments? ```{r} ncol(counts)-1 ``` let's make sure metadata id col matches the colnames of counts ```{r} colnames(counts)[-1] ``` ```{r} metadata$id ``` ```{r} all(colnames(counts)[-1] ==metadata$id) ``` all function to look across a vector of logicals ```{r} all(c(T,T,T)) ``` #Analysis: compare averages of controls are different from treated averages. First we need to access the columns of our countdata that are control and then find their mean. ```{r} metadata$dex =="control" ``` #these are the columns I want to access ```{r} control.id <-metadata[metadata$dex =="control", ]$id control.id ``` ```{r} head(counts[,control.id]) ``` #mean counts for control experiments(lenght(control.id) is number of columns -i.e. 4 here) ```{r} control.mean <-rowSums(counts[,control.id])/length(control.id) names(control.mean) <- counts$ensgene ``` #Do the same for drug treated exps ```{r} treated <- metadata[metadata [,"dex"]=="treated",] treated.mean <- rowSums(counts[, treated$id])/4 names(treated.mean) <- counts$ensgene ``` ```{r} meancounts <-data.frame(control.mean, treated.mean) ``` ```{r} plot(meancounts$control.mean, meancounts$treated.mean) ``` #Good case for a log plot ```{r} plot(meancounts$control.mean, meancounts$treated.mean, log="xy") ``` #add new column called log2fc to see the fold change ```{r} meancounts$log2fc <- log2(meancounts[,"treated.mean"]/meancounts[,"control.mean"]) head(meancounts) ``` #We want to remove NaN and the zero points from further analysis. Which will return only the values that you are looking for. #test for finding zero entries ```{r} x<- c(5,8,0,5) x==0 which(x==0) ``` ```{r} x<-data.frame(happy=c(5,6,0,0), sad=c(0,5,5,0)) x==0 ``` #arr.ind gives you more insights on the position (row and column) of the NAN or zero values. you can use it even to just know the position of a gene. unique allows you to exclude those ```{r} unique(which(x==0, arr.ind = TRUE)[,1]) ``` #focus on rows that only have zero entries ```{r} inds<-unique(which(x==0, arr.ind = TRUE)[,1]) x[-inds,] ``` #write another test ```{r} x<-data.frame(analine=c(1,2,0,0), giulia=c(0,0,3,0)) x==0 ``` ```{r} which(x==0, arr.ind = TRUE) ``` ```{r} unique(which(x==0, arr.ind = TRUE)[,1]) ``` # now apply it to our metacounts data (i.e. removing NaNs and zero) ```{r} to.rm<-unique(which(meancounts[,1:2]==0, arr.ind=TRUE)[,1]) mycounts <- meancounts[-to.rm,] head(mycounts) ``` #How many genes do I have left? ```{r} nrow(mycounts) ``` #A common threshold used for calling something differentially expressed is a log2(FoldChange) of greater than 2 or less than -2. Let’s filter the dataset both ways to see how many genes are up or down-regulated. ```{r} up.ind <- mycounts$log2fc > 2 down.ind <- mycounts$log2fc < (-2) ``` #To count how many are left: ```{r} sum(up.ind) sum(down.ind) ``` #In cases where you don't have a preferred annotation file at hand you can use other Bioconductor packages for annotation. #Bioconductor's annotation packages help with mapping various ID schemes to each other. Here we load the AnnotationDbi package and the annotation package org.Hs.eg.db. ```{r} library("AnnotationDbi") library("org.Hs.eg.db") ``` ```{r} columns(org.Hs.eg.db) ``` ```{r} mycounts$symbol <- mapIds(org.Hs.eg.db, keys=row.names(mycounts), # Our gene names keytype="ENSEMBL", # The format of our genenames column="SYMBOL", # The new format we want to add multiVals="first") ``` ```{r} head(mycounts) ``` #We still need to work on statistical tests. DESeq packages does everything we did for us included statistics. But in this way we learned a lot... ```{r} library(DESeq2) ``` #We will use the DESeqDataSetFromMatrix() function to build the required DESeqDataSet object and call it dds, short for our DESeqDataSet. ```{r} dds <- DESeqDataSetFromMatrix(countData=counts, colData=metadata, design=~dex, tidy=TRUE) ``` ```{r} dds <- DESeq(dds) ``` ```{r} res<-results(dds) res ``` #let's make a vulcano plot: summary figures are frequently used to highlight the proportion of genes that are both significantly regulated and display a high fold change.Typically these plots shows the log fold change on the X-axis, and the −log10 of the p-value on the Y-axis (the more significant the p-value, the larger the −log10 of that value will be). ```{r} plot(res$log2FoldChange, res$padj) ``` #the previous plot is not good because we are not seeing the data under p<0.05 which are the significant ones. Changing the axis would not work...we have to flip it adding -log. Points high up on the y-axis (above the horizontal line) are significantly regulated. ```{r} plot( res$log2FoldChange, -log(res$padj), xlab="Log2(FoldChange)", ylab="-Log(P-value)") ``` #We want color coding for significan changes and thresholds for -2 and 2 as well in the graph ```{r} plot(res$log2FoldChange, -log(res$padj), ylab="-Log(P-value)", xlab="Log2(FoldChange)") # Add some cut-off lines abline(v=c(-2,2), col="darkgray", lty=2) abline(h=-log(0.05), col="darkgray", lty=2) ``` ```{r} # Setup our custom point color vector mycols <- rep("gray", nrow(res)) mycols[ abs(res$log2FoldChange) > 2 ] <- "red" inds <- (res$padj < 0.01) & (abs(res$log2FoldChange) > 2 ) mycols[ inds ] <- "blue" # Volcano plot with custom colors plot( res$log2FoldChange, -log(res$padj), col=mycols, ylab="-Log(P-value)", xlab="Log2(FoldChange)" ) # Cut-off lines abline(v=c(-2,2), col="gray", lty=2) abline(h=-log(0.1), col="gray", lty=2) ``` <file_sep>/kmeanclass08.Rmd --- title: "machine learning" author: "<NAME>" date: "10/25/2019" output: html_document --- ##K-mean examples. Baby steps for machine learning (make up some data to cluster) ```{r} tmp <- c(rnorm(30,-3), rnorm(30,3)) #data are going to be flipped around -3/3 x <- cbind(x=tmp, y=rev(tmp)) plot(x) ``` #Use the kmeans() function setting k to 2 and nstart=20 #Inspect/print the results #Q. How many points are in each cluster? #Q. What ‘component’ of your result object details # cluster size? #cluster assignment/membership? #- cluster center? #Plot x colored by the kmeans cluster assignment and add cluster centers as blue points ```{r} k<-kmeans(x,centers=2,nstart=20) ``` ```{r} k$cluster ``` ```{r} table(k$cluster) ``` ```{r} plot(x,col=k$cluster) ##funciont point will add points to an existing plot points(k$centers, col="blue",pch=15) ``` #LET'S MOVE ON TO HIERARCHICAL CLUSTERING ```{r} hc <-hclust ( dist(x)) ``` #plot my results ```{r} plot (hc) abline(h=6, col="red") abline(h=4, col="blue") cutree(hc,h=6) ``` ```{r} grps<-cutree(hc,h=4) table(grps) ``` #I can also cut the tree to yeld a given 'k' groups/clusters ```{r} cutree(hc,k=2) ``` ```{r} plot(x, col=grps) ``` ```{r} # Step 1. Generate some example data for clustering x <- rbind( matrix(rnorm(100, mean=0, sd = 0.3), ncol = 2), # c1 matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2), # c2 matrix(c(rnorm(50, mean = 1, sd = 0.3), # c3 rnorm(50, mean = 0, sd = 0.3)), ncol = 2)) colnames(x) <- c("x", "y") ``` ```{r} # Step 2. Plot the data without clustering plot(x) ``` ```{r} # Step 3. Generate colors for known clusters # (just so we can compare to hclust results) col <- as.factor( rep(c("c1","c2","c3"), each=50) ) plot(x, col=col) ``` ```{r} hc <-hclust ( dist(x)) ``` #plot my results ```{r} plot (hc) ``` <file_sep>/class05/bimm143_05_rstats/Untitled.R read.table(file="bimm143_05_rstats/weight_chart.txt",header=TRUE) weight<-read.table(file="bimm143_05_rstats/weight_chart.txt", header=TRUE) plot(weight$Age,weight$Weight,typ="o", pch="15", cex= 1.5, lwd="2", ylim =c(2,10),xlab = "Age(Months)",ylab = "Weight(kg)",main = "weight") #pch changes the point character to be a filled square #cex=1.5 changes the plot point size to be 1.5x normal size #lwd=2 changes the line width thickness #ylim changes theyaxis limit #xlab and ylab change the axis labes #main changes the title on top of the plot.<file_sep>/README.md **Giulia's Bioinformatics Class (BGGN213, Fall 2019)** This is my work from [BGGN13 at UC San Diego] Fall 2019 Click [here](https://bioboot.github.io/bggn213_F19/) to go to the main class homepage. **Content of the class**: **-Class05:** [R graphics](https://github.com/giulialiv/bggn213/tree/master/class05) **-Class 06:** [R functions](https://github.com/giulialiv/bggn213/tree/master/class06) **-Class 07:** [R packages from CRAN and Bioconductor](https://github.com/giulialiv/bggn213/tree/master/class07) **-Class 08:** [introduction to machine learning](https://github.com/giulialiv/bggn213/tree/master/class08) **-class 09:** [unsuperised mini-project](https://github.com/giulialiv/bggn213/tree/master/class09) **-class 10:** [gene assignment] **class 11:** [structural bioinformatics](https://github.com/giulialiv/bggn213/tree/master/class11) **class 12:**[bioinformatics in drug discovery and analysis](https://github.com/giulialiv/bggn213/tree/master/class12) **class 13:** [no class] **class14:** [RNA seq](https://github.com/giulialiv/bggn213/tree/master/class14) **class 15:**[GO and KEGG](https://github.com/giulialiv/bggn213/tree/master/class15) **class 16:** [network analysis](https://github.com/giulialiv/bggn213/tree/master/class16) **class 17:** [UNIX](https://github.com/giulialiv/bggn213/tree/master/class17) **class 18:**[cancer genomics](https://github.com/giulialiv/bggn213/tree/master/class18) <file_sep>/class05/colorhistogram.R read.delim("bimm143_05_rstats/male_female_counts.txt", header=TRUE) mf<-read.delim("bimm143_05_rstats/male_female_counts.txt", header=TRUE) barplot(mf&Count, names.arg = mf$Sample, las=2, col=c("red","blue","green")) <file_sep>/class18/read.fastaGDC.Rmd --- title: "genomecancer" author: "<NAME>" date: "11/27/2019" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r} library(bio3d) ``` ```{r} seq<-read.fasta("lecture18_sequences.fa") ``` ```{r} seq ``` ```{r} ## Calculate positional identity scores ide <- conserv(seq$ali, method="identity") mutant.sites <- which(ide < 1) ``` ```{r} ## Exclude gap possitions from analysis gaps <- gap.inspect(seq) mutant.sites <- mutant.sites[mutant.sites %in% gaps$f.inds] mutant.sites ``` ```{r} ## Make a "names" label for our output sequences (one per mutant) mutant.names <- paste0(seq$ali["P53_wt",mutant.sites], mutant.sites, seq$ali["P53_mutant",mutant.sites]) mutant.names ``` ```{r} ## Sequence positions surounding each mutant site start.position <- mutant.sites - 8 end.position <- mutant.sites + 8 # Blank matrix to store sub-sequences store.seq <- matrix("-", nrow=length(mutant.sites), ncol=17) rownames(store.seq) <- mutant.names ## Extract each sub-sequence for(i in 1:length(mutant.sites)) { store.seq[i,] <- seq$ali["P53_mutant",start.position[i]:end.position[i]] } ``` ```{r} store.seq ``` ```{r} ## First blank out the gap positions store.seq[store.seq == "-"] <- "" ## Output a FASTA file for further analysis write.fasta(seq=store.seq, ids=mutant.names, file="subsequences.f") ``` <file_sep>/class08/genepractice.Rmd --- title: "PCAUKfood" author: "<NAME>" date: "10/25/2019" output: html_document --- ```{r} x <- read.csv("UK_foods.csv") mydata<-x ``` ```{r} dim(x) ``` ```{r} rownames(x) <- x[,1] x <- x[,-1] head(x) ``` ```{r} dim(x) ``` ```{r} barplot(as.matrix(x), beside=FALSE, col=rainbow(nrow(x))) ``` ```{r} pairs(x, col=rainbow(10), pch=16) ``` ```{r} pca <- prcomp( t(x) ) plot(pca$x[,1:2], xlab="PC1", ylab="PC2") text(pca$x[,1], pca$x[,2], colnames(x)) ``` ```{r} plot(pca$x[,1], pca$x[,2]) # xlab="PC1", ylab="PC2", xlim=c(-270,500) ) #text(pca$x[,1], pca$x[,2], colnames(x)) abline(h=0,col="grey",lty=2) ``` <file_sep>/class10/test.Rmd --- title: "Test" author: "<NAME>" date: "11/1/2019" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ## how to tell Git is important: add to stage by cliclink the box<file_sep>/class06/class.06.Rmd --- title: "Class 6 R functions" author: "Giulia" date: "10/18/2019" ``` ```{r} read.table ("test1.txt", sep="1", header="TRUE") ``` ```{r} ``` <file_sep>/class16/class16/class16.Rmd --- title: "class16" author: "<NAME>" date: "11/21/2019" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r} library(RCy3) ``` ```{r} library(igraph) ``` ```{r} library(RColorBrewer) ``` ```{r} # Test the connection to Cytoscape. cytoscapePing() ``` ```{r} # Check the version cytoscapeVersionInfo() ``` ```{r} g <- makeSimpleIgraph() createNetworkFromIgraph(g,"myGraph") ``` ```{r} fig <- exportImage(filename="demo", type="png", height=350) ``` ```{r} knitr::include_graphics("./demo.png") ``` ```{r} #play with Cytoscape stiles setVisualStyle("Marquee") ``` ```{r} fig <- exportImage(filename="demo_marquee", type="png", height=350) knitr::include_graphics("./demo_marquee.png") ``` ```{r} install.packages("readr") ``` ```{r} library(readr) ``` ```{r, echo=FALSE} class.file <- "https://bioboot.github.io/bimm143_S18/class-material/virus_prok_cor_abundant.tsv" dir.create("data") system("curl -O https://bioboot.github.io/bimm143_S18/class-material/virus_prok_cor_abundant.tsv data.") #download.file(class.file, "data/virus_prok_cor_abundant.tsv") ``` ```{r read-in-data} ## scripts for processing located in "inst/data-raw/" prok_vir_cor <- read.delim("./data/virus_prok_cor_abundant.tsv", stringsAsFactors = FALSE) ## Have a peak at the first 6 rows head(prok_vir_cor) ``` ``` ``` <file_sep>/class11/class11.Rmd --- title: "class11" output: github_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` #Q1: Download a CSV file from the PDB site (accessible from “Analyze” -> “PDB Statistics” #“by Experimental Method and Molecular Type”. Move this CSV file into your RStudio project #and determine the percentage of structures solved by X-Ray and Electron Microscopy. Also can #you determine what proportion of structures are protein ```{r} data<-read.csv("Data Export Summary.csv") ``` ```{r} total<-sum(data$Total) total ``` ```{r} data$Total ``` ```{r} ans <- data$Total/sum(data$Total) * 100 names(ans) <- data$Experimental.Method round(ans,2) ``` ```{r} round(sum(data$Proteins)/sum(data$Total) * 100, 2) ``` #working with biomolecular data in R ```{r} library(bio3d) ``` ```{r} pdb <- read.pdb("1hsg") ``` ```{r} pdb$atom ``` ``` ``` ```{r} pdb$atom[1,"resid"] ``` ```{r} aa321(pdb$atom[,"resid"]) ``` #select atoms Question 8. First select "protein" then write out a file: 1hsg_protein.pdb" ```{r} #atom select() prot<- atom.select(pdb, "protein", value=TRUE) #write.pdb() write.pdb(prot, file="1hsg_protein.pdb") ``` #now the same for the ligan ```{r} #atom select(): this function might be confusing so think about it as in vmd when we select for the ligand only or the protein. lig<- atom.select(pdb, "ligand", value=TRUE) #write.pdb() write.pdb(lig, file="1hsg_ligand.pdb") ``` ```{r} library(bio3d.view) #view(lig) view(pdb,"overview",col="sse") #this package bio3d.view is not working on all platform wight now. ``` #computing connectivity from coordinates: let's try a NMA: ```{r} # Load the package pdb <- read.pdb("1hel") # Normal mode analysis calculation modes <- nma(pdb) m7 <- mktrj(modes, mode=7, file="mode_7.pdb") view(m7, col=vec2color( rmsf(m7) )) ``` <file_sep>/class11/class11.md class11 ================ \#Q1: Download a CSV file from the PDB site (accessible from “Analyze” -\> “PDB Statistics” \#“by Experimental Method and Molecular Type”. Move this CSV file into your RStudio project \#and determine the percentage of structures solved by X-Ray and Electron Microscopy. Also can \#you determine what proportion of structures are protein ``` r data<-read.csv("Data Export Summary.csv") ``` ``` r total<-sum(data$Total) total ``` ## [1] 157530 ``` r data$Total ``` ## [1] 140299 12815 3961 303 152 ``` r ans <- data$Total/sum(data$Total) * 100 names(ans) <- data$Experimental.Method round(ans,2) ``` ## X-Ray NMR Electron Microscopy ## 89.06 8.13 2.51 ## Other Multi Method ## 0.19 0.10 ``` r round(sum(data$Proteins)/sum(data$Total) * 100, 2) ``` ## [1] 92.71 \`\`\` <file_sep>/class07/class07.md class07 ================ <NAME> 10/23/2019 ``` r source("http://tinyurl.com/rescale-R") ``` ``` r rescale(1:10) ``` ## [1] 0.0000000 0.1111111 0.2222222 0.3333333 0.4444444 0.5555556 0.6666667 ## [8] 0.7777778 0.8888889 1.0000000 \#understand the stop function which is built in our code. It allows you to give a more specific comment if an error occurs. # “\!” will flip something in true/false \#We want to write a function, called both\_na(), that counts how many positions in two input vectors, x and y, both have a missing value. start with a simple definition of x and y. You can use & (means and) to check at the same time 2 variables. ``` r x<- c (1,2,NA, 3,NA) y<-c( NA,3,NA,3,4) is.na(x) & is.na(y) ``` ## [1] FALSE FALSE TRUE FALSE FALSE ``` r which(is.na(x)) ``` ## [1] 3 5 \#let’s start making the code more straightforward ``` r both_na<- function(x,y) { sum(is.na(x)$is.na(y)) } ``` \#number of cases where we have both NA but we have to check the lenghts before to make them match ``` r both_na2 <- function(x, y) { if(length(x) != length(y)) { stop("inputs do not have the same lenght") } sum( is.na(x) & is.na(y) ) } ``` ``` r # student 1 s1<-c(100, 100, 100, 100, 100, 100, 100, 90) # student 2 s2<-c(100, NA, 90, 90, 90, 90, 97, 80) which.min (s1) ``` ## [1] 8 ``` r #exclude it from the average calculations mean(s2[-which.min(s2)],na.rm=TRUE) ``` ## [1] 92.83333 \`\`\` <file_sep>/class05/barplot_Compile.R read.csv(file="bimm143_05_rstats/feature_counts.txt", header = TRUE, sep="\t") mouse <-read.csv(file="bimm143_05_rstats/feature_counts.txt", header = TRUE, sep="\t") #or you can use read.delim("bimm143......) par(mar=c(4,11,4,2)) barplot(mouse$Count, names.arg =mouse$Feature, horiz=TRUE,las=1,main = "Number of features in the mouse GRCm38 genome",xlab="counts", col=rainbow(12)) #playwithcolors <file_sep>/genepracticeclass08.Rmd --- title: "data" author: "<NAME>" date: "10/25/2019" output: html_document --- ```{r} x <- read.csv("expression.csv",row.names = 1) mydata<-x ``` ```{r} pca <- prcomp(t(mydata), scale=TRUE) ``` ```{r} ## lets do PCA pca <- prcomp(t(mydata), scale=TRUE) ## See what is returned by the prcomp() function attributes(pca) # $names #[1] "sdev" "rotation" "center" "scale" "x" # # $class #[1] "prcomp" ``` ```{r} ## lets do PCA pca <- prcomp(t(mydata), scale=TRUE) ## See what is returned by the prcomp() function attributes(pca) # $names #[1] "sdev" "rotation" "center" "scale" "x" # # $class #[1] "prcomp" ``` ```{r} ## lets do PCA pca <- prcomp(t(mydata), scale=TRUE) ## A basic PC1 vs PC2 2-D plot plot(pca$x[,1], pca$x[,2]) ## Precent variance is often more informative to look at pca.var <- pca$sdev^2 pca.var.per <- round(pca.var/sum(pca.var)*100, 1) barplot(pca.var.per, main="Scree Plot", xlab="Principal Component", ylab="Percent Variation") ``` ```{r} plot(pca$x[,1:2], col=c("red","red","red","red","red","blue","blue","blue","blue", "blue")) #we can use function replicate to make the code shorter rep("red",5) ``` <file_sep>/class05/bimm143_05_rstats/color_to_value_map.r map.colors <- function (value,high.low,palette) { proportion <- ((value-high.low[1])/(high.low[2]-high.low[1])) index <- round ((length(palette)-1)*proportion)+1 return (palette[index]) }<file_sep>/class09/class09.Rmd --- title: "unsupervisedproject" author: "<NAME>" date: "10/30/2019" output: html_document --- ##Data input ```{r} library(readr) WisconsinCancer <- read.csv("WisconsinCancer.csv") View(WisconsinCancer) ``` ```{r} wisc.df<-read.csv("WisconsinCancer.csv") head(wisc.df) View(wisc.df) ``` here we examine data from `r nrow(wisc.df)` patient samples ```{r} knitr::opts_chunk$set(echo=TRUE) ``` ```{r} class(read.csv("WisconsinCancer.csv")) ``` ```{r} table(wisc.df$diagnosis) ``` In this data-set we have `rx["M"]` cancer and `r["B"]` non-cancer ```{r} wisc.data<-as.matrix(wisc.df[,3:32]) ``` ```{r} #access only mean columns colnames(wisc.df) ``` too look for patterns (like which column has a mean value) you can call `grep()` ```{r} grep("_mean", colnames(wisc.df), value = TRUE) ``` TO FIND OUT HOW MANY THERE ARE I CAN CALL `lenght()` on the result of `grep()` ```{r} lenght (grep("_mean", colnames(wisc.df), value = TRUE)) ``` performing PCA. Do we need to scale the data? this runs apply over the 2 columns and round the 3 ```{r} round(apply(wisc.data,2,sd),3) ``` looks like we need to `scale=TRUE` since our data are like everywhere(i.e sd values were too different from each other) ```{r} wisc.pr<-prcomp(wisc.data, scale=TRUE) summary(wisc.pr) ``` Plot PC1 vs PC2 and color by M/B cancer/noncancer diagnosis with no colors ```{r} plot (wisc.pr$x[,1], wisc.pr$x[,2]) ``` Plot PC1 vs PC2 and color by M/B cancer/noncancer diagnosis with colors ```{r} plot(wisc.pr$x[,1:2], col=wisc.df$diagnosis) ``` ```{r} x<-summary(wisc.pr) ``` the first PC captures `x$importance[,"PC1"]*100` of the original variance in the dataset ```{r} x$importance[,"PC1"] ``` Q8. How many principal components (PCs) are required to describe at least 70% of the original variance in the data? here I am looking for where my numbers get over 0.70. this cose will return logicals like TRUE or FALSE. ```{r} which(x$importance[3,]>0.7) ``` we can score genes based on how much they influence PC1. Cell1 PC1 score = (read count * influence) + … for all genes ```{r} data.scaled <-scale(wisc.data) ``` ```{r} data.dist <- dist(data.scaled) ``` ```{r} hclust(dist(wisc.pr$x[,1:3])) y<-hclust(dist(wisc.pr$x[,1:3])) plot(y) ``` ```{r} data.scaled<-scale(wisc.data) wisc.hclust<-hclust(dist(data.scaled)) plot(wisc.hclust) ``` ```{r} grps <- cutree(y, k=2) table(grps) ``` let's try clustering in PCA space since this looks bad we will take the results of `prcomp()` and build our distance matrix in PC space rather than from our raw data take the first 7 PCs ```{r} wisc.pr.hclust<-hclust(dist(wisc.pr$x[,1:7], method="ward.D2")) plot(wisc.pr.hclust) ``` and the cluster member vector might be obtained from `cutree()` ```{r} grps<-cutree(wisc.pr.hclust,h=70) table(grps) ``` ```{r} table(d=wisc.df$diagnosis) ``` let's compare i.e. cross tabilate these results ```{r} table(grps,wisc.df$diagnosis) ``` <file_sep>/class07/class07.Rmd --- title: "class07" author: "<NAME>" date: "10/23/2019" output: github_document editor_options: chunk_output_type: console --- ```{r} source("http://tinyurl.com/rescale-R") ``` ```{r} rescale(1:10) ``` #understand the stop function which is built in our code. It allows you to give a more specific comment if an error occurs. # "!" will flip something in true/false #We want to write a function, called both_na(), that counts how many positions in two input vectors, x and y, both have a missing value. start with a simple definition of x and y. You can use & (means and) to check at the same time 2 variables. ```{r} x<- c (1,2,NA, 3,NA) y<-c( NA,3,NA,3,4) is.na(x) & is.na(y) ``` ```{r} which(is.na(x)) ``` #let's start making the code more straightforward ```{r} both_na<- function(x,y) { sum(is.na(x)$is.na(y)) } ``` #number of cases where we have both NA but we have to check the lenghts before to make them match ```{r} both_na2 <- function(x, y) { if(length(x) != length(y)) { stop("inputs do not have the same lenght") } sum( is.na(x) & is.na(y) ) } ``` ```{r} # student 1 s1<-c(100, 100, 100, 100, 100, 100, 100, 90) # student 2 s2<-c(100, NA, 90, 90, 90, 90, 97, 80) which.min (s1) #exclude it from the average calculations mean(s2[-which.min(s2)],na.rm=TRUE) ``` ```
470d4c8187b0bfdc0a1a1210b868492e8179080d
[ "Markdown", "R", "RMarkdown" ]
23
RMarkdown
giulialiv/bggn213
b60071a42cb664889db450f6b4d4b6822e59e581
152a02de0ce27be012491b3b79b4c0c1486196fa
refs/heads/master
<repo_name>Valentina2103/Laboratorio-POO<file_sep>/POO/Player.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace POO { class Player { public String hand; public AddCard() { } public Init() { } } } <file_sep>/POO/Card.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace POO { class Card { public Int16 score; public String symbol; public String color; public String maso; public Card(String maso, String symbol) { } } }
e3f6751d3390182b5fc376b10d26b8d91256649e
[ "C#" ]
2
C#
Valentina2103/Laboratorio-POO
fd2a40e70a05f0d006d41bcd02e1d5b3a995c730
71b494c36d67a430b225f8cc141e3500db7aafa3
refs/heads/master
<file_sep>require('../jquery.renderSurvey'); $('#app').renderSurvey({ "question": 'What is your favorite color?', "answers": ["Red", "Green", "Blue", "Orange"], "submitUrl": "http://example.com", }); <file_sep># jquery-rendersurvey Simple jQuery plugin to create dynamic, multiple choice survey questions. ## How To 1. Include the jquery.renderSurvey script in your page. 2. Render a survey inside any element like this: ``` javascript $('#some-element').renderSurvey({ "question":"What is your least favorite color?", "answers":[ "Red", "Green", "Blue", "Orange" ], "submitUrl":"http://example.com" }); ``` <file_sep>(function($) { $.fn.renderSurvey = function(options) { const $form = $(` <form method="POST" action="${options.submitUrl}"> <h1 class="jq-rs-title">${options.question}</h1> <div data-contain="answers"></div> <div style="clear:both;"></div> <div data-contain="submit"> <button disabled="disabled" class="jq-rs-btn jq-rs-centered" type="submit">Submit</button> </div> </form> `); const $answer = $(` <div data-value="" data-selected="0" data-contain="answer" class="jq-rs-pill jq-rs-pill-floated"> <label></label> </div> `); const $answer1 = $(` <div data-value="" data-selected="0" data-contain="answer" class="jq-rs-pill jq-rs-pill-floated"> <img></img> </div> `); const $selected = $(`<div data-role="selected" class="jq-rs-selected"></div>`); function formIsValid() { const $selected = $form.find('[data-selected="1"]'); //const $other = $form.find('[data-contain="other"] [name="other_answer"]'); const atLeastOneSelect = !!$selected.length; //const otherSpecified = !!$other.val(); if (atLeastOneSelect) { return true; } else { return false; } } function toggleForm(enabled) { if (enabled) { $form.find('[data-contain="submit"] [type="submit"]').removeAttr('disabled'); } else { $form.find('[data-contain="submit"] [type="submit"]').attr('disabled', 'disabled'); } } key = options.key; arr1[key] = []; console.log(key); $.each(options.answers, (index, answer) => { let $answerClone; if(answer.includes("http")) { $answerClone = $answer1.clone(); } else { $answerClone = $answer.clone(); } $answerClone.click((e) => { const selected = !!parseInt($answerClone.attr('data-selected')); const value = $answerClone.attr('data-value'); if (selected) { var index = arr1[key].indexOf(value); if (index > -1) { arr1[key].splice(index, 1); } $answerClone.find('[data-role="selected"]').remove(); $answerClone.find('input').remove(); $answerClone.attr('data-selected', 0); } else { arr1[key].push(value); let $input; if(answer.includes("http")){ $input = $(`<img src="${value}">`); } else { $input = $(`<input type="hidden" name="answers[]" value="${value}">`); } $answerClone.append($selected.clone()); //$answerClone.append($input); $answerClone.attr('data-selected', 1); } toggleForm(formIsValid()); }); if(answer.includes("http")) { $answerClone.attr('data-value', answer); $answerClone.find('img').attr('src',answer); $answerClone.find('[name="answer"]').val(answer); $form.find('[data-contain="answers"]').append($answerClone); $form.attr('') } else { $answerClone.attr('data-value', answer); $answerClone.find('label').text(answer); $answerClone.find('[name="answer"]').val(answer); $form.find('[data-contain="answers"]').append($answerClone); $form.attr('') } }); $form.find('[data-contain="other"] [name="other_answer"]').on('input', () => { toggleForm(formIsValid()); }); this.append($form); return this; }; }(jQuery));
51b99d169236c8b9806c4db4684aeb2a9796baab
[ "JavaScript", "Markdown" ]
3
JavaScript
humanaise/humanaise.github.io
5d376f7e8003bfb70123476ffd1ba8ce451748a5
58143a390fadbb855d5a33f6cfd099200a496fbb
refs/heads/master
<file_sep># # TwitterBot/bots/statusbot.py """ - [x] Add the randomness of the Hashtags bot picks from the pull of hashtags - [ ] Create a function which tweets about the articles found on Economist - [ ] Create a function which tweets about the tech world news - [ ] Create a function which tweets about video games on Sundays """ import json import tweepy import logging import requests import random import time import dayandtime as dat from bs4 import BeautifulSoup from cfg import create_api logging.basicConfig(level=logging.INFO) LOGGER = logging.getLogger() class StatusUpdate(): """Bot Statusio - scraps the web-page for the new articles. Determins what day of the week it is, scraps articles from the predetermined pages and starts tweeting them. """ def __init__(self, api): self.api = api self.soups = [BeautifulSoup(requests.get(f'https://www.datasciencecentral.com/page/search?q={i}').text, 'html.parser') for i in ['AI', 'Machine+Learning', 'Deep+Learning']] def ds_central(self): ai_hashtags = ['DataScience', 'AI', 'MachineLearning', 'DataAnalytics', 'DataViz', 'BigData', 'ArtificialIntelligence', 'data', 'python', 'DeepLearning'] try: for s in self.soups: for i in s.find_all('a', href=True, text=True): if i['href'].startswith('https://www.datasciencecentral.com/profiles/blogs'): if i.string.startswith(('Subscribe', 'subscribe', 'See', 'More', 'Old')): pass else: hashtag = '' for h in random.sample(ai_hashtags, k=3): # Pick three unique random hashtags from the list. hashtag += " #" + str(h) self.api.update_status(str(i.string + ' >> ' + i['href']) + hashtag) except: self.api.update_status("How's your Data Science project going? #DataScience #MachineLearning #AI") def main(): api = create_api() # today = dat.find_day(dat.today()) # while today in ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']: while True: try: LOGGER.info(f'Today is a {today}, time to start posting') StatusUpdate(api).ds_central() except: LOGGER.info('waiting') time.sleep(300) # else: # print('Today is', today, 'I have an off') if __name__ == '__main__': main()
efe71cbb96c7f88e553cd7263ea06dec4cb95679
[ "Python" ]
1
Python
nestarz/TwitterBots
f5849fa694ca68054a99a0407ea081de56e51f46
cb08442e99e5d1b7cfcddc72a9212345e304cc02
refs/heads/master
<repo_name>n8glenn/FormBuilder<file_sep>/FormBuilder/Classes/Form Builder Classes/FBOptionSet.swift // // FBOptionSet.swift // FormBuilder // // Created by <NAME> on 5/6/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBOptionSet: NSObject { var id:String? = nil var range = (0, 0) // this is the range of lines in the spec file relating to this object. var field:FBField? = nil var options:Array<FBOption> = Array<FBOption>() public override init() { super.init() } public init(field:FBField?, file:FBFile, lines:(Int, Int)) { super.init() self.range = lines self.field = field var i:Int = lines.0 while (i <= lines.1) { switch (file.lines[i].keyword) { case FBKeyWord.Id: self.id = file.lines[i].value i += 1 break case FBKeyWord.Option: let optionIndent:Int = file.lines[i].indentLevel let optionSpace:Int = file.lines[i].spaceLevel i += 1 var optionRange = (i, i) while (i <= lines.1) { if ((file.lines[i].indentLevel > optionIndent) || (file.lines[i].spaceLevel > optionSpace) || (file.lines[i].keyword == FBKeyWord.None)) { i += 1 } else { break } } optionRange.1 = i - 1 self.options.append(FBOption(field: nil, file: file, lines: optionRange)) break default: i += 1 break } } } public func option(named: String) -> FBOption? { for option:FBOption in self.options { if (option.id.lowercased() == named.lowercased()) { return option } } return nil } public func optionArray()->Array<String> { var optionArray:Array<String> = Array<String>() for option:FBOption in self.options { optionArray.append(option.value) } return optionArray } public func updateOption(option:FBOption) { let oldOption = self.option(named: option.id) if (oldOption != nil) { oldOption!.value = option.value } else { self.options.append(option) } } } <file_sep>/FormBuilder/Classes/Form Builder Classes/FBDialog.swift // // FBDialog.swift // FormBuilder // // Created by <NAME> on 5/28/18. // import UIKit public enum FBDialogType:Int { case Date = 0 case Signature = 1 } open class FBDialog: NSObject { var field:FBInputField? = nil var tag:String? = nil var type:FBDialogType? = nil var style:FBStyleClass? = nil override public init() { super.init() } public init(type:FBDialogType, field:FBInputField, lines:(Int, Int)) { super.init() self.type = type self.field = field switch (self.type!) { case FBDialogType.Date: self.tag = "#DateDialog" break case FBDialogType.Signature: self.tag = "#SignatureDialog" break } if (FBStyleSet.shared.style(named: self.tag!) != nil) { self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: self.tag!)!) self.style!.parent = self.field!.style // override the default parents, our styles always descend from the style of the parent object! } var i:Int = lines.0 let file = self.field!.line!.section!.form!.file! while (i <= lines.1) { switch (file.lines[i].keyword) { case FBKeyWord.Style: if (FBStyleSet.shared.style(named: file.lines[i].value) != nil) { self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: file.lines[i].value)!) self.style!.parent = self.field!.style } i += 1 break default: i += 1 break } } } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/Label/FBLabelView.swift // // LabelView.swift // FormBuilder // // Created by <NAME> on 1/28/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBLabelView: FBFieldView { @IBOutlet var label:UILabel? var field:FBLabelField? override func height() -> CGFloat { return ((self.field!.style!.value(forKey: "margin") as! CGFloat) * 2.0) + self.field!.labelHeight + (self.field!.style!.value(forKey: "border") as! CGFloat) + 1.0 } override open func layoutSubviews() { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 self.label?.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2), height: self.frame.height - (margin * 2)) } open func updateDisplay(label:String) { self.label = UILabel() self.label?.numberOfLines = 0 self.addSubview(self.label!) self.label?.font = UIFont(name: self.field?.style!.value(forKey: "font-family") as! String, size: self.field?.style!.value(forKey: "font-size") as! CGFloat) self.label?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "foreground-color") as! String) self.label?.sizeToFit() self.label?.text = label } } <file_sep>/FormBuilder/Classes/Style/Parser/CssLexer.swift // // CssLexer.swift // SwiftCssParser // // Created by Mango on 2017/5/30. // Copyright © 2017年 Mango. All rights reserved. // import Foundation public class Lexer { let input: String var currentIndex: String.Index var currentCharcter : Character? public init(input: String) { self.input = input currentIndex = input.startIndex currentCharcter = input.first } public func consume() { guard currentIndex != input.endIndex else { return } currentIndex = input.index(after: currentIndex) if currentIndex == self.input.endIndex { currentCharcter = nil }else{ currentCharcter = self.input[currentIndex] } } } public class CssLexer: Lexer { public enum Token: CustomStringConvertible { case string(String) case selector(String) case double(Double) case rgb(Double,Double,Double,Double) case font(String,Double) case leftBrace //{ case rightBrace //} case colon //: case semicolon //; public var description: String { switch self { case let .string(string): return string case let .selector(selector): return selector case let .double(double): return String(double) case let .rgb(r,g,b,a): return "RGB(\(r),\(g),\(b),\(a))" case let .font(name,size): return "Font:\(name) size:\(size)" case .leftBrace: return "{" case .rightBrace: return "}" case .colon: return ":" case .semicolon: return ";" } } var type: String { switch self { case .string(_): return "StringType" case .selector(_): return "SelectorType" case .double(_): return "DoubleType" case .rgb(_, _, _, _): return "RGBType" case .font(_, _): return "FontType" default: return description } } } enum inputWrong: Error, CustomStringConvertible { case InvaidCharacter(Character) var description: String { switch self { case let .InvaidCharacter(character): return "Invalid character " + String(character) } } } } func ~=(pattern: (Character) -> Bool , value: Character) -> Bool { return pattern(value) } //MARK: Generate Tokens extension CssLexer { func nextToken() -> Token? { var consumedChars = [Character]() while let currentCharcter = self.currentCharcter { switch currentCharcter { case isSpace: self.consume() case "\n": self.consume() case isSelector: return combineSelector() case isLetter: return combineLetter() case isNumber: return combineNumber() case isRGB: return combineRGB() case ":": consume() return .colon case "{": consume() return .leftBrace case "}": consume() return .rightBrace case ";": consume() return .semicolon default: //fatalError("\(inputWrong.InvaidCharacter(currentCharcter)) Consumued:\(consumedChars)") self.consume() } consumedChars.append(currentCharcter) } return nil } func isSpace(char: Character) -> Bool { let string = String(char) let result = string.rangeOfCharacter(from: .whitespacesAndNewlines) return result != nil } func isLetter(char: Character) -> Bool { if char == "\"" { return true } else { return false } } func isAToZ(char: Character) -> Bool { if char >= "a" && char <= "z" || char >= "A" && char <= "Z" { return true }else{ return false } } func combineLetter() -> Token { self.consume() //吃掉" var string = "" while let next = self.currentCharcter , next != "\"" { string += String(next) self.consume() } self.consume() //吃掉" return .string(string) } func isSelector(char: Character) -> Bool { return char == "#" } func combineSelector() -> Token { var string = String(self.currentCharcter!) self.consume() while let next = self.currentCharcter , isAToZ(char: next) { string += String(next) self.consume() } return .selector(string) } func isNumber(char: Character) -> Bool { if (char >= "0" && char <= "9") || char == "." || char == "-" { return true } else { return false } } func combineNumber() -> Token { var string = String(self.currentCharcter!) self.consume() while let next = self.currentCharcter , isNumber(char: next) { string += String(next) self.consume() } if let double = Double(string) { return .double(double) } else { fatalError("Generate Number wrong with \(string)") } } func isRGB(char: Character) -> Bool { if char == "R" { return true } else { return false } } func combineRGB() -> Token { var string = "" while let next = self.currentCharcter { string += String(next) self.consume() if next == ")" { break } } string = string.removeCharacters(from: "RGB()") let values = string.components(separatedBy: ",") if values.count == 3 { return Token.rgb(Double(values[0])!, Double(values[1])!, Double(values[2])!, 1) } else if values.count == 4 { return Token.rgb(Double(values[0])!, Double(values[1])!, Double(values[2])!, Double(values[3])!) } else { fatalError("Invalid RGB value with \(string)") } } } extension String { public func removeCharacters(from forbiddenChars: CharacterSet) -> String { let passed = self.unicodeScalars.filter { !forbiddenChars.contains($0) } return String(String.UnicodeScalarView(passed)) } public func removeCharacters(from: String) -> String { return removeCharacters(from: CharacterSet(charactersIn: from)) } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/Date/FBDateView.swift // // DateView.swift // FormBuilder // // Created by <NAME> on 2/1/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit protocol FBDateViewDelegate: class { func selected(date:Date) func cleared() func dismiss() } open class FBDateView: UIView { @IBOutlet var datePicker:UIDatePicker? @IBOutlet var button:UIButton? @IBOutlet var deleteButton:UIButton? var textColor:UIColor = UIColor.white private var _buttonColor:UIColor = UIColor.gray var pickerWidth:CGFloat = 0.0 var pickerHeight:CGFloat = 0.0 var minimum:Date? = nil var maximum:Date? = nil weak var delegate:FBDateViewDelegate? override open func layoutSubviews() { self.datePicker!.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.width, height: self.frame.height - 60.0) self.deleteButton?.frame = CGRect(x: 5.0, y: (self.frame.height - 65.0), width: 50.0, height: 50.0) self.button?.frame = CGRect(x:(self.frame.width / 2.0) - ((self.frame.width - 10.0) / 2.0) + 55.0, y:(self.frame.height - 65.0), width:(self.frame.width - (10.0 + 50.0 + 5.0)), height:50.0) } open func updateDisplay(date:Date, buttonColor:UIColor, dateType:FBDateType) { let bundle = Bundle.init(for: self.classForCoder) // create "ok" button self.button = UIButton() self.button!.layer.cornerRadius = 7.5 self.button?.addTarget(self, action: #selector(okButtonPressed), for: UIControlEvents.touchUpInside) _buttonColor = buttonColor self.button?.backgroundColor = _buttonColor self.button?.setTitle("Ok", for: UIControlState.normal) self.button?.setTitleColor(UIColor.white, for: UIControlState.normal) self.addSubview(self.button!) // create delete button self.deleteButton = UIButton() self.deleteButton!.layer.cornerRadius = 7.5 self.deleteButton?.addTarget(self, action: #selector(deleteButtonPressed), for: UIControlEvents.touchUpInside) _buttonColor = buttonColor self.deleteButton?.backgroundColor = _buttonColor self.deleteButton?.setImage(UIImage.init(named: "trash-white", in: bundle, compatibleWith: nil), for: UIControlState.normal) self.deleteButton?.setTitleColor(UIColor.white, for: UIControlState.normal) self.addSubview(self.deleteButton!) // create date picker self.datePicker = UIDatePicker() self.datePicker?.setValue(self.textColor, forKey: "textColor") self.datePicker?.setValue(false, forKey: "highlightsToday") self.datePicker?.setDate(date, animated: false) switch (dateType) { case FBDateType.Date: self.datePicker?.datePickerMode = UIDatePickerMode.date break case FBDateType.Time: self.datePicker?.datePickerMode = UIDatePickerMode.time break case FBDateType.DateTime: self.datePicker?.datePickerMode = UIDatePickerMode.dateAndTime break } self.datePicker?.addTarget(self, action: #selector(dateChanged), for: UIControlEvents.valueChanged) self.addSubview(self.datePicker!) if (minimum != nil) { self.datePicker?.minimumDate = minimum } if (maximum != nil) { self.datePicker?.maximumDate = maximum } } @objc @IBAction func okButtonPressed() { if (self.delegate != nil) { self.delegate!.selected(date: self.datePicker!.date) self.delegate?.dismiss() } } @objc @IBAction func deleteButtonPressed() { if (self.delegate != nil) { self.delegate!.cleared() self.delegate?.dismiss() } } @objc @IBAction func dateChanged() { if (self.delegate != nil) { self.delegate!.selected(date: self.datePicker!.date) } } } <file_sep>/FormBuilder/Classes/Form Builder Classes/FBStyleSet.swift // // FBStyleSet.swift // FormBuilder // // Created by <NAME> on 2/5/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBStyleSet: NSObject { var classes:Array<FBStyleClass> = Array<FBStyleClass>() // initialize as a singleton... open class var shared:FBStyleSet { struct Singleton { static let instance = FBStyleSet() } return Singleton.instance; } func style(named: String) -> FBStyleClass? { for style in self.classes { if (style.name?.lowercased() == named.lowercased()) { return style } } return nil } private override init() { super.init() self.load(file: "Style") } open func load(file: String) { var path:URL? = nil path = Bundle.main.url(forResource: file, withExtension: "css") if (path == nil) { let bundle = Bundle.init(for: self.classForCoder) path = bundle.url(forResource: file, withExtension: "css") } if (path == nil) { return } let css = SwiftCSS(CssFileURL: path!) for item in css.parsedCss { //print(item) if (self.style(named: item.key) == nil) { let style:FBStyleClass = FBStyleClass() style.name = item.key style.properties = item.value as NSDictionary self.classes.append(style) } else { let style:FBStyleClass = self.style(named: item.key)! let properties:NSMutableDictionary = NSMutableDictionary(dictionary: style.properties!) for v in item.value { properties.setValue(v.value, forKey: v.key) } style.properties = NSDictionary(dictionary: properties) } } // go back and set the parents... for style in self.classes { if (style.properties!.value(forKey: "parent") != nil) { style.parent = self.style(named: style.properties!.value(forKey: "parent") as! String) } } } } <file_sep>/FormBuilder/Classes/Form Builder Classes/Fields/FBImageField.swift // // ImageField.swift // FormBuilder // // Created by <NAME> on 1/29/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class FBImageField: FBField { private var _data:Any? = nil override var data:Any? { get { return _data } set(newValue) { _data = newValue } } override public init() { super.init() } override public init(line:FBLine, lines:(Int, Int)) { super.init(line:line, lines:lines) self.tag = "#Image" if (FBStyleSet.shared.style(named: self.tag!) != nil) { self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: self.tag!)!) self.style!.parent = self.line!.style // override the default parents, our styles always descend from the style of the parent object! } var i:Int = lines.0 let file = self.line!.section!.form!.file! while (i <= lines.1) { switch (file.lines[i].keyword) { case FBKeyWord.Value: self.data = file.lines[i].value i += 1 break case FBKeyWord.Style: if (FBStyleSet.shared.style(named: file.lines[i].value) != nil) { self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: file.lines[i].value)!) } i += 1 break default: i += 1 break } } } var viewName:String { get { return self.style!.viewFor(type: self.fieldType) } } override var labelHeight:CGFloat { get { if (self.caption!.isEmpty) { return 0.0 } else { return self.caption!.height(withConstrainedWidth: self.width - (((self.style?.value(forKey: "margin") as! CGFloat) * 2) + self.borderWidth), font: self.style!.font) } } } } <file_sep>/Example/Podfile use_frameworks! target 'FormBuilder_Example' do pod 'FormBuilder', :path => '../' target 'FormBuilder_Tests' do inherit! :search_paths pod 'Quick', '~> 1.3.2' pod 'Nimble', '~> 7.3.1' end end <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/ComboBox/FBComboBoxFieldView.swift // // ComboBoxFieldView.swift // FormBuilder // // Created by <NAME> on 1/18/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBComboBoxFieldView: FBFieldView { @IBOutlet var label:UILabel? @IBOutlet var dropDownLabel:UILabel? @IBOutlet var button:FBDropDownView? @IBOutlet var requiredView:FBRequiredView? var gestureRecognizer:UITapGestureRecognizer? var field:FBField? override open func height() -> CGFloat { let margin:CGFloat = (self.field?.style?.value(forKey: "margin") as? CGFloat) ?? 5.0 let border:CGFloat = (self.field?.style?.value(forKey: "border") as? CGFloat) ?? 1.5 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: return (margin * 2) + self.field!.labelHeight + border case FBOrientation.Vertical: return (self.field!.labelHeight * 2) + (margin * 3) + border case FBOrientation.ReverseHorizontal: return (margin * 2) + self.field!.labelHeight + border case FBOrientation.ReverseVertical: return (self.field!.labelHeight * 2) + (margin * 3) + border case FBOrientation.PlaceHolder: return (margin * 2) + self.field!.labelHeight + border } } override open func layoutSubviews() { let labelWidth:CGFloat = (self.label!.text?.width(withConstrainedHeight: self.field!.textHeight, font: self.label!.font))! let margin:CGFloat = (self.field?.style?.value(forKey: "margin") as? CGFloat) ?? 5.0 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: self.label?.frame = CGRect(x: margin, y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: labelWidth, height: self.field!.labelHeight) self.button?.frame = CGRect(x: labelWidth + (margin * 2), y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - (labelWidth + self.field!.requiredWidth + (margin * 4)), height: self.field!.labelHeight) self.dropDownLabel?.frame = CGRect(x: labelWidth + (margin * 3), y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - (labelWidth + self.field!.requiredWidth + (margin * 5)), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.Vertical: self.label?.frame = CGRect(x: margin, y: margin, width: self.frame.width - (self.field!.requiredWidth + (margin * 2)), height: self.field!.labelHeight) self.button?.frame = CGRect(x: margin, y: self.field!.labelHeight + (margin * 2), width: self.frame.width - (self.field!.requiredWidth + (margin * 3)), height: self.field!.labelHeight) self.dropDownLabel?.frame = CGRect(x: margin * 2, y: self.field!.labelHeight + (margin * 2), width: self.frame.width - (self.field!.requiredWidth + (margin * 3)), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: self.button!.frame.origin.y + ((self.button!.frame.height / 2.0) - (self.field!.requiredHeight / 2.0)), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.ReverseHorizontal: self.button?.frame = CGRect(x: margin, y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - (labelWidth + self.field!.requiredWidth + (margin * 4)), height: self.field!.labelHeight) self.dropDownLabel?.frame = CGRect(x: margin * 2, y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - (labelWidth + self.field!.requiredWidth + (margin * 5)), height: self.field!.labelHeight) self.label?.frame = CGRect(x: self.button!.frame.width + (margin * 2), y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: labelWidth, height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.ReverseVertical: self.button?.frame = CGRect(x: margin, y: margin, width: self.frame.width - (self.field!.requiredWidth + (margin * 3)), height: self.field!.labelHeight) self.dropDownLabel?.frame = CGRect(x: margin * 2, y: margin, width: self.frame.width - (self.field!.requiredWidth + (margin * 4)), height: self.field!.labelHeight) self.label?.frame = CGRect(x: margin, y: self.field!.labelHeight + (margin * 2), width: self.frame.width - (margin * 3), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: self.dropDownLabel!.frame.origin.y + ((self.dropDownLabel!.frame.height / 2.0) - (self.field!.requiredHeight / 2.0)), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.PlaceHolder: self.label?.isHidden = true self.button?.frame = CGRect(x: margin, y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - (self.field!.requiredWidth + (margin * 3)), height: self.field!.labelHeight) self.dropDownLabel?.frame = CGRect(x: margin * 2, y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - (self.field!.requiredWidth + (margin * 3)), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break } } @objc @IBAction func buttonPressed() { // show popup dialog here to allow selecting an item. let configuration:FTConfiguration = FTConfiguration.shared configuration.menuWidth = button!.frame.width FTPopOverMenu.showForSender(sender: button!, with: field!.optionSet!.optionArray(), done: { (selectedIndex) -> () in self.dropDownLabel?.text = (self.field?.optionSet?.options[selectedIndex].value)! self.field!.input = self.field?.optionSet?.options[selectedIndex].id }) { } } open func updateDisplay(label:String, text:String, required:Bool) { self.label = UILabel() self.label?.font = UIFont(name: self.field?.style!.value(forKey: "font-family") as! String, size: self.field?.style!.value(forKey: "font-size") as! CGFloat) self.label?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "foreground-color") as! String) self.addSubview(self.label!) self.label!.sizeToFit() self.dropDownLabel = UILabel() self.dropDownLabel?.font = UIFont(name: self.field?.style!.value(forKey: "input-font-family") as! String, size: self.field?.style!.value(forKey: "input-font-size") as! CGFloat) self.dropDownLabel?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "input-foreground-color") as! String) self.addSubview(self.dropDownLabel!) self.button = FBDropDownView.fromNib(withName: "FBDropDownView") self.button!.backgroundColor = UIColor.clear self.addSubview(self.button!) self.gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(buttonPressed)) self.button!.addGestureRecognizer(self.gestureRecognizer!) self.requiredView = FBRequiredView() self.addSubview(self.requiredView!) if (self.field!.editing) { // set this field to edit mode self.button?.isUserInteractionEnabled = true self.button?.isHidden = false self.requiredView?.isHidden = !required self.dropDownLabel?.backgroundColor = UIColor.white switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: self.dropDownLabel?.textAlignment = NSTextAlignment.left break case FBOrientation.Vertical: self.dropDownLabel?.textAlignment = NSTextAlignment.left break case FBOrientation.ReverseHorizontal: self.dropDownLabel?.textAlignment = NSTextAlignment.left break case FBOrientation.ReverseVertical: self.dropDownLabel?.textAlignment = NSTextAlignment.left break case FBOrientation.PlaceHolder: self.dropDownLabel?.textAlignment = NSTextAlignment.left break } } else { // set this field to view mode self.button?.isUserInteractionEnabled = false self.button?.isHidden = true self.requiredView?.isHidden = true self.dropDownLabel?.backgroundColor = UIColor.clear switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: self.dropDownLabel?.textAlignment = NSTextAlignment.right break case FBOrientation.Vertical: self.dropDownLabel?.textAlignment = NSTextAlignment.left break case FBOrientation.ReverseHorizontal: self.dropDownLabel?.textAlignment = NSTextAlignment.left break case FBOrientation.ReverseVertical: self.dropDownLabel?.textAlignment = NSTextAlignment.left break case FBOrientation.PlaceHolder: self.dropDownLabel?.textAlignment = NSTextAlignment.right break } } self.label!.text = label self.dropDownLabel!.text = text } } <file_sep>/FormBuilder/Classes/Form Builder Classes/Fields/FBInputField.swift // // InputField.swift // FormBuilder // // Created by <NAME> on 2/2/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBInputField: FBField { private var _textViewHeight:CGFloat = 90.0 var requirements:Array<FBRequirement>? = Array<FBRequirement>() var valid:Bool = true var keyboard:UIKeyboardType = UIKeyboardType.default var capitalize:UITextAutocapitalizationType = UITextAutocapitalizationType.words private var _required:Bool = false override public var required:Bool { get { return _required } set(newValue) { _required = newValue } } private var _data:Any? = nil override public var data:Any? { get { return _data } set(newValue) { _data = newValue _input = newValue hasData = self.hasValue() //(newValue != nil) hasInput = self.hasValue() //(newValue != nil) } } private var _input:Any? = nil override public var input:Any? { get { return _input } set(newValue) { _input = newValue hasInput = self.hasValue() //(newValue != nil) self.line?.section?.form?.delegate?.updated(field: self, withValue: newValue) } } private var _editable:Bool? var editable:Bool? { get { // this field is ONLY editable if none of its parents are explicitly set as NOT editable. if ((self.line?.section?.form?.editable == nil) || (self.line?.section?.form?.editable == true)) { if ((self.line?.section?.editable == nil) || (self.line?.section?.editable == true)) { if ((self.line?.editable == nil) || (self.line?.editable == true)) { if ((_editable == nil) || (_editable == true)) { return true } } } } return false } set(newValue) { _editable = newValue } } override var mode:FBFormMode { get { if ((self.line?.section?.mode == FBFormMode.Edit) && self.editable!) { return FBFormMode.Edit } else if (self.line?.section?.mode == FBFormMode.Print) { return FBFormMode.Print } else { return FBFormMode.View } } } override var editing:Bool { get { return ((self.mode == FBFormMode.Edit) && (self.editable)!) } } var textViewHeight:CGFloat { get { var height:CGFloat = (self.data as! String).height(withConstrainedWidth: self.width - ((((self.style?.value(forKey: "margin") ?? 2.5) as! CGFloat) * 2) + self.borderWidth), font: self.style!.font) if (height < _textViewHeight) { height = _textViewHeight } return height } } override public init() { super.init() } override public init(line:FBLine, lines:(Int, Int)) { super.init(line:line, lines:lines) var i:Int = lines.0 self.range = lines let file = self.line!.section!.form!.file! while (i <= lines.1) { switch (file.lines[i].keyword) { case FBKeyWord.Required: self.required = (file.lines[i].value.lowercased() == "true") i += 1 break case FBKeyWord.Editable: self.editable = (file.lines[i].value.lowercased() != "false") i += 1 break case FBKeyWord.Requirements: let indentLevel:Int = file.lines[i].indentLevel let spaceLevel:Int = file.lines[i].spaceLevel i += 1 while (i <= lines.1) { if ((file.lines[i].indentLevel > indentLevel) || (file.lines[i].spaceLevel > spaceLevel) || (file.lines[i].keyword == FBKeyWord.None)) { self.requirements?.append(FBRequirement(line: file.lines[i])) i += 1 } else { break } } break case FBKeyWord.Dialog: let indentLevel:Int = file.lines[i].indentLevel let spaceLevel:Int = file.lines[i].spaceLevel i += 1 while (i <= lines.1) { if ((file.lines[i].indentLevel > indentLevel) || (file.lines[i].spaceLevel > spaceLevel) || (file.lines[i].keyword == FBKeyWord.None)) { i += 1 } else { break } } break case FBKeyWord.Capitalize: switch (file.lines[i].value.lowercased()) { case "none": self.capitalize = .none break case "allcharacters": self.capitalize = .allCharacters break case "sentences": self.capitalize = .sentences break case "words": self.capitalize = .words break default: self.capitalize = .words break } i += 1 break case FBKeyWord.Keyboard: switch (file.lines[i].value.lowercased()) { case "default": self.keyboard = .default break case "asciicapable": self.keyboard = .asciiCapable break case "asciicapablenumberpad": if #available(iOS 10, *) { self.keyboard = .asciiCapableNumberPad } else { self.keyboard = .default } break case "alphabet": self.keyboard = .alphabet break case "numberpad": self.keyboard = .numberPad break case "numbersandpunctuation": self.keyboard = .numbersAndPunctuation break case "emailaddress": self.keyboard = .emailAddress break case "decimalpad": self.keyboard = .decimalPad break case "url": self.keyboard = .URL break case "phonepad": self.keyboard = .phonePad break case "namephonepad": self.keyboard = .namePhonePad break case "twitter": self.keyboard = .twitter break case "websearch": self.keyboard = .webSearch break default: self.keyboard = .default break } i += 1 break default: i += 1 break } } } override func validate() -> FBException { let exception:FBException = FBException() exception.field = self if (self.required == true) { if (!self.hasInput) { exception.errors.append(FBRequirementType.Required) return exception } } if (self.requirements != nil) { for requirement in (self.requirements)! { if (!requirement.satisfiedBy(field: self)) { exception.errors.append(requirement.type) } } } return exception } override public func clear() { _input = _data hasInput = self.hasValue() //(_data != nil) } func hasValue() -> Bool { if (isNil(someObject: self.input)) { return false } switch (self.fieldType) { case FBFieldType.CheckBox: return ((self.input is Bool) && (self.input as! Bool) == true) case FBFieldType.OptionSet, FBFieldType.ComboBox, FBFieldType.Text, FBFieldType.TextArea: return ((self.input is String) && !(self.input as! String).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty) default: return self.input != nil } } } <file_sep>/FormBuilder/Classes/Form Builder Classes/Fields/FBImagePickerField.swift // // ImagePickerField.swift // FormBuilder // // Created by <NAME> on 1/29/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public enum FBImagePickerMode:Int { case Album = 0 case Camera = 1 } class FBImagePickerField: FBInputField { var imagePickerMode:FBImagePickerMode = FBImagePickerMode.Album static func imagePickerModeWith(string:String) -> FBImagePickerMode { switch (string.lowercased()) { case "album": return FBImagePickerMode.Album case "camera": return FBImagePickerMode.Camera default: return FBImagePickerMode.Album } } override public init() { super.init() } override public init(line:FBLine, lines:(Int, Int)) { super.init(line:line, lines:lines) self.tag = "#ImagePicker" if (FBStyleSet.shared.style(named: self.tag!) != nil) { self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: self.tag!)!) self.style!.parent = self.line!.style // override the default parents, our styles always descend from the style of the parent object! } var i:Int = lines.0 let file = self.line!.section!.form!.file! while (i <= lines.1) { switch (file.lines[i].keyword) { case FBKeyWord.Value: self.data = file.lines[i].value i += 1 break case FBKeyWord.PickerMode: self.imagePickerMode = FBImagePickerField.imagePickerModeWith(string: file.lines[i].value) i += 1 break case FBKeyWord.Style: if (FBStyleSet.shared.style(named: file.lines[i].value) != nil) { self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: file.lines[i].value)!) } i += 1 break default: i += 1 break } } } var viewName:String { get { return self.style!.viewFor(type: self.fieldType) } } override var labelHeight:CGFloat { get { return self.caption!.height(withConstrainedWidth: self.labelWidth, font: self.style!.font) } } override var labelWidth: CGFloat { get { return (self.width / 2.0) - (((self.style?.value(forKey: "margin") as! CGFloat) * 2) + self.borderWidth) } } } <file_sep>/FormBuilder/Classes/Form Builder UI/FTPopOverMenu_Swift/UIControl+Point.swift // // UIControl+Point.swift // FTPopOverMenu_Swift // // Created by <NAME> on 28/07/2017. // Copyright © 2016 LiuFengting (https://github.com/liufengting) . All rights reserved. // import UIKit extension UIControl { // solution found at: http://stackoverflow.com/a/5666430/6310268 internal func setAnchorPoint(anchorPoint: CGPoint) { var newPoint = CGPoint(x: self.bounds.size.width * anchorPoint.x, y: self.bounds.size.height * anchorPoint.y) var oldPoint = CGPoint(x: self.bounds.size.width * self.layer.anchorPoint.x, y: self.bounds.size.height * self.layer.anchorPoint.y) newPoint = newPoint.applying(self.transform) oldPoint = oldPoint.applying(self.transform) var position = self.layer.position position.x -= oldPoint.x position.x += newPoint.x position.y -= oldPoint.y position.y += newPoint.y self.layer.position = position self.layer.anchorPoint = anchorPoint } } <file_sep>/FormBuilder/Classes/Style/Parser/SwiftCssTheme.swift // // SwiftCssTheme.swift // SwiftCssParser // // Created by Mango on 2017/6/3. // Copyright © 2017年 Mango. All rights reserved. // import UIKit public class SwiftCssTheme { public static let updateThemeNotification = Notification.Name("SwiftCSSThemeUpdate") public enum Theme { case day case night } public static var theme: Theme = .day { didSet { switch theme { case .day: self.themeCSS = SwiftCSS(CssFileURL: URL.CssURL(name: "day")) case .night: self.themeCSS = SwiftCSS(CssFileURL: URL.CssURL(name: "night")) } NotificationCenter.default.post(name: updateThemeNotification, object: nil) } } public static var themeCSS = SwiftCSS(CssFileURL: URL.CssURL(name: "day")) } private extension URL { static func CssURL(name:String) -> URL { return Bundle.main.url(forResource: name, withExtension: "css")! } } extension UIView { private struct AssociatedKeys { static var selector = "themeColorSelector" static var key = "themeColorKey" } var backgroundColorCSS: (selector: String,key: String) { get { guard let selector = objc_getAssociatedObject(self, &AssociatedKeys.selector) as? String else { return ("","") } guard let key = objc_getAssociatedObject(self, &AssociatedKeys.key) as? String else { return ("","") } return (selector,key) } set { let selector = newValue.selector let key = newValue.key objc_setAssociatedObject(self, &AssociatedKeys.selector, selector, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(self, &AssociatedKeys.key, key, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) NotificationCenter.default.addObserver(self, selector: #selector(_cssUpdateBackgroundColor), name: SwiftCssTheme.updateThemeNotification, object: nil) //set css and update backgroundColor _cssUpdateBackgroundColor() } } @objc private dynamic func _cssUpdateBackgroundColor() { self.backgroundColor = SwiftCssTheme.themeCSS.color(selector: self.backgroundColorCSS.selector, key: self.backgroundColorCSS.key) } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/Date/FBDatePickerView.swift // // DatePickerView.swift // FormBuilder // // Created by <NAME> on 1/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBDatePickerView: FBFieldView, FBDateViewDelegate { var field:FBDatePickerField? @IBOutlet var label:UILabel? @IBOutlet var button:UIButton? @IBOutlet var dateLabel:UILabel? @IBOutlet var requiredView:FBRequiredView? var minimum:Date? = nil var maximum:Date? = nil var popover:Popover? override func height() -> CGFloat { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 let border:CGFloat = self.field?.style?.value(forKey: "border") as? CGFloat ?? 1.5 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: return (margin * 2) + self.field!.labelHeight + border case FBOrientation.Vertical: return (margin * 3) + self.field!.labelHeight + self.field!.textHeight + border case FBOrientation.ReverseHorizontal: return (margin * 2) + self.field!.labelHeight + border case FBOrientation.ReverseVertical: return (margin * 3) + field!.labelHeight + field!.textHeight + border case FBOrientation.PlaceHolder: return (margin * 2) + self.field!.labelHeight + border } } override open func layoutSubviews() { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: self.label!.frame = CGRect(x: margin, y: margin, width: self.frame.width / 2, height: self.field!.labelHeight) self.button!.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2.0), height: self.frame.height - (margin * 2.0)) let width:CGFloat = (self.dateLabel!.text?.width(withConstrainedHeight: self.field!.labelHeight, font: self.field!.style!.font))! self.dateLabel!.frame = CGRect(x: self.frame.width - ((margin * 2.0) + self.field!.requiredWidth + width), y: margin, width: width, height: self.field!.labelHeight) self.dateLabel!.textAlignment = NSTextAlignment.right self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.Vertical: self.label!.frame = CGRect(x: margin, y: margin, width: self.frame.width / 2, height: self.field!.labelHeight) self.button!.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2.0), height: self.frame.height - (margin * 2.0)) let width:CGFloat = (self.dateLabel!.text?.width(withConstrainedHeight: self.field!.labelHeight, font: self.field!.style!.font))! self.dateLabel!.frame = CGRect(x: margin, y: (margin * 2) + self.field!.labelHeight, width: width, height: self.field!.labelHeight) self.dateLabel!.textAlignment = NSTextAlignment.left self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: margin + ((self.field!.labelHeight / 2.0) - (self.field!.requiredHeight / 2)), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.ReverseHorizontal: let width:CGFloat = (self.label!.text?.width(withConstrainedHeight: self.field!.labelHeight, font: self.field!.style!.font))! self.label!.frame = CGRect(x: self.frame.width - ((margin * 2.0) + self.field!.requiredWidth + width), y: margin, width: width, height: self.field!.labelHeight) self.button!.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2.0), height: self.frame.height - (margin * 2.0)) self.dateLabel!.frame = CGRect(x: margin, y: margin, width: self.frame.width / 2, height: self.field!.labelHeight) self.dateLabel!.textAlignment = NSTextAlignment.left self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.ReverseVertical: let width:CGFloat = (self.label!.text?.width(withConstrainedHeight: self.field!.labelHeight, font: self.field!.style!.font))! self.label!.frame = CGRect(x: margin, y: (margin * 2) + self.field!.labelHeight, width: width, height: self.field!.labelHeight) self.button!.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2.0), height: self.frame.height - (margin * 2.0)) self.dateLabel!.frame = CGRect(x: margin, y: margin, width: self.frame.width / 2, height: self.field!.labelHeight) self.dateLabel!.textAlignment = NSTextAlignment.left self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (margin * 2) + self.field!.labelHeight + (self.field!.labelHeight / 2.0) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.PlaceHolder: self.label!.frame = CGRect(x: margin, y: margin, width: self.frame.width / 2, height: self.field!.labelHeight) self.button!.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2.0), height: self.frame.height - (margin * 2.0)) let width:CGFloat = (self.dateLabel!.text?.width(withConstrainedHeight: self.field!.labelHeight, font: self.field!.style!.font))! self.dateLabel!.frame = CGRect(x: self.frame.width - ((margin * 2.0) + self.field!.requiredWidth + width), y: margin, width: width, height: self.field!.labelHeight) self.dateLabel!.textAlignment = NSTextAlignment.right self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break } } open func updateDisplay(label:String, text:String, required:Bool) { self.label = UILabel() self.label?.numberOfLines = 0 self.addSubview(self.label!) self.label?.font = UIFont(name: self.field?.style!.value(forKey: "font-family") as! String, size: self.field?.style!.value(forKey: "font-size") as! CGFloat) self.label?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "foreground-color") as! String) self.button = UIButton() self.button?.addTarget(self, action: #selector(buttonPressed), for: UIControlEvents.touchUpInside) self.addSubview(self.button!) self.requiredView = FBRequiredView() self.addSubview(self.requiredView!) self.dateLabel = UILabel() self.addSubview(self.dateLabel!) self.label?.font = self.field!.style!.font self.dateLabel?.font = self.field!.style!.font if (self.field!.editing) { self.button!.isUserInteractionEnabled = true self.requiredView!.isHidden = false } else { self.button!.isUserInteractionEnabled = false self.requiredView!.isHidden = true } self.label?.text = label self.dateLabel?.text = text for requirement in self.field!.requirements! { switch (requirement.type) { case FBRequirementType.Minimum: self.minimum = requirement.value as? Date break case FBRequirementType.Maximum: self.maximum = requirement.value as? Date break default: break } } } @objc @IBAction func buttonPressed() { let style:FBStyleClass = (FBStyleSet.shared.style(named: "#DatePopover"))! let width:CGFloat = style.value(forKey: "width") as! CGFloat let height:CGFloat = style.value(forKey: "height") as! CGFloat let dateView = FBDateView(frame: CGRect(x: 0.0, y: 0.0, width: width, height: height)) var date:Date = Date() if ((self.field!.data != nil) && (self.field!.data as? String) != "") { let dateFormatter:DateFormatter = DateFormatter() switch (self.field!.dateType) { case FBDateType.Date: dateFormatter.dateFormat = style.value(forKey: "date-format") as! String break case FBDateType.Time: dateFormatter.dateFormat = style.value(forKey: "time-format") as! String break case FBDateType.DateTime: dateFormatter.dateFormat = style.value(forKey: "date-time-format") as! String break } date = dateFormatter.date(from: (self.field!.data as? String)!)! } let buttonColor:UIColor = UIColor.init(hexString: style.value(forKey: "button-color") as! String)! let backgroundColor:UIColor = UIColor.init(hexString: style.value(forKey: "background-color") as! String)! let textColor:UIColor = UIColor.init(hexString: style.value(forKey: "foreground-color") as! String)! dateView.updateDisplay(date: date, buttonColor:buttonColor , dateType: self.field!.dateType) dateView.backgroundColor = backgroundColor dateView.textColor = textColor dateView.delegate = self let rect:CGRect = self.convert(self.bounds, to: nil) var popoverType:PopoverType = PopoverType.down if (rect.origin.y > (self.window!.bounds.height / 2.0)) { popoverType = PopoverType.up } else { popoverType = PopoverType.down } self.popover = Popover() let options = [ .type(popoverType), .animationIn(0.2), .animationOut(0.2), .color(backgroundColor), ] as [PopoverOption] self.popover = Popover(options: options, showHandler: nil, dismissHandler: nil) self.popover!.show(dateView, fromView: self.button!) } func selected(date: Date) { let style:FBStyleClass = (FBStyleSet.shared.style(named: "#DatePopover"))! let dateFormatter:DateFormatter = DateFormatter() switch (self.field!.dateType) { case FBDateType.Date: dateFormatter.dateFormat = style.value(forKey: "date-format") as! String break case FBDateType.Time: dateFormatter.dateFormat = style.value(forKey: "time-format") as! String break case FBDateType.DateTime: dateFormatter.dateFormat = style.value(forKey: "date-time-format") as! String break } self.dateLabel!.text = dateFormatter.string(from: date) self.field!.input = self.dateLabel!.text self.setNeedsLayout() } func cleared() { self.dateLabel!.text = "" self.field!.input = nil self.setNeedsLayout() } func dismiss() { self.popover?.dismiss() } } <file_sep>/Example/FormBuilder/MySettings.spec format id email value [A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,64} format id telephone value (\+\d{2}\s*(\(\d{2}\))|(\(\d{2}\)))?\s*\d{4,5}\-?\d{4} format id date value \b(?:20)?(\d\d)[-./](0?[1-9]|1[0-2])[-./](3[0-1]|[1-2][0-9]|0?[1-9])\b format id date-display value yyyy-MM-dd format id time-display value hh:mm:ss a format id date-time-display value yyyy-MM-dd hh:mm:ss a option-set id MyCountry option id CA value Canada option id ES value Spain option id OT value Other option id US value United States option-set id State option id AL value Alabama option id AK value Alaska option id AZ value Arizona option id AR value Arkansas <file_sep>/FormBuilder/Assets/Settings.spec format id email value [A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,64} format id telephone value (\+\d{2}\s*(\(\d{2}\))|(\(\d{2}\)))?\s*\d{4,5}\-?\d{4} format id date value \b(?:20)?(\d\d)[-./](0?[1-9]|1[0-2])[-./](3[0-1]|[1-2][0-9]|0?[1-9])\b format id date-display value yyyy-MM-dd format id time-display value hh:mm:ss a format id date-time-display value yyyy-MM-dd hh:mm:ss a option-set id Country option id AF value Afghanistan option id AX value Aland Islands option id AL value Albania option id DZ value Algeria option id AS value American Samoa option id AD value Andorra option id AO value Angola option id AI value Anguilla option id AQ value Antarctica option id AG value Antigua and Barbuda option id AR value Argentina option id AM value Armenia option id AW value Aruba option id AU value Australia option id AT value Austria option id AZ value Azerbaijan option id BS value Bahamas, The option id BH value Bahrain option id BD value Bangladesh option id BB value Barbados option id BY value Belarus option id BE value Belgium option id BZ value Belize option id BJ value Benin option id BM value Bermuda option id BT value Bhutan option id BO value Bolivia option id BQ value Bonaire, St. Eustat, Saba option id BA value Bosnia and Herzegovina option id BW value Botswanaa option id BV value Bouvet Island option id BR value Brazil option id IO value British Indian Ocean Territories option id VG value British Virgin Islands option id BN value Brunei Darussalam option id BG value Bulgaria option id BF value Burkina Faso option id BI value Burundi option id CV value Cabo Verde option id KH value Cambodia option id CM value Cameroon option id CA value Canada option id KY value Cayman Islands option id CF value Central African Republic option id TD value Chad option id CL value Chile option id CN value China option id CX value Christmas Island option id CC value Cocos (Keeling) Islands option id CO value Columbia option id KM value Comoros option id CG value Congo option id CD value Congo, Democratic Republic of the option id CK value Cooke Islands option id CR value Costa Rica option id CI value Cote D'Ivoire option id HR value Croatia option id CU value Cuba option id CW value Curacao option id CY value Cyprus option id CZ value Czech Republic option id DK value Denmark option id DJ value Djibouti option id DM value Dominica option id DO value Dominican Republic option id TP value East Timor (Timor-Leste) option id EC value Ecuador option id EG value Egypt option id SV value El Salvador option id GQ value Equatorial Guinea option id ER value Eritrea option id EE value Estonia option id ET value Ethiopia option id EU value European Union option id FK value Falkland Islands (Malvinas) option id FO value Faroe Islands option id FJ value Fiji option id FI value Finland option id FR value France option id GF value French Guiana option id PF value French Polynesia option id TF value French Southern Territories option id GA value Gabon option id GM value Gambia, the option id GE value Georgia option id DE value Germany option id GH value Ghana option id GI value Gibraltar option id GR value Greece option id GL value Greenland option id GD value Grenada option id GP value Guadeloupe option id GU value Guam option id GT value Guatemala option id GG value Guernsey and Alderney option id GF value Guiana, French option id GN value Guinea option id GW value Guinea-Bissau option id GP value Guinea, Equatorial option id GY value Guyana option id HT value Haiti option id HM value Heard and McDonald Islands option id VA value Holy City (Vatican) option id HN value Honduras option id HK value Hong Kong (China) option id HU value Hungary option id IS value Iceland option id IN value India option id ID value Indonesia option id IR value Iran, Islamic Republic of option id IQ value Iraq option id IE value Ireland option id IL value Israel option id IT value Italy option id CI value Ivory Coast (Cote d'Ivoire) option id JM value Jamaica option id JP value Japan option id JE value Jersey option id JO value Jordan option id KZ value Kazakhstan option id KE value Kenya option id KI value Kiribati option id KP value Korea, Democratic People's Republic of option id KR value Korea (South) Republic of option id KV value Kosovo option id KW value Kuwait option id KG value Kyrgyzstan option id LA value Lao People's Democratic Republic option id LV value Latvia option id LB value Lebanon option id LS value Lesotho option id LR value Liberia option id LY value Libyan Arab Jamahiriya option id LI value Liechtenstein option id LT value Lithuania option id LU value Luxembourg option id MO value Macao (China) option id MK value Macedonia, TFYR option id MG value Madagascar option id MW value Malawi option id MY value Malaysia option id MV value Maldives option id ML value Mali option id MT value Malta option id IM value Man, Isle of option id MH value Marshall Islands option id MQ value Martinique (FR) option id MR value Mauritania option id MU value Mauritius option id YT value Mayotte (FR) option id MX value Mexico option id FM value Micronesia, Federated States of option id MD value Moldova, Republic of option id MC value Monaco option id MN value Mongolia option id CS value Montenegro option id MS value Montserrat option id MA value Morocco option id MZ value Mozambique option id MM value Myanmar (ex-Burma) option id NA value Namibia option id NR value Nauru option id NP value Nepal option id NL value Netherlands option id AN value Netherlands Antilles option id NC value New Caledonia option id NZ value New Zealand option id NI value Nicaragua option id NE value Niger option id NG value Nigeria option id NU value Niue option id NF value Norfolk Island option id MP value Northern Mariana Islands option id NO value Norway option id OM value Oman option id PK value Pakistan option id PW value Palau option id PS value Palestine option id PA value Panama option id PG value Papua New Guinea option id PY value Paraguay option id PE value Peru option id PH value Philippines option id PN value Pitcairn Island option id PL value Poland option id PT value Portugal option id PR value Puerto Rico option id QA value Qatar option id RE value Reunion (FR) option id RO value Romania option id RU value Russia (Russian Federation) option id RW value Rwanda option id EH value Sahara, Western option id BL value Saint Barthelemy (FR) option id SH value Saint Helena (UK) option id KN value Saint Kitts and Nevis option id LC value Saint Lucia option id MF value Saint Martin (FR) option id PM value Saint Pierre & Miquelon (FR) option id VC value Saint Vincent & Grenadines option id WS value Samoa option id SM value San Marino option id ST value Sao Tome and Principe option id SA value Saudi Arabia option id SN value Senegal option id RS value Serbia option id SC value Seychelles option id SL value Sierra Leone option id SG value Singapore option id SK value Slovakia option id SI value Slovenia option id SB value Solomon Islands option id SO value Somalia option id ZA value South Africa option id GS value Saint George & South Sandwich option id SS value South Sudan option id ES value Spain option id LK value Sri Lanka (ex-Ceilan) option id SD value Sudan option id SR value Suriname option id SJ value Svalbard & Jan Mayen Islands option id SZ value Swaziland option id SE value Sweden option id CH value Switzerland option id SY value Syrian Arab Republic option id TW value Taiwan option id TJ value Tajikistan option id TZ value Tanzania, United Republic of option id TH value Thailand option id TP value Timor-Leste (East Timor) option id TG value Togo option id TK value Tokelau option id TO value Tonga option id TT value Trinidad & Tobago option id TN value Tunisia option id TR value Turkey option id TM value Turkmenistan option id TC value Turks and Caicos Islands option id TV value Tuvalu option id UG value Uganda option id UA value Ukraine option id AE value United Arab Emirates option id UK value United Kingdom option id US value United States option id UM value US Minor Outlying Islands option id UY value Uruguay option id UZ value Uzbekistan option id VU value Vanuatu option id VA value Vatican (Holy City) option id VE value Venezuela option id VN value Vietnam option id VG value Virgin Islands, British option id VI value Virgin Islands, U.S. option id WF value Wallis and Futuna option id EH value Western Sahara option id YE value Yemen option id ZM value Zambia option id ZW value Zimbabwe option id OT value Other option-set id State option id AL value Alabama option id AK value Alaska option id AZ value Arizona option id AR value Arkansas option id CA value Califormia option id CO value Colorado option id CT value Connecticut option id DE value Delaware option id FL value Florida option id GA value Georgia option id HI value Hawaii option id ID value Idaho option id IL value Illinois option id IN value Indiana option id IA value Iowa option id KS value Kansas option id KY value Kentucky option id LA value Louisiana option id Maine value ME option id MD value Maryland option id MA value Massachusetts option id MI value Michigan option id MN value Minnesota option id MS value Mississippi option id MO value Missouri option id MT value Montana option id NE value Nebraska option id NV value Nevada option id NH value New Hampshire option id NJ value New Jersey option id NM value New Mexico option id NY value New York option id NC value North Carolina option id ND value North Dakota option id OH value Ohio option id OK value Oklahoma option id OR value Oregon option id PA value Pennsylvania option id RI value Rhode Island option id SC value South Carolina option id SD value South Dakota option id TN value Tennessee option id TX value Texas option id UT value Utah option id VT value Vermont option id VA value Virginia option id WA value Washington option id WV value West Virginia option id WI value Wisconsin option id WY value Wyoming option-set id Delivery option id USPS value Express Mail option id UPS value UPS option id FEDEX value Fed Ex option-set id WeekDay option id MON value Monday option id TUE value Tuesday option id WED value Wednesday option id THU value Thursday option id FRI value Friday option id SAT value Saturday option id SUN value Sunday option-set id Month option id JAN value January option id FEB value February option id MAR value March option id APR value April option id MAY value May option id JUN value June option id JUL value July option id AUG value August option id SEP value September option id OCT value October option id NOV value November option id DEC value December option-set id TimeZone option id HST value Hawaii-Aleutian Standard Time option id AKST value Alaska Standard Time option id PST value Pacific Standard Time option id MST value Mountain Standard Time option id CST value Central Standard Time option id EST value Eastern Standard Time option id AST value Atlantic Standard Time <file_sep>/FormBuilder/Classes/Style/Parser/SwiftCSS.swift // // SwiftCSS.swift // SwiftCssParser // // Created by Mango on 2017/6/3. // Copyright © 2017年 Mango. All rights reserved. // import UIKit public class SwiftCSS { let parsedCss: [String:[String:Any]] public init(CssFileURL: URL) { let content = try! String(contentsOf: CssFileURL, encoding: .utf8) let lexer = CssLexer(input: content) let parser = CssParser(lexer: lexer) parser.parse() parsedCss = parser.outputDic } public func int(selector: String, key: String) -> Int { return Int(double(selector: selector, key: key)) } public func double(selector: String, key: String) -> Double { return value(selector: selector, key: key) ?? 0 } public func string(selector: String, key: String) -> String { return value(selector: selector, key: key) ?? "" } public func size(selector: String, key: String) -> CGSize { guard let dic: [String:Double] = value(selector: selector, key: key), let double1 = dic["double1"], let double2 = dic["double2"] else { return CGSize(width: 0, height: 0) } return CGSize(width: double1, height: double2) } public func color(selector: String, key: String) -> UIColor { if let rgb:(Double,Double,Double,Double) = value(selector: selector, key: key) { return UIColor(red: CGFloat(rgb.0/255), green: CGFloat(rgb.1/255), blue: CGFloat(rgb.2/255), alpha: CGFloat(rgb.3)) } else { return UIColor(string(selector: selector, key: key)) } } public func font(selector: String, key: String, fontSize: CGFloat = 14) -> UIFont { if let name: String = value(selector: selector, key: key) { return UIFont(name: name, size: fontSize) ?? UIFont.systemFont(ofSize: fontSize) } else if let dic: [String:Any] = value(selector: selector, key: key) { guard let name = dic["name"] as? String ,let size = dic["size"] as? Double else { return UIFont.systemFont(ofSize: fontSize) } return UIFont(name: name, size: CGFloat(size)) ?? UIFont.systemFont(ofSize: fontSize) } else { return UIFont.systemFont(ofSize: fontSize) } } private func value<T>(selector: String, key: String) -> T? { guard let dic = parsedCss[selector] else { return nil } guard let value = dic[key] as? T else { return nil } return value } } <file_sep>/FormBuilder/Assets/dictionary.spec dictionary name Country details Country Dictionary item code AF name Afghanistan option id AX value Aland Islands option id AL value Albania option id DZ value Algeria option id AS value American Samoa <file_sep>/FormBuilder/Classes/Form Builder Classes/FBRequirement.swift // // Requirement.swift // FormBuilder // // Created by <NAME> on 1/16/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public enum FBRequirementType:Int { case Required = 0 case Minimum = 1 case Maximum = 2 case Datatype = 3 case Format = 4 case MemberOf = 5 } class FBRequirement: NSObject { // Requirement -- Represents a condition that can be placed on a field. var type:FBRequirementType = FBRequirementType.Minimum; var value:Any? = nil; var members:Array<String> = Array<String>() override public init() { super.init() } public init(line:FBFileLine) { super.init() switch (line.keyword) { case FBKeyWord.Required: self.type = FBRequirementType.Required break case FBKeyWord.Minimum: self.type = FBRequirementType.Minimum break case FBKeyWord.Maximum: self.type = FBRequirementType.Maximum break case FBKeyWord.Format: self.type = FBRequirementType.Format break case FBKeyWord.MemberOf: self.type = FBRequirementType.MemberOf break default: break } self.value = line.value } func requirementTypeWith(string:String) -> FBRequirementType { switch (string.lowercased()) { case "required": return FBRequirementType.Required case "minimum": return FBRequirementType.Minimum case "maximum": return FBRequirementType.Maximum case "datatype": return FBRequirementType.Datatype case "format": return FBRequirementType.Format case "memberof": return FBRequirementType.MemberOf default: return FBRequirementType.Required } } func satisfiedBy(field:FBField) -> Bool { switch (field.fieldType) { case FBFieldType.ImagePicker: switch (self.type) { case FBRequirementType.Required: /* if ((field.input == nil) || (field.input as! String).isEmpty) { return false } */ break case FBRequirementType.Minimum: if (field.input != nil) { if ((field.input as! NSData).length < (self.value as! Int)) { return false } } break case FBRequirementType.Maximum: if (field.input != nil) { if ((field.input as! NSData).length > (self.value as! Int)) { return false } } break default: break } break case FBFieldType.Text, FBFieldType.TextArea: switch (self.type) { case FBRequirementType.Required: /* if ((field.input == nil) || (field.input as! String).isEmpty) { return false } */ break case FBRequirementType.Minimum: if (field.input != nil) { if ((field.input as! String).count < Int(self.value as! String) ?? 0) { return false } } break case FBRequirementType.Maximum: if (field.input != nil) { if ((field.input as! String).count > Int(self.value as! String) ?? 0) { return false } } break case FBRequirementType.Datatype: break case FBRequirementType.Format: if (field.input != nil) { let format:String = FBSettings.shared.formats[self.value as! String]! let emailTest = NSPredicate(format:"SELF MATCHES %@", format) let valid:Bool = emailTest.evaluate(with: field.input as! String) if (!valid) { return false } } break case FBRequirementType.MemberOf: if (field.input != nil) { var found:Bool = false let value:String = field.input as! String for member in self.members { if (value == member) { found = true break } } if (!found) { return false } } break } break case FBFieldType.ComboBox, FBFieldType.CheckBox, FBFieldType.OptionSet, FBFieldType.Signature: switch (self.type) { case FBRequirementType.Required: /* if (field.input == nil) { return false } */ break default: break } break case FBFieldType.DatePicker: switch (self.type) { case FBRequirementType.Required: /* if (field.input == nil) { return false } */ break case FBRequirementType.Minimum: if (field.input != nil) { let minDate:Date = self.value as! Date let date:Date = field.input as! Date if (date.compare(minDate) == ComparisonResult.orderedAscending) { return false } } break case FBRequirementType.Maximum: if (field.input != nil) { let maxDate:Date = self.value as! Date let date:Date = field.input as! Date if (date.compare(maxDate) == ComparisonResult.orderedDescending) { return false } } break case FBRequirementType.Format: if (field.input != nil) { let format:String = FBSettings.shared.formats[self.value as! String]! let emailTest = NSPredicate(format:"SELF MATCHES %@", format) let valid:Bool = emailTest.evaluate(with: field.input as! String) if (!valid) { return false } } break default: break } break default: break } return true } } <file_sep>/FormBuilder/Classes/Form Builder Classes/FBFile.swift // // FBFile.swift // FormBuilder // // Created by <NAME> on 5/3/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public class FBFile: NSObject { public var lines:Array<FBFileLine> = Array<FBFileLine>() public override init() { super.init() } public init(file:String) { super.init() self.load(file: file) } public func load(file: String) { var path:String? = nil path = Bundle.main.path(forResource: file, ofType: "spec") if (path == nil) { let bundle = Bundle.init(for: self.classForCoder) path = bundle.path(forResource: file, ofType: "spec") } if (path == nil) { return } do { let content:String = try String(contentsOfFile: path!, encoding: String.Encoding.utf8) var textlines = content.split(separator: "\n") var continued:Bool = false while (textlines.count > 0) { let line:FBFileLine = FBFileLine.init(line: (textlines.first?.description)!, continued: continued) continued = line.continued lines.append(line) textlines.removeFirst() } } catch _ as NSError { return } } } <file_sep>/Example/FormBuilder/MyCombo.swift // // MyCombo.swift // FormBuilder // // Created by <NAME> on 1/29/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import FormBuilder class MyCombo: FBComboBoxFieldView { override func height() -> CGFloat { // height is where we decide how high this field should be return 50.0 } override func updateDisplay(label:String, text:String, required:Bool) { // updateDisplay is where we add subviews to our field view programmatically and set up the behaviors for buttons, etc. } override func layoutSubviews() { // layoutSubviews is where we position all of the subviews of the form in relation to each other. } } <file_sep>/FormBuilder/Classes/Extensions/UIView+fromNib.swift // // UIView+fromNib.swift // FormBuilder // // Created by <NAME> on 1/22/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import UIKit extension UIView { class func fromNib<T>(withName nibName: String) -> T? { var bundle = Bundle.main switch nibName { case "FBCheckBoxView": bundle = Bundle.init(for: FBCheckBoxView.self) break case "FBCheckView": bundle = Bundle.init(for: FBCheckView.self) break case "FBComboBoxFieldView": bundle = Bundle.init(for: FBComboBoxFieldView.self) break case "FBDatePickerView": bundle = Bundle.init(for: FBDatePickerView.self) break case "FBDateView": bundle = Bundle.init(for: FBDateView.self) break case "FBDropDownView": bundle = Bundle.init(for: FBDropDownView.self) break case "FBSectionHeaderView": bundle = Bundle.init(for: FBSectionHeaderView.self) break case "FBHeadingView": bundle = Bundle.init(for: FBHeadingView.self) break case "FBImagePickerView": bundle = Bundle.init(for: FBImagePickerView.self) break case "FBImageView": bundle = Bundle.init(for: FBImageView.self) break case "FBLabelView": bundle = Bundle.init(for: FBLabelView.self) break case "FBOptionSetView": bundle = Bundle.init(for: FBOptionSetView.self) break case "FBOptionView": bundle = Bundle.init(for: FBOptionView.self) break case "FBRequiredView": bundle = Bundle.init(for: FBRequiredView.self) break case "FBSignatureView": bundle = Bundle.init(for: FBSignatureView.self) break case "FBSignView": bundle = Bundle.init(for: FBSignView.self) break case "FBTextAreaView": bundle = Bundle.init(for: FBTextAreaView.self) break case "FBTextFieldView": bundle = Bundle.init(for: FBTextFieldView.self) break default: break } let nib = UINib.init(nibName: nibName, bundle: bundle) let nibObjects = nib.instantiate(withOwner: nil, options: nil) for object in nibObjects { if let result = object as? T { return result } } return nil } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/Signature/FBSignatureView.swift // // SignatureView.swift // FormBuilder // // Created by <NAME> on 2/10/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBSignatureView: FBFieldView, FBSignViewDelegate { var field:FBSignatureField? @IBOutlet var label:UILabel? @IBOutlet var imageView:UIImageView? @IBOutlet var requiredView:FBRequiredView? @IBOutlet var button:UIButton? var popover:Popover? override func height() -> CGFloat { let style:FBStyleClass? = self.field!.dialog!.style ?? nil let margin:CGFloat = (self.field?.style?.value(forKey: "margin") as? CGFloat) ?? 5.0 let border:CGFloat = (self.field?.style?.value(forKey: "border") as? CGFloat) ?? 5.0 let height:CGFloat = style?.value(forKey: "height") as? CGFloat ?? 150.0 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: if (self.field!.labelHeight > height) { return (margin * 2) + self.field!.labelHeight + border } else { return (margin * 2) + height + border } case FBOrientation.Vertical: return (margin * 3) + self.field!.labelHeight + height + border case FBOrientation.ReverseHorizontal: if (self.field!.labelHeight > height) { return (margin * 2) + self.field!.labelHeight + border } else { return (margin * 2) + height + border } case FBOrientation.ReverseVertical: return (margin * 3) + self.field!.labelHeight + height + border case FBOrientation.PlaceHolder: if (self.field!.labelHeight > height) { return (margin * 2) + self.field!.labelHeight + border } else { return (margin * 2) + height + border } } } override open func layoutSubviews() { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 let style:FBStyleClass? = self.field!.dialog!.style ?? nil let width:CGFloat = style?.value(forKey: "width") as? CGFloat ?? 300.0 let height:CGFloat = style?.value(forKey: "height") as? CGFloat ?? 150.0 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: self.label!.frame = CGRect(x: margin, y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width / 2, height: self.field!.labelHeight) self.button!.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2.0), height: self.frame.height - (margin * 2.0)) self.imageView!.frame = CGRect(x: self.frame.width - ((margin * 2) + self.field!.requiredWidth + width), y: margin, width: width, height: height) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.Vertical: self.label!.frame = CGRect(x: margin, y: margin, width: self.frame.width / 2, height: self.field!.labelHeight) self.button!.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2.0), height: self.frame.height - (margin * 2.0)) self.imageView!.frame = CGRect(x: margin, y: margin, width: width, height: height) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: margin + ((self.field!.labelHeight / 2.0) - (self.field!.requiredHeight / 2)), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.ReverseHorizontal: let width:CGFloat = (self.label!.text?.width(withConstrainedHeight: self.field!.labelHeight, font: self.field!.style!.font))! self.label!.frame = CGRect(x: self.frame.width - ((margin * 2.0) + self.field!.requiredWidth + width), y: margin, width: width, height: self.field!.labelHeight) self.button!.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2.0), height: self.frame.height - (margin * 2.0)) self.imageView!.frame = CGRect(x: margin, y: margin, width: width, height: height) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.ReverseVertical: let width:CGFloat = (self.label!.text?.width(withConstrainedHeight: self.field!.labelHeight, font: self.field!.style!.font))! self.label!.frame = CGRect(x: margin, y: (margin * 2) + self.field!.labelHeight, width: width, height: self.field!.labelHeight) self.button!.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2.0), height: self.frame.height - (margin * 2.0)) self.imageView!.frame = CGRect(x: margin, y: margin, width: width, height: height) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (margin * 2) + self.field!.labelHeight + (self.field!.labelHeight / 2.0) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.PlaceHolder: self.label!.frame = CGRect(x: margin, y: margin, width: self.frame.width / 2, height: self.field!.labelHeight) self.button!.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2.0), height: self.frame.height - (margin * 2.0)) self.imageView!.frame = CGRect(x: margin, y: margin, width: width, height: height) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break } } open func updateDisplay(label:String, signature:UIImage?, required: Bool) { self.label = UILabel() self.label?.numberOfLines = 0 self.addSubview(self.label!) self.label?.font = UIFont(name: self.field?.style!.value(forKey: "font-family") as! String, size: self.field?.style!.value(forKey: "font-size") as! CGFloat) self.label?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "foreground-color") as! String) self.imageView = UIImageView() self.addSubview(self.imageView!) if (self.field?.input != nil) { self.imageView!.image = self.field!.input as? UIImage } self.button = UIButton() self.button?.addTarget(self, action: #selector(buttonPressed), for: UIControlEvents.touchUpInside) self.addSubview(self.button!) self.requiredView = FBRequiredView() self.addSubview(self.requiredView!) self.label!.text = label self.label?.sizeToFit() if (self.field!.editing) { // set this field to edit mode self.requiredView?.isHidden = !required self.button!.isUserInteractionEnabled = true } else { // set this field to view mode self.requiredView?.isHidden = true self.button!.isUserInteractionEnabled = false } } @objc @IBAction func buttonPressed() { let style:FBStyleClass? = self.field!.dialog!.style ?? nil let width:CGFloat = style?.value(forKey: "width") as? CGFloat ?? 300.0 let height:CGFloat = style?.value(forKey: "height") as? CGFloat ?? 150.0 let backgroundColor:UIColor = UIColor.init(hexString: style?.value(forKey: "background-color") as? String ?? "#ffffffFF")! var image:UIImage? = nil; let signView:FBSignView = UIView.fromNib(withName: "FBSignView")! signView.frame = CGRect(x: 0.0, y: 0.0, width: width, height: height + 65.0) if (self.field!.input != nil) { image = self.field!.input as! UIImage? } signView.updateDisplay() if (image != nil) { signView.signatureView?.signature = image } signView.backgroundColor = backgroundColor signView.delegate = self let rect:CGRect = self.convert(self.bounds, to: nil) var popoverType:PopoverType = PopoverType.down if (rect.origin.y > (self.window!.bounds.height / 2.0)) { popoverType = PopoverType.up } else { popoverType = PopoverType.down } self.popover = Popover() let options = [ .type(popoverType), .animationIn(0.2), .animationOut(0.2), .color(backgroundColor), ] as [PopoverOption] self.popover = Popover(options: options, showHandler: nil, dismissHandler: nil) self.popover!.show(signView, fromView: self.button!) } func signatureUpdated(image: UIImage) { self.imageView!.image = image self.field!.input = image } func cleared() { self.imageView!.image = UIImage() self.field!.input = nil } func dismiss() { popover?.dismiss() } } <file_sep>/FormBuilder/Classes/Form Builder UI/FTPopOverMenu_Swift/FTPopOverMenuCell.swift // // FTPopOverMenuCell.swift // FTPopOverMenu_Swift // // Created by <NAME> on 28/07/2017. // Copyright © 2016 LiuFengting (https://github.com/liufengting) . All rights reserved. // import UIKit class FTPopOverMenuCell: UITableViewCell { fileprivate lazy var configuration : FTConfiguration = { return FTConfiguration.shared }() fileprivate lazy var iconImageView : UIImageView = { let imageView = UIImageView(frame: CGRect.zero) imageView.backgroundColor = UIColor.clear imageView.contentMode = UIViewContentMode.scaleAspectFit self.contentView.addSubview(imageView) return imageView }() fileprivate lazy var nameLabel : UILabel = { let label = UILabel(frame: CGRect.zero) label.backgroundColor = UIColor.clear self.contentView.addSubview(label) return label }() func setupCellWith(menuName: String, menuImage: String?) { self.backgroundColor = UIColor.clear // Configure cell text nameLabel.font = configuration.textFont nameLabel.textColor = configuration.textColor nameLabel.textAlignment = configuration.textAlignment nameLabel.text = menuName nameLabel.frame = CGRect(x: FT.DefaultCellMargin, y: 0, width: configuration.menuWidth - FT.DefaultCellMargin*2, height: configuration.menuRowHeight) // Configure cell icon if available if let menuImage = menuImage { if var iconImage = UIImage(named: menuImage) { if configuration.ignoreImageOriginalColor { iconImage = iconImage.withRenderingMode(UIImageRenderingMode.alwaysTemplate) } iconImageView.tintColor = configuration.textColor iconImageView.frame = CGRect(x: FT.DefaultCellMargin, y: (configuration.menuRowHeight - configuration.menuIconSize)/2, width: configuration.menuIconSize, height: configuration.menuIconSize) iconImageView.image = iconImage nameLabel.frame = CGRect(x: FT.DefaultCellMargin*2 + configuration.menuIconSize, y: (configuration.menuRowHeight - configuration.menuIconSize)/2, width: (configuration.menuWidth - configuration.menuIconSize - FT.DefaultCellMargin*3), height: configuration.menuIconSize) } } } } <file_sep>/FormBuilder/Classes/Form Builder Classes/FBLine.swift // // FBLine.swift // FormBuilder // // Created by <NAME> on 1/17/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public class FBLine: NSObject { public var id:String = "" public var tag:String? = "#Line" public var style:FBStyleClass? = nil public var visible:Bool = true var allowsRemove:Bool = false public var fields:Array<FBField> = Array<FBField>() public var section:FBSection? var range = (0, 0) private var _editable:Bool? var editable:Bool? { get { // this line is ONLY editable if none of its parents are explicitly set as NOT editable. if ((self.section?.form?.editable == nil) || (self.section?.form?.editable == true)) { if ((self.section?.editable == nil) || (self.section?.editable == true)) { if ((_editable == nil) || (_editable == true)) { return true } } } return false } set(newValue) { _editable = newValue } } override public init() { super.init() } public init(section:FBSection, lines:(Int, Int)) { super.init() self.section = section self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: self.tag!)!) let file = self.section!.form!.file! self.style!.parent = self.section!.style // override the default parents, our styles always descend from the style of the parent object! var i:Int = lines.0 while (i <= lines.1) { switch (file.lines[i].keyword) { case FBKeyWord.Id: self.id = file.lines[i].value i += 1 break case FBKeyWord.Visible: self.visible = (file.lines[i].value.lowercased() != "false") i += 1 break case FBKeyWord.Style: //self.tag = file.lines[i].value self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: file.lines[i].value)!) self.style!.parent = self.section!.style // override the default parents, our styles always descend from the style of the parent object! i += 1 break case FBKeyWord.Editable: self.editable = (file.lines[i].value.lowercased() != "false") i += 1 break case FBKeyWord.Field: let indentLevel:Int = file.lines[i].indentLevel let spaceLevel:Int = file.lines[i].spaceLevel i += 1 var fieldRange = (i, i) var fieldType:FBFieldType = FBFieldType.Unknown while (i <= lines.1) { if ((file.lines[i].indentLevel > indentLevel) || (file.lines[i].spaceLevel > spaceLevel) || (file.lines[i].keyword == FBKeyWord.None)) { if (file.lines[i].keyword == FBKeyWord.FieldType) { fieldType = FBField.typeWith(string: file.lines[i].value) } i += 1 } else { break } } fieldRange.1 = i - 1 switch (fieldType) { case FBFieldType.Section: break case FBFieldType.Heading: let field:FBHeadingField = FBHeadingField(line: self, lines: fieldRange) self.fields.append(field as FBField) break case FBFieldType.Label: let field:FBLabelField = FBLabelField(line: self, lines: fieldRange) self.fields.append(field as FBField) break case FBFieldType.Text: let field:FBTextField = FBTextField(line: self, lines: fieldRange) self.fields.append(field as FBField) break case FBFieldType.TextArea: let field:FBTextAreaField = FBTextAreaField(line: self, lines: fieldRange) field.line = self self.fields.append(field as FBField) break case FBFieldType.ComboBox: let field:FBComboBoxField = FBComboBoxField(line: self, lines: fieldRange) field.line = self self.fields.append(field as FBField) break case FBFieldType.CheckBox: let field:FBCheckBoxField = FBCheckBoxField(line: self, lines: fieldRange) field.line = self self.fields.append(field as FBField) break case FBFieldType.Image: let field:FBImageField = FBImageField(line: self, lines: fieldRange) field.line = self self.fields.append(field as FBField) break case FBFieldType.ImagePicker: let field:FBImagePickerField = FBImagePickerField(line: self, lines: fieldRange) field.line = self self.fields.append(field as FBField) break case FBFieldType.OptionSet: let field:FBOptionSetField = FBOptionSetField(line: self, lines: fieldRange) field.line = self self.fields.append(field as FBField) break case FBFieldType.DatePicker: let field:FBDatePickerField = FBDatePickerField(line: self, lines: fieldRange) field.line = self self.fields.append(field as FBField) break case FBFieldType.Signature: let field:FBSignatureField = FBSignatureField(line: self, lines: fieldRange) field.line = self self.fields.append(field as FBField) break case FBFieldType.Unknown: break } break default: i += 1 break } } } func initWith(section:FBSection, id:String) -> FBLine { self.section = section self.id = id as String self.visible = true self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: self.tag!)!) self.style!.parent = self.section!.style // override the default parents, our styles always descend from the style of the parent object! return self } func equals(value:String) -> Bool { return Bool(self.id.lowercased() == value.lowercased()) } func field(named:String) -> FBField? { for field in self.fields { if (field.id.lowercased() == named.lowercased()) { return field } } return nil } func visibleFields() -> Array<FBField> { var visible:Array<FBField> = Array<FBField>() for field in fields { if (field.visible == true) { visible.append(field) } } return visible } func fieldCount() -> Int { return self.visibleFields().count } func height() -> CGFloat { var height:CGFloat = 0.0 for field in self.visibleFields() { if (field.view == nil) { height = 50.0 } else { if (field.view!.height() > height) { height = field.view!.height() } } } return height } } <file_sep>/FormBuilder/Classes/Form Builder Classes/FBSettings.swift // // FBSettings.swift // FormBuilder // // Created by <NAME> on 1/21/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBSettings: NSObject { var editable:Bool = true //var dateFormat:String = "yyyy-MM-dd" //var timeFormat:String = "hh:mm:ss a" //var dateTimeFormat:String = "yyyy-MM-dd hh:mm:ss a" var formats:Dictionary<String, String> = Dictionary<String, String>() var optionSet:Dictionary<String, FBOptionSet> = Dictionary<String, FBOptionSet>() open class var shared: FBSettings { struct Singleton { static let instance = FBSettings(file: "Settings") } return Singleton.instance } open func load(file: String) { let settingsFile:FBFile = FBFile(file: file) var i:Int = 0 while (i < settingsFile.lines.count) { switch (settingsFile.lines[i].keyword) { case FBKeyWord.Format: let indentLevel:Int = settingsFile.lines[i].indentLevel let spaceLevel:Int = settingsFile.lines[i].spaceLevel i += 1 var key:String? = nil var value:String? = nil while (i < settingsFile.lines.count) { if ((settingsFile.lines[i].indentLevel > indentLevel) || (settingsFile.lines[i].spaceLevel > spaceLevel) || (settingsFile.lines[i].keyword == FBKeyWord.None)) { if (settingsFile.lines[i].keyword == FBKeyWord.Id) { key = settingsFile.lines[i].value } if (settingsFile.lines[i].keyword == FBKeyWord.Value) { value = settingsFile.lines[i].value } i += 1 } else { break } } if (key != nil && value != nil) { self.formats.updateValue(value!, forKey: key!) } break case FBKeyWord.OptionSet: let indentLevel:Int = settingsFile.lines[i].indentLevel let spaceLevel:Int = settingsFile.lines[i].spaceLevel i += 1 var optionSetRange = (i, i) var optionId:String = "" var inOption:Bool = false while (i < settingsFile.lines.count) { if ((settingsFile.lines[i].indentLevel > indentLevel) || (settingsFile.lines[i].spaceLevel > spaceLevel) || (settingsFile.lines[i].keyword == FBKeyWord.None)) { if ((settingsFile.lines[i].keyword == FBKeyWord.Id) && !inOption) { optionId = settingsFile.lines[i].value } else if (settingsFile.lines[i].keyword == FBKeyWord.Option) { inOption = true } i += 1 } else { break } } optionSetRange.1 = i - 1 if (self.optionSet[optionId] == nil) { self.optionSet[optionId] = FBOptionSet(field: nil, file: settingsFile, lines: optionSetRange) } else { let optionSet:FBOptionSet = FBOptionSet(field: nil, file: settingsFile, lines: optionSetRange) for option in optionSet.options { self.optionSet[optionId]?.updateOption(option: option) } } break default: i += 1 break } } } public init(file: String) { super.init() self.load(file: file) } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/OptionSet/FBOptionSetView.swift // // OptionSetView.swift // FormBuilder // // Created by <NAME> on 1/25/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBOptionSetView: FBFieldView, UIGestureRecognizerDelegate { var field:FBOptionSetField? @IBOutlet var label:UILabel? @IBOutlet var requiredView:FBRequiredView? var optionViews:Dictionary<String, FBOptionView> = Dictionary<String, FBOptionView>() var optionLabels:Dictionary<String, UILabel> = Dictionary<String, UILabel>() var buttons:Array<UITapGestureRecognizer> = Array<UITapGestureRecognizer>() var labelButtons:Array<UITapGestureRecognizer> = Array<UITapGestureRecognizer>() var selectedId:String? = nil override func height() -> CGFloat { let margin:CGFloat = (self.field?.style?.value(forKey: "margin") as? CGFloat) ?? 5.0 let border:CGFloat = (self.field?.style?.value(forKey: "border") as? CGFloat) ?? 5.0 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: if (self.field!.editing) { return (margin * 3) + (self.field!.labelHeight * 2) + border } else { return (margin * 2) + self.field!.labelHeight + border } case FBOrientation.Vertical: if (self.field!.editing) { return (margin * CGFloat(self.field?.optionSet?.options.count ?? 0 + 2)) + (self.field!.labelHeight * CGFloat(self.field?.optionSet?.options.count ?? 0 + 1)) + border } else { if (self.field!.data != nil) { return (margin * 3) + (self.field!.labelHeight * 2) + border } else { return (margin * 2) + self.field!.labelHeight + border } } case FBOrientation.ReverseHorizontal: if (self.field!.editing) { return (margin * 3) + (self.field!.labelHeight * 2) + border } else { return (margin * 2) + self.field!.labelHeight + border } case FBOrientation.ReverseVertical: if (self.field!.editing) { return (margin * CGFloat(self.field?.optionSet?.options.count ?? 0 + 2)) + (self.field!.labelHeight * CGFloat(self.field?.optionSet?.options.count ?? 0 + 1)) + border } else { if (self.field!.data != nil) { return (margin * 3) + (self.field!.labelHeight * 2) + border } else { return (margin * 2) + self.field!.labelHeight + border } } case FBOrientation.PlaceHolder: if (self.field!.editing) { return (margin * 3) + (self.field!.labelHeight * 2) + border } else { return (margin * 2) + self.field!.labelHeight + border } } } open func updateDisplay(label:String, optionSet:FBOptionSet, id:String?, required: Bool) { var index:Int = 0 self.selectedId = id self.label = UILabel() self.label?.numberOfLines = 0 self.addSubview(self.label!) self.requiredView = FBRequiredView() self.addSubview(self.requiredView!) self.label?.font = UIFont(name: self.field?.style!.value(forKey: "font-family") as! String, size: self.field?.style!.value(forKey: "font-size") as! CGFloat) self.label?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "foreground-color") as! String) self.label!.text = label self.label?.sizeToFit() for option in self.field!.optionSet!.options { let optionView:FBOptionView = UIView.fromNib(withName: "FBOptionView")! optionView.option = option self.optionViews[option.id] = optionView self.addSubview(optionView) optionView.setNeedsDisplay() let label:UILabel = UILabel() label.font = UIFont(name: self.field?.style!.value(forKey: "input-font-family") as! String, size: self.field?.style!.value(forKey: "input-font-size") as! CGFloat) label.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "input-foreground-color") as! String) label.text = option.value label.sizeToFit() self.optionLabels[option.id] = label optionView.button = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:))) optionView.button!.delegate = self optionView.addGestureRecognizer(optionView.button!) optionView.isUserInteractionEnabled = self.field!.editing optionView.labelButton = UITapGestureRecognizer(target: self, action: #selector(self.handleLabelTap(_:))) optionView.labelButton!.delegate = self label.addGestureRecognizer(optionView.labelButton!) label.isUserInteractionEnabled = self.field!.editing self.buttons.append(optionView.button!) self.labelButtons.append(optionView.labelButton!) self.addSubview(label) if (id != nil) { if (option.id == id) { optionView.state = FBCheckState.Checked } } index += 1 } if (self.field!.editing) { // set this field to edit mode self.requiredView?.isHidden = !required for optionView in self.optionViews.values { optionView.isHidden = false } for label in self.optionLabels.values { label.isHidden = false } } else { // set this field to view mode self.requiredView?.isHidden = true for optionView in self.optionViews.values { optionView.isHidden = true } for label in self.optionLabels.values { label.isHidden = true } if (self.selectedId != nil) { self.optionLabels[self.selectedId!]?.isHidden = false } } } @objc func handleTap(_ sender: UITapGestureRecognizer) { if (self.delegate != nil) { var index:Int = 0 for button in self.buttons { if (button == sender) { break } else { index += 1 } } var id:String? = nil for optionView in self.optionViews.values { if (optionView.button == sender) { optionView.state = FBCheckState.Checked id = optionView.option?.id } else { optionView.state = FBCheckState.Unchecked } } for optionView in self.optionViews.values { optionView.setNeedsDisplay() } self.field!.input = id ?? nil } } @objc func handleLabelTap(_ sender: UITapGestureRecognizer) { if (self.delegate != nil) { var index:Int = 0 for button in self.labelButtons { if (button == sender) { break } else { index += 1 } } var id:String? = nil for optionView in self.optionViews.values { if (optionView.labelButton == sender) { optionView.state = FBCheckState.Checked id = optionView.option?.id } else { optionView.state = FBCheckState.Unchecked } } for optionView in self.optionViews.values { optionView.setNeedsDisplay() } self.field!.input = id ?? nil } } override open func layoutSubviews() { self.label?.font = self.field!.style!.font let margin:CGFloat = (self.field?.style?.value(forKey: "margin") as? CGFloat) ?? 5.0 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: self.label?.frame = CGRect(x: margin, y: margin, width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (self.field!.requiredWidth + margin), y: margin + ((self.field!.labelHeight / 2.0) - (self.field!.requiredHeight / 2.0)), width: self.field!.requiredWidth, height: self.field!.requiredHeight) if (self.field!.editing) { var left:CGFloat = 0.0 let count:Int = self.optionViews.count var index:Int = 0 let width:CGFloat = self.frame.width / CGFloat(count) for optionView in self.optionViews.values { left = (width * CGFloat(index)) + (margin * CGFloat(index + 1)) optionView.frame = CGRect(x: left, y: (margin * 2) + self.field!.labelHeight + ((self.field!.labelHeight / 2.0) - self.field!.labelHeight / 4.0), width: self.field!.labelHeight / 2.0, height: self.field!.labelHeight / 2.0) index += 1 optionView.setNeedsDisplay() } index = 0 for labelView in self.optionLabels.values { left = (width * CGFloat(index)) + (margin * CGFloat(index + 1)) labelView.frame = CGRect(x: left + (self.field!.labelHeight / 2.0) + margin, y: (margin * 2) + self.field!.labelHeight, width: width - (self.field!.labelHeight + margin), height: self.field!.labelHeight) index += 1 labelView.setNeedsDisplay() } } else { if (self.field!.data != nil) { let text:String = self.field?.optionSet?.option(named: (self.field?.data as? String) ?? "")?.value ?? "" let width:CGFloat = text.width(withConstrainedHeight: self.field?.labelHeight ?? 0.0, font: self.optionLabels[self.field!.data as! String]!.font!) self.optionLabels[self.field!.data as! String]?.frame = CGRect(x: self.frame.width - (width + (margin * 2) + self.field!.requiredWidth), y: margin, width: width, height: self.field!.labelHeight) } } break case FBOrientation.Vertical: self.label?.frame = CGRect(x: margin, y: margin, width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (self.field!.requiredWidth + margin), y: margin + ((self.field!.labelHeight / 2.0) - (self.field!.requiredHeight / 2.0)), width: self.field!.requiredWidth, height: self.field!.requiredHeight) if (self.field!.editing) { var left:CGFloat = 0.0 let count:Int = self.optionViews.count var index:Int = 0 let width:CGFloat = self.frame.width / CGFloat(count) var top:CGFloat = (margin * 2) + self.field!.labelHeight + ((self.field!.labelHeight / 2.0) - self.field!.labelHeight / 4.0) var labelTop:CGFloat = (margin * 2) + self.field!.labelHeight for optionView in self.optionViews.values { left = margin optionView.frame = CGRect(x: left, y: top, width: self.field!.labelHeight / 2.0, height: self.field!.labelHeight / 2.0) index += 1 optionView.setNeedsDisplay() top += margin + self.field!.labelHeight labelTop += margin + self.field!.labelHeight } index = 0 for labelView in self.optionLabels.values { left = margin labelView.frame = CGRect(x: left + (self.field!.labelHeight / 2.0) + margin, y: labelTop, width: width - (self.field!.labelHeight + margin), height: self.field!.labelHeight) index += 1 labelView.setNeedsDisplay() top += margin + self.field!.labelHeight labelTop += margin + self.field!.labelHeight } } else { if (self.field!.data != nil) { self.optionLabels[self.field!.data as! String]?.frame = CGRect(x: margin, y: (margin * 2) + self.field!.labelHeight, width: self.frame.width - (margin * 2), height: self.field!.labelHeight) } } break case FBOrientation.ReverseHorizontal: let width:CGFloat = (self.label?.text!.width(withConstrainedHeight: (self.field?.labelHeight)!, font: (self.label?.font)!))! self.label?.frame = CGRect(x: self.frame.width - (width + (margin * 2) + self.field!.requiredWidth), y: margin, width: width, height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (self.field!.requiredWidth + margin), y: margin + ((self.field!.labelHeight / 2.0) - (self.field!.requiredHeight / 2.0)), width: self.field!.requiredWidth, height: self.field!.requiredHeight) if (self.field!.editing) { var left:CGFloat = 0.0 let count:Int = self.optionViews.count var index:Int = 0 let width:CGFloat = self.frame.width / CGFloat(count) for optionView in self.optionViews.values { left = (width * CGFloat(index)) + (margin * CGFloat(index + 1)) optionView.frame = CGRect(x: left, y: (margin * 2) + self.field!.labelHeight + ((self.field!.labelHeight / 2.0) - self.field!.labelHeight / 4.0), width: self.field!.labelHeight / 2.0, height: self.field!.labelHeight / 2.0) index += 1 optionView.setNeedsDisplay() } index = 0 for labelView in self.optionLabels.values { left = (width * CGFloat(index)) + (margin * CGFloat(index + 1)) labelView.frame = CGRect(x: left + (self.field!.labelHeight / 2.0) + margin, y: (margin * 2) + self.field!.labelHeight, width: width - (self.field!.labelHeight + margin), height: self.field!.labelHeight) index += 1 labelView.setNeedsDisplay() } } else { if (self.field!.data != nil) { self.optionLabels[self.field!.data as! String]?.frame = CGRect(x: margin, y: margin, width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.labelHeight) } } break case FBOrientation.ReverseVertical: self.label?.frame = CGRect(x: margin, y: self.frame.height - (margin + self.field!.labelHeight), width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (self.field!.requiredWidth + margin), y: self.frame.height - (margin + self.field!.labelHeight) + ((self.field!.labelHeight / 2.0) - (self.field!.requiredHeight / 2.0)), width: self.field!.requiredWidth, height: self.field!.requiredHeight) if (self.field!.editing) { var left:CGFloat = 0.0 let count:Int = self.optionViews.count var index:Int = 0 let width:CGFloat = self.frame.width / CGFloat(count) var top:CGFloat = margin + ((self.field!.labelHeight / 2.0) - self.field!.labelHeight / 4.0) var labelTop:CGFloat = margin for optionView in self.optionViews.values { left = margin optionView.frame = CGRect(x: left, y: top, width: self.field!.labelHeight / 2.0, height: self.field!.labelHeight / 2.0) index += 1 optionView.setNeedsDisplay() top += margin + self.field!.labelHeight labelTop += margin + self.field!.labelHeight } index = 0 for labelView in self.optionViews.values { left = margin labelView.frame = CGRect(x: left + (self.field!.labelHeight / 2.0) + margin, y: labelTop, width: width - (self.field!.labelHeight + margin), height: self.field!.labelHeight) index += 1 labelView.setNeedsDisplay() top += margin + self.field!.labelHeight labelTop += margin + self.field!.labelHeight } } else { if (self.field!.data != nil) { self.optionLabels[self.field!.data as! String]?.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2), height: self.field!.labelHeight) } } break case FBOrientation.PlaceHolder: self.label?.frame = CGRect(x: margin, y: margin, width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (self.field!.requiredWidth + margin), y: margin + ((self.field!.labelHeight / 2.0) - (self.field!.requiredHeight / 2.0)), width: self.field!.requiredWidth, height: self.field!.requiredHeight) if (self.field!.editing) { var left:CGFloat = 0.0 let count:Int = self.optionViews.count var index:Int = 0 let width:CGFloat = self.frame.width / CGFloat(count) for optionView in self.optionViews.values { left = (width * CGFloat(index)) + (margin * CGFloat(index + 1)) optionView.frame = CGRect(x: left, y: (margin * 2) + self.field!.labelHeight + ((self.field!.labelHeight / 2.0) - self.field!.labelHeight / 4.0), width: self.field!.labelHeight / 2.0, height: self.field!.labelHeight / 2.0) index += 1 optionView.setNeedsDisplay() } index = 0 for labelView in self.optionLabels.values { left = (width * CGFloat(index)) + (margin * CGFloat(index + 1)) labelView.frame = CGRect(x: left + (self.field!.labelHeight / 2.0) + margin, y: (margin * 2) + self.field!.labelHeight, width: width - (self.field!.labelHeight + margin), height: self.field!.labelHeight) index += 1 labelView.setNeedsDisplay() } } else { if (self.field!.data != nil) { let width:CGFloat = (self.optionLabels[self.field!.data as! String]?.text?.width(withConstrainedHeight: (self.field?.labelHeight)!, font: self.optionLabels.first!.value.font!))! self.optionLabels[self.field!.data as! String]?.frame = CGRect(x: self.frame.width - (width + (margin * 2) + self.field!.requiredWidth), y: margin, width: width, height: self.field!.labelHeight) } } break } } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/TextArea/FBTextAreaView.swift // // TextAreaView.swift // FormBuilder // // Created by <NAME> on 1/29/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBTextAreaView: FBFieldView, UITextViewDelegate { @IBOutlet var label:UILabel? @IBOutlet var textView:UITextView? @IBOutlet var requiredView:FBRequiredView? var field:FBTextAreaField? var maxLength:Int = 0 override func height() -> CGFloat { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 let border:CGFloat = self.field?.style?.value(forKey: "border") as? CGFloat ?? 1.5 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: return (margin * 3) + self.field!.textAreaHeight + self.field!.labelHeight + border + 30.0 case FBOrientation.Vertical: return (margin * 3) + self.field!.textAreaHeight + self.field!.labelHeight + border + 30.0 case FBOrientation.ReverseHorizontal: return (margin * 3) + self.field!.textAreaHeight + self.field!.labelHeight + border + 30.0 case FBOrientation.ReverseVertical: return (margin * 3) + self.field!.textAreaHeight + self.field!.labelHeight + border + 30.0 case FBOrientation.PlaceHolder: return (margin * 3) + self.field!.textAreaHeight + self.field!.labelHeight + border + 30.0 } } open func updateDisplay(label:String, text:String, required:Bool) { self.label = UILabel() self.label?.numberOfLines = 0 self.label?.lineBreakMode = NSLineBreakMode.byWordWrapping self.addSubview(self.label!) self.label?.font = UIFont(name: self.field?.style!.value(forKey: "font-family") as! String, size: self.field?.style!.value(forKey: "font-size") as! CGFloat) self.label?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "foreground-color") as! String) self.label?.text = label self.label?.sizeToFit() self.textView = UITextView() self.textView?.keyboardType = self.field?.keyboard ?? .default self.textView?.autocapitalizationType = self.field?.capitalize ?? .words self.addSubview(self.textView!) self.textView?.font = UIFont(name: self.field?.style!.value(forKey: "input-font-family") as! String, size: self.field?.style!.value(forKey: "input-font-size") as! CGFloat) self.textView?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "input-foreground-color") as! String) self.textView?.text = text self.textView?.sizeToFit() self.requiredView = FBRequiredView() self.addSubview(self.requiredView!) if (self.field!.editing) { // set this field to edit mode //self.textView?.borderStyle = UITextBorderStyle.bezel self.textView?.isUserInteractionEnabled = true self.requiredView?.isHidden = !required } else { // set this field to view mode //self.textView?.borderStyle = UITextBorderStyle.none self.textView?.isUserInteractionEnabled = false self.requiredView?.isHidden = true } for requirement in self.field!.requirements! { switch (requirement.type) { case FBRequirementType.Maximum: let max:Int = requirement.value as! Int self.maxLength = max break default: break } } } open func textViewDidChange(_ textView: UITextView) { if (self.maxLength > 0) { if (self.textView!.text!.count > self.maxLength) { self.textView!.deleteBackward() return } } self.field?.input = self.textView!.text } override open func layoutSubviews() { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal, FBOrientation.Vertical, FBOrientation.ReverseHorizontal, FBOrientation.PlaceHolder: self.label?.frame = CGRect(x: margin, y: margin, width: self.field!.labelWidth, height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (margin + self.field!.labelHeight / 2.0) - (self.field!.requiredHeight / 2.0), width: self.field!.requiredWidth, height: self.field!.requiredHeight) self.textView?.frame = CGRect(x: margin, y: (margin * 2) + self.field!.labelHeight, width: self.field!.textWidth, height: self.field!.textHeight - self.field!.borderHeight) break case FBOrientation.ReverseVertical: self.textView?.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2), height: self.frame.height - ((margin * 3) + self.field!.labelHeight)) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height - (self.field!.labelHeight + margin) + (self.field!.labelHeight / 2.0)) - (self.field!.requiredHeight / 2.0), width: self.field!.requiredWidth, height: self.field!.requiredHeight) self.label?.frame = CGRect(x: margin, y: self.frame.height - (self.field!.labelHeight + margin), width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.labelHeight) break } } } <file_sep>/FormBuilder/Classes/Form Builder Classes/FBException.swift // // FBException.swift // FormBuilder // // Created by <NAME> on 1/19/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public class FBException: NSObject { var field:FBField? var errors:Array<FBRequirementType> = Array<FBRequirementType>() } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/Signature/FBSignView.swift // // SignView.swift // FormBuilder // // Created by <NAME> on 2/10/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit protocol FBSignViewDelegate: class { func signatureUpdated(image:UIImage) func cleared() func dismiss() } open class FBSignView: UIView { @IBOutlet var signatureView:SwiftSignatureView? @IBOutlet var button:UIButton? @IBOutlet var deleteButton:UIButton? var textColor:UIColor = UIColor.white private var _buttonColor:UIColor = UIColor.gray weak var delegate:FBSignViewDelegate? open func updateDisplay() { let bundle = Bundle.init(for: self.classForCoder) // create "ok" button self.backgroundColor = UIColor.white self.button = UIButton() self.button!.layer.cornerRadius = 7.5 self.button?.addTarget(self, action: #selector(okButtonPressed), for: UIControlEvents.touchUpInside) //_buttonColor = buttonColor self.button?.backgroundColor = _buttonColor self.button?.setTitle("Ok", for: UIControlState.normal) self.button?.setTitleColor(UIColor.white, for: UIControlState.normal) self.addSubview(self.button!) // create delete button self.deleteButton = UIButton() self.deleteButton!.layer.cornerRadius = 7.5 self.deleteButton?.addTarget(self, action: #selector(deleteButtonPressed), for: UIControlEvents.touchUpInside) //_buttonColor = buttonColor self.deleteButton?.backgroundColor = _buttonColor self.deleteButton?.setImage(UIImage.init(named: "trash-white", in: bundle, compatibleWith: nil), for: UIControlState.normal) self.deleteButton?.setTitleColor(UIColor.white, for: UIControlState.normal) self.addSubview(self.deleteButton!) // create signature view self.signatureView = SwiftSignatureView(frame: CGRect(x:0, y:0, width: self.frame.width, height: self.frame.height - 70.0)) self.addSubview(self.signatureView!) self.signatureView!.backgroundColor = UIColor.white } override open func layoutSubviews() { self.signatureView?.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.width, height: self.frame.height - 70.0) self.deleteButton?.frame = CGRect(x: 5.0, y: (self.frame.height - 65.0), width: 50.0, height: 50.0) self.button?.frame = CGRect(x:(self.frame.width / 2.0) - ((self.frame.width - 10.0) / 2.0) + 55.0, y:(self.frame.height - 65.0), width:(self.frame.width - (10.0 + 50.0 + 5.0)), height:50.0) } @objc @IBAction func okButtonPressed() { self.delegate?.signatureUpdated(image:self.signatureView!.signature!) self.delegate?.dismiss() } @objc @IBAction func deleteButtonPressed() { self.signatureView?.signature = UIImage() self.signatureView?.setNeedsDisplay() self.delegate?.cleared() } } <file_sep>/Example/FormBuilder/ContactFormViewController.swift // // ContactFormViewController.swift // FormBuilder // // Created by <NAME> on 1/16/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import FormBuilder class ContactFormViewController: FBFormViewController { let address:Address = Address() // this is the object to be represented on this form. override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem // You must call "self.loadForm(named:"MyForm")" in order to load the form into this view. // Once the form is loaded, it will call "populate" in this form, so you should use // the populate method to load the properties of the objects you want to represent on this form // into the form fields. address.street = "123 some street" address.city = "cityville" address.county = "jones county" address.province = "british columbia" address.state = "MS" address.zipcode = "11111" address.postalcode = "11111" address.business = false address.country = "US" address.deliveryType = "UPS" self.loadSpecification(named: "Contact") } // -- Form delegate methods ---------------------------> // -- populate() --------------------------------------> load an object we want to display into the form (called automatically after form is loaded). // -- fieldValueChanged(field: FBField, value: Any?) --> handle user input into the form (you may need to update form based on user input -- or not). // -- validationFailed(exceptions:Array<FBException>) -> (!!! optional !!!) handle errors in data input or missing data (maybe show a popup describing errors). // -- save() ------------------------------------------> save the input data back into our object. // -- discard() ---------------------------------------> dismiss this form without saving any data (our object should not be altered in any way). // -- That's all, folks! ------------------------------> // load an object we want to display into the form (called automatically after form is loaded) override func populate() { // load form data now that the form has been built. // initialize a test object // load the test object into the form self.form?.field(withPath: "address.street")?.data = address.street self.form?.field(withPath: "address.province")?.data = address.province self.form?.field(withPath: "address.city")?.data = address.city self.form?.field(withPath: "address.postalcode")?.data = address.postalcode self.form?.field(withPath: "address.zipcode")?.data = address.zipcode self.form?.field(withPath: "address.county")?.data = address.county self.form?.field(withPath: "address.state")?.data = address.state if (address.business == true) { self.form?.field(withPath: "address.businessaddress")?.data = true } else { self.form?.field(withPath: "address.businessaddress")?.data = nil } self.form?.field(withPath: "address.country")?.data = address.country self.form?.field(withPath: "address.delivery")?.data = address.deliveryType } // handle user input into the form (you may need to update form based on user input -- or not) override func fieldValueChanged(field: FBField, value: Any?) { // whenever the user interacts with the form in any way, by changing field values, selecting items // in combo boxes, selecting option items, adding images, etc. this will be called. This will // give you an opportunity to update the form fields based on the input data or options selected by // the user. For instance if a user selects a country in a combo box on an address form, you will // need to update the form fields to represent the properties of the address for that country, and // you can also do things like change which fields are required, etc. switch (field.id.lowercased()) { case "country": // the user changed the country for this address, oops, we better update the address fields! let section:FBSection = field.line!.section! switch (value as! String) { case "CA": // canada section.line(named: "county")?.visible = false section.line(named: "province")?.visible = true section.line(named: "state")?.visible = false section.line(named: "zipcode")?.visible = false section.line(named: "postalcode")?.visible = false // set required section.field(withPath: "street")?.required = true // fyi: we don't need to provide the field name if there is only one field on a line. section.field(withPath: "province.province")?.required = true // but we can if we want to. section.field(withPath: "city")?.required = true section.field(withPath: "postalcode")?.required = true break case "ES": // spain section.line(named: "county")?.visible = false section.line(named: "province")?.visible = false section.line(named: "state")?.visible = false section.line(named: "zipcode")?.visible = false section.line(named: "postalcode")?.visible = true // set required section.field(withPath: "street")?.required = true section.field(withPath: "city")?.required = true section.field(withPath: "postalcode")?.required = true break case "OT": // other section.line(named: "county")?.visible = false section.line(named: "province")?.visible = true section.line(named: "state")?.visible = false section.line(named: "zipcode")?.visible = false section.line(named: "postalcode")?.visible = true // set required section.field(withPath: "street")?.required = false section.field(withPath: "province")?.required = false section.field(withPath: "city")?.required = false section.field(withPath: "postalcode")?.required = false break case "US": // united states section.line(named: "county")?.visible = true section.line(named: "province")?.visible = false section.line(named: "state")?.visible = true section.line(named: "zipcode")?.visible = true section.line(named: "postalcode")?.visible = false // set required section.field(withPath: "street")?.required = true section.field(withPath: "city")?.required = true section.field(withPath: "state")?.required = true section.field(withPath: "zipcode")?.required = true break default: break } self.updateDisplay() // once the form is updated, it needs to be reloaded into the table. break default: break } } /* // handle errors in data input or missing data (maybe show a popup describing errors) override func validationFailed(exceptions:Array<FBException>) { // validation failed, so we should handle the errors here however the developer wants. var message:String = "Validation Failed...\n" for exception:FBException in exceptions { for type in exception.errors { switch (type) { case FBRequirementType.Required: message = message + (exception.field?.caption)! + " is required.\n" break case FBRequirementType.Maximum: message = message + (exception.field?.caption)! + " exceeds the maximum.\n" break case FBRequirementType.Minimum: message = message + (exception.field?.caption)! + " does not meet the minimum.\n" break case FBRequirementType.Format: message = message + (exception.field?.caption)! + " is not valid.\n" break case FBRequirementType.MemberOf: message = message + (exception.field?.caption)! + " is not one of the available options.\n" break default: break } } } let hud:SwiftHUD = SwiftHUD.show(message, view: self.view, style: SwiftHUDStyle.error) hud.hide(message, after: 3) } */ // save the input data back into our object. override func save() { // validation succeeded, so we should take the data from the form and shove it back into the objects represented on the form and save them. /* let hud:SwiftHUD = SwiftHUD.show("Validation Successful", view: self.view, style: SwiftHUDStyle.success) hud.hide("Validation Successful", after: 3000) */ // save the form data back into the test object address.street = self.form?.field(withPath: "address.street")?.data as? String address.province = self.form?.field(withPath: "address.province")?.data as? String address.city = self.form?.field(withPath: "address.city")?.data as? String address.postalcode = self.form?.field(withPath: "address.postalcode")?.data as? String address.zipcode = self.form?.field(withPath: "address.zipcode")?.data as? String address.county = self.form?.field(withPath: "address.county")?.data as? String address.state = self.form?.field(withPath: "address.state")?.data as? String if ((self.form?.field(withPath: "address.businessaddress")?.data as! Bool) == true) { address.business = true } else { address.business = false } address.country = self.form?.field(withPath: "address.country")?.data as? String address.deliveryType = self.form?.field(withPath: "address.delivery")?.data as? String } // dismiss this form without saving any data (our object should not be altered in any way) /* override func discard() { // cancel changes and dismiss form, this should leave the object displayed in the form as is } */ // -- End of the form delegate methods ------ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>/FormBuilder/Classes/Form Builder UI/Form/FBFormViewController.swift // // FormViewController.swift // FormBuilder // // Created by <NAME> on 1/16/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBFormViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, FormLineDelegate, FormDelegate, FBSectionHeaderDelegate { // ---------------------------------------------------------> // -- ATTENTION: If you want to use the form builder, you must // -- make a new table view controller and set this // -- class as the parent class, then implement the // -- methods listed below in your class. // ---------------------------------------------------------> // -- Form delegate methods --------------------------------> // -- populate() -------------------------------------------> load an object we want to display into the form (called automatically after form is loaded). // -- fieldValueChanged(field: FBField, value: Any) --------> handle user input into the form (you may need to update form based on user input -- or not). // -- validationFailed(exceptions:Array<FBException>) ------> (!!! optional !!!) handle errors in data input or missing data (maybe show a popup describing errors). // -- save() -----------------------------------------------> save the input data back into our object. // -- discard() --------------------------------------------> dismiss this form without saving any data (our object should not be altered in any way). // -- That's all, folks! -----------------------------------> @IBOutlet var tableView:UITableView? public var form:FBForm? = nil // the form represents the data we went to display, divided up into sections, lines, and fields. var modified:Bool = false // has this form been modified? If so we may need to save it, if not, then why bother? var displayCommandBar:Bool = true // should we display the "edit", "save", "cancel" buttons at the bottom? open override func viewDidLoad() { super.viewDidLoad() let bundle = Bundle.init(for: FormLineTableViewCell.self) self.tableView?.register(UINib(nibName: "FBFormCell", bundle: bundle), forCellReuseIdentifier: "FormCell") } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView!.tableFooterView = UIView(frame: CGRect.zero) self.tableView!.backgroundColor = UIColor.init(hexString: form?.style?.value(forKey: "border-color") as! String) } open override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source public func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return form?.visibleSections().count ?? 0 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return form!.visibleSections()[section].lineCount() } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // we will calculate the height for each field based on the style and data contained in it, and set the height of the containing row accordingly. if (self.form?.visibleSections()[indexPath.section].collapsed == true) { return 0.0 } else { return (self.form?.visibleSections()[indexPath.section].visibleLines()[indexPath.row].height())! } } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // create a line of data in the form... let cell:FormLineTableViewCell = tableView.dequeueReusableCell(withIdentifier: "FormCell", for: indexPath) as! FormLineTableViewCell // Configure the cell... cell.line = form?.visibleSections()[indexPath.section].visibleLines()[indexPath.row] cell.backgroundColor = UIColor.init(hexString: form?.style?.value(forKey: "border-color") as! String) cell.setupFields() cell.delegate = self return cell } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view:FBSectionHeaderView = UIView.fromNib(withName: self.form!.sections[section].style!.viewFor(type: FBFieldType.Section))! view.updateDisplay(index: section, section: self.form!.sections[section]) view.delegate = self return view } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let view:FBSectionHeaderView = UIView.fromNib(withName: self.form!.sections[section].style!.viewFor(type: FBFieldType.Section))! view.updateDisplay(index: section, section: self.form!.sections[section]) return view.height() + (self.form?.visibleSections()[section].style?.value(forKey: "border") as! CGFloat) + ((self.form?.visibleSections()[section].style?.value(forKey: "margin") as! CGFloat) * 2) } public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { let line:FBLine = (form?.visibleSections()[indexPath.section].visibleLines()[indexPath.row])! return line.allowsRemove } public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == UITableViewCellEditingStyle.delete) { let line:FBLine = (form?.visibleSections()[indexPath.section].visibleLines()[indexPath.row])! self.removeItem(indexPath: indexPath, type: line.visibleFields().first!.fieldType) } } public func loadSpecification(named:String) { // load the sections, lines, fields, requirements, layout, etc for this form from a data file. self.form = FBForm(file: named, delegate:self) formLoaded() self.form?.tableView = self.tableView self.form?.mode = FBFormMode.View } public func formLoaded() { // when the form is loaded, we should allow the user to add any data they want to display... I guess... self.populate() self.modified = false // we just loaded the form so it hasn't been modified yet } open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { self.updateDisplay() } public func updateDisplay() { // shortcut to update the display after the form has changed. self.tableView!.reloadData() } // form line delegate methods open func updated(field: FBField, withValue: Any?) { self.modified = true self.fieldValueChanged(field: field, value: withValue) } open func fieldValueChanged(field: FBField, value: Any?) { // this should be overridden in child forms. // IF you want to provide custonm behavior based on data input. } func editing() -> Bool { return self.form?.mode == FBFormMode.Edit } func setForm(mode: FBFormMode) { self.form?.mode = mode self.updateDisplay() } func editSelected(section:Int) { self.form?.visibleSections()[section].mode = FBFormMode.Edit self.tableView?.reloadSections([section], with: UITableViewRowAnimation.fade) } func saveSelected(section:Int) { // user wants to save the form let exceptions:Array<FBException> = self.form!.validate() if (exceptions.count > 0) { self.validationFailed(exceptions: exceptions) } else { if (self.modified) { self.update() self.save() } self.form?.visibleSections()[section].mode = FBFormMode.View self.tableView?.reloadSections([section], with: UITableViewRowAnimation.fade) } } func cancelSelected(section:Int) { // user wants to cancel and discard changes for field in self.form!.fields() { field.clear() } self.form?.visibleSections()[section].mode = FBFormMode.View self.discard() self.populate() self.tableView?.reloadSections([section], with: UITableViewRowAnimation.fade) } open func populate() { // this should be overridden by the child form. assert(false, "This method must be overriden by the subclass") } open func validationFailed(exceptions:Array<FBException>) { // this can be overridden in the child form, if you want to change the way the validation errors are displayed. // validation failed, so we should handle the errors here however the developer wants. var message:String = "" for exception:FBException in exceptions { for type in exception.errors { switch (type) { case FBRequirementType.Required: message = message + (exception.field?.caption)! + " is required.\n" break case FBRequirementType.Maximum: message = message + (exception.field?.caption)! + " exceeds the maximum.\n" break case FBRequirementType.Minimum: message = message + (exception.field?.caption)! + " does not meet the minimum.\n" break case FBRequirementType.Format: message = message + (exception.field?.caption)! + " is not valid.\n" break case FBRequirementType.MemberOf: message = message + (exception.field?.caption)! + " is not one of the available options.\n" break default: break } } } let alert:UIAlertController = UIAlertController(title: "Validation Failed", message: message, preferredStyle: UIAlertControllerStyle.alert) let alertAction:UIAlertAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil) alert.addAction(alertAction) if let presenter = alert.popoverPresentationController { presenter.sourceView = self.view! } present(alert, animated: true, completion: nil) } func update() { for field in self.form!.fields() { field.data = field.input } } open func save() { // this should be overridden in the child form. assert(false, "This method must be overriden by the subclass") } open func discard() { // cancel changes and dismiss form, this should leave the object displayed in the form as is } func collapse(section: Int) { // collapse a collapsible section self.form!.sections[section].collapsed = true var indexSet:IndexSet = IndexSet() indexSet.insert(section) self.tableView!.reloadSections(indexSet, with: UITableViewRowAnimation.fade) } func expand(section: Int) { // expand a collapsed section self.form!.sections[section].collapsed = false var indexSet:IndexSet = IndexSet() indexSet.insert(section) self.tableView!.reloadSections(indexSet, with: UITableViewRowAnimation.fade) } func addItem(section: Int, type: FBFieldType) { // add a new section, or item to a section. switch (type) { case FBFieldType.Section: let s:FBSection = FBSection(form: self.form!, lines: self.form!.sections[section].range) s.allowsRemove = true self.form!.sections.insert(s, at: section + 1) self.tableView!.reloadData() break case FBFieldType.Image: let alert:UIAlertController = UIAlertController(title: "Image Label Text", message: "Enter text for the label of this image.", preferredStyle: UIAlertControllerStyle.alert) alert.addTextField( configurationHandler: {(textField: UITextField!) in textField.placeholder = "Image Label Text" }) let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: {[weak self] (paramAction:UIAlertAction!) in if let textFields = alert.textFields{ let theTextFields = textFields as [UITextField] let enteredText = theTextFields[0].text let currentSection:FBSection = self!.form!.sections[section] let count:Int = currentSection.lines!.count let line:FBLine = FBLine().initWith(section: currentSection, id: "Line." + String(count + 1)) line.allowsRemove = true let field:FBImagePickerField = FBImagePickerField().initWith(line: line, id: "Field." + String(count + 1), label:enteredText ?? "", type: FBFieldType.ImagePicker) as! FBImagePickerField line.fields.insert(field, at: 0) currentSection.lines?.insert(line, at: count) self?.tableView!.beginUpdates() self?.tableView!.insertRows(at: [IndexPath(row: currentSection.visibleLines().count - 1, section:section)], with: UITableViewRowAnimation.none) self?.tableView!.endUpdates() } }) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil) alert.addAction(action) alert.addAction(cancelAction) if let presenter = alert.popoverPresentationController { presenter.sourceView = self.view! } present(alert, animated: true, completion: nil) break case FBFieldType.Label: let alert:UIAlertController = UIAlertController(title: "Label Text", message: "Enter text for the label.", preferredStyle: UIAlertControllerStyle.alert) alert.addTextField( configurationHandler: {(textField: UITextField!) in textField.placeholder = "Label Text" }) let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: {[weak self] (paramAction:UIAlertAction!) in if let textFields = alert.textFields{ let theTextFields = textFields as [UITextField] let enteredText = theTextFields[0].text let currentSection:FBSection = self!.form!.sections[section] let count:Int = currentSection.lines!.count let line:FBLine = FBLine().initWith(section: currentSection, id: "Line." + String(count + 1)) line.allowsRemove = true let field:FBLabelField = FBLabelField().initWith(line: line, id: "Field." + String(count + 1), label:enteredText ?? "", type: FBFieldType.Label) as! FBLabelField line.fields.insert(field, at: 0) currentSection.lines?.insert(line, at: count) self?.tableView!.beginUpdates() self?.tableView!.insertRows(at: [IndexPath(row: currentSection.visibleLines().count - 1, section:section)], with: UITableViewRowAnimation.none) self?.tableView!.endUpdates() } }) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil) alert.addAction(action) alert.addAction(cancelAction) if let presenter = alert.popoverPresentationController { presenter.sourceView = self.view! } present(alert, animated: true, completion: nil) break case FBFieldType.Signature: let alert:UIAlertController = UIAlertController(title: "Signature Label Text", message: "Enter text for the label of this signature.", preferredStyle: UIAlertControllerStyle.alert) alert.addTextField( configurationHandler: {(textField: UITextField!) in textField.placeholder = "Signature Label Text" }) let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: {[weak self] (paramAction:UIAlertAction!) in if let textFields = alert.textFields{ let theTextFields = textFields as [UITextField] let enteredText = theTextFields[0].text let currentSection:FBSection = self!.form!.sections[section] let count:Int = currentSection.lines!.count let line:FBLine = FBLine().initWith(section: currentSection, id: "Line." + String(count + 1)) line.allowsRemove = true let field:FBSignatureField = FBSignatureField().initWith(line: line, id: "Field." + String(count + 1), label:enteredText ?? "", type: FBFieldType.Signature) as! FBSignatureField line.fields.insert(field, at: 0) currentSection.lines?.insert(line, at: count) self?.tableView!.beginUpdates() self?.tableView!.insertRows(at: [IndexPath(row: currentSection.visibleLines().count - 1, section:section)], with: UITableViewRowAnimation.none) self?.tableView!.endUpdates() } }) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil) alert.addAction(action) alert.addAction(cancelAction) if let presenter = alert.popoverPresentationController { presenter.sourceView = self.view! } present(alert, animated: true, completion: nil) break default: break } } func removeItem(indexPath: IndexPath, type: FBFieldType) { // remove a section or an item from a section switch (type) { case FBFieldType.Section: let alert:UIAlertController = UIAlertController(title: "Remove", message: "Remove this section?", preferredStyle: UIAlertControllerStyle.alert) let okAction:UIAlertAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default) { (UIAlertAction) in self.form!.sections.remove(at: indexPath.section) self.tableView!.reloadData() } let cancelAction:UIAlertAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (UIAlertAction) in } alert.addAction(okAction) alert.addAction(cancelAction) if let presenter = alert.popoverPresentationController { presenter.sourceView = self.view! } self.present(alert, animated: true, completion: nil) break case FBFieldType.ImagePicker: self.form!.sections[indexPath.section].removeLine(row: indexPath.row) self.tableView?.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none) break case FBFieldType.Label: self.form!.sections[indexPath.section].removeLine(row: indexPath.row) self.tableView?.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none) break case FBFieldType.Signature: self.form!.sections[indexPath.section].removeLine(row: indexPath.row) self.tableView?.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none) break default: break } } func lineHeightChanged(line: FBLine) { var i:Int = 0 var j:Int = 0 for section in self.form!.visibleSections() { for l in section.visibleLines() { if ((section.id == line.section?.id) && (l.id == line.id)) { self.tableView!.reloadRows(at: [IndexPath.init(row: j, section: i)], with: UITableViewRowAnimation.none) return } j += 1 } i += 1 } } } <file_sep>/FormBuilder/Classes/Form Builder Classes/FBField.swift // // Field.swift // FormBuilder // // Created by <NAME> on 1/16/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public enum FBFieldType:Int { case Unknown = 0 case Section = 1 case Heading = 2 case Label = 3 case Image = 4 case ImagePicker = 5 case Text = 6 case TextArea = 7 case ComboBox = 8 case CheckBox = 9 case OptionSet = 10 case Signature = 11 case DatePicker = 12 } public enum FBDateType:Int { case Date = 0 case Time = 1 case DateTime = 2 } open class FBField: NSObject { // Field -- represents a line of data in the form (although potentially more than one field can // be put on one line, this won't usually be the case) the field is an item of data to // be entered into the form, it can be validated and it can also potentially be // replicated if allowed by the section it's in. public var id:String = "" public var hasInput:Bool = false public var hasData:Bool = false var tag:String? = "#Field" var style:FBStyleClass? = nil public var line:FBLine? public var fieldType:FBFieldType = FBFieldType.Heading var view:FBFieldView? = nil public var caption:String? = "" public var visible:Bool = true var range = (0, 0) private var _labelHeight:CGFloat = 30.0 private var _textHeight:CGFloat = 30.0 var requiredWidth:CGFloat = 5.0 var requiredHeight:CGFloat = 5.0 // the style properties control how the field is displayed, the display properties may be set in any parent class // all the way up to the form, and it may be overridden at every level as well. So first we check to see if the value // has been set for this field, if not, has it been set for the line, if not, has it been set for the section, if not // has it been set for the form, and if not, is it set in the settings singleton? public var required:Bool { get { return false } set(newValue) { // do nothing } } public var input:Any? { get { return nil } set(newValue) { // do nothing } } public var data:Any? { get { return nil } set(newValue) { // do nothing } } var optionSet:FBOptionSet? { get { return nil } set(newValue) { // do nothing } } var borderWidth:CGFloat { get { var borderWidth:CGFloat = 0.0 if ((self == self.line!.fields.first) && (self == self.line!.fields.last)) { borderWidth = (self.style?.value(forKey: "border") as! CGFloat) * 2.0 } else if ((self == self.line!.fields.first) || (self == self.line!.fields.last)) { borderWidth = (self.style?.value(forKey: "border") as! CGFloat) * 1.5 } else { borderWidth = (self.style?.value(forKey: "border") as! CGFloat) } return borderWidth } } var borderHeight:CGFloat { get { return (self.style?.value(forKey: "border") as! CGFloat) } } var width:CGFloat { get { return (self.line!.section!.form!.tableView!.frame.width / CGFloat(self.line!.fields.count)) - self.borderWidth } } var labelHeight:CGFloat { get { return 0.0 } } var labelWidth:CGFloat { get { return 0.0 } } var textHeight:CGFloat { get { return 0.0 } } var textWidth:CGFloat { get { return 0.0 } } var mode:FBFormMode { get { return FBFormMode.View } } var editing:Bool { get { return false } } override public init() { super.init() } public init(line:FBLine, lines:(Int, Int)) { super.init() self.line = line self.range = lines let file = self.line!.section!.form!.file! self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: self.tag!)!) self.style!.parent = self.line!.style // override the default parents, our styles always descend from the style of the parent object! var i:Int = lines.0 while (i <= lines.1) { switch (file.lines[i].keyword) { case FBKeyWord.None: i += 1 break case FBKeyWord.Unknown: i += 1 break case FBKeyWord.Id: self.id = file.lines[i].value i += 1 break case FBKeyWord.Visible: self.visible = (file.lines[i].value.lowercased() != "false") i += 1 break case FBKeyWord.Style: //self.tag = file.lines[i].value self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: file.lines[i].value)!) self.style!.parent = self.line!.style // override the default parents, our styles always descend from the style of the parent object! i += 1 break case FBKeyWord.Dialog: let indentLevel:Int = file.lines[i].indentLevel let spaceLevel:Int = file.lines[i].spaceLevel i += 1 while (i <= lines.1) { if ((file.lines[i].indentLevel > indentLevel) || (file.lines[i].spaceLevel > spaceLevel) || (file.lines[i].keyword == FBKeyWord.None)) { i += 1 } else { break } } break case FBKeyWord.Requirements: let indentLevel:Int = file.lines[i].indentLevel let spaceLevel:Int = file.lines[i].spaceLevel i += 1 while (i <= lines.1) { if ((file.lines[i].indentLevel > indentLevel) || (file.lines[i].spaceLevel > spaceLevel) || (file.lines[i].keyword == FBKeyWord.None)) { i += 1 } else { break } } break case FBKeyWord.FieldType: self.fieldType = FBField.typeWith(string: file.lines[i].value) i += 1 break case FBKeyWord.Caption: self.caption = file.lines[i].value while (i < lines.1) { if (file.lines[i].continued) { i += 1 if (i <= lines.1) { var value:String = file.lines[i].value value = value.replacingOccurrences(of: "\\n", with: "\n", options: [], range: nil) value = value.replacingOccurrences(of: "\\t", with: "\t", options: [], range: nil) value = value.replacingOccurrences(of: "\\r", with: "\r", options: [], range: nil) value = value.replacingOccurrences(of: "\\\"", with: "\"", options: [], range: nil) self.caption = (self.caption ?? "") + value } } else { break } } i += 1 break default: i += 1 break } } } func initWith(line:FBLine, id:String, label:String, type:FBFieldType) -> FBField { self.line = line self.id = id as String self.fieldType = type self.caption = label self.visible = true self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: self.tag!)!) self.style!.parent = self.line!.style // override the default parents, our styles always descend from the style of the parent object! return self } func validate() -> FBException { let exception:FBException = FBException() exception.field = self return exception } public func clear() { // do nothing here } func equals(value:String) -> Bool { return Bool(self.id.lowercased() == value.lowercased()) } static func typeWith(string:String) -> FBFieldType { switch (string.lowercased()) { case "section": return FBFieldType.Section case "heading": return FBFieldType.Heading case "label": return FBFieldType.Label case "image": return FBFieldType.Image case "imagepicker": return FBFieldType.ImagePicker case "text": return FBFieldType.Text case "textarea": return FBFieldType.TextArea case "combobox": return FBFieldType.ComboBox case "checkbox": return FBFieldType.CheckBox case "optionset": return FBFieldType.OptionSet case "signature": return FBFieldType.Signature case "datepicker": return FBFieldType.DatePicker default: return FBFieldType.Heading } } static func dateTypeWith(string:String) -> FBDateType { switch (string.lowercased()) { case "date": return FBDateType.Date case "time": return FBDateType.Time case "datetime": return FBDateType.DateTime default: return FBDateType.Date } } func isNil(someObject: Any?) -> Bool { if someObject is String { if (someObject as? String) != nil && !((someObject as? String)?.isEmpty)! { return false } } if someObject is Array<Any> { if (someObject as? Array<Any>) != nil { return false } } if someObject is Dictionary<AnyHashable, Any> { if (someObject as? Dictionary<String, Any>) != nil { return false } } if someObject is Data { if (someObject as? Data) != nil { return false } } if someObject is Date { if (someObject as? Date != nil) { return false } } if someObject is NSNumber { if (someObject as? NSNumber) != nil{ return false } } if someObject is UIImage { if (someObject as? UIImage) != nil { return false } } return true } } <file_sep>/Example/FormBuilder/Contact.spec // this is a sample form specification file which shows all of the different fields and attributes you can set. // you may want to use this as a guide to build your own form spec. notice that the file format is thus: // [keyword] [value block] // comment // here are the keywords you can use... (keywords are case insensitive) // ==================================== // Style // Editable // Visible // Section // Line // Field // Id // Title // Collapsible // Collapsed // AllowsAdd // AddItems // FieldType // Caption // Required // Value // Requirements // Minimum // Maximum // Format // DataType // MemberOf // OptionSet // Option // PickerMode // DateMode // Image // Label // Signature // Capitalize // Keyboard // ==================================== // the value block is everything after the keyword and before the comment or newline character, // excluding the whitespace before the first character and after the last character. // you don't need to surround your value block in quotes, but you do need to pay close attention to tabs or spaces which specify indentation. // indentation determines whether objects represented in this file are siblings or have a parent child relationship. // for instance, if you want to specify properties for a section, you must use the "section" keyword, then new line // then make a line with indentation level greater than that of the section line for each property to be specified for that item. // if a line does not have a greater indentation level, it will be treated as a new object and not a property of your previous object. // for long text values, such as labels or text areas, you may want to split up the value over multiple lines. // to do this you simply put an underscore character ("_") at the end of the line, after a trailing space. // the next line will be a continuation of the value from the previous line, and you can do this as any times as you wish. // you can also put a comment after the trailing underscore if you want. // quotation marks do not have to be escaped in value blocks, and if you want to format text with newlines or tabs, // just use the "\t" or "\n" or "\r" character sequences. // style #Form // the default form style class, you can use a custom style class here if you want. section // start the first section id Address // each element must have an id so we can refer back to it later style #Section // the default section style class title Address Section // the title for this section, "Address Section". collapsible true // this section is collapsible, default is false collapsed false // initially show the section as expanded allows-add true // allow the user to add new items add-items // here is the list of items the user can add section // add a new section identical to this one image // add an image picker to this section label // add a label to this section signature // add a signature field to this section line // here we start specifying the lines to display, each section is composed of lines of data id AddressHeading // the id of this line style #Line // the default line style class field // here we specify the fields for this line, each line is composed of one or more fields. id AddressHeading // the id for this field. type heading // this is a heading field. caption Address // this field has a label of "Address" line id Street field id Street style #MyText type text caption Street required true capitalize words // words, sentences, allcharacters, none keyboard default // default, asciicapable, asciicapablenumberpad, alphabet, numberpad, // numbersandpunctuation, emailaddress, decimalpad, url, phonepad, namephonepad, twitter, websearch line id City field id City type text caption City required true line id County field id County type text caption County line id State field id State type combobox caption State option-set State value TX required true line id Province visible false field id Province type text caption Province required true line id ZipCode field id ZipCode type text caption Zip Code required true requirements minimum 5 line id Email field id Email type text caption Email required true requirements format email keyboard email capitalize none line id PostalCode visible false field id PostalCode type text caption Postal Code required true line id BusinessAddress field id BusinessAddress type checkbox caption Business Address required true line id Country field id Country type combobox caption Country option-set MyCountry value US required true line id Delivery field id Delivery type optionset caption Delivery Type option-set Delivery value UPS line id LikeMe field id LikeMe type optionset caption Do you like me? option-set id LikeMe option id YES value Yes! option id NO value No, I do not. value YES line id TextFields field id Text1 type label caption Text 1 222 _ // this is how you continue a value block on the next line, with an "_" character. 3333 _ // you can do it as many times as you want. \n\t"4444" // notice the \r and \t to format text, you can also use \n, quotes aren't escaped. field id Text2 type label caption Text 2 value test text here 2 field id Text3 type label caption Text 3 test text here 3 test test test test test test test test test test test test 2 value test text here 3 test test test test test test test test test test test test line id TextAreas field id TextArea1 type textarea caption Text Area 1 value test text here required true field id TextArea2 type textarea caption Text Area 2 test test test test test test test test test test test test test test 2 value Text Area 2 test test test test test test test test test test test test test test 2 Text Area 2 test test test test test test test test test test test test test test 2 required true line id Image field id welcome type image caption you're welcome! value welcome line id StartDate field id StartDate type datepicker caption Start Date required true date-mode date dialog style #DatePopover line id MyImage field id MyImage type imagepicker caption Select an Image! required true picker-mode album line id Signature field id Signature type signature caption Sign Here! required true dialog style #SignaturePopover <file_sep>/Example/FormBuilder/Address.swift // // Address.swift // FormBuilder // // Created by <NAME> on 1/20/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public class Address: NSObject { var street:String? var city:String? var county:String? var state:String? var province:String? var zipcode:String? var postalcode:String? var business:Bool? var country:String? var deliveryType:String? } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/FBFieldView.swift // // FieldView.swift // FormBuilder // // Created by <NAME> on 1/29/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit protocol FBFieldViewDelegate: class { func fieldHeightChanged() } open class FBFieldView: UIView { weak var delegate:FBFieldViewDelegate? func height() -> CGFloat { // this should be overridden in child views. return 0.0 } } <file_sep>/FormBuilder/Classes/Style/Parser/SwiftDeviceCss.swift // // SwiftDeviceCss.swift // SwiftCssParser // // Created by Mango on 2017/6/4. // Copyright © 2017年 Mango. All rights reserved. // import UIKit public let SwiftDeviceCss = SwiftCssStyleSheet.deviceCss() class SwiftCssStyleSheet { private enum ScreenSize { case _320_480 //iPhone4 etc. case _320_568 //iPhone5 etc. case _375_667 //iPhone6 etc. case _414_736 //iPhone6 plus etc. case _768_1024 //iPad etc. case _1024_1366 //iPad Pro } static private let screenSize: ScreenSize = { let screen = UIScreen.main let size = UIScreen.main.fixedCoordinateSpace.bounds.size switch (size.width,size.height) { case (320,640): return ._320_480 case (320,568): return ._320_568 case (375,667): return ._375_667 case (414,736): return ._414_736 case (768,1024): return ._768_1024 case (1024,1366): return ._1024_1366 default: print("Warning: Can NOT detect screenModel! bounds: \(screen.bounds) nativeScale: \(screen.nativeScale)") return ._375_667 // Default } }() static func deviceCss() -> SwiftCSS { switch self.screenSize { case ._320_480: return SwiftCSS(CssFileURL: URL.CssURL(name: "iPhone4")) case ._320_568: return SwiftCSS(CssFileURL: URL.CssURL(name: "iPhone5")) case ._375_667: return SwiftCSS(CssFileURL: URL.CssURL(name: "iPhone6")) case ._414_736: return SwiftCSS(CssFileURL: URL.CssURL(name: "iPhone6P")) case ._768_1024: return SwiftCSS(CssFileURL: URL.CssURL(name: "iPad")) case ._1024_1366: return SwiftCSS(CssFileURL: URL.CssURL(name: "iPadPro")) } } } private extension URL { static func CssURL(name:String) -> URL { return Bundle.main.url(forResource: name, withExtension: "css")! } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/CheckBox/FBCheckBoxView.swift // // CheckBoxView.swift // FormBuilder // // Created by <NAME> on 1/23/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBCheckBoxView: FBFieldView { @IBOutlet var checkBoxLabel:UILabel? @IBOutlet var button:FBCheckView? @IBOutlet var requiredView:FBRequiredView? var gestureRecognizer:UITapGestureRecognizer? var field:FBCheckBoxField? override func height() -> CGFloat { return ((self.field!.style!.value(forKey: "margin") as! CGFloat) * 2) + self.field!.labelHeight + (self.field!.style!.value(forKey: "border") as! CGFloat) } open func updateDisplay(label:String, state:FBCheckState, required:Bool) { self.checkBoxLabel = UILabel() self.checkBoxLabel?.numberOfLines = 0 self.addSubview(self.checkBoxLabel!) self.checkBoxLabel?.font = UIFont(name: self.field?.style!.value(forKey: "font-family") as! String, size: self.field?.style!.value(forKey: "font-size") as! CGFloat) self.checkBoxLabel?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "foreground-color") as! String) self.checkBoxLabel?.sizeToFit() self.button = FBCheckView.fromNib(withName: "FBCheckView") self.button?.backgroundColor = UIColor.clear self.gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(buttonPressed)) self.button?.addGestureRecognizer(self.gestureRecognizer!) self.addSubview(self.button!) self.requiredView = FBRequiredView() self.addSubview(self.requiredView!) self.checkBoxLabel?.font = self.field!.style!.font if (self.field!.editing) { // set this field to edit mode self.requiredView?.isHidden = !required self.button?.isUserInteractionEnabled = true self.button?.state = state } else { // set this field to view mode self.requiredView?.isHidden = true self.button?.isUserInteractionEnabled = false self.button?.state = state } self.checkBoxLabel!.text = label } override open func layoutSubviews() { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: self.button?.frame = CGRect(x: margin, y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.labelHeight) self.checkBoxLabel?.frame = CGRect(x: self.field!.labelHeight + (margin * 2), y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - (self.field!.requiredWidth + (self.field!.labelHeight + (margin * 4))), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.Vertical: self.button?.frame = CGRect(x: margin, y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.labelHeight) self.checkBoxLabel?.frame = CGRect(x: self.field!.labelHeight + (margin * 2), y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - (self.field!.requiredWidth + (self.field!.labelHeight + (margin * 4))), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.ReverseHorizontal: self.button?.frame = CGRect(x: margin, y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.labelHeight) self.checkBoxLabel?.frame = CGRect(x: self.field!.labelHeight + (margin * 2), y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - (self.field!.requiredWidth + (self.field!.labelHeight + (margin * 4))), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.ReverseVertical: self.button?.frame = CGRect(x: margin, y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.labelHeight) self.checkBoxLabel?.frame = CGRect(x: self.field!.labelHeight + (margin * 2), y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - (self.field!.requiredWidth + (self.field!.labelHeight + (margin * 4))), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.PlaceHolder: self.button?.frame = CGRect(x: margin, y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.labelHeight) self.checkBoxLabel?.frame = CGRect(x: self.field!.labelHeight + (margin * 2), y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: self.frame.width - (self.field!.requiredWidth + (self.field!.labelHeight + (margin * 4))), height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break } self.button?.setNeedsDisplay() } @objc @IBAction func buttonPressed() { // toggle between checked and unchecked... if (self.button?.state == FBCheckState.Checked) { self.button?.state = FBCheckState.Unchecked } else { self.button?.state = FBCheckState.Checked } self.button?.setNeedsDisplay() if (self.button?.state == FBCheckState.Checked) { self.field?.input = true } else { self.field?.input = nil } } } <file_sep>/FormBuilder/Assets/FBPopOverMenu/FTConstants.swift // // FTConstants.swift // FTPopOverMenu_Swift // // Created by <NAME> on 27/07/2017. // Copyright © 2016 LiuFengting (https://github.com/liufengting) . All rights reserved. // import UIKit struct FT { internal static let DefaultMargin = CGFloat(4) internal static let DefaultCellMargin = CGFloat(6) internal static let DefaultMenuIconSize = CGFloat(24) internal static let DefaultMenuCornerRadius = CGFloat(4) internal static let DefaultMenuArrowWidth = CGFloat(0) //CGFloat(8) internal static let DefaultMenuArrowHeight = CGFloat(0) //CGFloat(10) internal static let DefaultAnimationDuration = TimeInterval(0.2) internal static let DefaultBorderWidth = CGFloat(0.5) internal static let DefaultCornerRadius = CGFloat(6) internal static let DefaultMenuRowHeight = CGFloat(40) internal static let DefaultMenuWidth = CGFloat(120) internal static let DefaultTintColor = UIColor(red: 80/255, green: 80/255, blue: 80/255, alpha: 1) internal static let PopOverMenuTableViewCellIndentifier = "FTPopOverMenuTableViewCellIndentifier" } <file_sep>/FormBuilder/Classes/Form Builder Classes/Fields/FBSignatureField.swift // // SignatureField.swift // FormBuilder // // Created by <NAME> on 1/29/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class FBSignatureField: FBInputField { var dialog:FBDialog? = nil override public init() { super.init() } override public init(line:FBLine, lines:(Int, Int)) { super.init(line:line, lines:lines) self.tag = "#Signature" if (FBStyleSet.shared.style(named: self.tag!) != nil) { self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: self.tag!)!) self.style!.parent = self.line!.style // override the default parents, our styles always descend from the style of the parent object! } var i:Int = lines.0 let file = self.line!.section!.form!.file! while (i <= lines.1) { switch (file.lines[i].keyword) { case FBKeyWord.Value: self.data = file.lines[i].value i += 1 break case FBKeyWord.Style: if (FBStyleSet.shared.style(named: file.lines[i].value) != nil) { self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: file.lines[i].value)!) } i += 1 break case FBKeyWord.Requirements: let indentLevel:Int = file.lines[i].indentLevel let spaceLevel:Int = file.lines[i].spaceLevel i += 1 while (i <= lines.1) { if ((file.lines[i].indentLevel > indentLevel) || (file.lines[i].spaceLevel > spaceLevel) || (file.lines[i].keyword == FBKeyWord.None)) { i += 1 } else { break } } break case FBKeyWord.Dialog: let indentLevel:Int = file.lines[i].indentLevel let spaceLevel:Int = file.lines[i].spaceLevel i += 1 var fieldRange = (i, i) while (i <= lines.1) { if ((file.lines[i].indentLevel > indentLevel) || (file.lines[i].spaceLevel > spaceLevel) || (file.lines[i].keyword == FBKeyWord.None)) { i += 1 } else { break } } fieldRange.1 = i - 1 self.dialog = FBDialog(type: FBDialogType.Signature, field: self, lines: fieldRange) break default: i += 1 break } } } var viewName:String { get { return self.style!.viewFor(type: self.fieldType) } } override var labelHeight:CGFloat { get { return self.caption!.height(withConstrainedWidth: self.labelWidth, font: self.style!.font) } } override var labelWidth: CGFloat { get { let style:FBStyleClass? = self.dialog?.style ?? nil let signatureWidth:CGFloat = style?.value(forKey: "width") as? CGFloat ?? 300.0 return self.width - (((self.style?.value(forKey: "margin") as! CGFloat) * 2) + self.borderWidth + signatureWidth) } } } <file_sep>/FormBuilder/Classes/Form Builder Classes/FBSection.swift // // FBSection.swift // FormBuilder // // Created by <NAME> on 1/16/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public class FBSection: NSObject { // FBSection -- a group of fields in a form, it can have a title, and can allow new fields // to be added, it can also be collapsed or removed from the form based on user interaction. var id:String = "" var tag:String? = "#Section" var style:FBStyleClass? = nil var title:String? = "" public var lines:Array<FBLine>? = Array<FBLine>() public var visible:Bool = true var collapsible:Bool = false var collapsed:Bool = false public var form:FBForm? var headerView:FBSectionHeaderView? var mode:FBFormMode = FBFormMode.View var allowsAdd:Bool = false var allowsRemove:Bool = false var addSection:Bool = false var addLine:Bool = false var fieldsToAdd:Array<FBFieldType> = Array<FBFieldType>() var range = (0, 0) private var _editable:Bool? var editable:Bool? { get { // this section is ONLY editable if none of its parents are explicitly set as NOT editable. if ((self.form?.editable == nil) || (self.form?.editable == true)) { if ((_editable == nil) || (_editable == true)) { return true } } return false } set(newValue) { _editable = newValue } } public init(form: FBForm, lines:(Int, Int)) { super.init() self.form = form let file = form.file! self.range = lines self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: self.tag!)!) self.style!.parent = self.form!.style // override the default parents, our styles always descend from the style of the parent object! var i:Int = lines.0 while (i <= lines.1) { switch (file.lines[i].keyword) { case FBKeyWord.Id: self.id = file.lines[i].value i += 1 break case FBKeyWord.Style: //self.tag = file.lines[i].value self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: file.lines[i].value)!) self.style!.parent = self.form!.style i += 1 break case FBKeyWord.Editable: self.editable = (file.lines[i].value.lowercased() != "false") i += 1 break case FBKeyWord.Collapsible: self.collapsible = (file.lines[i].value.lowercased() != "false") i += 1 break case FBKeyWord.Collapsed: self.collapsed = (file.lines[i].value.lowercased() == "true") i += 1 break case FBKeyWord.AllowsAdd: self.allowsAdd = (file.lines[i].value.lowercased() == "true") i += 1 break case FBKeyWord.AddItems: let indentLevel:Int = file.lines[i].indentLevel let spaceLevel:Int = file.lines[i].spaceLevel i += 1 while (i <= lines.1) { if ((file.lines[i].indentLevel > indentLevel) || (file.lines[i].spaceLevel > spaceLevel) || (file.lines[i].keyword == FBKeyWord.None)) { switch (file.lines[i].keyword) { case FBKeyWord.Section: self.fieldsToAdd.append(FBFieldType.Section) break case FBKeyWord.Image: self.fieldsToAdd.append(FBFieldType.Image) break case FBKeyWord.Label: self.fieldsToAdd.append(FBFieldType.Label) break case FBKeyWord.Signature: self.fieldsToAdd.append(FBFieldType.Signature) break default: break } i += 1 } else { break } } break case FBKeyWord.Title: self.title = file.lines[i].value i += 1 break case FBKeyWord.Line: let indentLevel:Int = file.lines[i].indentLevel let spaceLevel:Int = file.lines[i].spaceLevel i += 1 var lineRange = (i, i) while (i <= lines.1) { if ((file.lines[i].indentLevel > indentLevel) || (file.lines[i].spaceLevel > spaceLevel) || (file.lines[i].keyword == FBKeyWord.None)) { i += 1 } else { break } } lineRange.1 = i - 1 self.lines?.append(FBLine(section: self, lines: lineRange)) break default: i += 1 break } } } func equals(value:String) -> Bool { return Bool(self.id.lowercased() == value.lowercased()) } public func line(named:String) -> FBLine? { for line in self.lines! { if (line.id.lowercased() == named.lowercased()) { return line } } return nil } public func field(withPath:String) -> FBField? { var line:FBLine? = nil var path:Array<String> = withPath.components(separatedBy: ".") if (path.count > 0) { line = self.line(named: path[0]) } if (line != nil) { if (line?.fields.count == 1) { return line?.fields[0] } else { if (path.count > 2) { return line?.field(named: path[2]) } } } return nil } func visibleLines() -> Array<FBLine> { var visible:Array<FBLine> = Array<FBLine>() for line in self.lines! { if (line.visible == true) { visible.append(line) } } return visible } func removeLine(row:Int) { var visible:Int = 0 var actual:Int = 0 for line in self.lines! { if (line.visible == true) { if (visible == row) { break } visible += 1 } actual += 1 } self.lines?.remove(at: actual) } func lineCount() -> Int { return self.visibleLines().count } func colorFor(line:FBLine) -> UIColor { var color:UIColor = UIColor.init(hexString: self.style?.value(forKey: "background-color") as! String) ?? UIColor.white if ((self.style?.value(forKey: "alternate-colors") as! String).lowercased() == "true") { var count:Int = 0 for currentLine in self.visibleLines() { if (line.id == currentLine.id) { return color } if (count % 2 == 1) { color = UIColor.init(hexString: self.style?.value(forKey: "background-color") as! String) ?? UIColor.white } else { color = UIColor.init(hexString: self.style?.value(forKey: "alternate-background-color") as! String) ?? UIColor.lightGray } count += 1 } } return color } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/CheckBox/FBCheckView.swift // // CheckView.swift // FormBuilder // // Created by <NAME> on 1/23/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public enum FBCheckState:Int { case Disabled = 0 case Unchecked = 1 case Checked = 2 } open class FBCheckView: UIView { var state:FBCheckState = FBCheckState.Unchecked override open func draw(_ rect: CGRect) { // Drawing code super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } let scale = UIScreen.main.scale let width = 4/scale let offset = width/2 context.setLineWidth(width) context.setStrokeColor(UIColor.darkGray.cgColor) context.beginPath() context.move(to: CGPoint(x: 0.0 + offset, y: 0.0 + offset)) context.addLine(to: CGPoint(x: self.frame.height - offset, y: 0.0 + offset)) context.addLine(to: CGPoint(x: self.frame.height - offset, y: self.frame.height - offset)) context.addLine(to: CGPoint(x: 0.0 + offset, y: self.frame.height - offset)) context.addLine(to: CGPoint(x: 0.0 + offset, y: 0.0 + offset)) context.strokePath() if (self.state == FBCheckState.Checked) { context.setStrokeColor(UIColor.gray.cgColor) context.setFillColor(UIColor.gray.cgColor) let rect:CGRect = CGRect(x: (self.frame.height / 6.0) + offset, y: (self.frame.height / 6.0) + offset, width: self.frame.height - ((self.frame.height / 6.0) * 2) - (offset * 2), height: self.frame.height - ((self.frame.height / 6.0) * 2) - (offset * 2)) context.addRect(rect) context.drawPath(using: CGPathDrawingMode.fillStroke) } } } <file_sep>/FormBuilder/Classes/Style/Parser/CssParser.swift // // CssParser.swift // SwiftCssParser // // Created by Mango on 2017/6/3. // Copyright © 2017年 Mango. All rights reserved. // import Foundation public class CssParser { let lexer: CssLexer lazy var lookaheads: [Token?] = Array(repeating: nil, count: self.k) let k = 6 //LL(6) var index = 0 //circular index of next token position to fill typealias Token = CssLexer.Token public var outputDic = [String:[String:Any]]() public init(lexer: CssLexer) { self.lexer = lexer for _ in 1...k { consume() } } private var consumedToken = [Token]() func consume() { lookaheads[index] = lexer.nextToken() index = (index + 1) % k //for debug if let token = lookaheads[index] { consumedToken.append(token) } } // form 1 to k func lookaheadToken(_ index: Int) -> Token? { let circularIndex = (self.index + index - 1) % k return lookaheads[circularIndex] } @discardableResult func match(token: Token) -> Token { guard let lookaheadToken = lookaheadToken(1) else { fatalError("lookahead token is nil") } guard lookaheadToken.type == token.type else { fatalError("expecting (\(token.type)) but found (\(lookaheadToken) consumedTokens: \(consumedToken))") } consume() return lookaheadToken } } //MARK: Rules extension CssParser { func element(selector: String ) { guard var selectorDic = outputDic[selector] else { fatalError("\(selector) dic not found") } let key = match(token: .string("")) match(token: .colon) guard let currentToken = lookaheadToken(1) else { fatalError("lookahead token is nil") } switch currentToken { case let .double(value): guard let token2 = lookaheadToken(2) else { fatalError("token2 is nil") } switch token2 { case let .double(double): // key : double double; match(token: currentToken) match(token: token2) selectorDic[key.description] = ["double1":value,"double2":double] default: // normal double match(token: currentToken) selectorDic[key.description] = value } case let .string(value): //LL(2) guard let token2 = lookaheadToken(2) else { fatalError("token2 is nil") } switch token2 { case let .double(double): //key : name double match(token: currentToken) match(token: token2) selectorDic[key.description] = ["name":value,"size":double] default: //normal string match(token: currentToken) selectorDic[key.description] = value } case let .rgb(r,g,b,a): match(token: currentToken) selectorDic[key.description] = (r,g,b,a) default: break } outputDic[selector] = selectorDic } func elements(selector: String) { element(selector: selector) while let lookaheadToken = lookaheadToken(1), lookaheadToken.type == Token.semicolon.type { match(token: .semicolon) //if current token is "}", it means elements rule is parsed. if let currentToken = self.lookaheadToken(1), currentToken.type == Token.rightBrace.type { return } element(selector: selector) } } func selector() { let selector = match(token: .selector("")) let dic = [String:Int]() outputDic[selector.description] = dic match(token: .leftBrace) elements(selector: selector.description) match(token: .rightBrace) } func css() { while lookaheadToken(1) != nil { selector() } } public func parse() { css() } } <file_sep>/FormBuilder/Classes/Form Builder UI/Form/Header/FBSectionHeaderView.swift // // SectionHeaderView.swift // FormBuilder // // Created by <NAME> on 2/2/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit protocol FBSectionHeaderDelegate: class { func editSelected(section:Int) func saveSelected(section:Int) func cancelSelected(section:Int) func collapse(section:Int) func expand(section:Int) func addItem(section:Int, type:FBFieldType) func removeItem(indexPath:IndexPath, type:FBFieldType) } open class FBSectionHeaderView: UIView { @IBOutlet var backgroundView:UIView? @IBOutlet var editButton:UIButton? @IBOutlet var cancelButton:UIButton? @IBOutlet var collapseButton:UIButton? @IBOutlet var label:UILabel? @IBOutlet var addButton:UIButton? @IBOutlet var removeButton:UIButton? var collapsible:Bool = false var collapsed:Bool = false var allowsAdd:Bool = false var allowsRemove:Bool = false var addItems:Array<String> = Array<String>() var index:Int? var section:FBSection? var style:FBStyleClass? weak var delegate:FBSectionHeaderDelegate? open func updateDisplay(index:Int, section:FBSection) { let bundle = Bundle.init(for: self.classForCoder) section.headerView = self self.section = section self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: "#SectionHeader")!) self.style!.parent = FBStyleSet.shared.style(named: "#Section") self.backgroundColor = UIColor.init(hexString: self.style!.value(forKey: "border-color") as! String) self.backgroundView = UIView() self.backgroundView?.backgroundColor = UIColor.init(hexString: self.style!.value(forKey: "background-color") as! String) self.addSubview(self.backgroundView!) self.label = UILabel() self.label?.numberOfLines = 0 self.label?.font = UIFont(name: self.style!.value(forKey: "font-family") as! String, size: self.style!.value(forKey: "font-size") as! CGFloat) self.label?.textColor = UIColor.init(hexString: self.style!.value(forKey: "foreground-color") as! String) self.label?.text = section.title ?? "" self.label?.sizeToFit() self.backgroundView?.addSubview(self.label!) self.index = index self.collapsible = section.collapsible if (self.collapsible) { self.collapsed = section.collapsed self.collapseButton = UIButton() if (self.collapsed) { self.collapseButton?.setImage(UIImage.init(named: "right", in: bundle, compatibleWith: nil), for: UIControlState.normal) } else { self.collapseButton?.setImage(UIImage.init(named: "down", in: bundle, compatibleWith: nil), for: UIControlState.normal) } self.collapseButton?.addTarget(self, action: #selector(collapsePressed), for: UIControlEvents.touchUpInside) self.backgroundView?.addSubview(self.collapseButton!) } self.allowsAdd = section.allowsAdd if (self.allowsAdd) { self.addButton = UIButton() self.addButton?.setImage(UIImage.init(named: "plus", in: bundle, compatibleWith: nil), for: UIControlState.normal) self.addButton?.addTarget(self, action: #selector(addPressed), for: UIControlEvents.touchUpInside) self.backgroundView?.addSubview(self.addButton!) } self.allowsRemove = section.allowsRemove if (self.allowsRemove) { self.removeButton = UIButton() self.removeButton?.setImage(UIImage.init(named: "minus", in: bundle, compatibleWith: nil), for: UIControlState.normal) self.removeButton?.addTarget(self, action: #selector(removePressed), for: UIControlEvents.touchUpInside) self.backgroundView?.addSubview(self.removeButton!) } if (self.section?.editable == true) { self.editButton = UIButton() if (self.section!.mode == FBFormMode.View) { self.editButton?.setImage(UIImage.init(named: "edit", in: bundle, compatibleWith: nil), for: UIControlState.normal) } else { self.editButton?.setImage(UIImage.init(named: "save", in: bundle, compatibleWith: nil), for: UIControlState.normal) } self.editButton?.addTarget(self, action: #selector(editPressed), for: UIControlEvents.touchUpInside) self.backgroundView?.addSubview(self.editButton!) self.cancelButton = UIButton() self.cancelButton?.setImage(UIImage.init(named: "cancel", in: bundle, compatibleWith: nil), for: UIControlState.normal) self.cancelButton?.addTarget(self, action: #selector(cancelPressed), for: UIControlEvents.touchUpInside) self.backgroundView?.addSubview(self.cancelButton!) if (self.section!.mode == FBFormMode.Edit) { self.cancelButton!.isHidden = false } else { self.cancelButton!.isHidden = true } } for item in section.fieldsToAdd { self.addItems.append(self.stringFrom(field: item)) } } private func stringFrom(field:FBFieldType) -> String { switch (field) { case FBFieldType.Section: return "Section" case FBFieldType.Image: return "Image" case FBFieldType.Label: return "Label" case FBFieldType.Signature: return "Signature" default: return "" } } private func fieldFrom(string:String) -> FBFieldType { switch (string.lowercased()) { case "section": return FBFieldType.Section case "image": return FBFieldType.Image case "label": return FBFieldType.Label case "signature": return FBFieldType.Signature default: return FBFieldType.Image } } func height() -> CGFloat { var labelHeight:CGFloat = self.labelHeight() if (labelHeight < 30.0) { labelHeight = 30.0 } return (self.marginWidth() * 2) + labelHeight + self.borderWidth() } override open func layoutSubviews() { let border:CGFloat = self.style?.value(forKey: "border") as! CGFloat let margin:CGFloat = self.style?.value(forKey: "margin") as! CGFloat self.backgroundView?.frame = CGRect(x: border, y: 0.0, width: self.frame.width - (border * 2.0), height: self.frame.height - border) if (self.collapsible) { self.collapseButton!.frame = CGRect(x: margin + border, y: (self.frame.height / 2) - 15.0, width: 30.0, height: 30.0) } var left:CGFloat = margin if (self.collapsible) { left += 30.0 + margin } self.label!.frame = CGRect(x:left, y:(self.frame.height / 2) - (labelHeight() / 2), width:self.labelWidth(), height: self.labelHeight()) if (self.allowsAdd) { self.addButton!.frame = CGRect(x: self.frame.width - (border + margin + 30.0), y: (self.frame.size.height / 2) - 15.0, width: 30.0, height: 30.0) } if (self.allowsRemove) { self.removeButton!.frame = CGRect(x: self.frame.width - (border + (margin * 2) + 60.0), y: (self.frame.size.height / 2) - 15.0, width: 30.0, height: 30.0) } if (self.section?.editable == true) { var buttonOffset:CGFloat = 30.0 if (self.allowsAdd) { buttonOffset += 30.0 + margin } if (self.allowsRemove) { buttonOffset += 30.0 + margin } self.editButton!.frame = CGRect(x: self.frame.width - (border + margin + buttonOffset), y: (self.frame.size.height / 2) - 15.0, width: 30.0, height: 30.0) self.cancelButton!.frame = CGRect(x: self.frame.width - (border + margin + buttonOffset + 30.0 + margin), y: (self.frame.size.height / 2) - 15.0, width: 30.0, height: 30.0) } } func borderWidth() -> CGFloat { if (self.style == nil) { return 0.0 } return self.style?.value(forKey: "border") as! CGFloat } func marginWidth() -> CGFloat { if (self.style == nil) { return 0.0 } return self.style?.value(forKey: "margin") as! CGFloat } func labelWidth() -> CGFloat { var width:CGFloat = self.backgroundView!.frame.size.width - ((self.marginWidth() * 2) + (self.borderWidth() * 2)) if (self.collapsible) { width -= (30.0 + self.marginWidth()) } if (self.allowsAdd) { width -= (30.0 + self.marginWidth()) } if (self.allowsRemove) { width -= (30.0 + self.marginWidth()) } if (self.section?.editable == true) { width -= (30.0 + self.marginWidth()) if (self.section?.mode == FBFormMode.Edit) { width -= (30.0 + self.marginWidth()) } } return width } func labelHeight() -> CGFloat { return self.label?.text?.height(withConstrainedWidth: self.labelWidth(), font: self.style!.font) ?? 0.0 } @objc @IBAction func editPressed() { let bundle = Bundle.init(for: self.classForCoder) if (self.section!.mode == FBFormMode.View) { self.editButton?.setImage(UIImage.init(named: "save", in: bundle, compatibleWith: nil), for: UIControlState.normal) if (self.delegate != nil) { self.delegate!.editSelected(section: self.index!) } } else { if (self.delegate != nil) { self.delegate!.saveSelected(section: self.index!) } } } @objc @IBAction func cancelPressed() { let bundle = Bundle.init(for: self.classForCoder) self.section!.mode = FBFormMode.View self.editButton?.setImage(UIImage.init(named: "edit", in: bundle, compatibleWith: nil), for: UIControlState.normal) self.cancelButton?.isHidden = true if (self.delegate != nil) { self.delegate!.cancelSelected(section: self.index!) } } @objc @IBAction func collapsePressed() { let bundle = Bundle.init(for: self.classForCoder) if (self.delegate != nil) { if (self.collapsed) { self.delegate!.expand(section: self.index!) } else { self.delegate!.collapse(section: self.index!) } self.collapsed = !self.collapsed if (self.collapsed) { self.collapseButton?.setImage(UIImage.init(named: "right", in: bundle, compatibleWith: nil), for: UIControlState.normal) } else { self.collapseButton?.setImage(UIImage.init(named: "down", in: bundle, compatibleWith: nil), for: UIControlState.normal) } } } @objc @IBAction func addPressed() { // show popup dialog here to allow selecting an item. let configuration:FTConfiguration = FTConfiguration.shared configuration.menuWidth = 100.0 FTPopOverMenu.showForSender(sender: self.addButton!, with: self.addItems, done: { (selectedIndex) -> () in if (self.delegate != nil) { self.delegate!.addItem(section: self.index!, type: self.fieldFrom(string: self.addItems[selectedIndex])) } }) { } } @objc @IBAction func removePressed() { if (self.delegate != nil) { self.delegate?.removeItem(indexPath: IndexPath(row: 0, section: self.index!), type: FBFieldType.Section) } } } <file_sep>/FormBuilder/Classes/Form Builder Classes/Fields/FBDropDownView.swift // // DropDownView.swift // FormBuilder // // Created by <NAME> on 1/18/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class FBDropDownView: UIView { // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } let scale = UIScreen.main.scale let width = 2/scale let offset = width/2 context.setLineWidth(width) context.setStrokeColor(UIColor.darkGray.cgColor) context.beginPath() context.move(to: CGPoint(x: 0.0, y: 0.0)) context.addLine(to: CGPoint(x: self.frame.width - offset, y: 0.0)) context.addLine(to: CGPoint(x: self.frame.width - offset, y: self.frame.height - offset)) context.addLine(to: CGPoint(x: 0.0, y: self.frame.height - offset)) context.addLine(to: CGPoint(x: 0.0, y: 0.0)) context.move(to: CGPoint(x: self.frame.width - (offset + self.frame.height + offset), y: 0.0)) context.addLine(to: CGPoint(x: self.frame.width - (offset + self.frame.height + offset), y: self.frame.height - offset)) // draw the diamond on the right context.move(to: CGPoint(x: (self.frame.width - self.frame.height) + (self.frame.height / 4), y: self.frame.height / 2)) context.addLine(to: CGPoint(x: (self.frame.width - frame.height) + (self.frame.height / 2), y: self.frame.height / 4)) context.addLine(to: CGPoint(x: (self.frame.width - frame.height) + ((self.frame.height / 4) * 3), y: self.frame.height / 2)) context.addLine(to: CGPoint(x: (self.frame.width - frame.height) + (self.frame.height / 2), y: (self.frame.height / 4) * 3)) context.addLine(to: CGPoint(x: (self.frame.width - frame.height) + (self.frame.height / 4), y: self.frame.height / 2)) context.strokePath() } } <file_sep>/FormBuilder/Classes/Form Builder UI/FTPopOverMenu_Swift/FTConfiguration.swift // // FTConfiguration.swift // FTPopOverMenu_Swift // // Created by <NAME> on 28/07/2017. // Copyright © 2016 LiuFengting (https://github.com/liufengting) . All rights reserved. // import UIKit public class FTConfiguration : NSObject { public var menuRowHeight : CGFloat = FT.DefaultMenuRowHeight public var menuWidth : CGFloat = FT.DefaultMenuWidth public var textColor : UIColor = UIColor.white public var textFont : UIFont = UIFont.systemFont(ofSize: 14) public var borderColor : UIColor = FT.DefaultTintColor public var borderWidth : CGFloat = FT.DefaultBorderWidth public var backgoundTintColor : UIColor = FT.DefaultTintColor public var cornerRadius : CGFloat = FT.DefaultCornerRadius public var textAlignment : NSTextAlignment = NSTextAlignment.left public var ignoreImageOriginalColor : Bool = false public var menuIconSize : CGFloat = FT.DefaultMenuIconSize public var menuSeparatorColor : UIColor = UIColor.lightGray public var menuSeparatorInset : UIEdgeInsets = UIEdgeInsetsMake(0, FT.DefaultCellMargin, 0, FT.DefaultCellMargin) public var cellSelectionStyle : UITableViewCellSelectionStyle = .none open static var shared : FTConfiguration { struct StaticConfig { static let instance : FTConfiguration = FTConfiguration() } return StaticConfig.instance } } //public class FTConfiguration : NSObject { // // public var menuRowHeight : CGFloat = FTDefaultMenuRowHeight // public var menuWidth : CGFloat = FTDefaultMenuWidth // public var textColor : UIColor = UIColor.white // public var textFont : UIFont = UIFont.systemFont(ofSize: 14) // public var borderColor : UIColor = FTDefaultTintColor // public var borderWidth : CGFloat = FTDefaultBorderWidth // public var backgoundTintColor : UIColor = FTDefaultTintColor // public var cornerRadius : CGFloat = FTDefaultCornerRadius // public var textAlignment : NSTextAlignment = NSTextAlignment.left // public var ignoreImageOriginalColor : Bool = false // public var menuSeparatorColor : UIColor = UIColor.lightGray // public var menuSeparatorInset : UIEdgeInsets = UIEdgeInsetsMake(0, FTDefaultCellMargin, 0, FTDefaultCellMargin) // public var cellSelectionStyle : UITableViewCellSelectionStyle = .none // // public static var shared : FTConfiguration { // struct StaticConfig { // static let instance : FTConfiguration = FTConfiguration() // } // return StaticConfig.instance // } //} <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/ImagePicker/FBImagePickerView.swift // // ImagePickerView.swift // FormBuilder // // Created by <NAME> on 1/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBImagePickerView: FBFieldView, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet var label:UILabel? @IBOutlet var button:UIButton? @IBOutlet var requiredView:FBRequiredView? @IBOutlet var clearButton:UIButton? //var image:UIImage? var field:FBImagePickerField? var imagePicker:UIImagePickerController? override func height() -> CGFloat { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 let border:CGFloat = self.field?.style?.value(forKey: "border") as? CGFloat ?? 1.5 if (self.field!.input != nil) { var width:CGFloat = (self.field?.caption!.width(withConstrainedHeight: (self.field?.labelHeight)!, font: (self.field?.style?.font)!))! if (width < 50.0 + border + (margin * 2)) { width = 50.0 + border + (margin * 2) } let resized:UIImage = (self.field!.input! as! UIImage).resize(width: Double(self.field!.width - ((margin * 4) + width + self.field!.requiredWidth)))! return resized.size.height + (margin * 2) + border } else { return (margin * 2) + border + 50.0 } } override open func layoutSubviews() { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 let border:CGFloat = self.field?.style?.value(forKey: "border") as? CGFloat ?? 1.5 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: self.label?.frame = CGRect(x: margin, y: margin, width: self.field!.labelWidth, height: self.field!.labelHeight) /* self.label!.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2), height: self.field!.labelHeight) */ if (self.field!.input != nil) { var width:CGFloat = (self.field?.caption!.width(withConstrainedHeight: (self.field?.labelHeight)!, font: (self.field?.style?.font)!))! if (width < 50.0 + border + (margin * 2)) { width = 50.0 + border + (margin * 2) } let resized:UIImage = (self.field!.input! as! UIImage).resize(width: Double(self.field!.width - ((margin * 4) + width + self.field!.requiredWidth)))! self.button!.frame = CGRect(x: self.frame.width - (resized.size.width + (margin * 2) + self.field!.requiredWidth), y: margin, width: resized.size.width, height: resized.size.height) if (self.clearButton != nil) { self.clearButton!.frame = CGRect(x: margin, y: (margin + resized.size.height) - 50.0, //self.frame.height - (50.0 + border + margin), width: 50.0, height: 50.0) } } else { self.button!.frame = CGRect(x: self.frame.width - (60.0 + (margin * 2) + self.field!.requiredWidth), y: margin, width: 60.0, height: 50.0) } self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2.0) - (self.field!.requiredHeight / 2.0), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.Vertical: break case FBOrientation.ReverseHorizontal: break case FBOrientation.ReverseVertical: break case FBOrientation.PlaceHolder: break } } open func updateDisplay(label:String, image:UIImage?) { let bundle = Bundle.init(for: self.classForCoder) let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 self.label = UILabel() self.label?.numberOfLines = 0 self.label?.lineBreakMode = NSLineBreakMode.byWordWrapping self.addSubview(self.label!) self.label?.font = UIFont(name: self.field?.style!.value(forKey: "font-family") as! String, size: self.field?.style!.value(forKey: "font-size") as! CGFloat) self.label?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "foreground-color") as! String) self.label?.sizeToFit() if (image != nil) { self.field!.input = image! } self.label?.text = label self.button = UIButton() if (image != nil) { let width:CGFloat = (self.field?.caption!.width(withConstrainedHeight: (self.field?.labelHeight)!, font: (self.field?.style?.font)!))! let resized:UIImage = image!.resize(width: Double(self.field!.width - ((margin * 4) + width + self.field!.requiredWidth)))! self.button?.setImage(resized, for: UIControlState.normal) if (self.field!.editing) { self.clearButton = UIButton() self.clearButton?.addTarget(self, action: #selector(clearPressed), for: UIControlEvents.touchUpInside) self.clearButton?.setImage(UIImage.init(named: "trash", in: bundle, compatibleWith: nil), for: UIControlState.normal) self.addSubview(self.clearButton!) } } else { self.button?.setImage(UIImage.init(named: "camera", in: bundle, compatibleWith: nil), for: UIControlState.normal) } self.button?.addTarget(self, action: #selector(buttonPressed), for: UIControlEvents.touchUpInside) self.addSubview(self.button!) if (self.field!.editing) { self.requiredView = FBRequiredView() self.addSubview(self.requiredView!) if (self.clearButton != nil) { self.clearButton?.isUserInteractionEnabled = true } self.button?.isUserInteractionEnabled = true } else { if (self.clearButton != nil) { self.clearButton?.isUserInteractionEnabled = false } self.button?.isUserInteractionEnabled = false } } @objc @IBAction func buttonPressed() { self.imagePicker = UIImagePickerController() self.imagePicker!.delegate = self if (self.field!.imagePickerMode == FBImagePickerMode.Album) { self.imagePicker!.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum } else { self.imagePicker!.sourceType = UIImagePickerControllerSourceType.camera } self.imagePicker!.allowsEditing = true UIApplication.shared.keyWindow?.rootViewController?.present(imagePicker!, animated: true, completion: nil) } @objc @IBAction func clearPressed() { self.field!.input = nil if (self.delegate != nil) { self.delegate?.fieldHeightChanged() } } open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 let width:CGFloat = (self.field?.caption!.width(withConstrainedHeight: (self.field?.labelHeight)!, font: (self.field?.style?.font)!))! self.field!.input = image.resize(width: Double(self.field!.width - ((margin * 4) + width + self.field!.requiredWidth)))! self.button?.setImage((self.field!.input! as! UIImage), for: UIControlState.normal) self.button!.frame = CGRect(x: self.button!.frame.origin.x, y: self.button!.frame.origin.y, width: image.size.width, height: image.size.height) self.field?.input = image self.setNeedsLayout() if (self.delegate != nil) { self.delegate?.fieldHeightChanged() } self.imagePicker?.dismiss(animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 let width:CGFloat = (self.field?.caption!.width(withConstrainedHeight: (self.field?.labelHeight)!, font: (self.field?.style?.font)!))! self.field!.input = image.resize(width: Double(self.field!.width - ((margin * 4) + width + self.field!.requiredWidth)))! self.button?.setImage((self.field!.input! as! UIImage), for: UIControlState.normal) self.button!.frame = CGRect(x: self.button!.frame.origin.x, y: self.button!.frame.origin.y, width: image.size.width, height: image.size.height) self.setNeedsLayout() if (self.delegate != nil) { self.delegate?.fieldHeightChanged() } } open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.imagePicker?.dismiss(animated: true, completion: nil) } } <file_sep>/FormBuilder/Classes/Form Builder Classes/FBOption.swift // // FBOption.swift // FormBuilder // // Created by <NAME> on 5/5/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public class FBOption: NSObject { public var id:String = "" var tag:String? = "#Option" var style:FBStyleClass? = nil var visible:Bool = true public var value:String = "" var field:FBField? = nil var range = (0, 0) override public init() { super.init() } public init(field:FBField?, file:FBFile, lines:(Int, Int)) { super.init() self.field = field self.range = lines var i:Int = lines.0 while (i <= lines.1) { switch (file.lines[i].keyword) { case FBKeyWord.Id: self.id = file.lines[i].value i += 1 break case FBKeyWord.Value: self.value = file.lines[i].value i += 1 break case FBKeyWord.Visible: self.visible = (file.lines[i].description.lowercased() != "false") i += 1 break case FBKeyWord.Style: self.tag = file.lines[i].description self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: self.tag!)!) if (self.field != nil) { self.style!.parent = self.field!.style // override the default parents, our styles always descend from the style of the parent object! } i += 1 break default: i += 1 break } } } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/OptionSet/FBOptionView.swift // // OptionView.swift // FormBuilder // // Created by <NAME> on 1/25/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class FBOptionView: UIView { var button:UITapGestureRecognizer? var labelButton:UITapGestureRecognizer? var selectedImage:UIImage? var normalImage:UIImage? var disabledImage:UIImage? var state:FBCheckState = FBCheckState.Unchecked var option:FBOption? // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } let scale = UIScreen.main.scale let width = 4/scale //let offset = width/2 context.setLineWidth(width) context.setStrokeColor(UIColor.darkGray.cgColor) context.setFillColor(UIColor.red.cgColor) context.beginPath() let circlePath = UIBezierPath(arcCenter: CGPoint(x: self.frame.height / 2, y: self.frame.height / 2), radius: CGFloat(self.frame.height / 2), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true) let shapeLayer = CAShapeLayer() shapeLayer.path = circlePath.cgPath //change the fill color shapeLayer.fillColor = UIColor.white.cgColor //you can change the stroke color shapeLayer.strokeColor = UIColor.darkGray.cgColor //you can change the line width shapeLayer.lineWidth = 2.5 self.layer.addSublayer(shapeLayer) if (self.state == FBCheckState.Checked) { let circlePath = UIBezierPath(arcCenter: CGPoint(x: self.frame.height / 2, y: self.frame.height / 2), radius: CGFloat(self.frame.height / 2), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true) let shapeLayer = CAShapeLayer() shapeLayer.path = circlePath.cgPath //change the fill color shapeLayer.fillColor = UIColor.darkGray.cgColor //you can change the stroke color shapeLayer.strokeColor = UIColor.darkGray.cgColor //you can change the line width shapeLayer.lineWidth = 2.5 self.layer.addSublayer(shapeLayer) } } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/Required View/FBRequiredView.swift // // RequiredView.swift // FormBuilder // // Created by <NAME> on 1/27/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class FBRequiredView: UIView { // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code guard let context = UIGraphicsGetCurrentContext() else { return } let scale = UIScreen.main.scale let width = 4/scale //let offset = width/2 context.setLineWidth(width) context.setStrokeColor(UIColor.red.cgColor) context.setFillColor(UIColor.red.cgColor) context.beginPath() let circlePath = UIBezierPath(arcCenter: CGPoint(x: self.frame.width / 2.0, y: self.frame.height / 2.0), radius: CGFloat(self.frame.height / 2.0), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true) let shapeLayer = CAShapeLayer() shapeLayer.path = circlePath.cgPath //change the fill color shapeLayer.fillColor = UIColor.red.cgColor //you can change the stroke color shapeLayer.strokeColor = UIColor.red.cgColor //you can change the line width shapeLayer.lineWidth = 1.5 self.layer.addSublayer(shapeLayer) } } <file_sep>/FormBuilder/Classes/Form Builder Classes/FBStyleClass.swift // // FBStyleClass.swift // FormBuilder // // Created by <NAME> on 2/5/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public class FBStyleClass: NSObject { @objc var parent:FBStyleClass? = nil var name:String? = nil var properties:NSDictionary? = nil override public init() { super.init() } public init(withClass: FBStyleClass) { super.init() self.name = withClass.name if (withClass.properties != nil) { self.properties = NSDictionary(dictionary: withClass.properties!) } self.parent = withClass.parent } override public func value(forKey: String) -> Any? { if (properties?.value(forKey: forKey) != nil) { return properties?.value(forKey: forKey) } else { if (parent != nil) { return parent?.value(forKey:forKey) } else { return nil } } } var font:UIFont { get { let name:String = self.value(forKey: "font-family") as? String ?? "Helvetica" let size:CGFloat = self.value(forKey: "font-size") as? CGFloat ?? 17.0 return UIFont(name: name, size: size) ?? UIFont.systemFont(ofSize: 17.0) } } var inputFont:UIFont { get { let name:String = self.value(forKey: "input-font-family") as? String ?? "Helvetica" let size:CGFloat = self.value(forKey: "input-font-size") as? CGFloat ?? 17.0 return UIFont(name: name, size: size) ?? UIFont.systemFont(ofSize: 17.0) } } var orientation:FBOrientation { get { let name:String? = self.value(forKey: "orientation") as? String if (name != nil) { switch (name!.lowercased()) { case "horizontal": return FBOrientation.Horizontal case "vertical": return FBOrientation.Vertical case "reverse-horizontal": return FBOrientation.ReverseHorizontal case "reverse-vertical": return FBOrientation.ReverseVertical case "placeholder": return FBOrientation.PlaceHolder default: return FBOrientation.Horizontal } } else { return FBOrientation.Horizontal } } } func viewFor(type:FBFieldType) -> String { switch (type) { case FBFieldType.Section: return self.value(forKey: "section-header-view") as? String ?? "FBSectionHeaderView" case FBFieldType.Heading: return self.value(forKey: "heading-view") as? String ?? "FBHeadingView" case FBFieldType.Label: return self.value(forKey: "label-view") as? String ?? "FBLabelView" case FBFieldType.Text: return self.value(forKey: "textfield-view") as? String ?? "FBTextFieldView" case FBFieldType.TextArea: return self.value(forKey: "textarea-view") as? String ?? "FBTextAreaView" case FBFieldType.ComboBox: return self.value(forKey: "combobox-view") as? String ?? "FBComboBoxFieldView" case FBFieldType.CheckBox: return self.value(forKey: "checkbox-view") as? String ?? "FBCheckBoxView" case FBFieldType.OptionSet: return self.value(forKey: "optionset-view") as? String ?? "FBOptionSetView" case FBFieldType.Image: return self.value(forKey: "image-view") as? String ?? "FBImageView" case FBFieldType.ImagePicker: return self.value(forKey: "imagepicker-view") as? String ?? "FBImagePickerView" case FBFieldType.DatePicker: return self.value(forKey: "datepicker-view") as? String ?? "FBDatePickerView" case FBFieldType.Signature: return self.value(forKey: "signature-view") as? String ?? "FBSignatureView" case FBFieldType.Unknown: return "" } } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/Image/FBImageView.swift // // ImageView.swift // FormBuilder // // Created by <NAME> on 1/30/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBImageView: FBFieldView { @IBOutlet var label:UILabel? @IBOutlet var imageView:UIImageView? var image:UIImage? var field:FBImageField? override func height() -> CGFloat { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 let border:CGFloat = self.field?.style?.value(forKey: "border") as? CGFloat ?? 1.5 return self.field!.labelHeight + (self.imageView?.image?.size.height ?? 20.0) + (margin * 3) + border } override open func layoutSubviews() { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 self.label?.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2), height: self.field!.labelHeight) self.imageView?.frame = CGRect(x: margin, y: (margin * 2) + self.field!.labelHeight, width: self.image!.size.width, height: self.image!.size.height) } open func updateDisplay(label:String, image:UIImage) { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 self.label = UILabel() self.addSubview(self.label!) self.label?.font = UIFont(name: self.field?.style!.value(forKey: "font-family") as! String, size: self.field?.style!.value(forKey: "font-size") as! CGFloat) self.label?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "foreground-color") as! String) self.label?.sizeToFit() self.imageView = UIImageView() self.image = image.resize(width: Double(self.field!.width - (margin * 2))) self.imageView?.image = self.image self.addSubview(self.imageView!) self.label?.text = label } } <file_sep>/FormBuilder/Classes/Form Builder Classes/FBForm.swift // // UIForm.swift // FormBuilder // // Created by <NAME> on 1/16/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public enum FBFormMode:Int { case View = 0 case Edit = 1 case Print = 2 } public enum FBOrientation:Int { case Horizontal = 0 case Vertical = 1 case ReverseHorizontal = 2 case ReverseVertical = 3 case PlaceHolder = 4 } public protocol FormDelegate: class { func formLoaded() func updated(field:FBField, withValue:Any?) } public class FBForm: NSObject { // UIForm -- this represents the entire form, it holds sections of fields, it has data // and methods to be used by the user interface to facilitate displaying data, // data entry, validation of data, etc. var tag:String? = "#Form" var style:FBStyleClass? = nil public var sections:Array<FBSection> = Array<FBSection>() var mode:FBFormMode = FBFormMode.View var width:CGFloat = 0.0 var file:FBFile? = nil var tableView:UITableView? private var _editable:Bool? var editable:Bool? { get { // this form is ONLY editable if none of its parents are explicitly set as NOT editable. if ((_editable == nil) || (_editable == true)) { return true } return false } set(newValue) { _editable = newValue } } weak var delegate:FormDelegate? public init(file:String, delegate:FormDelegate) { super.init() self.delegate = delegate self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: self.tag!)!) self.style!.parent = FBStyleSet.shared.style(named: "#App") // override the default parents, our styles always descend from the style of the parent object! self.file = FBFile(file: file) var i:Int = 0 while (i < self.file!.lines.count) { switch (self.file!.lines[i].keyword) { case FBKeyWord.Style: //self.tag = self.file!.lines[i].value self.style = FBStyleClass(withClass:FBStyleSet.shared.style(named: self.file!.lines[i].value)!) i += 1 break case FBKeyWord.Editable: self.editable = (self.file!.lines[i].value.lowercased() != "false") i += 1 break case FBKeyWord.Section: let indentLevel:Int = self.file!.lines[i].indentLevel let spaceLevel:Int = self.file!.lines[i].spaceLevel i += 1 var range = (i, i) while ((i < self.file!.lines.count) && ((self.file!.lines[i].indentLevel > indentLevel) || (self.file!.lines[i].spaceLevel > spaceLevel) || (self.file!.lines[i].keyword == FBKeyWord.None))) { i += 1 } range.1 = i - 1 self.sections.append(FBSection(form: self, lines: range)) break default: i += 1 break } } } func validate() -> Array<FBException> { // loop through all of the fields in the form and validate each one. // return all of the exceptions found during validation. var exceptions:Array<FBException> = Array<FBException>() for section in self.visibleSections() { for line in section.visibleLines() { for field in line.visibleFields() { let exception:FBException = field.validate() if (exception.errors.count > 0) { exceptions.append(exception) } } } } return exceptions } func save() { for field in self.fields() { field.data = field.input } } public func line(section:String, name:String) -> FBLine { return (self.section(named: section)?.line(named: name))! } public func section(named:String) -> FBSection? { for section in self.sections { if (section.id.lowercased() == named.lowercased()) { return section } } return nil } public func line(withPath:String) -> FBLine? { var section:FBSection? = nil var path:Array<String> = withPath.components(separatedBy: ".") if (path.count > 0) { section = self.section(named: path[0]) } if ((section != nil) && (path.count > 1)) { return section?.line(named: path[1]) } return nil } public func field(withPath:String) -> FBField? { var section:FBSection? = nil var line:FBLine? = nil var path:Array<String> = withPath.components(separatedBy: ".") if (path.count > 0) { section = self.section(named: path[0]) } if ((section != nil) && (path.count > 1)) { line = section?.line(named: path[1]) } if (line != nil) { if (line?.fields.count == 1) { return line?.fields[0] } else { if (path.count > 2) { return line?.field(named: path[2]) } } } return nil } func visibleSections() -> Array<FBSection> { var visible:Array<FBSection> = Array<FBSection>() for section in self.sections { if (section.visible == true) { visible.append(section) } } return visible } func fieldCount() -> Int { var count:Int = 0 for section in self.visibleSections() { count += section.lineCount() } return count } public func fields() -> Array<FBField> { var fields:Array<FBField> = Array<FBField>() for section:FBSection in self.sections { for line:FBLine in section.lines! { for field:FBField in line.fields { fields.append(field) } } } return fields } } <file_sep>/FormBuilder/Classes/Form Builder UI/Form/FormLineTableViewCell.swift // // FormLineTableViewCell.swift // FormBuilder // // Created by <NAME> on 1/17/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit protocol FormLineDelegate: class { func fieldValueChanged(field: FBField, value: Any?) func lineHeightChanged(line: FBLine) } class FormLineTableViewCell: UITableViewCell, FBFieldViewDelegate { var line:FBLine? weak var delegate:FormLineDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func layoutSubviews() { super.layoutSubviews() self.setupFields() } func setupFields() { for field in self.contentView.subviews { field.removeFromSuperview() } var fieldCount:CGFloat = CGFloat(self.line!.visibleFields().count) if (fieldCount < 1.0) { fieldCount = 1.0 } let width:CGFloat = self.contentView.frame.width / fieldCount var left:CGFloat = 0.0 for field in (self.line?.visibleFields())! { let border:CGFloat = field.style?.value(forKey: "border") as? CGFloat ?? 1.5 var backgroundColor:UIColor = UIColor.init(hexString: field.style?.value(forKey: "background-color") as! String)! if ((field.style?.value(forKey: "alternate-colors") as? String)?.lowercased() == "true") { backgroundColor = field.line!.section!.colorFor(line: field.line!) } let borderColor:UIColor = UIColor.init(hexString: field.style?.value(forKey: "border-color") as! String)! var leftOffset:CGFloat = 0.0; var rightOffset:CGFloat = 0.0; if ((field == self.line?.visibleFields().first) && (field == self.line?.visibleFields().last)) { leftOffset = border rightOffset = border } else if (field == self.line?.visibleFields().first) { leftOffset = border if (border > 0) { rightOffset = border / 2 } } else if (field == self.line?.visibleFields().last) { if (border > 0) { leftOffset = border / 2 } rightOffset = border } else { if (border > 0) { leftOffset = border / 2 rightOffset = border / 2 } } switch (field.fieldType) { case FBFieldType.Section: break case FBFieldType.Heading: // header field let headingView:FBHeadingView = UIView.fromNib(withName: field.style!.viewFor(type: field.fieldType))! field.view = headingView as FBFieldView let cellFrame:CGRect = CGRect(x: left + leftOffset, y: self.contentView.frame.origin.y, width: width - (leftOffset + rightOffset), height: self.contentView.frame.size.height - border) headingView.frame = cellFrame left += width headingView.field = field as? FBHeadingField headingView.updateDisplay(label: field.caption!) headingView.backgroundColor = backgroundColor self.contentView.backgroundColor = borderColor self.contentView.addSubview(headingView) break case FBFieldType.Label: // label field let labelView:FBLabelView = UIView.fromNib(withName: field.style!.viewFor(type: field.fieldType))! field.view = labelView as FBFieldView let cellFrame:CGRect = CGRect(x: left + leftOffset, y: self.contentView.frame.origin.y, width: width - (leftOffset + rightOffset), height: self.contentView.frame.size.height - border) labelView.frame = cellFrame left += width labelView.field = field as? FBLabelField labelView.updateDisplay(label: field.caption!) labelView.backgroundColor = backgroundColor self.contentView.backgroundColor = borderColor self.contentView.addSubview(labelView) break case FBFieldType.Image: // image field let imageView:FBImageView = UIView.fromNib(withName: field.style!.viewFor(type: field.fieldType))! field.view = imageView as FBFieldView let cellFrame:CGRect = CGRect(x: left + leftOffset, y: self.contentView.frame.origin.y, width: width - (leftOffset + rightOffset), height: self.contentView.frame.size.height - border) imageView.frame = cellFrame left += width imageView.field = field as? FBImageField imageView.updateDisplay(label: field.caption!, image:UIImage(named:"welcome")!) imageView.backgroundColor = backgroundColor self.contentView.backgroundColor = borderColor self.contentView.addSubview(imageView) break case FBFieldType.ImagePicker: // image picker field // image field let imagePickerView:FBImagePickerView = UIView.fromNib(withName: field.style!.viewFor(type: field.fieldType))! field.view = imagePickerView as FBFieldView let cellFrame:CGRect = CGRect(x: left + leftOffset, y: self.contentView.frame.origin.y, width: width - (leftOffset + rightOffset), height: self.contentView.frame.size.height - border) imagePickerView.frame = cellFrame left += width imagePickerView.field = field as? FBImagePickerField if (field.editing) { if (field.hasInput) { imagePickerView.updateDisplay(label: field.caption!, image: field.input as? UIImage) } else { imagePickerView.updateDisplay(label: field.caption!, image: nil) } } else { imagePickerView.updateDisplay(label: field.caption!, image: field.data as? UIImage) } //imageView.updateDisplay(label: field.caption!, image:UIImage(named:"welcome")!) imagePickerView.backgroundColor = backgroundColor self.contentView.backgroundColor = borderColor imagePickerView.delegate = self if (field.input != nil) { //let margin:CGFloat = field.style!.value(forKey: "margin") as? CGFloat ?? 5.0 //let width:CGFloat = field.caption!.width(withConstrainedHeight: (field.labelHeight), font: field.style!.font) //imagePickerView.image = (field.data as! UIImage).resize(width: Double(self.field!.width - ((margin * 3) + width))) //imagePickerView.image = field.input as? UIImage } self.contentView.addSubview(imagePickerView) break case FBFieldType.Text: // text input field let textFieldView:FBTextFieldView = UIView.fromNib(withName: field.style!.viewFor(type: field.fieldType))! field.view = textFieldView as FBFieldView let cellFrame:CGRect = CGRect(x: left + leftOffset, y: self.contentView.frame.origin.y, width: width - (leftOffset + rightOffset), height: self.contentView.frame.size.height - border) textFieldView.frame = cellFrame left += width textFieldView.field = field as? FBTextField if (field.editing) { textFieldView.updateDisplay(label: field.caption!, text: field.input as? String ?? "", required: field.required) } else { textFieldView.updateDisplay(label: field.caption!, text: field.data as? String ?? "", required: field.required) } textFieldView.backgroundColor = backgroundColor self.contentView.backgroundColor = borderColor self.contentView.addSubview(textFieldView) break case FBFieldType.TextArea: // text input area let textAreaView:FBTextAreaView = UIView.fromNib(withName: field.style!.viewFor(type: field.fieldType))! field.view = textAreaView as FBFieldView let cellFrame:CGRect = CGRect(x: left + leftOffset, y: self.contentView.frame.origin.y, width: width - (leftOffset + rightOffset), height: self.contentView.frame.size.height - border) textAreaView.frame = cellFrame left += width textAreaView.field = field as? FBTextAreaField textAreaView.delegate = self var text:String = "" if (field.editing) { text = field.input as? String ?? "" } else { text = field.data as? String ?? "" } textAreaView.updateDisplay(label: field.caption!, text: text, required: field.required) textAreaView.backgroundColor = backgroundColor self.contentView.backgroundColor = borderColor self.contentView.addSubview(textAreaView) break case FBFieldType.ComboBox: // combo box for selecting among predefined options let comboboxFieldView:FBComboBoxFieldView = UIView.fromNib(withName: field.style!.viewFor(type: field.fieldType))! field.view = comboboxFieldView as FBFieldView let cellFrame:CGRect = CGRect(x: left + leftOffset, y: self.contentView.frame.origin.y, width: width - (leftOffset + rightOffset), height: self.contentView.frame.size.height - border) comboboxFieldView.frame = cellFrame left += width comboboxFieldView.field = field as? FBComboBoxField comboboxFieldView.delegate = self var data:String = "" if (field.editing) { if (field.input != nil) { var option:FBOption? option = field.optionSet?.option(named: field.input as! String) ?? nil if (option != nil) { data = option!.value } } } else { if (field.data != nil) { var option:FBOption? option = field.optionSet?.option(named: field.data as! String) ?? nil if (option != nil) { data = option!.value //(field.optionSet?.options[index!].value)! } } } comboboxFieldView.updateDisplay(label: field.caption!, text: data, required: field.required) comboboxFieldView.backgroundColor = backgroundColor self.contentView.backgroundColor = borderColor self.contentView.addSubview(comboboxFieldView) break case FBFieldType.CheckBox: // check box to turn an item on or off let checkBoxView:FBCheckBoxView = UIView.fromNib(withName: field.style!.viewFor(type: field.fieldType))! field.view = checkBoxView as FBFieldView let cellFrame:CGRect = CGRect(x: left + leftOffset, y: self.contentView.frame.origin.y, width: width - (leftOffset + rightOffset), height: self.contentView.frame.size.height - border) checkBoxView.frame = cellFrame left += width checkBoxView.field = field as? FBCheckBoxField checkBoxView.delegate = self var data:FBCheckState = FBCheckState.Unchecked if (field.editing) { if (field.input != nil) { if (field.input is FBCheckState) { data = field.input as! FBCheckState } else if (field.input is Bool) { if ((field.input as! Bool) == true) { data = FBCheckState.Checked } else { data = FBCheckState.Unchecked } } } } else { if (field.data != nil) { if (field.data is FBCheckState) { data = field.data as! FBCheckState } else if (field.data is Bool) { if ((field.data as! Bool) == true) { data = FBCheckState.Checked } else { data = FBCheckState.Unchecked } } } } checkBoxView.updateDisplay(label: field.caption!, state: data, required: field.required) checkBoxView.backgroundColor = backgroundColor self.contentView.backgroundColor = borderColor self.contentView.addSubview(checkBoxView) break case FBFieldType.OptionSet: let optionSetView:FBOptionSetView = UIView.fromNib(withName: field.style!.viewFor(type: field.fieldType))! field.view = optionSetView as FBFieldView let cellFrame:CGRect = CGRect(x: left + leftOffset, y: self.contentView.frame.origin.y, width: width - (leftOffset + rightOffset), height: self.contentView.frame.size.height - border) optionSetView.frame = cellFrame left += width optionSetView.field = field as? FBOptionSetField optionSetView.delegate = self if (field.editing) { optionSetView.updateDisplay(label: field.caption!, optionSet: field.optionSet!, id: field.input as! String?, required: field.required) } else { optionSetView.updateDisplay(label: field.caption!, optionSet: field.optionSet!, id: field.input as! String?, required: field.required) } optionSetView.backgroundColor = backgroundColor self.contentView.backgroundColor = borderColor self.contentView.addSubview(optionSetView) break case FBFieldType.Signature: let signatureView:FBSignatureView = UIView.fromNib(withName: field.style!.viewFor(type: field.fieldType))! field.view = signatureView as FBFieldView let cellFrame:CGRect = CGRect(x: left + leftOffset, y: self.contentView.frame.origin.y, width: width - (leftOffset + rightOffset), height: self.contentView.frame.size.height - border) signatureView.frame = cellFrame left += width signatureView.field = field as? FBSignatureField signatureView.delegate = self if (field.editing) { signatureView.updateDisplay(label: field.caption!, signature:field.input as? UIImage, required: field.required) } else { signatureView.updateDisplay(label: field.caption!, signature:field.data as? UIImage, required: field.required) } signatureView.backgroundColor = backgroundColor self.contentView.backgroundColor = borderColor self.contentView.addSubview(signatureView) break case FBFieldType.DatePicker: // date picker field let datePickerView:FBDatePickerView = UIView.fromNib(withName: field.style!.viewFor(type: field.fieldType))! field.view = datePickerView as FBFieldView let cellFrame:CGRect = CGRect(x: left + leftOffset, y: self.contentView.frame.origin.y, width: width - (leftOffset + rightOffset), height: self.contentView.frame.size.height - border) datePickerView.frame = cellFrame left += width datePickerView.field = field as? FBDatePickerField var text:String = "" if (field.editing) { if (field.input != nil && (field.input as? String) != "") { text = field.input as! String //dateFormatter.string(from: field.data as! Date) } } else { if (field.data != nil && (field.data as? String) != "") { text = field.data as! String //dateFormatter.string(from: field.data as! Date) } } datePickerView.updateDisplay(label: field.caption!, text: text, required: field.required) datePickerView.backgroundColor = backgroundColor self.contentView.backgroundColor = borderColor self.contentView.addSubview(datePickerView) break case .Unknown: break } } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func fieldHeightChanged() { // the height of one of our fields has changed, so notify the table to redraw this cell... self.delegate?.lineHeightChanged(line: self.line!) } } <file_sep>/FormBuilder/Classes/Form Builder Classes/FBFileLine.swift // // FBFileLine.swift // FormBuilder // // Created by <NAME> on 5/3/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public enum FBKeyWord:Int { case Unknown = 0 case None = 1 case Style = 2 case Editable = 3 case Visible = 4 case Section = 5 case Line = 6 case Field = 7 case Id = 8 case Title = 9 case Collapsible = 10 case Collapsed = 11 case AllowsAdd = 12 case AddItems = 13 case FieldType = 14 case Caption = 15 case Required = 16 case Value = 17 case Requirements = 18 case Minimum = 19 case Maximum = 20 case Format = 21 case DataType = 22 case MemberOf = 23 case OptionSet = 24 case Option = 25 case PickerMode = 26 case DateMode = 27 case Image = 28 case Label = 29 case Signature = 30 case Capitalize = 31 case Keyboard = 32 case Dialog = 33 } public class FBFileLine: NSObject { public var indentLevel:Int = 0 public var spaceLevel:Int = 0 public var keyword:FBKeyWord = FBKeyWord.None public var value:String = "" public var comment:String = "" public var continued:Bool = false public override init() { super.init() } public init(line:String) { super.init() self.load(line: line, continued: false) } public init(line:String, continued:Bool) { super.init() self.load(line: line, continued: continued) } public func load(line: String, continued:Bool) { // shortcut for comment lines if (line.trimmingCharacters(in: CharacterSet.whitespaces).hasPrefix("//")) { self.comment = line self.keyword = .None self.value = "" return } // shortcut for blank lines if (line.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty) { self.comment = "" self.keyword = .None self.value = "" return } var text = line // get indentation level var first = "" repeat { first = text.first?.description ?? "" if (first == "\t") { text.removeFirst() indentLevel += 1 } } while (first == "\t") // get space level repeat { first = text.first?.description ?? "" if (first == " ") { text.removeFirst() spaceLevel += 1 } } while (first == " ") // get the keyword for this line var tokens = text.split(separator: " ") if (!continued && (tokens.count > 0)) { switch (tokens.first?.lowercased()) { case "style": self.keyword = FBKeyWord.Style break case "editable": self.keyword = FBKeyWord.Editable break case "visible": self.keyword = FBKeyWord.Visible break case "section": self.keyword = FBKeyWord.Section break case "line": self.keyword = FBKeyWord.Line break case "field": self.keyword = FBKeyWord.Field break case "id": self.keyword = FBKeyWord.Id break case "title": self.keyword = FBKeyWord.Title break case "collapsible": self.keyword = FBKeyWord.Collapsible break case "collapsed": self.keyword = FBKeyWord.Collapsed break case "allows-add": self.keyword = FBKeyWord.AllowsAdd break case "add-items": self.keyword = FBKeyWord.AddItems break case "type": self.keyword = FBKeyWord.FieldType break case "caption": self.keyword = FBKeyWord.Caption break case "required": self.keyword = FBKeyWord.Required break case "value": self.keyword = FBKeyWord.Value break case "requirements": self.keyword = FBKeyWord.Requirements break case "minimum": self.keyword = FBKeyWord.Minimum break case "maximum": self.keyword = FBKeyWord.Maximum break case "format": self.keyword = FBKeyWord.Format break case "data-type": self.keyword = FBKeyWord.DataType break case "member-of": self.keyword = FBKeyWord.MemberOf break case "option-set": self.keyword = FBKeyWord.OptionSet break case "option": self.keyword = FBKeyWord.Option break case "picker-mode": self.keyword = FBKeyWord.PickerMode break case "date-mode": self.keyword = FBKeyWord.DateMode break case "image": self.keyword = FBKeyWord.Image break case "label": self.keyword = FBKeyWord.Label break case "signature": self.keyword = FBKeyWord.Signature break case "capitalize": self.keyword = FBKeyWord.Capitalize break case "keyboard": self.keyword = FBKeyWord.Keyboard break case "dialog": self.keyword = FBKeyWord.Dialog break default: self.keyword = FBKeyWord.Unknown break } tokens.removeFirst() } var inComment:Bool = false while (tokens.count > 0) { if (tokens.first?.hasPrefix("//") == true) { inComment = true self.comment = self.comment + (tokens.first?.description)! tokens.removeFirst() } else if ((tokens.first?.description == "_") && !inComment) { self.continued = true tokens.removeAll() } else if (inComment) { self.comment = self.comment + (tokens.first?.description)! tokens.removeFirst() if (tokens.count > 0) { self.comment = self.comment + " " } } else { self.value = self.value + (tokens.first?.description.trimmingCharacters(in: CharacterSet.whitespaces))! tokens.removeFirst() if (tokens.count > 0) { self.value = self.value + " " } } } self.value = self.value.trimmingCharacters(in: CharacterSet.whitespaces) } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/Signature/SwiftSignatureView.swift // // SwiftSignatureView.swift // SwiftSignatureView // // Created by <NAME> on 6/23/15. // // SwiftSignatureView is available under the MIT license. See the LICENSE file for more info. import UIKit public protocol SwiftSignatureViewDelegate: class { func swiftSignatureViewDidTapInside(_ view: SwiftSignatureView) func swiftSignatureViewDidPanInside(_ view: SwiftSignatureView) } /// A lightweight, fast and customizable option for capturing fluid, variable-stroke-width signatures within your app. open class SwiftSignatureView: UIView { // MARK: Public Properties open weak var delegate: SwiftSignatureViewDelegate? /** The maximum stroke width. */ @IBInspectable open var maximumStrokeWidth:CGFloat = 4 { didSet { if(maximumStrokeWidth < minimumStrokeWidth || maximumStrokeWidth <= 0) { maximumStrokeWidth = oldValue } } } /** The minimum stroke width. */ @IBInspectable open var minimumStrokeWidth:CGFloat = 1 { didSet { if(minimumStrokeWidth > maximumStrokeWidth || minimumStrokeWidth <= 0) { minimumStrokeWidth = oldValue } } } /** The stroke color. */ @IBInspectable open var strokeColor:UIColor = UIColor.black /** The stroke alpha. Prefer higher values to prevent stroke segments from showing through. */ @IBInspectable open var strokeAlpha:CGFloat = 1.0 { didSet { if(strokeAlpha <= 0.0 || strokeAlpha > 1.0) { strokeAlpha = oldValue } } } /** The UIImage representation of the signature. Read only. */ open var signature:UIImage? // MARK: Public Methods open func clear() { signature = nil self.setNeedsDisplay() } // MARK: Private Methods fileprivate var previousPoint = CGPoint.zero fileprivate var previousEndPoint = CGPoint.zero fileprivate var previousWidth:CGFloat = 0.0 public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override public init(frame: CGRect) { super.init(frame: frame) initialize() } fileprivate func initialize() { let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SwiftSignatureView.tap(_:))) self.addGestureRecognizer(tap) let pan:UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(SwiftSignatureView.pan(_:))) pan.minimumNumberOfTouches = 1 pan.maximumNumberOfTouches = 1 self.addGestureRecognizer(pan) } @objc func tap(_ tap:UITapGestureRecognizer) { let rect = self.bounds UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale) if(signature == nil) { signature = UIGraphicsGetImageFromCurrentImageContext() } signature?.draw(in: rect) let currentPoint = tap.location(in: self) drawPointAt(currentPoint, pointSize: 5.0) signature = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.setNeedsDisplay() self.delegate?.swiftSignatureViewDidTapInside(self) } @objc func pan(_ pan:UIPanGestureRecognizer) { switch(pan.state) { case .began: previousPoint = pan.location(in: self) previousEndPoint = previousPoint case .changed: let currentPoint = pan.location(in: self) let strokeLength = distance(previousPoint, pt2: currentPoint) if(strokeLength >= 1.0) { let rect = self.bounds UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale) if(signature == nil) { signature = UIGraphicsGetImageFromCurrentImageContext() } // Draw the prior signature signature?.draw(in: rect) let delta:CGFloat = 0.5 let strokeScale:CGFloat = 50 // fudge factor based on empirical tests let currentWidth = max(minimumStrokeWidth,min(maximumStrokeWidth, 1/strokeLength*strokeScale*delta + previousWidth*(1-delta))) let midPoint = CGPointMid(p0:currentPoint, p1:previousPoint) drawQuadCurve(previousEndPoint, control: previousPoint, end: midPoint, startWidth:previousWidth, endWidth: currentWidth) signature = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() previousPoint = currentPoint previousEndPoint = midPoint previousWidth = currentWidth self.setNeedsDisplay() } default: break } self.delegate?.swiftSignatureViewDidPanInside(self) } fileprivate func distance(_ pt1:CGPoint, pt2:CGPoint) -> CGFloat { return sqrt((pt1.x - pt2.x)*(pt1.x - pt2.x) + (pt1.y - pt2.y)*(pt1.y - pt2.y)) } fileprivate func CGPointMid(p0:CGPoint, p1:CGPoint)->CGPoint { return CGPoint(x: (p0.x+p1.x)/2.0, y: (p0.y+p1.y)/2.0) } override open func draw(_ rect: CGRect) { signature?.draw(in: rect) } fileprivate func getOffsetPoints(p0:CGPoint, p1:CGPoint, width:CGFloat) -> (p0:CGPoint, p1:CGPoint) { let pi_by_2:CGFloat = 3.14/2 let delta = width/2.0 let v0 = p1.x - p0.x let v1 = p1.y - p0.y let divisor = sqrt(v0*v0 + v1*v1) let u0 = v0/divisor let u1 = v1/divisor // rotate vector let ru0 = cos(pi_by_2)*u0 - sin(pi_by_2)*u1 let ru1 = sin(pi_by_2)*u0 + cos(pi_by_2)*u1 // scale the vector let du0 = delta * ru0 let du1 = delta * ru1 return (CGPoint(x: p0.x+du0, y: p0.y+du1),CGPoint(x: p0.x-du0, y: p0.y-du1)) } fileprivate func drawQuadCurve(_ start:CGPoint, control:CGPoint, end:CGPoint, startWidth:CGFloat, endWidth:CGFloat) { if(start != control) { let path = UIBezierPath() let controlWidth = (startWidth+endWidth)/2.0 let startOffsets = getOffsetPoints(p0: start, p1: control, width: startWidth) let controlOffsets = getOffsetPoints(p0: control, p1: start, width: controlWidth) let endOffsets = getOffsetPoints(p0: end, p1: control, width: endWidth) path.move(to: startOffsets.p0) path.addQuadCurve(to: endOffsets.p1, controlPoint: controlOffsets.p1) path.addLine(to: endOffsets.p0) path.addQuadCurve(to: startOffsets.p1, controlPoint: controlOffsets.p0) path.addLine(to: startOffsets.p1) let signatureColor = strokeColor.withAlphaComponent(strokeAlpha) signatureColor.setFill() signatureColor.setStroke() path.lineWidth = 1 path.lineJoinStyle = CGLineJoin.round path.lineCapStyle = CGLineCap.round path.stroke() path.fill() } } fileprivate func drawPointAt(_ point:CGPoint, pointSize:CGFloat = 1.0) { let path = UIBezierPath() let signatureColor = strokeColor.withAlphaComponent(strokeAlpha) signatureColor.setStroke() path.lineWidth = pointSize path.lineCapStyle = CGLineCap.round path.move(to: point) path.addLine(to: point) path.stroke() } } <file_sep>/FormBuilder/Classes/Extensions/UIImage+width.swift // // UIImage+width.swift // FormBuilder // // Created by <NAME> on 1/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit extension UIImage { func imageResize (sizeChange:CGSize)-> UIImage { let hasAlpha = true let scale: CGFloat = 0.0 // Use scale factor of main screen UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale) self.draw(in: CGRect(origin: CGPoint.zero, size: sizeChange)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() return scaledImage! } } import UIKit extension UIImage { func resize(width : Double)-> UIImage? { let actualHeight = Double(size.height) let actualWidth = Double(size.width) var maxWidth = 0.0 var maxHeight = 0.0 maxWidth = width let per = (100.0 * width / actualWidth) maxHeight = (actualHeight * per) / 100.0 let hasAlpha = true let scale: CGFloat = 0.0 UIGraphicsBeginImageContextWithOptions(CGSize(width: maxWidth, height: maxHeight), !hasAlpha, scale) self.draw(in: CGRect(origin: .zero, size: CGSize(width: maxWidth, height: maxHeight))) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() return scaledImage } } <file_sep>/FormBuilder/Classes/Form Builder UI/Field Views/Text/FBTextFieldView.swift // // TextFieldView.swift // FormBuilder // // Created by <NAME> on 1/17/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit open class FBTextFieldView: FBFieldView, UITextFieldDelegate { @IBOutlet var label:UILabel? @IBOutlet var textField:UITextField? @IBOutlet var requiredView:FBRequiredView? var field:FBTextField? var maxLength:Int = 0 override func height() -> CGFloat { let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 let border:CGFloat = self.field?.style?.value(forKey: "border") as? CGFloat ?? 1.5 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: return (margin * 2) + self.field!.labelHeight + border case FBOrientation.Vertical: return (margin * 3) + self.field!.labelHeight + self.field!.textHeight + border case FBOrientation.ReverseHorizontal: return (margin * 2) + self.field!.labelHeight + border case FBOrientation.ReverseVertical: return (margin * 3) + field!.labelHeight + field!.textHeight + border case FBOrientation.PlaceHolder: return (margin * 2) + self.field!.labelHeight + border } } override open func layoutSubviews() { let labelWidth:CGFloat = (self.label!.text?.width(withConstrainedHeight: self.frame.height, font: self.label!.font))! let margin:CGFloat = self.field?.style?.value(forKey: "margin") as? CGFloat ?? 5.0 switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: self.label?.frame = CGRect(x: margin, y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: labelWidth, height: self.field!.labelHeight) let textX:CGFloat = (self.label?.frame.origin.x)! + labelWidth + margin let textY:CGFloat = (self.frame.height / 2) - (self.field!.textHeight / 2) self.textField?.frame = CGRect(x: textX, y: textY, width: self.frame.width - (textX + (margin * 2) + self.field!.requiredWidth), height: self.field!.textHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.Vertical: self.label?.frame = CGRect(x: margin, y: margin, width: self.frame.width - (margin * 2), height: self.field!.labelHeight) self.textField?.frame = CGRect(x: margin, y: self.field!.labelHeight + (margin * 2), width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.textHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.textField?.frame.origin.y)! + ((self.textField?.frame.height)! / 2.0) - (self.field!.requiredHeight / 2.0), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.ReverseHorizontal: self.textField?.frame = CGRect(x: margin, y: (self.frame.height / 2) - (self.field!.textHeight / 2), width: self.frame.width - (labelWidth + (margin * 4) + self.field!.requiredWidth), height: self.field!.textHeight) self.label?.frame = CGRect(x: self.textField!.frame.width + (margin * 2), y: (self.frame.height / 2) - (self.field!.labelHeight / 2), width: labelWidth, height: self.field!.labelHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.ReverseVertical: self.textField?.frame = CGRect(x: margin, y: margin, width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.textHeight) self.label?.frame = CGRect(x: margin, y: (margin * 2) + self.field!.textHeight, width: self.frame.width - (margin * 2), height: self.field!.textHeight) self.requiredView?.frame = CGRect(x: self.frame.width - (self.field!.requiredWidth + margin), y: (self.textField?.frame.origin.y)! + ((self.textField?.frame.height)! / 2.0) - (self.field!.requiredHeight / 2.0), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break case FBOrientation.PlaceHolder: self.label?.isHidden = true self.textField?.frame = CGRect(x: margin, y: (self.frame.height / 2) - (self.field!.textHeight / 2), width: self.frame.width - ((margin * 3) + self.field!.requiredWidth), height: self.field!.textHeight) self.textField?.placeholder = self.label?.text self.requiredView?.frame = CGRect(x: self.frame.width - (margin + self.field!.requiredWidth), y: (self.frame.height / 2) - (self.field!.requiredHeight / 2), width: self.field!.requiredWidth, height: self.field!.requiredHeight) break } } @objc @IBAction func textChanged() { if (self.maxLength > 0) { if (self.textField!.text!.count > self.maxLength) { self.textField!.deleteBackward() return } } self.field?.input = self.textField?.text } open func textFieldDidEndEditing(_ textField: UITextField) { } open func updateDisplay(label:String, text:String, required:Bool) { self.label = UILabel() self.label?.numberOfLines = 0 self.addSubview(self.label!) self.label?.font = UIFont(name: self.field?.style!.value(forKey: "font-family") as! String, size: self.field?.style!.value(forKey: "font-size") as! CGFloat) self.label?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "foreground-color") as! String) self.label?.text = label self.label?.sizeToFit() self.textField = UITextField() self.textField?.keyboardType = self.field?.keyboard ?? .default self.textField?.autocapitalizationType = self.field?.capitalize ?? .words self.textField?.delegate = self self.textField?.addTarget(self, action: #selector(textChanged), for: UIControlEvents.editingChanged) self.addSubview(self.textField!) self.textField?.font = UIFont(name: self.field?.style!.value(forKey: "input-font-family") as! String, size: self.field?.style!.value(forKey: "input-font-size") as! CGFloat) self.textField?.textColor = UIColor.init(hexString: self.field?.style!.value(forKey: "input-foreground-color") as! String) self.textField?.text = text self.textField?.sizeToFit() self.requiredView = FBRequiredView() self.addSubview(self.requiredView!) if (self.field!.editing) { // set this field to edit mode self.textField?.borderStyle = UITextBorderStyle.bezel self.textField?.isUserInteractionEnabled = true self.requiredView?.isHidden = !required switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: self.textField?.textAlignment = NSTextAlignment.left break case FBOrientation.Vertical: self.textField?.textAlignment = NSTextAlignment.left break case FBOrientation.ReverseHorizontal: self.textField?.textAlignment = NSTextAlignment.left break case FBOrientation.ReverseVertical: self.textField?.textAlignment = NSTextAlignment.left break case FBOrientation.PlaceHolder: self.textField?.textAlignment = NSTextAlignment.left break } } else { // set this field to view mode self.textField?.borderStyle = UITextBorderStyle.none self.textField?.isUserInteractionEnabled = false self.requiredView?.isHidden = true switch (self.field!.style!.orientation) { case FBOrientation.Horizontal: self.textField?.textAlignment = NSTextAlignment.right break case FBOrientation.Vertical: self.textField?.textAlignment = NSTextAlignment.left break case FBOrientation.ReverseHorizontal: self.textField?.textAlignment = NSTextAlignment.left break case FBOrientation.ReverseVertical: self.textField?.textAlignment = NSTextAlignment.left break case FBOrientation.PlaceHolder: self.textField?.textAlignment = NSTextAlignment.left break } } for requirement in self.field!.requirements! { switch (requirement.type) { case FBRequirementType.Maximum: let max:Int = requirement.value as! Int self.maxLength = max break default: break } } } }
9eca81c45207466a3a21e0e5c02e11f2d3323994
[ "Swift", "Ruby" ]
58
Swift
n8glenn/FormBuilder
8abf5c5c0feb06e034a7eab1d4f30f770b16c81a
bcfa7660600ceecdd55c3e1f3c86b15c30eae320
refs/heads/master
<file_sep># DOACCalculator - DOAC計算プログラム - Visual Studio 2019 で作成 - 使い方 - 起動し、身長・体重・年齢・性別・血中クレアチニン値(mg/dl) を入力 - 計算ボタンを押すだけ [Binary Download](https://github.com/vascarpenter/DOACCalculatorVS/releases)<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace DOACCalculator { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { double height = double.Parse(bodyHeightField.Text); double weight = double.Parse(bodyWeightField.Text); double age = double.Parse(ageField.Text); double crea = double.Parse(sCrField.Text); double egfr = 194 * Math.Pow(age, -0.287) * Math.Pow(crea, -1.094); double bsa = 0.007184 * Math.Pow(weight, 0.425) * Math.Pow(height, 0.725); if(femaleRadioButton.IsChecked==true) egfr *= 0.739; double gfr = egfr * bsa; CcrField.Content = $"{gfr:0.0}"; BSAField.Content = $"{bsa:0.0}"; eGFRField.Content = $"{egfr:0.0}"; string stage = ""; if (egfr >= 90) stage = "正常"; else if (egfr >= 60) stage = "軽度腎障害"; else if (egfr >= 30) stage = "中等度腎障害"; else if (egfr >= 15) stage = "高度腎障害"; else stage = "末期腎不全"; renalStageField.Content = stage; // プラザキサ if (gfr >= 50 && age < 70) stage = "75mg 4C / 2xMA"; else if (gfr >= 30 || age >= 70) stage = "110mg 2C / 2xMA"; else stage = "非推奨"; prazaxaField.Content = stage; // イグザレルト if (gfr >= 50) stage = "15mg 1T / 1xM"; else if (gfr >= 30) stage = "10mg 1T / 1xM"; else if (gfr >= 15) stage = "10mg 1T / 1xM 慎重投与"; else stage = "非推奨"; xareltoField.Content = stage; // エリキュース int check = 0; if (age >= 80) check++; if (weight <= 60) check++; if (crea >= 1.5) check++; if (gfr < 15) stage = "非推奨"; else if (check >= 2) stage = "2.5mg 2T / 2xMA"; else stage = "5mg 2T / 2xMA"; eliquisField.Content = stage; // リクシアナ if (weight >= 60 && gfr >= 50) stage = "60mg 1T / 1xM"; else if (gfr >= 30) stage = "30mg 1T / 1xM"; else if (gfr >= 15) stage = "30mg 1T / 1xM 慎重投与"; else stage = "非推奨"; lixianaField.Content = stage; } } }
5f3aee78c139afb5440e5e4e0ff4318c9cf45396
[ "Markdown", "C#" ]
2
Markdown
vascarpenter/DOACCalculatorVS
4a749a0a42adcb42bbfbd075313da05cde3e83f9
7ea6baa1bcc122f9bc9d7d0d8f56c8bb9a0f5dea
refs/heads/master
<repo_name>MarcosCostaDev/snake<file_sep>/src/const/const.ts export let CONST = { SCORE: 0, HIGHSCORE: 0 };<file_sep>/README.md to play this game [click here](https://marcoscostadev.github.io/snake/)
334428a7ae52c38d7e051ea0282218e76e45c519
[ "Markdown", "TypeScript" ]
2
TypeScript
MarcosCostaDev/snake
7410bb6302bfebba31245d81cfec4e1a7151cef3
e4d4fca7258f72fc2b8e6f9579e3d8b9935c2159
refs/heads/master
<repo_name>Edii698/turtle-power-clickyGame<file_sep>/README.md # Turtle Power Clicky-Game! Teenage Ninja Turtle themed game build with **React** JS and Bootstrap 4. ## Overview TMNT clicker memory game. Click an image to gain points, but don't click on the same image twice! Every click will shuffle the images, so try to remember the characters you've clicked on. Keep playing, and try to beat your best score. Demo: [Play the Clicky Game!](https://quiet-ocean-77319.herokuapp.com/) ![page preview img](readme-img.jpg) <file_sep>/src/App.js import React, { Component } from 'react'; import Score from './components/Score'; import Characters from './components/Characters'; import Wrapper from './components/Wrapper'; import Header from './components/Header'; import characters from './characters.json'; class App extends Component { // set the state for the app state = { characters: characters, wasClicked: [], score: 0, topScore: 0, message: "Click an image to begin!" }; // shuffle array everytime an img is clicked shuffle = array => { let currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }; // function that will run everytime an img is clicked getId = (id, clicked) => { // load the score state into a variable const currentScore = this.state.score // load the top score into a variable let top = this.state.topScore // if the players current score is greater than the current top score, top will equal the current score if (currentScore > this.state.topScore) { top = currentScore; } // if img has not been clicke run the following if(clicked === "false"){ // map over characters and change the matching img id to true const clicked = this.state.characters.map(character =>{ if(character.id === id){ character.clicked = "true"; // change state of clicked on matching character id this.setState({ clicked }); const goShuffle = this.shuffle(this.state.characters) // change state to shuffle characters, update score, and message this.setState({ characters: goShuffle, score: this.state.score + 5, message: "You guessed correctly!" }); } }) }else{ // map over all characters and change clicked state back to false const rest = this.state.characters.map(character =>{ character.clicked = "false"; // rest the state this.setState({rest}); this.setState({ score: this.state.score = 0, message: "You guessed incorrectly! :(", topScore: top }); }) } console.log(this.state.characters) }; render() { return ( <div> <Score message={this.state.message} score={this.state.score} topScore={this.state.topScore} /> <Header/> <Wrapper> {this.state.characters.map(character => ( <Characters onClick={this.getId} image={character.image} name={character.name} id={character.id} key={character.id} clicked={character.clicked} /> ))} </Wrapper> </div> ); } } export default App; <file_sep>/src/components/Score/Score.js import React from "react"; import "./Score.css"; const Score = props => <nav className="navbar"> <h2 className="text-left logo">Clicky Game</h2> <h3 className="text-center message">{props.message}</h3> <h3 className="text-left score">Your Score: {props.score} | Top Score: {props.topScore}</h3> </nav> export default Score; <file_sep>/src/components/Header/Header.js import React from "react"; import "./Header.css"; const Header = props => <div className="jumbotron jumbotron-fluid appHeader"> <h1 className="text-center title">Clicky Game!!</h1> <h4 className="text-center sub">Click on an image to earn points, but don't click on an image more than once.</h4> </div>; export default Header;<file_sep>/src/components/Characters/Characters.js import React from "react"; import "./Characters.css"; const Characters = props => ( <div className="col-sm-3"> <span onClick={() => props.onClick(props.id, props.clicked)}> <img className="char-img" src={props.image} alt={props.name} name={props.name}/> </span> </div> ); export default Characters;
3f3f37201d57bc6c132c9704e2170a920295e002
[ "Markdown", "JavaScript" ]
5
Markdown
Edii698/turtle-power-clickyGame
c4e4a45d09d6d11f1753c8a475a902ec981d3335
188f0952730522eaf0a34a67b6461cea5b56551b
refs/heads/master
<file_sep><style> #staffidimg{ display:block; width:50%; height:50%; object-fit: cover; } </style> <?php /** * Template Name: Staff * Template Post Type: staff */ $fields = get_fields($post->ID); if( $fields['status'] ){ $format_staff = ' <ul> <li> <div class=""><img id="staffidimg" src="%s"><div style="background-image: url(%s)" class="site__bgimg_img"></div></div> </li> </ul> <div><center> <h3>%s</h3> %s</center> </div> '; $return_staff = sprintf( $format_staff ,$fields['image']['url'] ,$fields['image']['url'] ,$post->post_title ,$fields['full_bio'] ); } else { $return_staff = ''; } $return = ' <section class="mod__featured_grid"><center> <div class="container"> <div class="site__grid site__fade site__fade-up"> '.$return_staff.' </div> </div></center> </section> '; get_header(); ?> <main id="single_about"> <?php echo $return; get_footer(); ?><file_sep> <style> h1{ color:<?php echo get_theme_mod( 'color_h1', '#000000' ); ?>; } h2{ color:<?php echo get_theme_mod( 'color_h2', '#000000' ); ?>; } h3{ color:<?php echo get_theme_mod( 'color_h3', '#000000' ); ?>; } h4{ color:<?php echo get_theme_mod( 'color_h4', '#000000' ); ?>; } h5{ color:<?php echo get_theme_mod( 'color_h5', '#000000' ); ?>; } h6{ color:<?php echo get_theme_mod( 'color_h6', '#000000' ); ?>; } body{ color:<?php echo get_theme_mod( 'color_p', '#000000' ); ?> !important; } section.block__food_menus > .container .menu_section.menu_photo_list .menu_items .menu_item > div:last-of-type > div.menu__item-price{ color:<?php echo get_theme_mod( 'color_p', '#000000' ); ?> !important; } section.block__food_menus > .container .menu_section.menu_text_sub_group_half > div .menu_items .menu_item > h3.menu__item-price > span{ color:<?php echo get_theme_mod( 'color_p', '#000000' ); ?> !important; } section.block__contact > .container ul.locations > li > div{ color:<?php echo get_theme_mod( 'color_p', '#000000' ); ?> !important; } header#opt_header_four > nav .navlinks { background-color: <?php echo get_theme_mod( 'background_setting_nav', '#FFFFFF' ); ?>; } header#opt_header_four > nav .navlinks .navlinks-item:before, header#opt_header_four > nav .navlinks .navlinks-item:after { background-color: <?php echo get_theme_mod( 'background_setting_nav', '#FFFFFF' ); ?>; } header#opt_header_five { background-color: <?php echo get_theme_mod( 'background_setting_header', '#FFFFFF' ); ?>; } header#opt_header_five > div:first-of-type { background-color: <?php echo get_theme_mod( 'background_setting_header', '#FFFFFF' ); ?>; } header#opt_header_one > div:last-of-type > nav .navlinks-item-link { color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } header#opt_header_one > div:last-of-type .site__social-media li a { color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } header#opt_header_one > div:first-of-type .site__iconlink{ color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> !important; } header#opt_header_one > div:first-of-type > div .site__iconlink-phone > div > span{ color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> !important; } header#opt_header_one > div:first-of-type > div .site__iconlink-phone > div{ color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> !important; } header#opt_header_two > div > div > nav .navlinks-item-link { color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } header#opt_header_two > div > div > a { color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } .sidebar_menu{ background-color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } header#opt_header_three > div:first-of-type > span a{ color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> !important; } header#opt_header_three > div:last-of-type .navlinks .navlinks-item .navlinks-item-link{ color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } header#opt_header_four > nav .navlinks .navlinks-item .navlinks-item-link{ color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } header#opt_header_four .inner_div > .site__iconlink-phone{ color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> !important; } header#opt_header_four .inner_div .site__social-media li a{ color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> ; } header#opt_header_five > div:first-of-type .site__iconlink-address, header#opt_header_five > div:first-of-type .site__iconlink-phone{ color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> !important; } header#opt_header_five .inner_div nav .navlinks .navlinks-item .navlinks-item-link{ color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } header#opt_header_six > div:first-of-type .site__iconlink-phone, header#opt_header_six > div:first-of-type .site__iconlink-address{ color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> !important; } header#opt_header_six > div:first-of-type .site__social-media > li > a{ color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> ; } header#opt_header_six > div:last-of-type > nav .navlinks .navlinks-item .navlinks-item-link{ color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } header#opt_header_seven > div .site__social-media > li > a{ color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> ; } header#opt_header_seven > div > .site__iconlink-phone{ color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> !important; } header#opt_header_seven > div > .site__iconlink-phone:before{ color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> !important; } header#opt_header_seven > nav:before{ border-bottom: 2px solid <?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> !important; } header#opt_header_seven > nav .navlinks-item-link { color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } header#opt_header_eight > div:first-of-type > nav .navlinks .navlinks-item .navlinks-item-link{ color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } header#opt_header_nine .inner_div > .site__iconlink, header#opt_header_nine .inner_div .site__social-media a { color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> ; } header#opt_header_nine > div:last-of-type .inner_div > nav .navlinks .navlinks-item .navlinks-item-link{ color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } header#opt_header_ten > div:first-of-type .site__social-media li a { color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> ; } .site__bars > span{ background:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> !important; } /* section.block__contact > .container ul.locations > li .site__button,header#opt_header_three > div:first-of-type > .site__button-quote{ background-color:<?php echo get_theme_mod( 'color_button', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_button_text', '#FFFFFF' ); ?> !important; border-radius: <?php echo get_theme_mod( 'section_buttons', '64' ); ?>px !important; } section.block__contact > .container ul.locations > li .site__button:hover,header#opt_header_three > div:first-of-type > .site__button-quote:hover{ background-color:<?php echo get_theme_mod( 'color_button_hover', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_button_text', '#FFFFFF' ); ?> !important; } */ section.block__blog_posts > div.container ul li > a > div.content > p.read_more{ background-color:<?php echo get_theme_mod( 'color_button', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_button_text', '#FFFFFF' ); ?> !important; } section.block__blog_posts > div.container ul li > a > div.content > p.read_more:hover{ background-color:<?php echo get_theme_mod( 'color_button_hover', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_button_text', '#FFFFFF' ); ?> !important; } section.hero .hero_foreground a.site__button{ background-color:<?php echo get_theme_mod( 'color_button', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_button_text', '#FFFFFF' ); ?> !important; } section.hero .hero_foreground a.site__button:hover{ background-color:<?php echo get_theme_mod( 'color_button_hover', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_button_text', '#FFFFFF' ); ?> !important; } section.hero .hero_foreground a.site__button{ color:<?php echo get_theme_mod( 'color_button_hero', '#FFFFFF' ); ?> !important; } section.hero .hero_foreground h1{ color:<?php echo get_theme_mod( 'color_hero', '#000000' ); ?> ; } section.block__food_menus > .container .menu_section.menu_photo_list .menu_items .menu_item > div:last-of-type > div.menu__item-description { border: 4px <?php echo get_theme_mod( 'section_divid1', 'none' );?> <?php echo get_theme_mod( 'color_divider', '#FFFFFF' ); ?> !important; } section.block__food_menus > .container .menu_section > p, section.block__food_menus > .container .menu_section.menu_text_sub_group_half > div > p{ border-bottom: 3px <?php echo get_theme_mod( 'section_divid1', 'none' );?> <?php echo get_theme_mod( 'color_divider', '#FFFFFF' ); ?> !important; } footer div.container .footer_address,footer div.container a[class^=footer_phone],footer#footer_one > div.container #footer_posts > ul > li > a,footer div.container #footer_nav .navlinks .navlinks-item-link ,footer#footer_one > div.container #footer_social .site__social-media li a i,footer#footer_two > div.container > div.site__copyright_banner > a,footer div.container .site__copyright_banner > span, footer#footer_two > div.container > div.footer_last_div > div#footer_social > h3,footer#footer_two > div.container > div.footer_last_div > div#footer_social > ul.site__social-media li a i { color:<?php echo get_theme_mod( 'color_footer', '#FFFFFF' ); ?> !important; /*border-bottom: 4px <?php echo get_theme_mod( 'section_divid1', 'none' );?> <?php echo get_theme_mod( 'color_footer', '#FFFFFF' ); ?> !important;*/ } footer#footer_one > div.container #footer_social .site__social-media li a i,footer#footer_two > div.container > div.footer_last_div > div#footer_social > ul.site__social-media li a i { box-shadow: 0px 0px 0px 3px <?php echo get_theme_mod( 'color_footer', '#FFFFFF' ); ?> !important; } footer#footer_two > div.container > #footer_company_info > div#footer_nav{ border: 4px <?php echo get_theme_mod( 'section_divid1', 'none' );?> <?php echo get_theme_mod( 'color_footer', '#FFFFFF' ); ?> !important; } footer#footer_three > div.container #footer_company_info #footer_nav { border-top: 2px <?php echo get_theme_mod( 'section_divid1', 'none' );?> <?php echo get_theme_mod( 'color_footer', '#FFFFFF' ); ?> !important; border-bottom: 2px <?php echo get_theme_mod( 'section_divid1', 'none' );?> <?php echo get_theme_mod( 'color_footer', '#FFFFFF' ); ?> !important; } section.block__locations > .container div.locations__block-form > p{ border-bottom: 3px <?php echo get_theme_mod( 'section_divid1', 'none' );?> #fff ; } ul > li.coupons__one > a, ul > li.coupons__two > a, ul > li.coupons__three > a, ul > li.coupons__four > a{ border: 4px <?php echo get_theme_mod( 'section_divid1', 'none' );?> #fff ; } section.block__blog_posts > div.container ul li > a > div.content > h5{ border-bottom: 3px <?php echo get_theme_mod( 'section_divid1', 'none' );?> #fff ; } section.block__staff > .container div.staff__one.site__grid > ul > li > a > div.staff__content > h3{ border-bottom: 3px <?php echo get_theme_mod( 'section_divid1', 'none' );?> #fff ; } section.block__contact > .container ul.locations > li > h3.area__heading{ border-bottom: 3px <?php echo get_theme_mod( 'section_divid1', 'none' );?> #fff ; } section.site__block.block__testimonials > div.container > .site__grid > ul li > div .testimonial_content > div:first-of-type{ border-bottom: 3px <?php echo get_theme_mod( 'section_divid1', 'none' );?> #fff ; } footer#footer_one > div.container h3 { color:<?php echo get_theme_mod( 'color_footer', '#FFFFFF' ); ?> !important; } footer#footer_one > div.footer_copyright > div .site__copyright_banner > span { color: <?php echo get_theme_mod( 'color_footer_copyright', '#FFFFFF' ); ?> !important; } footer div.container .site__social-media li a i{ color:<?php echo get_theme_mod( 'color_footer', '#FFFFFF' ); ?> !important; } .image2 { background-blend-mode:<?php echo get_theme_mod( 'background_setting_hero_foreground_blend3', 'normal' ); ?> ; } section.hero .hero_foreground.narrow { width: 100vw; } section.hero .hero_foreground.medium { width: 100vw; } section.hero .hero_foreground.wide { width: 100vw; } section.hero .hero_foreground.full { width: 100vw; } section.hero { overflow: hidden; position: relative; width: 100vw; max-width: -webkit-fill-available; height: 100vh; max-height: -webkit-fill-available; } .spacerdivier{ position: absolute; width: 100%; left:0px; bottom: 0px; z-index: 2; } .spacerdivier2{ position: absolute; width: 100%; top: 0px; left: 0px; z-index: 2; } .spacerdiviermenutop{ position: relative; width: 100%; top: 0px; left: 0px; } .spacerdiviermenubottom{ position: relative; width: 100%; bottom: 0px; left: 0px; } .site__button:focus, .site__button:active, .site__button:hover { box-shadow: none; } .header{ background-color: <?php echo get_theme_mod( 'background_setting_header', '#FFFFFF' ); ?>!important; color:<?php echo get_theme_mod( 'color_header', '#FFFFFF' ); ?> !important; } .nav{ background-color: <?php echo get_theme_mod( 'background_setting_nav', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_nav', '#FFFFFF' ); ?> !important; } header#opt_header_one > div:first-of-type .site__iconlink-address:before, header#opt_header_one > div:first-of-type .site__iconlink-phone:before{ border: 3px solid <?php echo get_theme_mod( 'background_setting_accent2', '#386591' ); ?> ; color: <?php echo get_theme_mod( 'background_setting_accent2', '#386591' ); ?> ; } section.site__block .container, section.page__template .container, section.single__page .container, section.page_404 .container { margin: 0 auto 0px; } section.block__staff > .container div.staff__one.site__grid > ul > li > a > div.staff__content, section.block__staff > .container div.staff__one.site__grid > ul > li > div.staff__social,section.block__staff > .container div.staff__one.site__grid > ul > li > div.staff__social > ul > li > a > i, section.site__block.block__testimonials > div.container > .site__grid > ul{ background-color: <?php echo get_theme_mod( 'color_staff', '#dedede' ); ?> ; } section.site__block.block__testimonials > div.container > .site__grid > ul:before { border: 42px solid #71b9ff00; border-top-color: #38659100; } section.site__block.block__testimonials > div.container > .site__grid.gray_triangle_after:after{ border: 60px solid transparent; } section.site__block.block__testimonials > div.container > .site__grid > ul:after{ border-top-color: <?php echo get_theme_mod( 'color_testi', '#dedede' ); ?> ; } section.site__block.block__testimonials > div.container > .site__grid > ul{ box-shadow:0px 0px 0px 3px <?php echo get_theme_mod( 'color_testi', '#dedede' ); ?> !important; } header.mobileheader{ background-color: <?php echo get_theme_mod( 'background_setting_header', '' ); ?> ; } .mobile_header_sidebar{ background-color: <?php echo get_theme_mod( 'background_setting_nav', '' ); ?> ; } header.mobileheader > div:first-of-type > a > span{ background:<?php echo get_theme_mod( 'background_setting_accent2', '#386591' ); ?> !important ; } header.mobileheader > div:first-of-type > a > span{ background:<?php echo get_theme_mod( 'background_setting_accent2', '#386591' ); ?> !important; } section.block__blog_posts > div.container ul li > a{ box-shadow: 0px 0px 0px 3px <?php echo get_theme_mod( 'color_outline', '#dedede' ); ?> ; } section.site__block.block__testimonials > div.container > .site__grid.gray_triangle_after:after{ border-top-color: <?php echo get_theme_mod( 'color_outline', '#dedede' ); ?>; } section.site__block.block__testimonials > div.container > .site__grid > ul:before { content: ""; position: absolute; bottom: 0px; left: 50%; width: 0; height: 0; border: 42px solid #dd0a0a00; border-top-color: <?php echo get_theme_mod( 'background_setting_body1', '#fff' ); ?>; border-bottom: none; margin-left: -42px; z-index: 500; margin-bottom: -42px; } footer#footer_three > div.container > div.site__copyright_banner > a{ color: <?php echo get_theme_mod( 'color_footer', '#dedede' ); ?> !important; } section.hero .hero_foreground img{ max-height: 100%; } .image2 { background-blend-mode:<?php echo get_theme_mod( 'background_setting_hero_foreground_blend3', 'normal' ); ?> ; } section.hero .hero_foreground.narrow { width: 900px; } section.hero .hero_foreground.medium { width: 70%; } section.hero .hero_foreground.wide { width: 1200px !important; } section.hero .hero_foreground.full { width: 95%; } section.hero .hero_foreground{ padding:0px; } section.block__contact > .container div.contact__block-form input[type^=submit]{ background-color:<?php echo get_theme_mod( 'color_button', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_button_text', '#FFFFFF' ); ?> !important; } section.block__contact > .container div.contact__block-form input[type^=submit]:hover{ background-color:<?php echo get_theme_mod( 'color_button_hover', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_button_text', '#FFFFFF' ); ?> !important; } /* header#opt_header_two > div .site__button-quote{ background-color:<?php echo get_theme_mod( 'color_button', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_button_text', '#FFFFFF' ); ?> !important; } header#opt_header_two > div .site__button-quote:hover{ background-color:<?php echo get_theme_mod( 'color_button_hover', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_button_text', '#FFFFFF' ); ?> !important; }*/ header.mobileheader > div:first-of-type { box-shadow: none; } section.block__food_menus > .container #tabs_style__pills > ul.button_group li.tab_active a{ background-color:<?php echo get_theme_mod( 'color_button', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_button_text', '#FFFFFF' ); ?> !important; border: none; } section.block__food_menus > .container #tabs_style__pills > ul.button_group li.tab_active a:hover{ background-color:<?php echo get_theme_mod( 'color_button_hover', '#FFFFFF' ); ?> !important; color:<?php echo get_theme_mod( 'color_button_text', '#FFFFFF' ); ?> !important; } section.site__block .container.medium .site__grid > ul > li > a, section.page__template .container.medium .site__grid > ul > li > a, section.single__page .container.medium .site__grid > ul > li > a, section.page_404 .container.medium .site__grid > ul > li > a:hover{ pointer-events: none; } @media only screen and (max-width: 900px) { section.hero .hero_foreground img { max-height: 40%; } } <?php $media= get_theme_mod( 'setting_hero_mobile_image', '' ); if($media!=''){ echo ' @media (max-width: 900px) { .image { background-image: url("'.$media.'"); } }'; }?> @media (max-width: 960px){ .custom-logo { margin-top: 15px; max-width: 100px; height: auto; object-fit: cover; } } <?php $headersize1= get_theme_mod( 'section_header_size1', '' ); if($headersize1=='narrow'){ echo ' header#opt_header_five > div:first-of-type { max-width:900px !important; } header#opt_header_five .inner_div{ max-width:900px !important; } header#opt_header_one > div:first-of-type { max-width:900px !important; } header#opt_header_one .inner_div{ max-width:900px !important; } header#opt_header_two > div:first-of-type { max-width:900px !important; } header#opt_header_two .inner_div{ max-width:900px !important; } header#opt_header_three > div:first-of-type { max-width:900px !important; } header#opt_header_three .inner_div{ max-width:900px !important; } header#opt_header_four > div:first-of-type { max-width:900px !important; } header#opt_header_four .inner_div{ max-width:900px !important; } header#opt_header_six > div:first-of-type { max-width:900px !important; } header#opt_header_six .inner_div{ max-width:900px !important; } header#opt_header_seven > div:first-of-type { max-width:900px !important; } header#opt_header_seven .inner_div{ max-width:900px !important; } header#opt_header_eight > div:first-of-type { max-width:900px !important; } header#opt_header_eight .inner_div{ max-width:900px !important; } header#opt_header_nine > div:first-of-type { max-width:900px !important; } header#opt_header_nine .inner_div{ max-width:900px !important; } header#opt_header_ten > div:first-of-type { max-width:900px !important; } header#opt_header_ten .inner_div{ max-width:900px !important; } '; } if($headersize1=='wide'){ echo ' header#opt_header_five > div:first-of-type { max-width:70% !important; } header#opt_header_five .inner_div{ max-width:70% !important; } header#opt_header_one > div:first-of-type { max-width:70% !important; } header#opt_header_one .inner_div{ max-width:70% !important; } header#opt_header_two > div:first-of-type { max-width:70% !important; } header#opt_header_two .inner_div{ max-width:70% !important; } header#opt_header_three > div:first-of-type { max-width:70% !important; } header#opt_header_three .inner_div{ max-width:70% !important; } header#opt_header_four > div:first-of-type { max-width:70% !important; } header#opt_header_four .inner_div{ max-width:70% !important; } header#opt_header_six > div:first-of-type { max-width:70% !important; } header#opt_header_six .inner_div{ max-width:70% !important; } header#opt_header_seven > div:first-of-type { max-width:70% !important; } header#opt_header_seven .inner_div{ max-width:70% !important; } header#opt_header_eight > div:first-of-type { max-width:70% !important; } header#opt_header_eight .inner_div{ max-width:70% !important; } header#opt_header_nine > div:first-of-type { max-width:70% !important; } header#opt_header_nine .inner_div{ max-width:70% !important; } header#opt_header_ten > div:first-of-type { max-width:70% !important; } header#opt_header_ten .inner_div{ max-width:70% !important; } '; } if($headersize1=='medium'){ echo ' header#opt_header_five > div:first-of-type { max-width:1200px !important; } header#opt_header_five .inner_div{ max-width:1200px !important; } header#opt_header_one > div:first-of-type { max-width:1200px !important; } header#opt_header_one .inner_div{ max-width:1200px !important; } header#opt_header_two > div:first-of-type { max-width:1200px !important; } header#opt_header_two .inner_div{ max-width:1200px !important; } header#opt_header_three > div:first-of-type { max-width:1200px !important; } header#opt_header_three .inner_div{ max-width:1200px !important; } header#opt_header_four > div:first-of-type { max-width:1200px !important; } header#opt_header_four .inner_div{ max-width:1200px !important; } header#opt_header_six > div:first-of-type { max-width:1200px !important; } header#opt_header_six .inner_div{ max-width:1200px !important; } header#opt_header_seven > div:first-of-type { max-width:1200px !important; } header#opt_header_seven .inner_div{ max-width:1200px !important; } header#opt_header_eight > div:first-of-type { max-width:1200px !important; } header#opt_header_eight .inner_div{ max-width:1200px !important; } header#opt_header_nine > div:first-of-type { max-width:1200px !important; } header#opt_header_nine .inner_div{ max-width:1200px !important; } header#opt_header_ten > div:first-of-type { max-width:1200px !important; } header#opt_header_ten .inner_div{ max-width:1200px !important !important; } '; } if($headersize1=='full'){ echo ' header#opt_header_five > div:first-of-type { max-width:90% !important; } header#opt_header_five .inner_div{ max-width:90% !important; } header#opt_header_one > div:first-of-type { max-width:90% !important; } header#opt_header_one .inner_div{ max-width:90% !important; } header#opt_header_two > div:first-of-type { max-width:90% !important; } header#opt_header_two .inner_div{ max-width:90% !important; } header#opt_header_three > div:first-of-type { max-width:90% !important; } header#opt_header_three .inner_div{ max-width:90% !important; } header#opt_header_four > div:first-of-type { max-width:90% !important; } header#opt_header_four .inner_div{ max-width:90% !important; } header#opt_header_six > div:first-of-type { max-width:90% !important; } header#opt_header_six .inner_div{ max-width:90% !important; } header#opt_header_seven > div:first-of-type { max-width:90% !important; } header#opt_header_seven .inner_div{ max-width:90% !important; } header#opt_header_eight > div:first-of-type { max-width:90% !important; } header#opt_header_eight .inner_div{ max-width:90% !important; } header#opt_header_nine > div:first-of-type { max-width:90% !important; } header#opt_header_nine .inner_div{ max-width:90% !important; } header#opt_header_ten > div:first-of-type { max-width:90% !important; } header#opt_header_ten .inner_div{ max-width:90% !important; } '; } ?> header#opt_header_five .inner_div nav .navlinks .navlinks-item .navlinks-item-link:hover, header#opt_header_five .inner_div nav .navlinks .navlinks-item .navlinks-item-link:active, header#opt_header_five .inner_div nav .navlinks .navlinks-item .navlinks-item-link:focus { background-color:<?php echo get_theme_mod( 'color_nav_onhover', '#386591' ); ?> !important; } .site__colors_buttons_bg{ background-color:<?php echo get_theme_mod( 'background_setting_buttons_header', '' ); ?> !important; color:<?php echo get_theme_mod( 'text_setting_buttons_header', '' ); ?> !important; opacity: 1 !important; } .site__colors_buttons_bg:hover{ background-color:<?php echo get_theme_mod( 'background_setting_buttons_header_hover', '' ); ?> !important; color:<?php echo get_theme_mod( 'text_setting_buttons_header_hover', '' ); ?> !important; } header> div:first-of-type .site__iconlink-address:before, header> div:first-of-type .site__iconlink-phone:before{ color:<?php echo get_theme_mod( 'text_setting_buttons_header_icons_phone', '' ); ?> !important; } header > div:first-of-type .site__social-media li a{ color:<?php echo get_theme_mod( 'text_setting_buttons_header_icons_social', '#FFFFFF' ); ?> important; } .site__fade { opacity: 1; transition: none!important; transform: translateY(0); } footer#footer_one > div.footer_copyright > div .footer_payment_types ul > li > i.fas { padding: 5px 10px; color: #ffffff; font-size: 28px; } html{ overflow-x:hidden; } section.site__block .container.medium .site__grid > ul > li, section.page__template .container.medium .site__grid > ul > li, section.single__page .container.medium .site__grid > ul > li, section.page_404 .container.medium .site__grid > ul > li{ width: 30%; height: auto; float: left; } header.mobileheader > div:first-of-type > a{ left: 10px; } </style> <?php $value=get_theme_mod( 'header_style', 'one' ); $option='options_header_style'; update_option($option, $value); ?> <file_sep><?php /** * Services Block * */ // empty return string $return = []; $guide = []; $return['section'] = ''; $guide['section'] = ''; $guide['grid'] = ''; $return['grid'] ='<ul class="site__fade site__fade-up square_ul">'; foreach($cB['testimonials'] as $i => $testimonial){ $fields = get_fields($testimonial['testimonial']->ID); if( $fields['type'] == 'text' ){ $guide['grid'] = ' <li class="testimonial_text"> <div> %s <div class="testimonial_content"> <div class="testimonial_name"> %s %s </div> <div class="testimonial_details block__item-body">%s</div> </div> </div> </li> '; $return['grid'] .= sprintf( $guide['grid'] ,(!empty($fields['image']) ? '<div class="block" style="background-image:url('.$fields['image']['url'].');"></div>' : '') ,(!empty($fields['name']) ? '<h3>'.$fields['name'].'</h3>' : '') ,(!empty($fields['location']) ? '<p>'.$fields['location'].'</p>' : '') ,(!empty($fields['details']) ? $fields['details'] : '') ); } else if( $fields['type'] == 'image' ){ $guide['grid'] = ' <li class="testimonial_image"> <div> %s <div class="testimonial_content"> <div class="testimonial_name"> %s %s </div> <div class="testimonial_details block__item-body">%s</div> </div> </div> </li> '; $return['grid'] .= sprintf( $guide['grid'] ,(!empty($fields['image']) ? '<div class="block" style="background-image:url('.$fields['image']['url'].');"></div>' : '') ,(!empty($fields['name']) ? '<h3>'.$fields['name'].'</h3>' : '') ,(!empty($fields['location']) ? '<p>'.$fields['location'].'</p>' : '') ,(!empty($fields['details']) ? $fields['details'] : '') ); } else if( $fields['type'] == 'video' ){ $guide['grid'] = ' <li class="testimonial_video"> <div> %s <div class="testimonial_content"> <div class="testimonial_name"> %s %s </div> <div class="testimonial_details block__item-body">%s</div> </div> </div> </li> '; $return['grid'] .= sprintf( $guide['grid'] ,(!empty($fields['video_file']['url']) ? '<video controls><source src="'.$fields['video_file']['url'].'"type="video/mp4"></video>' : '') ,(!empty($fields['name']) ? '<h3>'.$fields['name'].'</h3>' : '') ,(!empty($fields['location']) ? '<p>'.$fields['location'].'</p>' : '') ,(!empty($fields['details']) ? $fields['details'] : '') ); } } $return['grid'] .= '</ul>'; $imagetestimonial = get_theme_mod( 'setting_testimonial_buttom_divider', '' ); $imagetestimonial2 = get_theme_mod( 'setting_testimonial_buttom_divider_top', '' ); // empty guide string $guide['section'] = ' <section %s class="site__block block__testimonials" style="%s %s %s %s %s %s %s %s"> <img class="spacerdiviermenutop" src='.'"'. esc_url( $imagetestimonial2 ).'"'.'> <div class=" container %s %s" style="%s %s"> %s %s %s %s </div> <img class="spacerdiviermenubottom" src='.'"'. esc_url( $imagetestimonial ).'"'.'> </section> '; $return['section'] .= sprintf( $guide['section'] ,( !empty($cB['anchor_enabled']) ? 'id="'.strtolower($cB['anchor_link_text']).'"' : '' ) // add an ID tag for the long scroll ,( !empty($cB['background_settings']['background_image']) ? 'background-image:url('."'".strtolower($cB['background_settings']['background_image'])."'".');' : '' )//this is the background image ,( !empty($cB['background_settings']['background_position']) ? 'background-position:'.strtolower($cB['background_settings']['background_position']).';' : '' )//this is for background position ,( !empty($cB['background_settings']['background_size']) ? 'background-size:'.strtolower($cB['background_settings']['background_size']).';' : '' )//this is for background size ,( !empty($cB['background_settings']['background_repeat']) ? 'background-repeat:'.strtolower($cB['background_settings']['background_repeat']).';' : '' )//this is for background repeat ,( !empty($cB['background_setting']['background_attachment']) ? 'background-attachment:'.strtolower($cB['background_setting']['background_attachment']).';' : '' )//this is for background attachment ,( !empty($cB['background_setting']['background_origin']) ? 'background-origin:'.strtolower($cB['background_setting']['background_origin']).';' : '' )//this is for background origin ,( !empty($cB['background_setting']['background_clip']) ? 'background-clip:'.strtolower($cB['background_setting']['background_clip']).';' : '' )//this is for background clip ,( !empty($cB['background_setting']['background_color']) ? 'background-color:'.strtolower($cB['background_setting']['background_color']).';' : '' )//this is for background color ,( !empty( $cB['width'] ) ? $cB['width'] : '' ) // container width ,( !empty( $cB['background_color'] ) ? 'hasbg' :'' ) // container has bg color class ,( !empty( $cB['background_color'] ) ? 'background-color:'.$cB['background_color'].';' : '' ) // container bg color style ,( !empty( $cB['foreground_color'] ) ? 'color:'.$cB['foreground_color'].';' : '' ) // container bg color style ,( !empty($cB['heading']) ? '<h2 class="site__fade site__fade-up block__heading" style="text-align:'.$cB['heading_alignment'].';">'.$cB['heading'].'</h2>' : '' ) ,( !empty($cB['text']) ? '<div class="slider site__fade site__fade-up block__details">'.$cB['text'].'</div>' : '' ) ,( !empty($return['grid']) ? '<div class=" site__grid">'.$return['grid'].'</div>' : '' ) ,( !empty($cB['view_all_button']['link']) ? '<a class="site__button" href="'.$cB['view_all_button']['link']['url'].'">'.$cB['view_all_button']['link']['title'].'</a>' : '' ) ); // echo return string echo $return['section']; // clear the $cB, $return, $index and $guide vars for the next block unset($cB, $return, $guide); ?> <script> function myFunction() {var delayInMilliseconds = 10000; //1 second setTimeout(function() { var x = document.getElementsByClassName("testimonial_next"); x[0].click(); myFunction(); }, delayInMilliseconds); } myFunction(); </script><file_sep><?php /** * Timed Popup * This file is only loaded if the timed popup exists; conditionals handled before call */ // empty overlay return $return['overlay'] = ''; $guide['overlay'] = ''; // get fields $fields = get_field('popups', 'options')['timed_overlay']; // overlay guide $guide['overlay'] = ' <div id="popups__timed_overlay"> <i class="fas fa-times overlay__closebutton"></i> <div class="container"> <figure><img src="%s"></figure> <div> %s %s <div class="popup_form">'.( !empty($fields['overlay']['form']) ? do_shortcode('[gravityform id="'.$fields['overlay']['form']['id'].'" title="false" description="true"]') : '' ).'</div> </div> </div> </div> '; // write the overlay $return['overlay'] .= sprintf( $guide['overlay'] ,(!empty($fields['overlay']['image']['url']) ? $fields['overlay']['image']['url'] : '') ,(!empty($fields['overlay']['heading']) ? '<div class="popup_heading">'.$fields['overlay']['heading'].'</div>' : '') ,(!empty($fields['overlay']['details']) ? '<div class="popup_details">'.$fields['overlay']['details'].'</div>': '') ); // echo the overlay // the overlay is initially hidden // this will be the first content within the <body> echo $return['overlay']; // clear all the vars we used to protect the rest of the document //unset($return, $guide, $fields); ?><file_sep><?php /** * NavHandler Class */ class NavHandler { // Public Vars public $header_one = ''; public $header_two = ''; public $header_three = ''; public $header_four = ''; public $header_five = ''; public $header_six = ''; public $header_seven = ''; public $header_eight = ''; public $header_nine = ''; public $header_ten = ''; // Constructor function __construct(){ $this->_init(); } // Initialize function _init(){ $popups = get_field('popups','options'); // get header field group $header = get_field('header','options'); // check if fade-in nav is enabled $fadenav = ''; if( !empty($header['fade_background']) ){ $fadenav = 'site__fadenav'; } // look for a 'custom logo' $content_logo = ''; // if we have a custom logo if( !empty( get_theme_mod( 'custom_logo' ) ) ){ $logo_src = wp_get_attachment_image_src(get_theme_mod( 'custom_logo' )); $logo_srcset = wp_get_attachment_image_srcset(get_theme_mod( 'custom_logo' )); $format_logo = ' <a class="header-logo" href="%s" title="Logo button"> <img src="%s" srcset="%s" alt="%s" /> </a> '; $content_logo .= sprintf( $format_logo ,site_url() ,$logo_src[0] ,$logo_srcset ,get_bloginfo('sitename') ); } $hamburger_icon = '<a class="site__bars" href="javascript:;" title="3 Line menu icon button"><span></span><span></span><span></span></a>'; // get company info field group $company_info = get_field('company_info','options'); // get company info fields $company_address_br = get_full_address_br(); $company_address = get_full_address(); $phone_number_1 = get_phone_number_1(); $phone_number_2 = get_phone_number_2(); $company_email = get_email(); // check for social media Icons $social_media = ($company_info['social_media'] ? $company_info['social_media'] : ''); $site__iconlink_location_br = ''; if( !empty($company_address_br) ){ $site__iconlink_location_br .= ' <a href="javascript:;" class="site__iconlink site__iconlink-address">'.$company_address_br.'</a> '; } $site__iconlink_location = ''; if( !empty($company_address) ){ $site__iconlink_location .= ' <a href="javascript:;" class="site__iconlink site__iconlink-address">'.$company_address.'</a> '; } $site__iconlink_phone = ''; if( !empty($phone_number_1) ){ $site__iconlink_phone .= ' <a href="tel:'.$phone_number_1.'" class="site__iconlink site__iconlink-phone">'.$phone_number_1.'</a> '; } $header_1_phone = ''; if( !empty($phone_number_1) ){ $header_1_phone .= ' <a href="tel:'.$phone_number_1.'" class="site__iconlink site__iconlink-phone"><div>CALL US TODAY:<br/><span>'.$phone_number_1.'</span></div></a> '; } // needsfix $quotebtn_txt = $popups['banner']['button']['text']; if( !empty($quotebtn_txt) ){ $format_quotebtn = ' <a href="#" class="topbanner-quickquote" title="Get a quote button"> <span>%s</span> <i class="fas fa-angle-right"></i> </a> '; $content_quotebtn = sprintf( $format_quotebtn ,$quotebtn_txt ); } // /needsfix $format_address_phone_number = ' <span> %s %s </span> '; $content_address_phone_number = sprintf( $format_address_phone_number ,$site__iconlink_location ,$site__iconlink_phone ); // theme3 pink social bar above header $format_socialtopbar = ' <div id="opt__topbanner"> <span> <a href="#" alt="Address button"><i class="fas fa-map-marker-alt"></i> <span>%s</span> </a> <a href="tel:%s" title="Phone number button"> <i class="fas fa-phone"></i> </a> </span> %s </div> '; $content_socialtopbar = sprintf( $format_socialtopbar ,$company_address ,$phone_number_1 ,$phone_number_1 ); // phone iconLink $desktop_social = '<a href="tel:'.$phone_number_1.'" title=""><i class="fas fa-phone"></i> '.$phone_number_1.'</a>'; // header popup button $quickquote = ''; if( get_field('popups', 'options')['header']['status'] ){ $quickquote = '<a href="javascript:;" class="site__button site__button-quote site__colors_buttons_bg" title="'.get_field('popups', 'options')['header']['button']['text'].'">' . get_field('popups', 'options')['header']['button']['text'] . '</a>'; } // banner popup if( $popups['banner']['status'] ){ $topbar_text = $popups['banner']['button']['text']; $format_topbar = ' <div class="opt__estimatebar"> <a href="#" class="topbanner-quickquote" title="Get a quote button">%s</a> </div> '; $content_topbar = sprintf( $format_topbar ,$topbar_text ); } /** * * Start Header Style 1 * */ $format_header = ' <header class="%s header" id="opt_header_one" ><meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <div class="header"> %s <div> %s %s </div> </div> <div class="nav" > <nav > %s %s </nav> </div> </header> '; $this->header_one = sprintf( $format_header ,$fadenav ,$content_logo ,$site__iconlink_location_br ,$header_1_phone ,get_site_nav() ,get_social_icons() ); /** * * End Header Style 1 * */ /** * * Start Header Style 2 * */ $format_header = ' <header class="header %s site_colors_header_bg" id="opt_header_two" > <div class="header-tint site_colors_header_bg" > %s <div> %s <nav class="site_colors_header_nav_bg nav"> %s </nav> </div> %s </div> </header> '; $this->header_two = sprintf( $format_header ,$fadenav ,get_custom_logo() ,$desktop_social ,get_site_nav() ,$quickquote ); /** * * End Header Style 2 * */ /** * * Start Header Style 3 * */ $format_header = ' <header class="header %s" id="opt_header_three" > <divclass="header" > %s %s </div> <div class="header-content nav" > %s %s </div> </header> '; $this->header_three = sprintf( $format_header ,$fadenav ,$content_address_phone_number ,$quickquote ,get_custom_logo() ,get_site_nav() ); /** * End Header Style 3 */ /** * Start Header Style 4 */ $format_header = ' <header class="%s header" id="opt_header_four" > <div class="outer_div" > <div class="inner_div" > %s %s %s </div> </div> <nav class="nav"> %s </nav> </header> '; $this->header_four = sprintf( $format_header ,$fadenav ,get_social_icons() ,get_custom_logo() ,$site__iconlink_phone ,get_site_nav() ); /** * * End Header Style 4 * */ /** * * Start Header Style 5 * */ $format_header = ' <header class="%s header" id="opt_header_five" > <div > %s %s %s %s </div> <div class="outer_div nav" > <div class="inner_div nav" > %s <nav> %s </nav> </div> </div> </header> '; $this->header_five = sprintf( $format_header ,$fadenav ,get_social_icons() ,$site__iconlink_location ,$site__iconlink_phone ,$quickquote ,get_custom_logo() ,get_site_nav() ); /** * * End Header Style 5 * */ /** * * Start Header Style 6 * */ $format_header = ' <header class="%s header" id="opt_header_six" > <div class="header"> %s %s %s </div> <div class="nav"> <nav class="nav"> %s %s %s </nav> </div> </header> '; $this->header_six = sprintf( $format_header ,$fadenav ,$site__iconlink_phone ,$site__iconlink_location ,get_social_icons() ,get_custom_logo() ,get_site_nav() ,$quickquote ); /** * * End Header Style 6 * */ /** * * Start Header Style 7 * */ $format_header = ' <header class="%s header" id="opt_header_seven" > <div> %s %s %s </div> <nav> %s </nav> </header> '; $this->header_seven = sprintf( $format_header ,$fadenav ,get_social_icons() ,get_custom_logo() ,$site__iconlink_phone ,get_site_nav() ); /** * * End Header Style 7 * */ /** * * Start Header Style 8 * */ $format_header = ' <header class="%s header" id="opt_header_eight" > <div class="nav"> %s <nav> %s </nav> </div> </header> '; $this->header_eight = sprintf( $format_header ,$fadenav ,get_custom_logo() ,get_site_nav() ); /** * * End Header Style 8 * */ /** * * Start Header Style 9 * */ $format_header = ' <header class="%s header" id="opt_header_nine"> <div class="outer_div" > <div class="inner_div" > %s %s %s </div> </div> <div class="nav"> <div class="inner_div"> %s <nav> %s %s </nav> </div> </div> </header> '; $this->header_nine = sprintf( $format_header ,$fadenav ,$site__iconlink_phone ,$site__iconlink_location ,get_social_icons() ,get_custom_logo() ,get_site_nav() ,$quickquote ); /** * * End Header Style 9 * */ /** * * Start Header Style 10 * */ $format_header = ' <header class="%s header" id="opt_header_ten" > <div> %s %s %s </div> <div class="sidebar_menu nav"> <nav> %s %s </nav> </div> </header> '; $this->header_ten = sprintf( $format_header ,$fadenav ,$hamburger_icon ,get_custom_logo() ,get_social_icons() ,get_site_nav() ,$site__iconlink_phone ); /** * * End Header Style 10 * */ } } ?><file_sep><?php /** * */ // // libs require('includes/util.general.php'); // helpers require('includes/acf.extensions.php'); // php extensions for acf (options pages, manually defined fields, other stuff?) require('classes/class.NavWalker.php'); // wordpress built in nav require('classes/class.NavHandler.php'); // handler for creating theme headers require('classes/customizer/class.Customizer.php'); // wordpress customizer stuff // // setup the theme require('classes/class.Setup.php'); // Theme Setup / Init require('classes/class.UserRoles.php'); // Custom Users and Roles require('classes/class.customposts.php'); // custom posts include_once( dirname( __FILE__ ) . '/includes/kirki/kirki.php' ); function mytheme_kirki_configuration() { return array( 'url_path' => get_stylesheet_directory_uri() . '/includes/kirki/' ); } add_filter( 'kirki/config', 'mytheme_kirki_configuration' ); function mytheme_kirki_sections( $wp_customize ) { /** * Add panels */ $wp_customize->add_panel( 'style', array( 'priority' => 10, 'title' => __( 'Style', 'kirki' ), ) ); $wp_customize->add_panel( 'tex', array( 'priority' => 10, 'title' => __( 'Typography', 'kirki' ), ) ); $wp_customize->add_panel( 'global', array( 'priority' => 10, 'title' => __( 'Global', 'kirki' ), ) ); /** * Add sections */ $wp_customize->add_section( 'section_color', array( 'title' => __( 'Colors + Backgrounds', 'kirki' ), 'priority' => 20, 'panel' => 'style', ) ); $wp_customize->add_section( 'section_typography', array( 'title' => __( 'Typography', 'kirki' ), 'priority' => 20, 'panel' => 'style', ) ); $wp_customize->add_section( 'section_global', array( 'title' => __( 'Global Style', 'kirki' ), 'priority' => 20, 'panel' => 'style', ) ); } add_action( 'customize_register', 'mytheme_kirki_sections' ); function mytheme_kirki_fields( $wp_customize ) { $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="bartitle">' . esc_html__( 'Header', 'kirki' ) . '</div>', 'priority' => 10, ); //header $fields[] = array( 'type' => 'color', 'settings' => 'background_setting_header', 'label' => esc_html__( 'Header Background ', 'kirki' ), 'description' => esc_html__( 'Header Background Color Controls ', 'kirki' ), 'section' => 'section_color', 'default' => '#fff', 'choices' => [ 'alpha' => true, ], ); // header colors fields $fields[] = array( 'type' => 'color', 'settings' => 'color_header', 'label' => esc_html__( 'Header text colors ', 'kirki' ), 'description' => esc_html__( 'Select color for Header element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'select', 'settings' => 'section_header_size1', 'label' => esc_html__( 'Header Size', 'kirki' ), 'section' => 'section_color', 'default' => 'default', 'priority' => 10, 'multiple' => 1, 'choices' => [ 'default' => esc_html__( 'default', 'kirki' ), 'narrow' => esc_html__( 'narrow', 'kirki' ), 'medium' => esc_html__( 'medium', 'kirki' ), 'wide' => esc_html__( 'wide', 'kirki' ), 'full' => esc_html__( 'full', 'kirki' ), ], ); $fields[] = array( 'type' => 'color', 'settings' => 'background_setting_buttons_header', 'label' => esc_html__( 'Backgroung Button on Header ', 'kirki' ), 'description' => esc_html__( 'Backgroung Button on header ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'color', 'settings' => 'background_setting_buttons_header_hover', 'label' => esc_html__( 'Button on Header on Hover ', 'kirki' ), 'description' => esc_html__( 'Button on header on Hover ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'color', 'settings' => 'text_setting_buttons_header', 'label' => esc_html__( 'Backgroung Button on Header ', 'kirki' ), 'description' => esc_html__( 'Backgroung Button on header ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'color', 'settings' => 'text_setting_buttons_header_hover', 'label' => esc_html__( 'Button on Header on Hover ', 'kirki' ), 'description' => esc_html__( 'Button on header on Hover ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'color', 'settings' => 'text_setting_buttons_header_icons_phone', 'label' => esc_html__( 'Header icon ', 'kirki' ), 'description' => esc_html__( 'Header iconsr ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'color', 'settings' => 'text_setting_buttons_header_icons_social', 'label' => esc_html__( 'Header social icon ', 'kirki' ), 'description' => esc_html__( 'Header social icons ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); // accent fields $fields[] = array( 'type' => 'color', 'settings' => 'background_setting_accent2', 'label' => esc_html__( 'Accent color ', 'kirki' ), 'description' => esc_html__( 'Accent color ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_nav', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="bartitle">' . esc_html__( 'Nav', 'kirki' ) . '</div>', 'priority' => 10, ); //nav $fields[] = array( 'type' => 'color', 'settings' => 'background_setting_nav', 'label' => esc_html__( 'Nav Background ', 'kirki' ), 'description' => esc_html__( 'Nav Background Color Controls ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); // nav colors fields $fields[] = array( 'type' => 'color', 'settings' => 'color_nav', 'label' => esc_html__( 'Navigation text colors ', 'kirki' ), 'description' => esc_html__( 'Select color for navegation element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'color', 'settings' => 'color_nav_onhover', 'label' => esc_html__( 'Navigation On Hover ', 'kirki' ), 'description' => esc_html__( 'Select color for navegation element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_hero', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="bartitle">' . esc_html__( 'Hero', 'kirki' ) . '</div>', 'priority' => 10, ); // hero background color $fields[] = array( 'type' => 'background', 'settings' => 'background_setting_hero', 'label' => esc_html__( 'Hero Background ', 'kirki' ), 'description' => esc_html__( 'Hero Background Color Controls ', 'kirki' ), 'section' => 'section_color', 'default' => [ 'background-color' => '#ffffff', 'background-image' => '', 'background-repeat' => 'repeat', 'background-position' => 'center center', 'background-size' => 'cover', 'background-attachment' => 'scroll', ], 'transport' => 'auto', 'output' => [ [ 'element' => '.image2', ], ], ); $fields[] = array( 'type' => 'image', 'settings' => 'setting_hero_mobile_image', 'label' => esc_html__( 'Mobile Background image', 'kirki' ), 'section' => 'section_color', 'default' => '', ); // foreground background color $fields[] = array( 'type' => 'background', 'settings' => 'background_setting_hero_foreground', 'label' => esc_html__( 'Background Overlays ', 'kirki' ), 'description' => esc_html__( 'this set over the background', 'kirki' ), 'section' => 'section_color', 'default' => [ 'background-color' => 'transparent', 'background-image' => '', 'background-repeat' => 'repeat', 'background-position' => 'center center', 'background-size' => 'cover', 'background-attachment' => 'scroll', ], 'transport' => 'auto', 'output' => [ [ 'element' => 'section.hero .tinto', ], ], ); //blend mode $fields[] = array( 'type' => 'select', 'settings' => 'background_setting_hero_foreground_blend3', 'label' => esc_html__( 'Tint Overlay Blend Mode', 'kirki' ), 'section' => 'section_color', 'default' => 'normal', 'placeholder' => esc_html__( 'Blend Mode', 'kirki' ), 'priority' => 10, 'multiple' => 1, 'choices' => [ 'normal' => esc_html__( 'normal', 'kirki' ), 'multiply' => esc_html__( 'multiply', 'kirki' ), 'screen' => esc_html__( 'screen', 'kirki' ), 'overlay' => esc_html__( 'overlay', 'kirki' ), 'darken' => esc_html__( 'darken', 'kirki' ), 'lighten' => esc_html__( 'lighten', 'kirki' ), 'color-dodge' => esc_html__( 'color-dodge', 'kirki' ), 'saturation' => esc_html__( 'saturation', 'kirki' ), 'color' => esc_html__( 'color', 'kirki' ), 'luminosity' => esc_html__( 'luminosity', 'kirki' ), ], ); // Hero text $fields[] = array( 'type' => 'color', 'settings' => 'color_hero', 'label' => esc_html__( 'Hero text colors ', 'kirki' ), 'description' => esc_html__( 'Select color for Hero element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); //radio buttons $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_global_HEADER_STYLE', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_global', 'default' => '<div class="bartitle">' . esc_html__( 'HEADER STYLE', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'select', 'settings' => 'header_style', 'label' => esc_html__( 'SELECT HEADER STYLE', 'kirki' ), 'section' => 'section_global', 'default' => 'one', 'placeholder' => esc_html__( 'HEADER STYLE', 'kirki' ), 'priority' => 10, 'multiple' => 1, 'choices' => [ 'one' => esc_html__( 'one', 'kirki' ), 'two' => esc_html__( 'two', 'kirki' ), 'three' => esc_html__( 'three', 'kirki' ), 'four' => esc_html__( 'four', 'kirki' ), 'five' => esc_html__( 'five', 'kirki' ), 'six' => esc_html__( 'six', 'kirki' ), 'seven' => esc_html__( 'seven', 'kirki' ), 'eight' => esc_html__( 'eight', 'kirki' ), 'nine' => esc_html__( 'nine', 'kirki' ), 'ten' => esc_html__( 'ten', 'kirki' ), ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_global_button', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_global', 'default' => '<div class="bartitle">' . esc_html__( 'BUTTONS (round corners)', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'slider', 'settings' => 'section_buttons', 'label' => esc_html__( 'Corner Radius ', 'kirki' ), 'section' => 'section_global', 'default' => 42, 'choices' => [ 'min' => 0, 'max' => 100, 'step' => 1, ], ); //type lines $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_global_dividers', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_global', 'default' => '<div class="bartitle">' . esc_html__( 'DIVIDERS', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'select', 'settings' => 'section_divid1', 'label' => esc_html__( 'Dividers', 'kirki' ), 'section' => 'section_global', 'default' => 'solid', 'priority' => 10, 'multiple' => 1, 'choices' => [ 'solid' => esc_html__( 'solid', 'kirki' ), 'dotted' => esc_html__( 'dotted', 'kirki' ), 'dashed' => esc_html__( 'dashed', 'kirki' ), 'double' => esc_html__( 'double', 'kirki' ), 'groove' => esc_html__( 'groove', 'kirki' ), 'ridge' => esc_html__( 'ridge', 'kirki' ), 'insert' => esc_html__( 'inset', 'kirki' ), 'outset' => esc_html__( 'outset', 'kirki' ), 'none' => esc_html__( 'none', 'kirki' ), 'hidden' => esc_html__( 'hidden', 'kirki' ), ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_divider', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_global', 'default' => '<div class="bartitle">' . esc_html__( 'Shape Dividers', 'kirki' ) . '</div>', 'priority' => 10, ); //divider hero bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_hero_buttom_divider_top', 'label' => esc_html__( 'Hero Shape divider top', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider hero bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_hero_buttom_divider', 'label' => esc_html__( 'Hero Shape divider bottom', 'kirki' ), 'section' => 'section_global', 'default' => '', ); $fields[] = array( 'type' => 'radio-buttonset', 'settings' => 'setting_true_false_true1', 'label' => esc_html__( 'Hero Shape Divider Mobile', 'kirki' ), 'section' => 'section_global', 'default' => 'ON', 'priority' => 10, 'choices' => [ 'ON' => esc_html__( 'ON', 'kirki' ), 'OFF' => esc_html__( 'OFF', 'kirki' ), ], ); //divider menu top $fields[] = array( 'type' => 'image', 'settings' => 'setting_menu1_buttom_divider_top', 'label' => esc_html__( 'Menu Shape divider top', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider menu bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_menu1_buttom_divider', 'label' => esc_html__( 'Menu Shape divider bottom', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider location bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_location_buttom_divider_top', 'label' => esc_html__( 'Location Shape divider top', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider location bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_location_buttom_divider', 'label' => esc_html__( 'Location Shape divider bottom', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider coupon bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_coupon_buttom_divider_top', 'label' => esc_html__( 'Coupon Shape divider top', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider coupon bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_coupon_buttom_divider', 'label' => esc_html__( 'Coupon Shape divider bottom', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider gallery bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_gallery_buttom_divider_top', 'label' => esc_html__( 'Gallery Shape divider top', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider gallery bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_gallery_buttom_divider', 'label' => esc_html__( 'Gallery Shape divider bottom', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider services bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_services_buttom_divider_top', 'label' => esc_html__( 'services Shape divider top', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider services bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_services_buttom_divider', 'label' => esc_html__( 'services Shape divider bottom', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider blog bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_blog_buttom_divider_top', 'label' => esc_html__( 'blog Shape divider top', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider blog bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_blog_buttom_divider', 'label' => esc_html__( 'blog Shape divider bottom', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider testimonial bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_testimonial_buttom_divider_top', 'label' => esc_html__( 'testimonial Shape divider top', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider testimonial bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_testimonial_buttom_divider', 'label' => esc_html__( 'testimonial Shape divider bottom', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider staff bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_staff_buttom_divider_top', 'label' => esc_html__( 'staff Shape divider top', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider staff bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_staff_buttom_divider', 'label' => esc_html__( 'staff Shape divider bottom', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider contact bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_contact_buttom_divider_top', 'label' => esc_html__( 'contact Shape divider top', 'kirki' ), 'section' => 'section_global', 'default' => '', ); //divider contact bottom $fields[] = array( 'type' => 'image', 'settings' => 'setting_contact_buttom_divider', 'label' => esc_html__( 'contact Shape divider bottom', 'kirki' ), 'section' => 'section_global', 'default' => '', ); // body background color /* $fields[] = array( 'type' => 'color', 'settings' => 'background_setting_body1', 'label' => esc_html__( 'Body Background ', 'kirki' ), 'description' => esc_html__( 'Body Background Color Controls ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], );*/ $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_body', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="bartitle">' . esc_html__( 'Body', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'background', 'settings' => 'background_setting_body2', 'label' => esc_html__( ' ', 'kirki' ), 'description' => esc_html__( ' ', 'kirki' ), 'section' => 'section_color', 'default' => [ 'background-color' => '#ffffff', 'background-image' => '', 'background-repeat' => 'repeat', 'background-position' => 'center center', 'background-size' => 'cover', 'background-attachment' => 'scroll', ], 'transport' => 'auto', 'output' => [ [ 'element' => 'body', ], ], ); // body colors fields $fields[] = array( 'type' => 'color', 'settings' => 'color_p', 'label' => esc_html__( 'Body text colors ', 'kirki' ), 'description' => esc_html__( 'Select color for body element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_footer', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="bartitle">' . esc_html__( 'Footer', 'kirki' ) . '</div>', 'priority' => 10, ); // footer fields $fields[] = array( 'type' => 'background', 'settings' => 'background_setting_footer', 'label' => esc_html__( 'Footer Background ', 'kirki' ), 'description' => esc_html__( 'Footer Background Color Controls ', 'kirki' ), 'section' => 'section_color', 'default' => [ 'background-color' => '#ffffff', 'background-image' => '', 'background-repeat' => 'repeat', 'background-position' => 'center center', 'background-size' => 'cover', 'background-attachment' => 'scroll', ], 'transport' => 'auto', 'output' => [ [ 'element' => 'footer', ], ], ); // footer copyright fields $fields[] = array( 'type' => 'color', 'settings' => 'background_setting_footercopyright', 'label' => esc_html__( 'Footer Copyright Background ', 'kirki' ), 'description' => esc_html__( 'Footer Copyright Background Color Controls ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); // footer text $fields[] = array( 'type' => 'color', 'settings' => 'color_footer', 'label' => esc_html__( 'Footer text colors ', 'kirki' ), 'description' => esc_html__( 'Select text color for Footer element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); // Footer copyright text $fields[] = array( 'type' => 'color', 'settings' => 'color_footer_copyright', 'label' => esc_html__( 'Footer copyright colors ', 'kirki' ), 'description' => esc_html__( 'Select color for footer copyright element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_sections', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="bartitle">' . esc_html__( 'Sections / Pages', 'kirki' ) . '</div>', 'priority' => 10, ); // about colors $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_about', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="header-one">' . esc_html__( 'About', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'color', 'settings' => 'color_about', 'label' => esc_html__( 'Staff Background Colors ', 'kirki' ), 'description' => esc_html__( ' Background Colors', 'kirki' ), 'section' => 'section_color', 'default' => '#dedede', 'choices' => [ 'alpha' => true, ], ); // Steff colors $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_staff', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="header-one">' . esc_html__( 'About Staff', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'color', 'settings' => 'color_staff', 'label' => esc_html__( 'Staff Background Colors ', 'kirki' ), 'description' => esc_html__( ' Background Colors', 'kirki' ), 'section' => 'section_color', 'default' => '#dedede', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_Blog', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="header-one">' . esc_html__( 'Blog', 'kirki' ) . '</div>', 'priority' => 10, ); // blog colors $fields[] = array( 'type' => 'background', 'settings' => 'background_setting_blog', 'label' => esc_html__( 'Blog Background ', 'kirki' ), 'description' => esc_html__( 'Blog Background Color Controls ', 'kirki' ), 'section' => 'section_color', 'default' => [ 'background-color' => '#dedede', 'background-image' => '', 'background-repeat' => 'repeat', 'background-position' => 'center center', 'background-size' => 'cover', 'background-attachment' => 'scroll', ], 'transport' => 'auto', 'output' => [ [ 'element' => 'section.block__blog_posts > div.container ul li > a > div.content', ], ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_coupons', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="header-one">' . esc_html__( 'Coupons', 'kirki' ) . '</div>', 'priority' => 10, ); // coupon colors $fields[] = array( 'type' => 'background', 'settings' => 'background_setting_coupon', 'label' => esc_html__( 'Coupons Background ', 'kirki' ), 'description' => esc_html__( 'Coupons Background Color Controls ', 'kirki' ), 'section' => 'section_color', 'default' => [ 'background-color' => '#dedede', 'background-image' => '', 'background-repeat' => 'repeat', 'background-position' => 'center center', 'background-size' => 'cover', 'background-attachment' => 'scroll', ], 'transport' => 'auto', 'output' => [ [ 'element' => 'ul > li.coupons__one, ul > li.coupons__two, ul > li.coupons__three, ul > li.coupons__four', ], ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_services', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="header-one">' . esc_html__( 'Services', 'kirki' ) . '</div>', 'priority' => 10, ); // Services colors $fields[] = array( 'type' => 'background', 'settings' => 'background_setting_services', 'label' => esc_html__( 'Services Background ', 'kirki' ), 'description' => esc_html__( 'Services Background Color Controls ', 'kirki' ), 'section' => 'section_color', 'default' => [ 'background-color' => '#dedede', 'background-image' => '', 'background-repeat' => 'repeat', 'background-position' => 'center center', 'background-size' => 'cover', 'background-attachment' => 'scroll', ], 'transport' => 'auto', 'output' => [ [ 'element' => 'section.block__services > .container.services__one .site__grid > ul > li > a > div:last-of-type', ], ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_testimonials', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="header-one">' . esc_html__( 'Testimonials', 'kirki' ) . '</div>', 'priority' => 10, ); // Testimonials colors $fields[] = array( 'type' => 'color', 'settings' => 'color_testi', 'label' => esc_html__( 'Testimonail Background Colors ', 'kirki' ), 'description' => esc_html__( 'Testimonail Background Colors', 'kirki' ), 'section' => 'section_color', 'default' => '#dedede', 'choices' => [ 'alpha' => true, ], ); // Testimonials colors $fields[] = array( 'type' => 'color', 'settings' => 'color_outline', 'label' => esc_html__( 'Outline Background Colors ', 'kirki' ), 'description' => esc_html__( 'Outline Background Colors', 'kirki' ), 'section' => 'section_color', 'default' => '#dedede', 'choices' => [ 'alpha' => true, ], ); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //type $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_type', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="bartitle">' . esc_html__( 'TYPE', 'kirki' ) . '</div>', 'priority' => 10, ); // h1 colors fields $fields[] = array( 'type' => 'color', 'settings' => 'color_h1', 'label' => esc_html__( 'h1 colors ', 'kirki' ), 'description' => esc_html__( 'Select color for h1 element', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); // h2 colors fields $fields[] = array( 'type' => 'color', 'settings' => 'color_h2', 'label' => esc_html__( 'h2 colors ', 'kirki' ), 'description' => esc_html__( 'Select color for h2 element', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); // h3 colors fields $fields[] = array( 'type' => 'color', 'settings' => 'color_h3', 'label' => esc_html__( 'h3 colors ', 'kirki' ), 'description' => esc_html__( 'Select color for h3 element', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); // h4 colors fields $fields[] = array( 'type' => 'color', 'settings' => 'color_h4', 'label' => esc_html__( 'h4 colors ', 'kirki' ), 'description' => esc_html__( 'Select color for h4 element', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); // h5 colors fields $fields[] = array( 'type' => 'color', 'settings' => 'color_h5', 'label' => esc_html__( 'h5 colors ', 'kirki' ), 'description' => esc_html__( 'Select color for h5 element', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); // h6 colors fields $fields[] = array( 'type' => 'color', 'settings' => 'color_h6', 'label' => esc_html__( 'h6 colors ', 'kirki' ), 'description' => esc_html__( 'Select color for h6 element', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); //button text color $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_botton', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="bartitle">' . esc_html__( 'Buttons', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'color', 'settings' => 'color_button_text', 'label' => esc_html__( 'Button text colors ', 'kirki' ), 'description' => esc_html__( 'Select color for button element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); //button background $fields[] = array( 'type' => 'color', 'settings' => 'color_button', 'label' => esc_html__( 'Button Background colors ', 'kirki' ), 'description' => esc_html__( 'Select color for button background element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); // button background hover $fields[] = array( 'type' => 'color', 'settings' => 'color_button_hover', 'label' => esc_html__( 'Button background colors on hover ', 'kirki' ), 'description' => esc_html__( 'Select color for button background element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'color', 'settings' => 'color_button_border', 'label' => esc_html__( 'Button border colors ', 'kirki' ), 'description' => esc_html__( 'Select color for button border ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_Divider', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="bartitle">' . esc_html__( 'Divider', 'kirki' ) . '</div>', 'priority' => 10, ); // Hero text $fields[] = array( 'type' => 'color', 'settings' => 'color_divider', 'label' => esc_html__( 'Divider colors ', 'kirki' ), 'description' => esc_html__( 'Select color for Divider element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //links5 //link color text $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_links', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_color', 'default' => '<div class="bartitle">' . esc_html__( 'LINKS', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'color', 'settings' => 'color_links', 'label' => esc_html__( 'Links text colors ', 'kirki' ), 'description' => esc_html__( 'Select color for links element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); //links hover color $fields[] = array( 'type' => 'color', 'settings' => 'color_links_hover', 'label' => esc_html__( 'Links text colors on hover ', 'kirki' ), 'description' => esc_html__( 'Select color for links on hover element ', 'kirki' ), 'section' => 'section_color', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], ); //color bg links /* $fields[] = array( 'type' => 'color', 'settings' => 'color_links', 'label' => esc_html__( 'Links text colors ', 'kirki' ), 'description' => esc_html__( 'Select color for links element ', 'kirki' ), 'section' => 'links', 'default' => '#0088CC', 'choices' => [ 'alpha' => true, ], );*/ //typography headline $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_typo_headline', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_typography', 'default' => '<div class="bartitle">' . esc_html__( 'HEADLINE', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'typography', 'settings' => 'headline_h1', 'label' => esc_html__( 'H1', 'kirki' ), 'section' => 'section_typography', 'default' => [ 'font-family' => 'Roboto', 'variant' => 'regular', 'font-size' => '100px', 'line-height' => '1.5', 'letter-spacing' => '0', 'text-transform' => 'none', 'text-align' => 'none', 'text-decoration' => 'none', ], 'priority' => 10, 'transport' => 'auto', 'output' => [ [ 'element' => 'h1', ], ], ); //headline h2 $fields[] = array( 'type' => 'typography', 'settings' => 'headline_h2', 'label' => esc_html__( 'H2', 'kirki' ), 'section' => 'section_typography', 'default' => [ 'font-family' => 'Roboto', 'variant' => 'regular', 'font-size' => '50px', 'line-height' => '1.5', 'letter-spacing' => '0', 'text-transform' => 'none', 'text-align' => 'none', 'text-decoration' => 'none', ], 'priority' => 10, 'transport' => 'auto', 'output' => [ [ 'element' => 'h2', ], ], ); //headline h3 $fields[] = array( 'type' => 'typography', 'settings' => 'headline_h3', 'label' => esc_html__( 'H3', 'kirki' ), 'section' => 'section_typography', 'default' => [ 'font-family' => 'Roboto', 'variant' => 'regular', 'font-size' => '100px', 'line-height' => '1.5', 'letter-spacing' => '0', 'text-transform' => 'none', 'text-align' => 'none', 'text-decoration' => 'none', ], 'priority' => 10, 'transport' => 'auto', 'output' => [ [ 'element' => 'h3,h5, section.block__blog_posts > div.container ul li > a > div.content > h5, ul > li.coupons__one h5, ul > li.coupons__two h5, ul > li.coupons__three h5, ul > li.coupons__four h5,section.block__services > .container.services__one .site__grid > ul > li > a > div:last-of-type > h3,section.block__contact > .container ul.locations > li > h3.area__heading,section.site__block.block__testimonials > div.container > .site__grid > ul li > div .testimonial_content > div.testimonial_name > h3,section.site__block.block__testimonials > div.container > .site__grid > ul li > div .testimonial_content > div.testimonial_name > p', ], ], ); //headline h4 $fields[] = array( 'type' => 'typography', 'settings' => 'headline_h4', 'label' => esc_html__( 'H4', 'kirki' ), 'section' => 'section_typography', 'default' => [ 'font-family' => 'Roboto', 'variant' => 'regular', 'font-size' => '100px', 'line-height' => '1.5', 'letter-spacing' => '0', 'text-transform' => 'none', 'text-align' => 'none', 'text-decoration' => 'none', ], 'priority' => 10, 'transport' => 'auto', 'output' => [ [ 'element' => 'h4', ], ], ); //headline h5 $fields[] = array( 'type' => 'typography', 'settings' => 'headline_h5', 'label' => esc_html__( 'H5', 'kirki' ), 'section' => 'section_typography', 'default' => [ 'font-family' => 'Roboto', 'variant' => 'regular', 'font-size' => '100px', 'line-height' => '1.5', 'letter-spacing' => '0', 'text-transform' => 'none', 'text-align' => 'none', 'text-decoration' => 'none', ], 'priority' => 10, 'transport' => 'auto', 'output' => [ [ 'element' => 'h5', ], ], ); //headline <h6> $fields[] = array( 'type' => 'typography', 'settings' => 'headline_h6', 'label' => esc_html__( 'H6', 'kirki' ), 'section' => 'section_typography', 'default' => [ 'font-family' => 'Roboto', 'variant' => 'regular', 'font-size' => '100px', 'line-height' => '1.5', 'letter-spacing' => '0', 'text-transform' => 'none', 'text-align' => 'none', 'text-decoration' => 'none', ], 'priority' => 10, 'transport' => 'auto', 'output' => [ [ 'element' => 'h6', ], ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_typo_body', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_typography', 'default' => '<div class="bartitle">' . esc_html__( 'BODY (Blog Post Content)', 'kirki' ) . '</div>', 'priority' => 10, ); //headline <body> $fields[] = array( 'type' => 'typography', 'settings' => 'body_body', 'label' => esc_html__( 'Body', 'kirki' ), 'section' => 'section_typography', 'default' => [ 'font-family' => 'Roboto', 'variant' => 'regular', 'font-size' => '30px', 'line-height' => '1.5', 'letter-spacing' => '0', 'text-transform' => 'none', 'text-align' => 'none', 'text-decoration' => 'none', ], 'priority' => 10, 'transport' => 'auto', 'output' => [ [ 'element' => 'body', ], ], ); $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_typo_navigation', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_typography', 'default' => '<div class="bartitle">' . esc_html__( 'NAVIGATION', 'kirki' ) . '</div>', 'priority' => 10, ); //headline <nav> $fields[] = array( 'type' => 'typography', 'settings' => 'nav', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_typography', 'default' => [ 'font-family' => 'Roboto', 'variant' => 'regular', 'font-size' => '100px', 'line-height' => '1.5', 'letter-spacing' => '0', 'text-transform' => 'none', 'text-align' => 'none', 'text-decoration' => 'none', ], 'priority' => 10, 'transport' => 'auto', 'output' => [ [ 'element' => 'nav,header#opt_header_eight > div:first-of-type > nav .navlinks .navlinks-item .navlinks-item-link', ], ], ); //typography_hero_title $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_typo_hero_title', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_typography', 'default' => '<div class="bartitle">' . esc_html__( 'HERO TITLE', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'typography', 'settings' => 'hero_title', 'label' => esc_html__( 'Hero Title', 'kirki' ), 'section' => 'section_typography', 'default' => [ 'font-family' => 'Roboto', 'variant' => '600', 'font-size' => '100px', 'line-height' => '1.5', 'letter-spacing' => '0', 'text-transform' => 'none', 'text-align' => 'none', 'text-decoration' => 'none', ], 'priority' => 10, 'transport' => 'auto', 'output' => [ [ 'element' => 'section.hero .hero_foreground h1', ], ], ); //typography_hero_title $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_typo_hero_sub_title', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_typography', 'default' => '<div class="bartitle">' . esc_html__( 'HERO SUB-TITLE', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'typography', 'settings' => 'hero_subtitle', 'label' => esc_html__( 'Hero Sub-Title', 'kirki' ), 'section' => 'section_typography', 'default' => [ 'font-family' => 'Roboto', 'variant' => '600', 'font-size' => '100px', 'line-height' => '1.5', 'letter-spacing' => '0', 'text-transform' => 'none', 'text-align' => 'none', 'text-decoration' => 'none', ], 'priority' => 10, 'transport' => 'auto', 'output' => [ [ 'element' => '',//sub title ? ], ], ); //typography buttons $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_typo_buttons', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_typography', 'default' => '<div class="bartitle">' . esc_html__( 'BUTTONS', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'typography', 'settings' => 'typography_button', 'label' => esc_html__( 'Button', 'kirki' ), 'section' => 'section_typography', 'default' => [ 'font-family' => 'Roboto', 'variant' => '600', 'font-size' => '30px', 'line-height' => '1.5', 'letter-spacing' => '0', 'text-transform' => 'none', 'text-align' => 'none', 'text-decoration' => 'none', ], 'priority' => 10, 'transport' => 'auto', 'output' => [ [ 'element' => 'section.block__contact > .container ul.locations > li .site__button','section.block__blog_posts > div.container ul li > a > div.content > p.read_more', ], ], ); //typography_alt_text $fields[] = array( 'type' => 'custom', 'settings' => 'my_setting_typo_alt_text', 'label' => esc_html__( '', 'kirki' ), 'section' => 'section_typography', 'default' => '<div class="bartitle">' . esc_html__( 'ALT TEXT(Sub title under food menu item)', 'kirki' ) . '</div>', 'priority' => 10, ); $fields[] = array( 'type' => 'typography', 'settings' => 'typography_alttext', 'label' => esc_html__( 'Button', 'kirki' ), 'section' => 'section_typography', 'default' => [ 'font-family' => 'Roboto', 'variant' => '600', 'font-size' => '30px', 'line-height' => '1.5', 'letter-spacing' => '0', 'text-transform' => 'none', 'text-align' => 'none', 'text-decoration' => 'none', ], 'priority' => 10, 'transport' => 'auto', 'output' => [ [ 'element' => 'section.block__food_menus > .container .menu_section.menu_photo_list .menu_items .menu_item > div:last-of-type > div.menu__item-description', ], ], ); return $fields; } add_filter( 'kirki/fields', 'mytheme_kirki_fields' ); /** * Returns the SITE LOGO * * @return void */ function my_acf_init() { acf_update_setting('google_api_key', '<KEY>'); } add_action('acf/init', 'my_acf_init'); function get_site_logo() { // look for a 'custom logo' $content_logo = ''; // if we have a custom logo if (!empty(get_theme_mod('custom_logo'))) { $logo_src = wp_get_attachment_image_src(get_theme_mod('custom_logo')); $logo_srcset = wp_get_attachment_image_srcset(get_theme_mod('custom_logo')); $format_logo = ' <a class="" href="%s" title="Logo button"> <img src="%s" srcset="%s" alt="%s"> </a> '; $content_logo .= sprintf( $format_logo, site_url(), $logo_src, $logo_srcset, get_bloginfo('sitename') ); } return $content_logo; } /** * Returns the SITE NAV * * @param string $pre * @return void */ function get_site_nav($pre = 'navlinks') { if (get_field('header', 'options')['long_scroll']) { // get them fields $fields = get_fields(get_option('page_on_front')); $return['blocks_links'] = ''; if (!empty($fields['content_blocks'])) { $guide['blocks_links'] = '<li class="navlinks-item"><a class="navlinks-item-link scroll" href="#%s">%s</a></li>'; $return['blocks_links'] = '<ul class="navlinks nav__spyscroll">'; foreach ($fields['content_blocks'] as $i => $cB) { if ($cB['anchor_enabled']) { $return['blocks_links'] .= sprintf( $guide['blocks_links'], strtolower(str_replace(' ', '_', $cB['anchor_link_text'])), $cB['anchor_link_text'] ); } } $return['blocks_links'] .= '</ul>'; } return $return['blocks_links']; } else { // create an unwrapped site nav $site__nav = wp_nav_menu(array( 'menu' => 'nav__header', 'container' => '', 'items_wrap' => '<ul class="nav-menu navlinks">%3$s</ul>', 'walker' => new NavWalker, 'echo' => false )); return $site__nav; } } /** * TRAINING WIDGET IN DASHBOARD */ if (!function_exists('add_dashboard_widgets')) { function add_dashboard_widgets() { wp_add_dashboard_widget('dashboard_questions_comments_widget', 'Questions, Comments, Concerns ?', 'do_create_training_widget'); } } if (!function_exists('do_create_training_widget')) { function do_create_training_widget($post, $callback_args) { ?> <a target="_blank" href="http://www.123websites.com/training"> <img style="width: 100%;" src="http://www.123websites.com/images/training-ad-dashboard.png"> </a> <?php } } add_action('wp_dashboard_setup', 'add_dashboard_widgets'); function wpb_image_editor_default_to_gd( $editors ) { $gd_editor = 'WP_Image_Editor_GD'; $editors = array_diff( $editors, array( $gd_editor ) ); array_unshift( $editors, $gd_editor ); return $editors; } add_filter( 'wp_image_editors', 'wpb_image_editor_default_to_gd' ); /** * G. PLEASE CLEAN UP THIS JUNK BELOW. */ function get_gmaps_api_key() { return '<KEY>'; } function get_phone_number_1() { $company_info = get_field('company_info', 'options'); return (!empty($company_info['phone_number_1']) ? $company_info['phone_number_1'] : ''); } function get_phone_number_2() { $company_info = get_field('company_info', 'options'); return (!empty($company_info['phone_number_2']) ? $company_info['phone_number_2'] : ''); } function get_email() { return (!empty($company_info['email']) ? $company_info['email'] : ''); } function get_social_icons() { $company_info = get_field('company_info', 'options'); $content_social_icons = ''; // if we have social media icons if (!empty($company_info['social_media'])) { $content_social_icons .= '<ul class="site__social-media">'; $format_social_icons = ' <li> <a href="%s" title="Social icon button" target="_blank"> %s </a> </li> '; foreach ($company_info['social_media'] as $social_icon) { $url = $social_icon['url']; $img = $social_icon['image']; $fa = $social_icon['icon']; $custom_png_url = ''; $icon_url = ''; // we have a preconfigured URL if (strpos($url, 'booksy')) { $custom_png_url = get_template_directory_uri() . '/library/img/social_icons/booksy.png'; } if (strpos($url, 'groupon')) { $custom_png_url = get_template_directory_uri() . '/library/img/social_icons/groupon.png'; } if (strpos($url, 'pinterest')) { $custom_png_url = get_template_directory_uri() . '/library/img/social_icons/pinterest.png'; } if (!empty($custom_png_url)) { $icon_url = $custom_png_url; } else { // we have img if (!empty($img)) { $icon_url = $img; } // img is empty, we have fa else if (!empty($fa)) { $icon_url = ''; $fa_icon = '<i class="fab ' . $fa . '"></i>'; } // img and fa are empty // something went wrong... else { $icon_url = ''; } } if (!empty($url)) { $content_social_icons .= sprintf( $format_social_icons, $url, (!empty($icon_url)) ? '<img src="' . $icon_url . '">' : $fa_icon ); } } $content_social_icons .= '</ul>'; } return $content_social_icons; } function get_full_address_br() { $company_info = get_field('company_info', 'options'); $location = ($company_info['location'] ? $company_info['location'] : ''); $full_address_br = ''; if (!empty($location['address_street'])) { $street_1 = $location['address_street']; $street_2 = $location['address_street_2']; $city = $location['address_city']; $state = $location['address_state']; $postcode = $location['address_postcode']; $country = $location['address_country']; $format_full_address_br = '%s %s <br/>%s, %s %s'; $full_address_br = sprintf( $format_full_address_br, $street_1, $street_2, $city, $state, $postcode // ,$country ); } return $full_address_br; } function get_full_address() { $company_info = get_field('company_info', 'options'); $location = ($company_info['location'] ? $company_info['location'] : ''); $full_address = ''; if (!empty($location['address_street'])) { $street_1 = $location['address_street']; $street_2 = $location['address_street_2']; $city = $location['address_city']; $state = $location['address_state']; $postcode = $location['address_postcode']; $country = $location['address_country']; $format_full_address = '%s %s, %s, %s %s'; $full_address = sprintf( $format_full_address, $street_1, $street_2, $city, $state, $postcode // ,$country ); } return $full_address; } function admin_style() { wp_enqueue_style('admin-styles', 'https://40fourth.com/wp-backend/backend.css'); } add_action('admin_enqueue_scripts', 'admin_style'); ?><file_sep><?php /** * Copy Content Block * * */ // set return and guide string arrays $return = []; $guide = []; $return['section'] = ''; $guide['section'] = ''; // guide string for the section $guide['section'] = ' <section %s class="site__block block__copy" style="%s %s %s %s %s %s %s %s"> <h2>%s</h2> <div class="coupon_description block__item-body">%s</div> <div class="container %s %s" style="%s"> %s </div> </section> '; $return['section'] .= sprintf( $guide['section'] ,( !empty($cB['anchor_enabled']) ? 'id="'.strtolower($cB['anchor_link_text']).'"' : '' ) // add an ID tag for the long scroll ,( !empty($cB['background_settings']['background_image']) ? 'background-image:url('."'".strtolower($cB['background_settings']['background_image'])."'".');' : '' )//this is the background image ,( !empty($cB['background_settings']['background_position']) ? 'background-position:'.strtolower($cB['background_settings']['background_position']).';' : '' )//this is for background position ,( !empty($cB['background_settings']['background_size']) ? 'background-size:'.strtolower($cB['background_settings']['background_size']).';' : '' )//this is for background size ,( !empty($cB['background_settings']['background_repeat']) ? 'background-repeat:'.strtolower($cB['background_settings']['background_repeat']).';' : '' )//this is for background repeat ,( !empty($cB['background_setting']['background_attachment']) ? 'background-attachment:'.strtolower($cB['background_setting']['background_attachment']).';' : '' )//this is for background attachment ,( !empty($cB['background_setting']['background_origin']) ? 'background-origin:'.strtolower($cB['background_setting']['background_origin']).';' : '' )//this is for background origin ,( !empty($cB['background_setting']['background_clip']) ? 'background-clip:'.strtolower($cB['background_setting']['background_clip']).';' : '' )//this is for background clip ,( !empty($cB['background_setting']['background_color']) ? 'background-color:'.strtolower($cB['background_setting']['background_color']).';' : '' )//this is for background color ,( !empty( $cB['width'] ) ? $cB['heading_title'] : '' ) ,( !empty( $cB['width'] ) ? $cB['heading_subtitle'] : '' ) ,( !empty( $cB['width'] ) ? $cB['width'] : '' ) // container width ,( !empty( $cB['background_color'] ) ? 'hasbg' :'' ) // container has bg color class ,( !empty( $cB['background_color'] ) ? 'background-color:'.$cB['background_color'].';' : '' ) // container bg color style ,'<div style="color: '.$cB['foreground_color'].'">'.$cB['copy'].'</div>' // copy content w/ foreground color on container for easy override ); // echo return string echo $return['section']; // clear the $cB, $return and $guide vars unset($cB, $return, $guide); ?><file_sep><style> #myImg { border-radius: 5px; cursor: pointer; transition: 0.3s; } #myImg:hover {opacity: 0.7;} /* The Modal (background) */ .modal { display: none; /* Hidden by default */ position: fixed; /* Stay in place */ z-index: 999; /* Sit on top */ padding-top: 100px; /* Location of the box */ left: 0; top: 0; width: 100%; /* Full width */ height: 100%; /* Full height */ overflow: hidden; /* Enable scroll if needed */ background-color: rgb(0,0,0); /* Fallback color */ background-color: rgba(0,0,0,0.9); /* Black w/ opacity */ } /* Modal Content (image) */ .modal-content { margin: auto; display: block; width: 80%; max-width: 700px; } /* Caption of Modal Image */ #caption { margin: auto; display: block; width: 80%; max-width: 700px; text-align: center; color: #ccc; padding: 10px 0; height: 150px; } /* Add Animation */ .modal-content, #caption { -webkit-animation-name: zoom; -webkit-animation-duration: 0.6s; animation-name: zoom; animation-duration: 0.6s; } @-webkit-keyframes zoom { from {-webkit-transform:scale(0)} to {-webkit-transform:scale(1)} } @keyframes zoom { from {transform:scale(0)} to {transform:scale(1)} } /* The Close Button */ .close { position: absolute; top: 65px; right: 35px; color: #f1f1f1; font-size: 40px; font-weight: bold; transition: 0.3s; } .close:hover, .close:focus { color: #bbb; text-decoration: none; cursor: pointer; } /* 100% Image Width on Smaller Screens */ @media only screen and (max-width: 700px){ .modal-content { width: 100%; } } </style> <?php /** * Galleries Block * */ // empty return string $return = []; $guide = []; $return['section'] = ''; $return['tabs'] = ''; // if we have galleries if( !empty($cB['galleries']) ){ $return['galleries'] = ''; // set the galleries guide string $guide['galleries'] = '<li class="site__fade site__fade-up"><div><div class="image" style="background-image: url(%s)" onclick="openimage('."'".'%s'."'".')"></div></div></li>'; // set the galleries return string $return['galleries'] .= '<div class="">'; // open the tabs list if( $cB['tab_type'] != 'none' ){ $return['tabs'] .= '<div class="tabs site__fade site__fade-up"><ul>'; } // loop thru the galleries foreach( $cB['galleries'] as $i => $gallery ){ // create a tab for each gallery if( $cB['tab_type'] !== 'none' ){ $return['tabs'] .= '<li class="'.( ($i === 0 ) ? 'tab_active' : '' ).'"><a href="javascript:;" style="color:'.$cB['foreground_color'].';">'.$gallery['title'].'</a></li>'; } // open the galleries grid if ( $cB['tab_type'] == 'none' ){ $return['galleries'] .= '<div class="site__grid '.( ($i===0) ? 'current_gallery' : 'hidden_gallery' ).'"><h2 class="site__fade site__fade-up">'.$gallery['title'].'</h2><ul>'; }else{ $return['galleries'] .= '<div class="site__grid '.( ($i===0) ? 'current_gallery' : 'hidden_gallery' ).'"><ul>'; } // loop thru the gallery images to create line items foreach( $gallery['images'] as $image ){ $return['galleries'] .= sprintf( $guide['galleries'] ,$image['url'] ,$image['url'] ); } $return['galleries'] .= '</ul></div>'; } // close the tabs list if( $cB['tab_type'] !== 'none' ){ $return['tabs'] .= '</ul></div>'; } $return['galleries'] .= '</div>'; } $imagegallery = get_theme_mod( 'setting_gallery_buttom_divider', '' ); $imagegallery2 = get_theme_mod( 'setting_gallery_buttom_divider_top', '' ); // empty guide string $guide['section'] = ' <section %s class="site__block block__galleries" style="%s %s %s %s %s %s %s %s"> <img class="spacerdiviermenutop" src='.'"'. esc_url( $imagegallery2 ).'"'.'> <div class="container %s %s" style="%s %s"> %s %s <div class=""> %s %s </div> %s </div> <img class="spacerdiviermenubottom" src='.'"'. esc_url( $imagegallery ).'"'.'> </section> '; $return['section'] .= sprintf( $guide['section'] // options for every block ,( !empty($cB['anchor_enabled']) ? 'id="'.strtolower($cB['anchor_link_text']).'"' : '' ) // add an ID tag for the long scroll ,( !empty($cB['background_settings']['background_image']) ? 'background-image:url('."'".strtolower($cB['background_settings']['background_image'])."'".');' : '' )//this is the background image ,( !empty($cB['background_settings']['background_position']) ? 'background-position:'.strtolower($cB['background_settings']['background_position']).';' : '' )//this is for background position ,( !empty($cB['background_settings']['background_size']) ? 'background-size:'.strtolower($cB['background_settings']['background_size']).';' : '' )//this is for background size ,( !empty($cB['background_settings']['background_repeat']) ? 'background-repeat:'.strtolower($cB['background_settings']['background_repeat']).';' : '' )//this is for background repeat ,( !empty($cB['background_setting']['background_attachment']) ? 'background-attachment:'.strtolower($cB['background_setting']['background_attachment']).';' : '' )//this is for background attachment ,( !empty($cB['background_setting']['background_origin']) ? 'background-origin:'.strtolower($cB['background_setting']['background_origin']).';' : '' )//this is for background origin ,( !empty($cB['background_setting']['background_clip']) ? 'background-clip:'.strtolower($cB['background_setting']['background_clip']).';' : '' )//this is for background clip ,( !empty($cB['background_setting']['background_color']) ? 'background-color:'.strtolower($cB['background_setting']['background_color']).';' : '' )//this is for background color ,( !empty( $cB['width'] ) ? $cB['width'] : '' ) // container width ,( !empty( $cB['background_color'] ) ? 'hasbg' :'' ) // container has bg color class ,( !empty( $cB['background_color'] ) ? 'background-color:'.$cB['background_color'].';' : '' ) // container bg color style ,( !empty( $cB['foreground_color'] ) ? 'color:'.$cB['foreground_color'].';' : '' ) // container bg color style // post object grid options ,( !empty($cB['heading']) ? '<h2 class=" block__heading site__fade site__fade-up">'.$cB['heading'].'</h2>' : '' ) ,( !empty($cB['text']) ? '<div class="block__details site__fade site__fade-up">'.$cB['text'].'</div>' : '' ) // gallery options ,( !empty($return['tabs']) ? $return['tabs'] : '' ) ,( !empty($return['galleries']) ? $return['galleries'] : '' ) // view all ,( !empty($cB['view_all_button']['link']) ? '<a class="site__button" href="'.$cB['view_all_button']['link']['url'].'">'.$cB['view_all_button']['link']['title'].'</a>' : '' ) ); // echo return string echo $return['section']; // clear the $cB, $return, $index and $guide vars for the next block unset($cB, $return, $guide); ?> <div id="myModal" class="modal"> <span class="close">&times;</span> <img class="modal-content" id="img01"> <div id="caption"></div> </div> <script> // Get the modal var modal = document.getElementById("myModal"); function openimage(url){ // Get the image and insert it inside the modal - use its "alt" text as a caption var modalImg = document.getElementById("img01"); modal.style.display = "block"; modalImg.src = url; } // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } </script><file_sep><?php /** * Contact Block * * */ if( !function_exists('return_column_content') ){ /** * return the content for a column * * @param array $column * @return void */ function return_column_content( $column ){ // reset the column return string $return['column'] = ''; // guide string for a location $guide['locations'] = ' <li class="site__fade site__fade-up"> %s <div> %s %s %s %s %s %s </div> <a class="site__button" href="javascript:;">Directions</a> </li> '; if( !empty($column) ){ // each row in this column (acf flex content layouts) foreach( $column as $row ){ // check which layout this row is switch ($row['acf_fc_layout']) { // this row is a locations block case 'locations': // open the locations wrapper $return['column'] .='<ul class="locations">'; // loop thru location items if( !empty($row['locations']) ){ foreach( $row['locations'] as $location ){ // get this location posts fields $fields = get_fields($location['location']->ID); //echo json_encode($fields['content']['hours_of_op']); // shorten using the address field (bad practice tho) $hours=''; for($i=0;$i<7;$i++){ $hours.=$fields['content']['hours_of_op'][$i]['days'].' '.$fields['content']['hours_of_op'][$i]['opening_hours'].'-'.$fields['content']['hours_of_op'][$i]['closing_hours'].'<br>'; } //echo $hours.'miguel'; $address = ( !empty($fields['content']['address']) ? $fields['content']['address'] : ''); // write this location to the return string for the column $return['column'] .= sprintf( $guide['locations'] ,( !empty($fields['content']['heading']) ? '<h3 class="area__heading">'.$fields['content']['heading'].'</h3>' : '') ,( !empty($address['address_street']) ? '<p class="area__address-1">'.$address['address_street'].'</p>' : '') ,( !empty($address['address_street_2']) ? '<p class="area__address-2">'.$address['address_street_2'].'</p>' : '') ,'<span class="area__city-state-post">'.$address['address_city'] . ', ' . $address['address_state'] . ' ' . $address['address_postcode'].'</span>' ,( !empty($fields['content']['phone_number_1']) ? '<br><a class="area__phone-1" href="tel:'.$fields['content']['phone_number_1'].'"><span>Phone: </span>'.$fields['content']['phone_number_1'].'</a>' : '' ) ,( !empty($fields['content']['phone_number_2']) ? '<br><a class="area__phone-2" href="tel:'.$fields['content']['phone_number_2'].'"><span>Phone: </span>'.$fields['content']['phone_number_2'].'</a>' : '' ) , '<br><span>'.$hours. '</span>' ); } } // close the locations wrapper $return['column'] .= '</ul>'; break; case 'form': $return['column'] .= '<div class="contact__block-form site__fade site__fade-up"><p>Send Us An Email</p>'.do_shortcode('[gravityform id="'.$row['form']['id'].'" title="false" description="false"]').'</div>'; break; default: # code... break; } } } return $return['column']; } } // set return and guide string arrays $return = []; $guide = []; $imagetescontact = get_theme_mod( 'setting_contact_buttom_divider', '' ); $imagetescontact2 = get_theme_mod( 'setting_contact_buttom_divider_top', '' ); // guide string for the section $guide['section'] = ' <section %s class="site__block block__contact" style="%s %s %s %s %s %s %s %s"> <img class="spacerdiviermenutop" src='.'"'. esc_url( $imagetescontact2 ).'"'.'> <div class="container %s %s" style="%s %s"> %s %s <ul class="columns"> <li class="left">%s</li> <li class="right">%s</li> </ul> </div> <img class="spacerdiviermenubottom" src='.'"'. esc_url( $imagetescontact ).'"'.'> </section> '; // if left has rows $return['left'] = ''; $return['right'] = ''; $return['left'] .= return_column_content($cB['left']); $return['right'] .= return_column_content($cB['right']); $return['section'] = ''; // write all the content we can into the opening until the left/right part $return['section'] .= sprintf( $guide['section'] // options for every block ,( !empty($cB['anchor_enabled']) ? 'id="'.strtolower($cB['anchor_link_text']).'"' : '' ) // add an ID tag for the long scroll ,( !empty($cB['background_settings']['background_image']) ? 'background-image:url('."'".strtolower($cB['background_settings']['background_image'])."'".');' : '' )//this is the background image ,( !empty($cB['background_settings']['background_position']) ? 'background-position:'.strtolower($cB['background_settings']['background_position']).';' : '' )//this is for background position ,( !empty($cB['background_settings']['background_size']) ? 'background-size:'.strtolower($cB['background_settings']['background_size']).';' : '' )//this is for background size ,( !empty($cB['background_settings']['background_repeat']) ? 'background-repeat:'.strtolower($cB['background_settings']['background_repeat']).';' : '' )//this is for background repeat ,( !empty($cB['background_setting']['background_attachment']) ? 'background-attachment:'.strtolower($cB['background_setting']['background_attachment']).';' : '' )//this is for background attachment ,( !empty($cB['background_setting']['background_origin']) ? 'background-origin:'.strtolower($cB['background_setting']['background_origin']).';' : '' )//this is for background origin ,( !empty($cB['background_setting']['background_clip']) ? 'background-clip:'.strtolower($cB['background_setting']['background_clip']).';' : '' )//this is for background clip ,( !empty($cB['background_setting']['background_color']) ? 'background-color:'.strtolower($cB['background_setting']['background_color']).';' : '' )//this is for background color ,( !empty( $cB['width'] ) ? $cB['width'] : '' ) // container width ,( !empty( $cB['background_color'] ) ? 'hasbg' :'' ) // container has bg color class ,( !empty( $cB['background_color'] ) ? 'background-color:'.$cB['background_color'].';' : '' ) // container bg color style ,( !empty( $cB['foreground_color'] ) ? 'color:'.$cB['foreground_color'].';' : '' ) // container bg color style // post object grid options ,( !empty($cB['heading']) ? '<h2 class="block__heading site__fade site__fade-up">'.$cB['heading'].'</h2>' : '' ) ,( !empty($cB['text']) ? '<div class="block__details site__fade site__fade-up">'.$cB['text'].'</div>' : '' ) ,$return['left'] ,$return['right'] ); // echo return string echo $return['section']; // clear the $cB, $return and $guide vars unset($cB, $return, $guide); ?> <file_sep><?php /** * Services Block * */ // empty return string $return = []; $return['section'] = ''; $guide = []; $return['services'] ='<ul>'; foreach($cB['services'] as $i => $service) { $fields = get_fields($service['service']->ID); if( $cB['style'] == 'one'){ $guide['services'] = ' <li> <a href="%s"> <div><div class="image '.( ($cB['style'] == 'one') ? 'less_size_block' : '').'" style="background-image:url(%s);"></div></div> <div> %s <div class="service__details block__item-body">%s</div> <p class="service_price">%s</p> </div> </a> </li> '; if( $fields['status'] ){ $return['services'] .= sprintf( $guide['services'] ,get_permalink($service['service']->ID) ,(!empty($fields['image']['url']) ? $fields['image']['url'] : '') ,( !empty($service['service']->post_title ) ? '<h3>'.$service['service']->post_title.'</h3>' : '' ) ,(!empty($fields['details']) ? $fields['details'] : '') ,(!empty($fields['price']) ? $fields['price'] : '') ); } }else if( $cB['style'] == 'three' || $cB['style'] == 'two'){ if($i % 2 == 0){ $guide['services'] = ' <li> <a href="%s"> <div><div class="image '.( ($cB['style'] == 'one') ? 'less_size_block' : '').'" style="background-image:url(%s);"></div></div> <div> %s <div class="service__details block__item-body">%s</div> </div> </a> </li> '; if( $fields['status'] ){ $return['services'] .= sprintf( $guide['services'] ,get_permalink($service['service']->ID) ,(!empty($fields['image']['url']) ? $fields['image']['url'] : '') ,( !empty($service['service']->post_title) ? '<h3><span>'.$service['service']->post_title.'</span><span>'.(!empty($fields['price']) ? ''.$fields['price'] : '').'</span></h3>' : '' ) ,(!empty($fields['details']) ? $fields['details'] : '') ); } }else{ $guide['services'] = ' <li> <a href="%s"> <div> %s <div class="service__details block__item-body">%s</div> </div> <div><div class="image '.( ($cB['style'] == 'one') ? 'less_size_block' : '').'" style="background-image:url(%s);"></div></div> </a> </li> '; if( $fields['status'] ){ $return['services'] .= sprintf( $guide['services'] ,get_permalink($service['service']->ID) ,( !empty($service['service']->post_title) ? '<h3><span>'.$service['service']->post_title.'</span><span>'.(!empty($fields['price']) ? ''.$fields['price'] : '').'</span></h3>' : '' ) ,(!empty($fields['details']) ? $fields['details'] : '') ,(!empty($fields['image']['url']) ? $fields['image']['url'] : '') ); } } } } $return['services'] .= '</ul>'; $imageservice = get_theme_mod( 'setting_services_buttom_divider', '' ); $imageservice2 = get_theme_mod( 'setting_services_buttom_divider_top', '' ); // empty guide string $guide['section'] = ' <section %s class="site__block block__services" style="%s %s %s %s %s %s %s %s"> <img class="spacerdiviermenutop" src='.'"'. esc_url( $imageservice2 ).'"'.'> <div class="container %s %s services__%s" style="%s %s"> %s %s %s %s </div> <img class="spacerdiviermenubottom" src='.'"'. esc_url( $imageservice ).'"'.'> </section> '; $return['section'] .= sprintf( $guide['section'] ,( !empty($cB['anchor_enabled']) ? 'id="'.strtolower($cB['anchor_link_text']).'"' : '' ) // add an ID tag for the long scroll ,( !empty($cB['background_settings']['background_image']) ? 'background-image:url('."'".strtolower($cB['background_settings']['background_image'])."'".');' : '' )//this is the background image ,( !empty($cB['background_settings']['background_position']) ? 'background-position:'.strtolower($cB['background_settings']['background_position']).';' : '' )//this is for background position ,( !empty($cB['background_settings']['background_size']) ? 'background-size:'.strtolower($cB['background_settings']['background_size']).';' : '' )//this is for background size ,( !empty($cB['background_settings']['background_repeat']) ? 'background-repeat:'.strtolower($cB['background_settings']['background_repeat']).';' : '' )//this is for background repeat ,( !empty($cB['background_setting']['background_attachment']) ? 'background-attachment:'.strtolower($cB['background_setting']['background_attachment']).';' : '' )//this is for background attachment ,( !empty($cB['background_setting']['background_origin']) ? 'background-origin:'.strtolower($cB['background_setting']['background_origin']).';' : '' )//this is for background origin ,( !empty($cB['background_setting']['background_clip']) ? 'background-clip:'.strtolower($cB['background_setting']['background_clip']).';' : '' )//this is for background clip ,( !empty($cB['background_setting']['background_color']) ? 'background-color:'.strtolower($cB['background_setting']['background_color']).';' : '' )//this is for background color ,( !empty( $cB['width'] ) ? $cB['width'] : '' ) // container width ,( !empty( $cB['background_color'] ) ? 'hasbg' :'' ) // container has bg color class ,( !empty( $cB['style']) ? $cB['style'] : '') ,( !empty( $cB['background_color'] ) ? 'background-color:'.$cB['background_color'].';' : '' ) // container bg color style ,( !empty( $cB['foreground_color'] ) ? 'color:'.$cB['foreground_color'].';' : '' ) // container bg color style ,( !empty($cB['heading']) ? '<h2 class="block__heading" style="text-align:'.$cB['heading_alignment'].';">'.$cB['heading'].'</h2>' : '' ) ,( !empty($cB['text']) ? '<div class="block__details">'.$cB['text'].'</div>' : '' ) ,( !empty($return['services']) ? '<div '.( ($cB['style'] == 'one') ? 'class="site__grid"' : '').'>'.$return['services'].'</div>' : '' ) ,( !empty($cB['view_all_button']['link']) ? '<a class="site__button" href="'.$cB['view_all_button']['link']['url'].'">'.$cB['view_all_button']['link']['title'].'</a>' : '' ) ); // echo return string echo $return['section']; // clear the $cB, $return, $index and $guide vars for the next block unset($cB, $return, $guide); ?><file_sep><?php /** * Template Name: About Page */ $args = array( 'post_type' => 'staff' ,'posts_per_page' => -1 ); $res = get_posts($args); $fields = get_fields(get_the_ID()); $return['section'] = ''; if( !empty($res) ){ $return['staff'] = '<ul>'; foreach($res as $i => $staff_member){ $staff_fields = get_fields($staff_member->ID); $social_media = ''; if( !empty($staff_fields['social_media']) ){ $social_media .= '<ul class="site__social-media">'; $social_format = ' <li> <a href="%s" title="%s" target="_blank"> %s </a> </li> '; foreach( $staff_fields['social_media']['icons'] as $j => $social_icon ){ $img = $social_icon['image']; $fa = $social_icon['icon']; $url = ( !empty($social_icon['link']['url']) ? $social_icon['link']['url'] : ''); $title = ( !empty($social_icon['link']['title']) ? $social_icon['link']['title'] : ''); if( !empty($social_icon['image']) ){ $social_media .= sprintf( $social_format ,$url ,$title ,( !empty($img['url']) ? '<img src="'.$img['url'].'"/>' : '') ); }else if( !empty($social_icon['icon']) ){ $social_media .= sprintf( $social_format ,$url ,$title ,( !empty($fa) ? $fa : '') ); }else{ $social_media = ''; } } $social_media .= '</ul>'; } if( $fields['style'] == 'one' ){ $guide['staff'] = ' <li class="site__fade site__fade-up"> <a href="%s"> <div class="staff__image"> <div class="image less_size_block site__bgimg_img" style="background-image:url(%s);"></div> </div> <div class="staff__content"> <h3>%s</h3> <div class="staff__details block__item-body">%s</div> </div> </a> <div class="staff__social">%s</div> </li> '; $return['staff'] .= sprintf( $guide['staff'] ,get_permalink( $staff_member->ID) ,( !empty($staff_fields['image']['url']) ? $staff_fields['image']['url'] : '') ,$staff_member->post_title ,( !empty($staff_fields['short_bio']) ? $staff_fields['short_bio'] : '') ,$social_media ); }else if( $fields['style'] == 'two' ){ // style two grid guide string $guide['staff'] = ' <li class="site__fade site__fade-up"> <a href="%s"> <div class="staff__image"> <div class="image site__bgimg_img" style="background-image:url(%s);"></div> </div> </a> <div class="staff__details block__item-body">%s</div> </li> '; // write to return string $return['staff'] .= sprintf( $guide['staff'] ,get_permalink($staff_member->ID) ,( !empty($staff_fields['image']['url'] )? $staff_fields['image']['url'] : '' ) ,( !empty($staff_fields['full_bio']) ? $staff_fields['full_bio'] : '' ) ); } } $return['staff'] .= '</ul>'; // empty guide string $guide['section'] = ' <section class="page__template tpl_page_about"> <div class="container %s"> %s %s </div> </section> '; $return['section'] .= sprintf( $guide['section'] ,( !empty( $fields['width'] ) ? $fields['width'] : '' ) // container width ,( !empty($fields['heading']) ? '<h2 class="block__heading" style="text-align:'.$fields['heading_alignment'].';">'.$fields['heading'].'</h2>' : '' ) ,( !empty($fields['text']) ? '<div class="block__details">'.$fields['text'].'</div>' : '' ) // ,( !empty($return['staff']) ? '<div class="'.( ($fields['style'] == 'one')? 'staff__'.$fields['style'] .' site__grid' : 'staff__'.$fields['style']) .'">'.$return['staff'].'</div>' : '' ) ); } ?> <?php get_header(); ?> <main> <?php include( get_template_directory() . '/parts/part.hero.php'); echo $return['section']; unset($return, $guide); ?> <?php get_footer(); ?><file_sep><?php /** * Heading Content Block * * */ // set return and guide string arrays $return = []; $return['section'] = ''; $guide = []; // build a grid of post objects if( !empty($cB['staff_members']) ){ // set grid return string $return['staff'] = '<ul>'; // loop thru each staff member foreach($cB['staff_members'] as $i => $staff_member) { // get fields for this sttaff member $fields = get_fields($staff_member['staff_member']->ID); $social_media = ''; if( !empty($fields['social_media']) ){ $social_media .= '<ul class="site__social-media">'; $social_format = ' <li> <a href="%s" title="%s" target="_blank"> %s </a> </li> '; foreach( $fields['social_media']['icons'] as $i => $social_icon ){ $img = $social_icon['image']; $fa = $social_icon['icon']; $url = ( !empty($social_icon['link']['url']) ? $social_icon['link']['url'] : '' ); $title = ( !empty($social_icon['link']['title']) ? $social_icon['link']['title'] : '' ); if( !empty($social_icon['image']) ){ $social_media .= sprintf( $social_format ,$url ,$title ,( !empty($img['url']) ? '<img src="'.$img['url'].'" />' : '') ); }else if( !empty($social_icon['icon']) ){ $social_media .= sprintf( $social_format ,$url ,$title ,( !empty($fa) ? $fa : '') ); }else{ $social_media = ''; } } $social_media .= '</ul>'; } if( $cB['style'] == 'one' ){ // style one grid guide string $guide['staff'] = ' <li class="site__fade site__fade-up"> <a href="%s"> <div class="staff__image"> <div class="image less_size_block site__bgimg_img" style="background-image:url(%s);"></div> </div> <div class="staff__content"> <h3>%s</h3> <div class="staff__details block__item-body">%s</div> </div> </a> <div class="staff__social">%s</div> </li> '; // write to return string $return['staff'] .= sprintf( $guide['staff'] ,get_permalink($staff_member['staff_member']->ID) ,( !empty($fields['image']['url'] )? $fields['image']['url'] : '' ) ,$staff_member['staff_member']->post_title ,( !empty($fields['short_bio']) ? $fields['short_bio'] : '' ) ,$social_media ); }else if( $cB['style'] == 'two' ){ // style two grid guide string $guide['staff'] = ' <li class="site__fade site__fade-up"> <a href="%s"> <div> <div class="staff__image"> <div class="image site__bgimg_img" style="background-image:url(%s);"></div> </div> <div class="staff__details block__item-body">%s<br>%s</div> </div> </a> </li> '; // write to return string $return['staff'] .= sprintf( $guide['staff'] ,get_permalink($staff_member['staff_member']->ID) ,( !empty($fields['image']['url'] )? $fields['image']['url'] : '' ) ,$staff_member['staff_member']->post_title ,( !empty($fields['short_bio']) ? $fields['short_bio'] : '' ) ); } } // close grid return string $return['staff'] .= '</ul>'; } $imagetesstaff = get_theme_mod( 'setting_staff_buttom_divider', '' ); $imagetesstaff2 = get_theme_mod( 'setting_staff_buttom_divider_top', '' ); // empty guide string $guide['section'] = ' <section %s class="site__block block__staff" style="%s %s %s %s %s %s %s %s"> <img class="spacerdiviermenutop" src='.'"'. esc_url( $imagetesstaff2 ).'"'.'> <div class="container %s %s" style="%s %s"> %s %s %s %s </div> <img class="spacerdiviermenubottom" src='.'"'. esc_url( $imagetesstaff ).'"'.'> </section> '; $return['section'] .= sprintf( $guide['section'] ,( !empty($cB['anchor_enabled']) ? 'id="'.strtolower($cB['anchor_link_text']).'"' : '' ) // add an ID tag for the long scroll ,( !empty($cB['background_settings']['background_image']) ? 'background-image:url('."'".strtolower($cB['background_settings']['background_image'])."'".');' : '' )//this is the background image ,( !empty($cB['background_settings']['background_position']) ? 'background-position:'.strtolower($cB['background_settings']['background_position']).';' : '' )//this is for background position ,( !empty($cB['background_settings']['background_size']) ? 'background-size:'.strtolower($cB['background_settings']['background_size']).';' : '' )//this is for background size ,( !empty($cB['background_settings']['background_repeat']) ? 'background-repeat:'.strtolower($cB['background_settings']['background_repeat']).';' : '' )//this is for background repeat ,( !empty($cB['background_setting']['background_attachment']) ? 'background-attachment:'.strtolower($cB['background_setting']['background_attachment']).';' : '' )//this is for background attachment ,( !empty($cB['background_setting']['background_origin']) ? 'background-origin:'.strtolower($cB['background_setting']['background_origin']).';' : '' )//this is for background origin ,( !empty($cB['background_setting']['background_clip']) ? 'background-clip:'.strtolower($cB['background_setting']['background_clip']).';' : '' )//this is for background clip ,( !empty($cB['background_setting']['background_color']) ? 'background-color:'.strtolower($cB['background_setting']['background_color']).';' : '' )//this is for background color ,( !empty( $cB['width'] ) ? $cB['width'] : '' ) // container width ,( !empty( $cB['background_color'] ) ? 'hasbg' :'' ) // container has bg color class ,( !empty( $cB['background_color'] ) ? 'background-color:'.$cB['background_color'].';' : '' ) // container bg color style ,( !empty( $cB['foreground_color'] ) ? 'color:'.$cB['foreground_color'].';' : '' ) // container bg color style ,( !empty($cB['heading']) ? '<h2 class="block__heading" style="text-align:'.$cB['heading_alignment'].';">'.$cB['heading'].'</h2>' : '' ) ,( !empty($cB['text']) ? '<div class="block__details">'.$cB['text'].'</div>' : '' ) ,( !empty($cB['view_all_button']['link']) ? '<a class="site__button" href="'.$cB['view_all_button']['link']['url'].'">'.$cB['view_all_button']['link']['title'].'</a><div><br></div>' : '' ) ,( !empty($return['staff']) ? '<div class="'.( ($cB['style'] == 'one')? 'staff__'.$cB['style'] .' site__grid' : 'staff__'.$cB['style']) .'">'.$return['staff'].'</div>' : '' ) ); // echo return string echo $return['section']; // clear the $cB, $return, $index and $guide vars for the next block unset($cB, $return, $guide); ?><file_sep><?php /** * Part: Footer * Description: * logo, company info, address * nav links * payment types * social icons * copyright section */ function get_copyright_banner(){ $return = ''; $field = get_field('footer', 'options'); if( !empty($field['copyright_banner']['text']) ){ $company_name = ( !empty($field['copyright_banner']['text']) ? $field['copyright_banner']['text'] : ''); $format = ' <div class="site__copyright_banner" > <span>Copyright &copy; '.date('Y', time()).' '.$company_name.'</span> %s </div> '; $return .= sprintf( $format ,( !empty($field['copyright_banner']['text']) ? '<a href="'.$field['copyright_banner']['url'].'" target="_blank">Website Created By '.$field['copyright_banner']['text'].'</a>' : '<a href="https://123websites.com" target="_blank">Website Created By 123Websites.com</a>' ) ); } return $return; } function get_payment_types(){ $return = ''; $field = get_field('footer', 'options'); $footer_style = get_field('footer', 'options')['style']; if( !empty($field['payment_types']) ){ $return .= '<div class="footer_payment_types"><ul>'; $format = ' <li>%s</li> '; foreach( $field['payment_types'] as $type ){ $return .= sprintf( $format ,(!empty($type['icon']) ? $type['icon'] : '') ); } $return .= '</ul></div>'; } return $return; } function get_footer_logo(){ $return = ''; $field = get_field('footer', 'options'); if( !empty($field['logo']) ){ $format = ' <a class="site__footer_logo" href="%s" title="%s"> <div style="background-image:url(%s);"></div> </a> '; $return .= sprintf( $format ,site_url() ,( !empty($field['logo']['alt']) ? $field['logo']['alt'] : '') ,$field['logo']['url'] ); } return $return; } function get_company_info(){ $fields = get_field('content_blocks'); if( $fields ): foreach( $fields as $name => $value ): if($value['acf_fc_layout']=='contact_block'){ // if($value['right']['acf_fc_layout']=='locations') $ID=$value['right'][0]['locations'][0]['location']->ID; //echo $ID; $flields2 = get_fields($ID); //echo json_encode($flields2['content']['phone_number_1']); $domicilio= $flields2['content']['address']['address_street'].' '. $flields2['content']['address']['address_city'].' '. $flields2['content']['address']['address_state'].' '. $flields2['content']['address']['address_postcode']; $tel1= $flields2['content']['phone_number_1']; $tel2= $flields2['content']['phone_number_2']; } endforeach; endif; $footer_style = get_field('footer', 'options')['style']; $logo = get_footer_logo(); $address = (!empty($domicilio) ? '<a class="footer_address" href="javascript:;">'.$domicilio.'</a>': ''); $phone_number_1 = (!empty($tel1) ? '<a class="footer_phone_1" href="tel:'.$tel1.'"><span>P:</span> '.$tel1.'</a>': ''); $phone_number_2 =(!empty($tel2) ? '<a class="footer_phone_2" href="tel:'.$tel2.'"><span>F:</span> '.$tel2.'</a>': ''); $format_company_info = ' <div id="footer_company_info"> %s %s %s %s %s %s </div> '; if($footer_style == 'one'){ $format = ' <div id="footer_company_info"> %s %s %s %s </div> '; $company_info = sprintf( $format ,$logo ,$address ,$phone_number_1 ,$phone_number_2 ); }else if($footer_style == 'two'){ $address = ( !empty(get_full_address()) ? '<a class="footer_address" href="javascript:;">'.get_full_address().'</a>' : ''); $format = ' <div id="footer_company_info"> %s %s <div class="last_company_info"> %s %s %s </div> </div> '; $company_info = sprintf( $format ,$logo ,get_nav() ,$address ,$phone_number_1 ,$phone_number_2 ); }else if($footer_style == 'three'){ $address = (!empty(get_full_address()) ? '<a class="footer_address" href="javascript:;">'.get_full_address().'</a>': ''); $format = ' <div id="footer_company_info"> %s %s %s %s %s %s </div> '; $company_info = sprintf( $format ,$logo ,get_nav() ,(!empty(get_social_icons()) ? get_social_icons() : '') ,$address ,$phone_number_1 ,$phone_number_2 ); } return $company_info; } function get_nav(){ $footer_style = get_field('footer', 'options')['style']; $fields = get_fields( get_option('page_on_front') ); $anchor_link_count = 0; $nav = ''; if( !empty($fields['content_blocks']) ){ foreach($fields['content_blocks'] as $i => $block){ if( !empty($block['anchor_link_text']) ){ $anchor_link_count++; } } } if($anchor_link_count > 0){ if($footer_style == 'one'){ $format_nav = ' <div id="footer_nav"> <h3 class="nav_title">Navigate</h3> <nav> %s </nav> </div> '; }else{ $format_nav = ' <div id="footer_nav"> <nav> %s </nav> </div> '; } $nav = sprintf( $format_nav ,get_site_nav() ); } return $nav; } function get_recent_posts(){ $return = ''; $query = new WP_Query(array( 'posts_per_page' => 3, 'nopaging' => true )); $posts = get_posts($query); if(!empty($posts)){ $format = ' <div id="footer_posts"> <h3>Recent Posts</h3> <ul>%s</ul> </div> '; $format_post = ' <li><a href="%s">%s</a></li> '; for($x = 0; $x < 3; $x++){ $the_posts .= sprintf( $format_post ,get_post_permalink($posts[$x]) ,$posts[$x]->post_title ); } $return .= sprintf( $format ,$the_posts ); } return $return; } function get_footer_content(){ $footer_style = get_field('footer', 'options')['style']; $width = get_field('footer', 'options')['width']; if($footer_style == 'one'){ $format_footer_content = ' <div class="container '.$width.'"> %s %s %s <div id="footer_social"> %s </div> </div> <div class="footer_copyright" style=" background-color:'.get_theme_mod( 'background_setting_footercopyright', '#FFFFFF' ).'"> <div class="container '.$width.'"> %s %s </div> </div> '; $return = sprintf( $format_footer_content ,get_company_info() ,get_nav() ,get_recent_posts() ,(!empty(get_social_icons()) ? '<h3>Follow Us</h3>'.get_social_icons():'') ,get_copyright_banner() ,get_payment_types() ); }else if($footer_style == 'two'){ $format_footer_content = ' <div class="container '.$width.'"> %s %s <div class="footer_last_div"> %s <div id="footer_social"> %s </div> </div> </div> '; $return = sprintf( $format_footer_content ,get_company_info() ,get_copyright_banner() ,get_payment_types() ,(!empty(get_social_icons()) ? '<h3>Follow Us</h3>'.get_social_icons():'') ); }else if($footer_style == 'three'){ $format_footer_content = ' <div class="container '.$width.'"> %s %s %s </div> '; $return = sprintf( $format_footer_content ,get_company_info() ,get_copyright_banner() ,get_payment_types() ); } return $return; } ?> <?php ?> </main> <footer class="site__fade site__fade-up colors__main_footer_bg" id="footer_<?php echo get_field('footer', 'options')['style'] ?>"> <?php echo get_footer_content(); // live reload script if (in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1'))) { ?> <script src="//localhost:35729/livereload.js"></script> <?php } wp_footer(); ?> </footer> </body> </html><file_sep><?php $imagemobil= get_theme_mod( 'setting_nav_mobile_image', 'this site does not have mobile' ); $company_info = get_field('company_info','options'); $phone_number_1 = ($company_info['phone_number_1'] ? $company_info['phone_number_1'] : ''); $site__iconlink_phone = ''; if( !empty($phone_number_1) ){ $site__iconlink_phone .= ' <a href="tel:'.$phone_number_1.'" title="" class="site__iconlink site__iconlink-phone">'.$phone_number_1.'</a> '; } $hamburger_icon = '<a href="javascript:;" title="3 Line menu icon button"><span></span><span></span><span></span></a>'; $field_social_icons = $company_info['social_media']; $content_social_icons = ''; if( !empty($field_social_icons) ){ $content_social_icons = '<ul>'; $format_social_icons = ' <li> <a href="%s" title="Social icon button"> %s </a> </li> '; foreach( $field_social_icons as $social_icon ){ $url = $social_icon['url'] ; $img = $social_icon['image']; $fa = $social_icon['icon']; $custom_png_url = ''; // we have a preconfigured URL if( strpos($url, 'booksy') ){ $custom_png_url = get_template_directory_uri() . '/library/img/social_icons/booksy.png'; } if( strpos($url, 'groupon') ){ $custom_png_url = get_template_directory_uri() . '/library/img/social_icons/groupon.png'; } if( strpos($url, 'pinterest') ){ $custom_png_url = get_template_directory_uri() . '/library/img/social_icons/pinterest.png'; } if( !empty($custom_png_url) ){ $icon_url = $custom_png_url; } else { // we have img if( !empty($img) ){ $icon_url = $img; } // img is empty, we have fa else if( !empty($fa) ){ $icon_url = ''; $fa_icon = '<i class="fab '.$fa.'"></i>'; } // img and fa are empty // something went wrong... else { $icon_url = ''; } } if( !empty($url) ){ $content_social_icons .= sprintf( $format_social_icons ,$url ,( !empty($icon_url) ) ? '<img src="'.$icon_url.'">' : $fa_icon ); } } $content_social_icons .= '</ul>'; } $logo_src = wp_get_attachment_image_src(get_theme_mod( 'custom_logo' )); $format_nav_mobile = '<style> @media (max-width: 500px) { .custom-logo { margin-top:15px; max-width:100px;height:auto;object-fit: cover; } section.hero .hero_foreground h1{ text-align: center; }} </style> <header class="mobileheader" id="theme_name_maybe"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <div> %s <center> %s </center> </div> <div class="mobile_header_sidebar"> <nav> %s %s %s </nav> </div> </header> '; $content_nav_mobile = sprintf( $format_nav_mobile ,$hamburger_icon ,get_custom_logo() ,get_site_nav() ,$site__iconlink_phone ,$content_social_icons ); echo $content_nav_mobile; ?><file_sep><?php /** * Partial * Hero Section */ $header = 'header__' . get_field('header', 'options')['style']; // // // Get Foreground $fg = ( !empty($fields['foreground'] ) ? $fields['foreground'] : ''); // options $return['fgbgtint'] = ''; if (!empty($fg['options']['background_tint'])) { $return['fgbgtint'] = ' background-color: rgba(' . hex2rgb($fg['options']['background_tint']) . ',' . $fg['options']['tint_opacity'] . ')'; } // // // FG CONTENT $return['fg_content'] = ''; if( !empty($fg['content']) ){ foreach ($fg['content'] as $row) { // if ($row['acf_fc_layout'] == 'large_text') { // $return['fg_content'] .= '<h1>'.$row['text'].'</h1>'; } // else if ($row['acf_fc_layout'] == 'small_text') { // $return['fg_content'] .= '<p>'.$row['text'].'</p>'; } // else if ($row['acf_fc_layout'] == 'image') { // wrap the image with anchor if link url exists if( !empty($row['url']) ) { $return['fg_content'] .= '<a title="'.$row['url']['title'].'" target="'.$row['url']['target'].'" href="' . $row['url']['url'] . '">'; } $return['fg_content'] .= '<img alt="' . $row['image']['alt'] . '" src="' . $row['image']['url'] . '" />'; if ( !empty($row['url']) ) { $return['fg_content'] .= '</a>'; } } } } // fg button $return['button'] = ''; if (!empty($fg['button']['link']['url'])) { $guide['button'] = ' <a class="site__button" href="%s" style="%s %s" title="%s" target="%s">%s</a> '; $return['button'] = sprintf( $guide['button'], (!empty($fg['button']['link']['url']) ? $fg['button']['link']['url'] : ''), (!empty($fg['button']['foreground_color']) ? 'color:' . $fg['button']['foreground_color'] . ';' : ''), (!empty($fg['button']['background_color']) ? 'background-color:' . $fg['button']['background_color'] . ';' : ''), (!empty($fg['button']['link']['title']) ? $fg['button']['link']['title'] : ''), (!empty($fg['button']['link']['target']) ? $fg['button']['link']['target'] : ''), (!empty($fg['button']['link']['title']) ? $fg['button']['link']['title'] : '') ); } // fg return guide $image = get_theme_mod( 'setting_hero_buttom_divider', '' ); $image2 = get_theme_mod( 'setting_hero_buttom_divider_top', '' ); $divider = get_theme_mod( 'setting_true_false_true1', '' ); if($divider == "ON"){ $guide['fg'] = '<img class="spacerdivier2" src='.'"'. esc_url( $image2 ).'"'.'><div style="height: 100vh;" class="tinto"> <div style="%s %s" class="%s %s hero_foreground" > %s %s </div></div><img class="spacerdivier" src='.'"'. esc_url( $image ).'"'.'> '; }else { $guide['fg'] = ' <style> @media (max-width: 500px) { .imagenlogo { display:none; } } </style> <img class="spacerdivier2" src='.'"'. esc_url( $image2 ).'"'.'><div style="height: 100vh;" class="tinto"> <div style="%s %s" class="%s %s hero_foreground" > %s %s </div></div><img class="spacerdivier imagenlogo" src='.'"'. esc_url( $image ).'"'.'> '; } // fg return string $return['fg'] = sprintf( $guide['fg'] ,$return['fgbgtint'] ,( !empty($fg['options']['foreground_color']) ? 'color:'.$fg['options']['foreground_color'].';' : '') ,( !empty($fg['options']['placement']) ? $fg['options']['placement'] : '') ,( !empty($fg['options']['width']) ? $fg['options']['width'] : '') ,$return['fg_content'] ,$return['button'] ); // // // End Foreground // // // Get Background $bg = (!empty($fields['background']) ? $fields['background'] : ''); $return['bgtint'] = ''; if (!empty($bg['background_tint'])) { $return['bgtint'] = ' background-color: rgba('.hex2rgb($bg['background_tint']).','. $bg['tint_opacity'].')'; } // check bg type $type = $fields['hero_type']; if( $type !== 'none' ){ // open hero container echo '<section class="hero site__fade site__fade-up" id="hero_'.$type.'">'; // static image if( $type == 'image' ){ if($bg['image']['image']['url']=='') $stylo=''; else $stylo= 'style="background-image: url('.$bg['image']['image']['url'].')"'; echo '<div class="image image2"'.$stylo.' >'.$return['fg'].'</div>'; }else if( $type == 'slider' ){ // if ($bg['slider']['randomize']) { shuffle($slider_images); } if (!empty($bg['slider']['images'])) { $slider = '<div id="slick_slider_hero">'; foreach ($bg['slider']['images'] as $i => $image) { $slider .= '<div><img class="slider_img" alt="' . $image['alt'] . '" src="' . $image['url'] . '"></div>'; } $slider .= '</div>'; } echo $return['fg']; echo $slider; }else if( $type == 'video'){ // include(get_template_directory().'/parts/hero/part.hero.video.php'); }else if( $type == 'color' ){ // echo $return['fg']; echo '<div class="hero_bgtint" style="'.$return['bgtint'].'"></div>'; } // close hero container echo '</section>'; } ?><file_sep><!DOCTYPE html> <html prefix="og: http://ogp.me/ns#"> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><?php echo get_bloginfo('name'); ?></title> <?php if (is_single()) : ?> <meta property="og:image" content="<?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>" /> <meta property="og:title" content="<?php the_title(); ?>" /> <meta property="og:site_name" content="<?php echo get_bloginfo('name'); ?>" /> <meta property="og:url" content="<?php global $wp; echo home_url(add_query_arg(array(), $wp->request)); ?>" /> <?php else : ?> <meta property="og:image" content="<?php ?>" /> <meta property="og:title" content="<?php echo get_bloginfo('name'); ?>" /> <meta property="og:site_name" content="<?php echo get_bloginfo('name'); ?>" /> <meta property="og:url" content="<?php global $wp; echo home_url(add_query_arg(array(), $wp->request)); ?>" /> <?php endif; ?> <?php // wp_enqueue_scripts runs on the wp_head hook which is called by wp_head() wp_head(); ?> </head> <?php include_once 'css.php';?> <?php $header = get_field('header', 'options'); $selected_header = 'header__' . $header['style']; $banner_popup_status = ( get_field('popups', 'options')['banner']['status'] == 1 ? 'banner_popup' : '' ); $body_classes = array( (!empty(get_field('header', 'options')['long_scroll']) ? 'js__smoothscroll' : '') ,$selected_header ,$banner_popup_status ); ?> <body <?php body_class($body_classes); ?>> <?php include_once(get_template_directory() . '/parts/popups/popup.loader.php'); include('parts/nav.desktop.php'); include('parts/nav.mobile.php'); /** * Clean Up */ unset($body_classes); ?>
dc7d47a93f325b24e4081339c70530b8c8368454
[ "PHP" ]
16
PHP
40fourth/123_parent
0e78387682af8d7e68b7fa4f8adb2fef5ab7d41a
94ebbabc7776beb460fbb3d526767b36a0debe52
refs/heads/master
<repo_name>baptistemeunier/AttributionEcole<file_sep>/src/Attribution/AttributionHelper.java package Attribution; import java.util.ArrayList; public class AttributionHelper { private ArrayList<GroupeFinal> groupes; public AttributionHelper(ArrayList<GroupeFinal> groupes) { this.groupes = groupes; } public void run() { ArrayList<Integer> indexChoixEcole = new ArrayList<Integer>(); ArrayList<ArrayList<GroupeChoix>> choixEcole = new ArrayList<ArrayList<GroupeChoix>>(); /** Remplisage du tableau de choix ponderée **/ boolean finish = false; int i = 0; while(!finish) { for(int id = 0; id < groupes.size(); id++) { ArrayList<Integer> listes = groupes.get(id).getListechoix(); if(i < listes.size()) { finish = false; int c = listes.get(i); if(c != 0) { if(indexChoixEcole.contains(c)) { // Ajout à la liste de choixEcole choixEcole.get(indexChoixEcole.indexOf(c)).add(new GroupeChoix(id, i)); } else { // Ajout d'un nouveau choixEcole indexChoixEcole.add(c); ArrayList<GroupeChoix> array = new ArrayList<GroupeChoix>(); array.add(new GroupeChoix(id, i)); choixEcole.add(array); } } }else { finish = true; } } i++; } for(i = 0; i < indexChoixEcole.size(); i++) { int minValue = Integer.MAX_VALUE; ArrayList<Integer> g = new ArrayList<Integer>(); for(GroupeChoix gc : choixEcole.get(i)) { if(gc.getPoids() < minValue && groupes.get(gc.getGroupe()).naPasDeChoix()) { minValue = gc.getPoids(); g.clear(); g.add(gc.getGroupe()); }else if(gc.getPoids() == minValue && groupes.get(gc.getGroupe()).naPasDeChoix()) { g.add(gc.getGroupe()); } } if(g.size() > 0) { int rand = (int)(Math.random() * g.size()); groupes.get(g.get(rand)).setChoix(indexChoixEcole.get(i)); } } } } <file_sep>/src/CSVHelper/CSVReaderHelper.java package CSVHelper; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import Attribution.GroupeFinal; public class CSVReaderHelper { public static boolean parse(String filename, ArrayList<GroupeFinal> groupes) throws IOException { String path = CSVReaderHelper.getAbsolutePath(filename); System.out.println("Le chemin source est : " + path); File f = new File(path); readFile(f, groupes); return false; } private static void readFile(File f, ArrayList<GroupeFinal> groupes) throws IOException { FileReader fr = new FileReader(f); BufferedReader buffer = new BufferedReader(fr); buffer.readLine(); for(String line = buffer.readLine(); line != null; line = buffer.readLine()) { ArrayList<Integer> tmp = new ArrayList<Integer>(); String[] col = line.split(","); for(int i = 1; i < col.length; i++) { int n; try { n = Integer.parseInt(col[i]); }catch(Exception e) { n = 0; } tmp.add(n); } groupes.add(new GroupeFinal(col[0], tmp)); } buffer.close(); } private static String getAbsolutePath(String filename) { File f = new File(""); return f.getAbsolutePath() + File.separator + filename; } } <file_sep>/src/Program.java import java.util.ArrayList; import Attribution.AttributionHelper; import Attribution.GroupeFinal; import CSVHelper.CSVReaderHelper; import CSVHelper.CSVWriterHelper; public class Program { public static void main(String[] args) { try { ArrayList<GroupeFinal> groupes = new ArrayList<GroupeFinal>(); /** Lecture du fichier csv **/ CSVReaderHelper.parse("test.csv", groupes); /** Execution de l'algo **/ AttributionHelper ah = new AttributionHelper(groupes); ah.run(); /** Ecriture du fichier csv **/ CSVWriterHelper.write("result.csv", groupes); } catch (Exception e) { System.out.println("Imposible de faire marcher le programme"); e.printStackTrace(); } } } <file_sep>/src/Attribution/GroupeFinal.java package Attribution; import java.util.ArrayList; /** * Permet de representer un couple Groupe/Choix d'école * @author baptiste */ public class GroupeFinal { private String nom; private int choix = -1; private ArrayList<Integer> listechoix; public GroupeFinal(String nom, ArrayList<Integer> liste) { this.nom = nom; this.listechoix = liste; } public GroupeFinal(String nom, Integer choix) { this.nom = nom; this.choix = choix; // TODO Auto-generated constructor stub } /** * @return the nom */ public String getNom() { return nom; } /** * @param nom the nom to set */ public void setNom(String nom) { this.nom = nom; } /** * @return the choix */ public int getChoix() { return choix; } /** * @param choix the choix to set */ public void setChoix(int choix) { this.choix = choix; } public ArrayList<Integer> getListechoix() { return listechoix; } public boolean naPasDeChoix() { return this.choix == -1; } public String toString() { return this.nom + " -> " + this.choix; } } <file_sep>/README.md # AttributionEcole Algorithme permettant de repartir les groupes avec une école ## Exemple de fonctionement * Exporter le fichier tableur (Même disposition que le fichier de test) en CSV. * Placer au même niveau que le .jar * Executée le .jar * Le programme génere un fichier csv avec les groupes et leur école PS: Le fichier test.ods et test.csv sont des modèle à prendre en exemple <file_sep>/src/CSVHelper/CSVWriterHelper.java package CSVHelper; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import Attribution.GroupeFinal; /** * Class qui permet de gérer l'écriture des fichiers .csv * @author baptiste */ public class CSVWriterHelper { /** * Permet d'écrire la liste final des groupes dans un fichier .csv * @param String name Nom du fichier à l'exporation * @param ArrayList<GroupeFinal> attributions Liste des groupes avec leur école * @throws IOException Erreur lorsque qu'il est imposible d'écrire dans le dossier */ public static void write(String name, ArrayList<GroupeFinal> attributions) throws IOException { FileWriter fileWriter = new FileWriter(getAbsolutePath(name)); System.out.println("Le chemin final est : " + getAbsolutePath(name)); /** Ajout de chaque groupe un à un **/ for(GroupeFinal gf: attributions) { fileWriter.append(gf.getNom() + "," + gf.getChoix() + "\n"); } fileWriter.close(); } /** * Permet de récuperer le chemin relatif d'un fichier * @param String filename chemin du fichier en absolue * @return */ private static String getAbsolutePath(String filename) { File f = new File(""); return f.getAbsolutePath() + File.separator + filename; } }
3fc9b2c80bde6444f69af21e7c16aaf95a74158d
[ "Markdown", "Java" ]
6
Java
baptistemeunier/AttributionEcole
ba7ee36876ba49cae17b185f1e86da9373978f6a
e7a532d80ca9eda12578a8418a670c44708b09d6
refs/heads/master
<file_sep>print ("you can print texperiment ") if 43 > 42: print ("print this stmt") #they are lists , not arrays movies = ["list 1", "asdf", "asdf" ] print (movies[1])<file_sep>#Functions def recursive_list_printer(input_list): for each_item in input_list: if isinstance(each_item, list): recursive_list_printer(each_item) else: print(each_item) #single line comment: defining a nested list movies = ["The Holy Grail", 1975, "<NAME> & <NAME>", 91, ["<NAME>", ["<NAME>", "<NAME>","<NAME>", "<NAME>", "<NAME>"]]] """multi line comment This is a multi line comment""" recursive_list_printer(movies)<file_sep>#Module for recursive_list_printer #Functions def recursive_list_printer(input_list): for each_item in input_list: if isinstance(each_item, list): recursive_list_printer(each_item) else: print(each_item)<file_sep>movies = ["The Holy Grail", "The Life of Brian", "The Meaning of Life"] #insert Year before each movie movies.insert(1, 1975) movies.insert(3, 1979) movies.insert(5, 1983) #printing individually #print (movies[0]) #print (movies[1]) #print (movies[2]) #print (movies[3]) #print (movies[4]) #print (movies[5]) #looping ##for for each_movie in movies: print (each_movie) ##while count = 0 while ( count < len(movies) ): print (movies[count]) count = count + 1<file_sep>#Nested Lists movies = ["The Holy Grail", 1975, "<NAME> & <NAME>", 91, ["<NAME>", ["<NAME>", "<NAME>","<NAME>", "<NAME>", "<NAME>"]]] #Print the whole nested list mess #print (movies) for each_item in movies: if isinstance (each_item, list): for each_nest_item in each_item: print (each_nest_item) else: print (each_item)
07c05aace39963a0a93ff517f993e4371b3ef96f
[ "Python" ]
5
Python
JUKE89/PythonLearning
6507dbc98323e9fc17623acd95a3d0b2a8b431e3
d7131a36f1b76c53bb6d450b23a0ad2ee689d2b2
refs/heads/main
<file_sep># sum-of-prime-factors-function Python algorithm for a mathematical iteration problem on prime factors. If n is prime, double n. If n is composite, subtract the sum of the prime factors. Continue this procedure until you reach a cycle or 1. The assumption is that there are no further cycles (except 2,4,...). This algorithm tries to find counterexamples. <file_sep>from sympy import * x = 0 def sum_of_unique_prime_factors(n): divisor = 2 sum = 0 last = 0 while divisor <= n / 2: if (n % divisor) == 0: n = n / divisor if divisor != last: last = divisor sum = sum + divisor else: divisor = divisor + 1 return sum if n == last else sum + n for i in range(6, 20): x = i while x != 1: if not isprime(x): x = x - int(sum_of_unique_prime_factors(x)) else: x = x * 2
46bd1624ef37c75bcf38d0d16433e6953f30f51f
[ "Markdown", "Python" ]
2
Markdown
Django-42/sum-of-prime-factors-function
5fea9bc8e67504822b4b69706f12d31b8c773d26
83235af393eddf494c022944a131ad15cd29ebee
refs/heads/master
<file_sep>## Delta-gamma hedging In this part, I have added gamma hedging. To deploy the strategy, the second option, which pay off is a non-linear function of spot price, is needed. The expected P&L at every portfolio path should be less volatile than in the delta hedging brought in the previous section. As in the previous case, the whole algorithm was ran 10 times, with 4 rehedges intervals (1, 10, 100, 1000) ```{r delta_gamma_hedging3, include=F,eval=TRUE} length_<-1:10 full_results<-c() for(i in length_){ option <- option_simulation() results_tmp<-cbind( results(rehedges_interval=c(1,10,100,1000), state_space_matrix=option, delta_gamma_hedging = TRUE), i) full_results%<>%rbind(results_tmp) } full_results %<>% rename( risk_free_option = Ct, hedged_portfolio_value = pnl, hedged_option_value = value_opt1 ) to_filter <- full_results %>% group_by(i, rehedges_interval) %>% summarize(mean=mean(hedged_portfolio_value))%>% ungroup()%>% filter(between(mean,10,20))%>% mutate(filterr=paste0(i,'_',rehedges_interval))%$%filterr to_filter2<-paste0(full_results$i,'_',full_results$rehedges_interval)[full_results$gamma_to_hedge>quantile(full_results$gamma_to_hedge,0.99)]%>%unique() full_results%<>% mutate(to_filter3=paste0(i,'_',rehedges_interval))%>% filter(to_filter3 %in% to_filter, !(to_filter3 %in% to_filter2)) save(full_results,file='include/full_results_gamma.Rdata') ``` In the following plot, I have included portfolio value as a function of time. The results are more consistent than in the delta hedging case - value of portfolio in all instances smoothly increases over the time. ```{r plot1_gamma, include=TRUE} load(file='include/full_results_gamma.Rdata') full_results%>% ggplot(aes(x=t1-time_to_expiration,y=hedged_portfolio_value,colour=as.factor(i)))+ facet_wrap(~rehedges_interval,scales='free_y')+ geom_line()+ theme_economist()+ labs(x = "Time",y='Portfolio value')+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` Legend: Facets include rehedges interval. Each coloured line represents $i^th$ iteration. X axis shows Time in the range of $<0, 1>$. Y axis shows the hedged portfolio value. I have included the following plot, which includes Gamma Ratio, i.e. a ratio between gamma of the first option and gamma of the second option that I used for calculation. As we can see, as time passes this ratio tends to have more variability. ```{r plot2_gamma, include=TRUE,eval=T} full_results%>% ggplot(aes(x=t1-time_to_expiration, y=gamma_to_hedge, colour=as.factor(i)))+ facet_wrap(~rehedges_interval,scales='free_y')+ geom_line()+ theme_economist()+ labs(x = "Time",y='Value')+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` The next plot shows how 3 different variables, value of the first option, value of the portfolio, and value of the risk-free option, differ. In all cases, it can be clearly seen that portfolio value has no spikes in contrast to hedged option value. ```{r plot3_gamma, include=TRUE,eval=T} full_results%>% filter(i<6)%>% melt(id.vars=c('time_to_expiration','rehedges_interval','i'), measure.vars = c('hedged_option_value','hedged_portfolio_value','risk_free_option'))%>% ggplot(aes(x=t1-time_to_expiration,y=value,colour=variable))+ facet_grid(i~rehedges_interval)+ geom_line()+theme_economist()+ labs(x = "Time",y='Value')+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` Legend: Facets include rehedges interval (horizontally) and a number of simulation (vertically). X axis shows Time in the range of $<0, 1>$. Y axis shows the hedged portfolio value. In the following histogram, I have included $\delta$ P&L for Delta-Gamma Hedging portfolios. They are steeper than in delta hedging portfolios what is consistent with logic. ```{r frequency_plot_gamma, include=TRUE,eval=T} full_results%>% mutate(delta_pnl=round(delta_pnl,2), delta_pnl_f =cut(delta_pnl, breaks = seq(-10,10,by=0.05)))%>% filter(abs(delta_pnl)<=0.3)%>% group_by(rehedges_interval)%>% mutate(noo=n())%>% ungroup()%>% group_by(delta_pnl_f, rehedges_interval)%>% summarize(count=n()/mean(noo))%>% ggplot(aes(x=delta_pnl_f,y=count))+ facet_wrap( ~ rehedges_interval) + geom_bar(stat = 'identity') + #coord_cartesian(xlim=c(-0.10,0.10))+ theme_economist()+ theme(axis.text.x = element_text(angle = 90, hjust = 1))+ labs(x = "Delta P&L", y = 'Frequency') ``` Legend: Facets include rehedges interval. X axis shows $\delta$ PnL on the hedged portfolio. Y axis shows a fraction of all observation in a given bin. Note: Outliers are not included in the following plot. The table below includes all basic statistics for delta P&L I have obtained. ```{r table_of_results_2, include=TRUE, results='asis'} library('knitr') summary_full<-full_results%>% group_by(rehedges_interval)%>% summarize(mean=mean(delta_pnl,na.rm=T)%>%round(4), sd=sd(delta_pnl,na.rm=T)%>%round(4), `0% quantile`=quantile(delta_pnl,0,na.rm=T)%>%round(4), `25% quantile`=quantile(delta_pnl,0.25,na.rm=T)%>%round(4), `50% quantile`=quantile(delta_pnl,0.5,na.rm=T)%>%round(4), `75% quantile`=quantile(delta_pnl,0.75,na.rm=T)%>%round(4), `100% quantile`=quantile(delta_pnl,1,na.rm=T)%>%round(4)) kable(summary_full, format = "latex") ``` <file_sep>--- title: "Dynamic Delta and Delta-Gamma Hedging" author: "<NAME>" date: '2017-06-06' output: pdf_document --- ```{r setup, include=FALSE,eval=TRUE} knitr::opts_chunk$set(echo = FALSE, eval=T, cache = T, include = T) knitr::opts_knit$set(root.dir = normalizePath(".")) if(!'pacman'%in%installed.packages()) install.packages('pacman') require(pacman) p_load( magrittr, ggplot2, plyr, iterators, xts, fOptions, reshape2, devtools, dplyr, ggthemes ) options(scipen=999, digits=10, digit.secs=3) ``` ## Introduction The purpose for this paper was to check in practice how Delta Hedging and Delta-Gamma Hedging work. Specifically, we were obliged to check results with number of rehedges as a variable. The work was fully designed in R environment with use of R Markdown and several other packages, such as ggplot2, plyr, dplyr, and fOptions. The paper is divided into chapters inputs, which contains the data used for the research, Steps, where I describe how I obtained the state space, Delta Hedging, and Delta-Gamma Hedging - in both I present results. ## Inputs I divided inputs into 3 groups - global that consists of variables I use for pricing 2 options and the underlying asset, "First option inputs", which serves as inputs for the hedged option, and "Second option inputs", which serves for option used in Delta-Gamma Hedging. ## Steps The first step to complete the task was to create a data frame with all spot prices for the underlying asset, and values, $\delta$ and $\gamma$ for both options. To simulate spot price I have used Geometric Brownian motion (under Ito's lemma), given by the formula below: $$S_t=S_0\exp((\mu-\frac{\sigma^2}{2})t+\sigma W_t)$$ where: $W_t$ is a Wiener process $\mu$ is the drift $\sigma$ is the volatility The next step was to create the whole space with option values, the Greeks, time to expiration. It all was saved in a dedicated data frame and could be simulated by $option_simulation()$ function. For calculating all option-related values, I have used "fOptions" package. Alternatively, I could have used "RQuantLib" but its results were empirically flawed. After obtaining the base for the actual result calculations, I wrote the function for Delta and Delta-Gamma Hedging. This form was the most convenient one as it can be easily implemented for both problems without retyping all the code. The last step was to apply $results()$ function to both problems. In Delta-Gamma Hedging I received highly ambiguous results, so I tried to test the function on 2 perfectly matched options in terms of all parameters. Results turned out to be as expected. Therefore, I believe my calculations are likely to be correct. ```{r setup2, include=FALSE} # $ # \usepackage{amsmath} S_{t}=S_{0}\timesexp((\mu-\sigma^2/2)t+\sigmaW_{t})$ # Global inputs rf <- 0.05 S01 <- 100 mu1 <- 0.2 #First option inputs K1 <- 100 sigma1 <- 0.2 t1 <- 1 #Second option inputs K2 <- 90 sigma2 <- 0.3 t2 <- 1 dt <- 1 / 999 option_simulation<-function(){ t <- seq(0, t1, by = dt) N <<- length(t) W <- c(0,cumsum(rnorm(N-1))) St <- S01*exp((mu1-sigma1^2/2)*dt + sigma1*sqrt(dt)*W) option<-c() for(i in 1:length(St-1)){ opt<-c() opt<- GBSOption(TypeFlag = "c", S = St[i], X = K1, Time =tmp_t<-t1-t[i], r = rf, b = rf, sigma = sigma1)@price opt_tmp<-aaply(c('delta','gamma'), .margins = 1, .fun=function(x){ GBSGreeks(TypeFlag = 'c', Selection = x, S = St[i], X = K1, Time = (tmp_t <- t1 - t[i]), r = rf, b = rf, sigma = sigma1) }) opt <- cbind(opt, opt_tmp[1], opt_tmp[2]) %>% set_colnames(c('value_opt1','delta_opt1','gamma_opt1')) opt2<-c() opt2 <- GBSOption(TypeFlag = "c", S = St[i], X = K2, Time = (tmp_t2 <- t2 - t[i]), r = rf, b = rf, sigma = sigma2)@price opt2_tmp<-aaply(c('delta','gamma'), .margins=1, .fun=function(x){ GBSGreeks(TypeFlag = 'c', Selection=x, S = St[i], X = K2, Time =(tmp_t2<-t2-t[i]), r = rf, b = rf, sigma = sigma2) }) opt2<-cbind(opt2,opt2_tmp[1],opt2_tmp[2])%>% set_colnames(c('value_opt2','delta_opt2','gamma_opt2')) tmp <- data.frame( opt, opt2, time_to_expiration = tmp_t, time_to_expiration2 = tmp_t2 ) option%<>%rbind(tmp) } option%<>%cbind(St, dCt=c(NA,diff(option$value_opt1)), dCt2=c(NA,diff(option$value_opt2)), dSt=c(NA,diff(St))) option%<>%cbind(no=seq(1:nrow(.))) } ``` ```{r delta_hedging, child='src/delta_hedging.Rmd'} ``` ```{r delta_gamma_hedging, child='src/delta_gamma_hedging.Rmd'} ``` ## Conclusion The paper was to show and test how delta and Delta-Gamma Hedging portfolios perform. Results that I have obtained are consistent with the expectations, though I found out that gamma should not be hedged when time to expiration is close to 0 and option is deep in- or out-of-money. In such a scenario, gamma ratio $(\frac{\gamma_1}{\gamma_2})$, which serve as an indicator as to how much of an option and an underlying asset should be bought to hedge the portfolio, can be too high. This fact implies highly unpredictable results. <file_sep>require(knitr) require(rmarkdown) render('document_rmd.Rmd') <file_sep> ## Delta Hedging After obtaining all needed values, I could start with dynamic Delta Hedging. In the scenario I have used both number of price movements and number of rehedgings vary. I tried to capture how both influences deviations of PnL. It is needed to be added that number (interval) of rehedgings means that every ith observation (row in a data frame) is used to calibrate the delta to hedge. ```{r function_results, include=FALSE} results<-function(rehedges_interval=c(1,5,10,50,100), state_space_matrix=option_simulation(), delta_gamma_hedging=FALSE){ adply(rehedges_interval, .margins=1, .fun=function(y){ share_cost <- rep(0,N) total_cost <- rep(0,N) pnl <-rep(0,N) delta_portfolio<-rep(0,N) delta_of_delta_portfolio<-rep(0,N) # Declaration of variables if(delta_gamma_hedging){ gamma_option_cost <- rep(0, N) delta_of_gamma_portfolio <- rep(0, N) # How much option2 we need at time i gamma_ratio <- (state_space_matrix$gamma_opt1 / state_space_matrix$gamma_opt2) gamma_option_cost[1]<-gamma_ratio[1]*state_space_matrix$value_opt2[1] delta_portfolio[1]<-state_space_matrix$delta_opt1[1]-gamma_ratio[1]*state_space_matrix$delta_opt2[1] }else{ delta_portfolio[1]<-state_space_matrix$delta_opt1[1] } delta_of_delta_portfolio[1]<-0 share_cost[1] <- state_space_matrix$St[1] * delta_portfolio[1] total_cost[1] <- share_cost[1] + ifelse(delta_gamma_hedging, gamma_option_cost[1], 0) pnl[1] <- state_space_matrix$value_opt1[1] - total_cost[1] + share_cost[1] + ifelse(delta_gamma_hedging, gamma_option_cost[1], 0) state_space_matrix%<>%mutate( delta_to_hedge=ifelse(no%%as.numeric(y)==1 | replicate(nrow(state_space_matrix),y)==1, delta_opt1, NA)%>% na.locf(na.rm=F)) if(delta_gamma_hedging){ state_space_matrix%<>%cbind(gamma_ratio) %>% mutate(gamma_to_hedge=ifelse(no%%as.numeric(y)==1 | replicate(nrow(state_space_matrix),y)==1,gamma_ratio, NA)%>% na.locf(na.rm=F)) } for(i in 2:(N)){ if(delta_gamma_hedging){ delta_portfolio[i] <-state_space_matrix$delta_opt1[i] - state_space_matrix$gamma_to_hedge[i] * state_space_matrix$delta_opt2[i] delta_of_gamma_portfolio[i] <-state_space_matrix$gamma_to_hedge[i]-state_space_matrix$gamma_to_hedge[i-1] gamma_option_cost[i] <-delta_of_gamma_portfolio[i] * state_space_matrix$value_opt2[i]+gamma_option_cost[i-1] * exp(rf *dt * t1) delta_of_delta_portfolio[i] <-delta_portfolio[i] - delta_portfolio[i - 1] share_cost[i] <- delta_of_delta_portfolio[i] * state_space_matrix$St[i]+share_cost[i-1]* exp(rf *dt * t1) pnl[i]<-state_space_matrix$value_opt1[i]-delta_portfolio[i]*state_space_matrix$St[i]+share_cost[i]- state_space_matrix$gamma_to_hedge[i]*state_space_matrix$value_opt2[i]+gamma_option_cost[i] }else{ delta_portfolio[i]<-state_space_matrix$delta_to_hedge[i] delta_of_delta_portfolio[i]<-delta_portfolio[i]-delta_portfolio[i-1] share_cost[i]<-delta_of_delta_portfolio[i]*state_space_matrix$St[i]+share_cost[i-1]*exp(rf*dt*t1) pnl[i]<-state_space_matrix$value_opt1[i]-delta_portfolio[i]*state_space_matrix$St[i]+share_cost[i] } } state_space_matrix %<>% mutate( pnl=pnl, rehedges_interval=as.factor(y), share_cost=share_cost, total_cost=total_cost, pnl=pnl, delta_pnl=c(NA,diff(pnl)), Ct=state_space_matrix$value_opt1[1]*exp(rf*(state_space_matrix$no)*dt*t1)#, # gamma_option_cost=gamma_option_cost, # delta_portfolio=delta_portfolio ) return(state_space_matrix) }) } ``` ```{r delta_hedging, include=FALSE,eval=T} length_<-1:10 full_results<-c() for(i in length_){ option<-option_simulation() results_tmp<-cbind(results(rehedges_interval=c(1,10,100,1000), state_space_matrix=option, delta_gamma_hedging = FALSE), i) full_results%<>%rbind(results_tmp) } full_results%<>%rename(risk_free_option=Ct, hedged_portfolio_value=pnl, hedged_option_value=value_opt1) save(full_results,file='include/full_results_delta.Rdata') load(file='include/full_results_delta.Rdata') ``` Two plots are shown below. As we can see, when number of rehedgings increase, results are better, i.e. lines are smoother. It is crucial to mention that difference between value of hedged portfolio against risk-free equivalent comes mostly from the existence of $\gamma$. To polish the strategy, gamma hedging is implemented. ```{r plot1, include=FALSE,cache.vars=T} full_results%>% filter(i<=10)%>% ggplot(aes(x=t1-time_to_expiration,y=hedged_portfolio_value,colour=as.factor(rehedges_interval)))+ facet_wrap(~i)+ geom_line()+ theme_economist()+ labs(x = "Time",y='Portfolio value')+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` ```{r plot5, include=TRUE,cache.vars=T} full_results%>% ggplot(aes(x=t1-time_to_expiration,y=hedged_portfolio_value,colour=as.factor(i)))+ facet_wrap(~rehedges_interval,scales='free_y')+ geom_line()+ theme_economist()+ labs(x = "Time",y='Portfolio value')+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` Legend: Facets include rehedges interval. Each coloured line represents $i^th$ iteration. X axis shows Time in the range of $<0, 1>$. Y axis shows the hedged portfolio value. ```{r plot2, include=TRUE} full_results%>% filter(i<6)%>% melt(id.vars=c('time_to_expiration','rehedges_interval','i'), measure.vars = c('hedged_option_value','hedged_portfolio_value','risk_free_option'))%>% ggplot(aes(x=t1-time_to_expiration,y=value,colour=variable))+ facet_grid(i~rehedges_interval)+ geom_line()+theme_economist()+ labs(x = "Time",y='Value')+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` Legend: Facets include rehedges interval (horizontally) and a number of simulation (vertically). X axis shows Time in the range of $<0, 1>$. Y axis shows the hedged portfolio value. I have included PnLs of every price movement for 10 simulations, all with parametrized rehedges interval (every 1st, 10th, 100th, 1000th), which is shown below. It can be clearly seen that as interval of rehedging decreases, distribution gets steeper. ```{r frequency_plot_delta, include=TRUE} full_results%>% mutate(delta_pnl=round(delta_pnl,2), delta_pnl_f =cut(delta_pnl, breaks = seq(-10,10,by=0.05)))%>% filter(abs(delta_pnl)<=0.4)%>% group_by(rehedges_interval)%>% mutate(noo=n())%>% ungroup()%>% group_by(delta_pnl_f, rehedges_interval)%>% summarize(count=n()/mean(noo))%>% ggplot(aes(x=delta_pnl_f,y=count))+ facet_wrap(~rehedges_interval)+ geom_bar(stat='identity')+ #coord_cartesian(xlim=c(-0.10,0.10))+ theme_economist()+ theme(axis.text.x = element_text(angle = 90, hjust = 1))+ labs(x = "Delta P&L",y='Frequency') ``` Legend: Facets include rehedges interval. X axis shows $\delta$ PnL on the hedged portfolio. Y axis shows a fraction of all observation in a given bin. ```{r table_of_results, include=TRUE, results='asis'} library('knitr') summary_full<-full_results%>% group_by(rehedges_interval)%>% summarize(mean=mean(delta_pnl,na.rm=T)%>%round(4), sd=sd(delta_pnl,na.rm=T)%>%round(4), `0% quantile`=quantile(delta_pnl,0,na.rm=T)%>%round(4), `25% quantile`=quantile(delta_pnl,0.25,na.rm=T)%>%round(4), `50% quantile`=quantile(delta_pnl,0.5,na.rm=T)%>%round(4), `75% quantile`=quantile(delta_pnl,0.75,na.rm=T)%>%round(4), `100% quantile`=quantile(delta_pnl,1,na.rm=T)%>%round(4)) kable(summary_full, format = "latex") ``` <file_sep>--- title: "Dynamic Delta and Delta-Gamma Hedging" author: "<NAME>" date: '2015-01-06' output: pdf_document --- ```{r setup, include=FALSE,eval=TRUE} knitr::opts_chunk$set(echo = FALSE,cache=TRUE) packages_to_install<-c('magrittr','ggplot2','plyr','iterators','xts','fOptions','reshape2','dplyr','ggthemes' )[!c('magrittr','ggplot2','plyr','iterators','xts','fOptions','reshape2','dplyr','ggthemes') %in% installed.packages()] lapply(packages_to_install, FUN=function(x){install.packages(x)}) require(magrittr) require(ggplot2) require(plyr) require(iterators) require(xts) require(fOptions) require(reshape2) require(devtools) require(dplyr) require(ggthemes) ``` ## Introduction The purpose for this paper was to check in practice how Delta Hedging and Delta-Gamma Hedging work. Specifically, we were obliged to check results with number of rehedges as a variable. The work was fully designed in R environment with use of R Markdown and several other packages, such as ggplot2, plyr, dplyr, and fOptions. The paper is divided into chapters inputs, which contains the data used for the research, Steps, where I describe how I obtained the state space, Delta Hedging, and Delta-Gamma Hedging - in both I present results. ## Inputs I divided inputs into 3 groups - global that consists of variables I use for pricing 2 options and the underlying asset, "First option inputs", which serves as inputs for the hedged option, and "Second option inputs", which serves for option used in Delta-Gamma Hedging. ## Steps The first step to complete the task was to create a data frame with all spot prices for the underlying asset, and values, $\delta$ and $\gamma$ for both options. To simulate spot price I have used Geometric Brownian motion (under Ito's lemma), given by the formula below: $$S_t=S_0\exp((\mu-\frac{\sigma^2}{2})t+\sigma W_t)$$ where $W_t$ is a Wiener process $\mu$ ia the drift $\sigma$ is the volatility The next step was to create the whole space with option values, the Greeks, time to expiration. It all was saved in a dedicated data frame and could be simulated by $option_simulation()$ function. For calculating all option-related values, I have used "fOptions" package. Alternatively, I could have used "RQuantLib" but its results were empirically flawed. After obtaining the base for the actual result calculations, I wrote the function for Delta and Delta-Gamma Hedging. This form was the most convenient one as it can be easily implemented for both problems without retyping all the code. The last step was to apply $results()$ function to both problems. In Delta-Gamma Hedging I received highly ambiguous results, so I tried to test the function on 2 perfectly matched options in terms of all parameters. Results turned out to be as expected. Therefore, I believe my calculations are likely to be correct. ```{r setup2, include=FALSE, cache=T, eval=T, echo=FALSE} # $ # \usepackage{amsmath} S_{t}=S_{0}\timesexp((\mu-\sigma^2/2)t+\sigmaW_{t})$ require(magrittr) require(ggplot2) require(plyr) require(iterators) require(xts) require(fOptions) require(reshape2) require(devtools) require(dplyr) require(ggthemes) options(scipen=999, digits=10, digit.secs=3 ) # Global inputs rf<-0.05 S01<-100 mu1<-0.2 #First option inputs K1<-100 sigma1<-0.2 t1<-1 #Second option inputs K2<-90 sigma2<-0.3 t2<-1 dt<-1/999 option_simulation<-function(){ t <- seq(0, t1, by = dt) N <<- length(t) W <- c(0,cumsum(rnorm(N-1))) St <- S01*exp((mu1-sigma1^2/2)*dt + sigma1*sqrt(dt)*W) option<-c() for(i in 1:length(St-1)){ opt<-c() opt<- GBSOption(TypeFlag = "c", S = St[i], X = K1, Time =tmp_t<-t1-t[i], r = rf, b = rf, sigma = sigma1)@price opt_tmp<-aaply(c('delta','gamma'), .margins=1, .fun=function(x){ GBSGreeks(TypeFlag = 'c', Selection=x, S = St[i], X = K1, Time =(tmp_t<-t1-t[i]), r = rf, b = rf, sigma = sigma1) }) opt<-cbind(opt,opt_tmp[1],opt_tmp[2])%>% set_colnames(c('value_opt1','delta_opt1','gamma_opt1')) opt2<-c() opt2<- GBSOption(TypeFlag = "c", S = St[i], X = K2, Time =(tmp_t2<-t2-t[i]), r = rf, b = rf, sigma = sigma2)@price opt2_tmp<-aaply(c('delta','gamma'), .margins=1, .fun=function(x){ GBSGreeks(TypeFlag = 'c', Selection=x, S = St[i], X = K2, Time =(tmp_t2<-t2-t[i]), r = rf, b = rf, sigma = sigma2) }) opt2<-cbind(opt2,opt2_tmp[1],opt2_tmp[2])%>% set_colnames(c('value_opt2','delta_opt2','gamma_opt2')) tmp <- data.frame( opt, opt2, time_to_expiration = tmp_t, time_to_expiration2 = tmp_t2 ) option%<>%rbind(tmp) } option%<>%cbind(St, dCt=c(NA,diff(option$value_opt1)), dCt2=c(NA,diff(option$value_opt2)), dSt=c(NA,diff(St))) option%<>%cbind(no=seq(1:nrow(.))) } ``` ## Delta Hedging After obtaining all needed values, I could start with dynamic Delta Hedging. In the scenario I have used both number of price movements and number of rehedgings vary. I tried to capture how both influences deviations of PnL. It is needed to be added that number (interval) of rehedgings means that every ith observation (row in a data frame) is used to calibrate the delta to hedge. ```{r function_results, echo=FALSE,include=FALSE,cache=TRUE,eval=T} results<-function(rehedges_interval=c(1,5,10,50,100), state_space_matrix=option_simulation(), delta_gamma_hedging=FALSE){ adply(rehedges_interval, .margins=1, .fun=function(y){ share_cost <- rep(0,N) total_cost <- rep(0,N) pnl <-rep(0,N) delta_portfolio<-rep(0,N) delta_of_delta_portfolio<-rep(0,N) # Declaration of variables if(delta_gamma_hedging==TRUE){ gamma_option_cost <- rep(0, N) delta_of_gamma_portfolio <- rep(0, N) gamma_ratio<-(state_space_matrix$gamma_opt1/state_space_matrix$gamma_opt2) # How much option2 we need at time i gamma_option_cost[1]<-gamma_ratio[1]*state_space_matrix$value_opt2[1] delta_portfolio[1]<-state_space_matrix$delta_opt1[1]-gamma_ratio[1]*state_space_matrix$delta_opt2[1] }else{ delta_portfolio[1]<-state_space_matrix$delta_opt1[1] } delta_of_delta_portfolio[1]<-0 share_cost[1]<-state_space_matrix$St[1]*delta_portfolio[1] total_cost[1]<-share_cost[1]+ifelse(delta_gamma_hedging==TRUE,gamma_option_cost[1],0) pnl[1]=state_space_matrix$value_opt1[1]-total_cost[1]+share_cost[1]+ifelse(delta_gamma_hedging==TRUE,gamma_option_cost[1],0) state_space_matrix%<>%mutate( delta_to_hedge=ifelse(no%%as.numeric(y)==1 | replicate(nrow(state_space_matrix),y)==1, delta_opt1, NA)%>% na.locf(na.rm=F) ) if(delta_gamma_hedging==TRUE){ state_space_matrix%<>%cbind(gamma_ratio) state_space_matrix%<>% mutate( gamma_to_hedge=ifelse(no%%as.numeric(y)==1 | replicate(nrow(state_space_matrix),y)==1, gamma_ratio, NA)%>% na.locf(na.rm=F) ) } for(i in 2:(N)){ if(delta_gamma_hedging==TRUE){ delta_portfolio[i] <-state_space_matrix$delta_opt1[i] - state_space_matrix$gamma_to_hedge[i] * state_space_matrix$delta_opt2[i] #delta_of_gamma_portfolio[i] <-state_space_matrix$gamma_opt1[i] - state_space_matrix$gamma_to_hedge[i - 1] * state_space_matrix$gamma_opt2[i] delta_of_gamma_portfolio[i] <-state_space_matrix$gamma_to_hedge[i]-state_space_matrix$gamma_to_hedge[i-1] gamma_option_cost[i] <-delta_of_gamma_portfolio[i] * state_space_matrix$value_opt2[i]+gamma_option_cost[i-1] * exp(rf *dt * t1) delta_of_delta_portfolio[i] <-delta_portfolio[i] - delta_portfolio[i - 1] share_cost[i] <- delta_of_delta_portfolio[i] * state_space_matrix$St[i]+share_cost[i-1]* exp(rf *dt * t1) pnl[i]<-state_space_matrix$value_opt1[i]-delta_portfolio[i]*state_space_matrix$St[i]+share_cost[i]- state_space_matrix$gamma_to_hedge[i]*state_space_matrix$value_opt2[i]+gamma_option_cost[i] }else{ delta_portfolio[i]<-state_space_matrix$delta_to_hedge[i] delta_of_delta_portfolio[i]<-delta_portfolio[i]-delta_portfolio[i-1] share_cost[i]<-delta_of_delta_portfolio[i]*state_space_matrix$St[i]+share_cost[i-1]*exp(rf*dt*t1) pnl[i]<-state_space_matrix$value_opt1[i]-delta_portfolio[i]*state_space_matrix$St[i]+share_cost[i] } } state_space_matrix%<>%mutate( pnl=pnl, rehedges_interval=as.factor(y), share_cost=share_cost, total_cost=total_cost, pnl=pnl, delta_pnl=c(NA,diff(pnl)), Ct=state_space_matrix$value_opt1[1]*exp(rf*(state_space_matrix$no)*dt*t1)#, # gamma_option_cost=gamma_option_cost, # delta_portfolio=delta_portfolio ) return(state_space_matrix) }) } ``` ```{r delta_hedging, echo=FALSE,include=FALSE,cache=TRUE,eval=T} require(magrittr) length_<-1:10 full_results<-c() for(i in length_){ option<-option_simulation() results_tmp<-cbind(results(rehedges_interval=c(1,10,100,1000), state_space_matrix=option, delta_gamma_hedging = FALSE), i) full_results%<>%rbind(results_tmp) } full_results%<>% rename(risk_free_option=Ct, hedged_portfolio_value=pnl, hedged_option_value=value_opt1) save(full_results,file='include/full_results_delta.Rdata') load(file='include/full_results_delta.Rdata') ``` Two plots are shown below. As we can see, when number of rehedgings increase, results are better, i.e. lines are smoother. It is crucial to mention that difference between value of hedged portfolio against risk-free equivalent comes mostly from the existence of $\gamma$. To polish the strategy, gamma hedging is implemented. ```{r plot1, echo=FALSE,include=FALSE,eval=T,cache=TRUE,cache.vars=T} full_results%>% filter(i<=10)%>% ggplot(aes(x=t1-time_to_expiration,y=hedged_portfolio_value,colour=as.factor(rehedges_interval)))+ facet_wrap(~i)+ geom_line()+ theme_economist()+ labs(x = "Time",y='Portfolio value')+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` ```{r plot5, echo=FALSE,include=TRUE,eval=T,cache=TRUE,cache.vars=T} full_results%>% ggplot(aes(x=t1-time_to_expiration,y=hedged_portfolio_value,colour=as.factor(i)))+ facet_wrap(~rehedges_interval,scales='free_y')+ geom_line()+ theme_economist()+ labs(x = "Time",y='Portfolio value')+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` Legend: Facets include rehedges interval. Each coloured line represents $i^th$ iteration. X axis shows Time in the range of $<0, 1>$. Y axis shows the hedged portfolio value. ```{r plot2, echo=FALSE,include=TRUE,eval=T,cache=T} full_results%>% filter(i<6)%>% melt(id.vars=c('time_to_expiration','rehedges_interval','i'), measure.vars = c('hedged_option_value','hedged_portfolio_value','risk_free_option'))%>% ggplot(aes(x=t1-time_to_expiration,y=value,colour=variable))+ facet_grid(i~rehedges_interval)+ geom_line()+theme_economist()+ labs(x = "Time",y='Value')+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` Legend: Facets include rehedges interval (horizontally) and a number of simulation (vertically). X axis shows Time in the range of $<0, 1>$. Y axis shows the hedged portfolio value. I have included PnLs of every price movement for 10 simulations, all with parametrized rehedges interval (every 1st, 10th, 100th, 1000th), which is shown below. It can be clearly seen that as interval of rehedging decreases, distribution gets steeper. ```{r frequency_plot_delta, echo=FALSE,include=TRUE,eval=TRUE,cache=TRUE} full_results%>% mutate(delta_pnl=round(delta_pnl,2), delta_pnl_f =cut(delta_pnl, breaks = seq(-10,10,by=0.05)))%>% filter(abs(delta_pnl)<=0.4)%>% group_by(rehedges_interval)%>% mutate(noo=n())%>% ungroup()%>% group_by(delta_pnl_f, rehedges_interval)%>% summarize(count=n()/mean(noo))%>% ggplot(aes(x=delta_pnl_f,y=count))+ facet_wrap(~rehedges_interval)+ geom_bar(stat='identity')+ #coord_cartesian(xlim=c(-0.10,0.10))+ theme_economist()+ theme(axis.text.x = element_text(angle = 90, hjust = 1))+ labs(x = "Delta P&L",y='Frequency') ``` Legend: Facets include rehedges interval. X axis shows $\delta$ PnL on the hedged portfolio. Y axis shows a fraction of all observation in a given bin. ```{r table_of_results, echo=FALSE,include=TRUE,eval=TRUE,cache=TRUE} library('knitr') summary_full<-full_results%>% group_by(rehedges_interval)%>% summarize(mean=mean(delta_pnl,na.rm=T)%>%round(4), sd=sd(delta_pnl,na.rm=T)%>%round(4), `0% quantile`=quantile(delta_pnl,0,na.rm=T)%>%round(4), `25% quantile`=quantile(delta_pnl,0.25,na.rm=T)%>%round(4), `50% quantile`=quantile(delta_pnl,0.5,na.rm=T)%>%round(4), `75% quantile`=quantile(delta_pnl,0.75,na.rm=T)%>%round(4), `100% quantile`=quantile(delta_pnl,1,na.rm=T)%>%round(4)) kable(summary_full, format = "latex") ``` ## Delta-gamma hedging In this part, I have added gamma hedging. To deploy the strategy, the second option, which pay off is a non-linear function of spot price, is needed. The expected P&L at every portfolio path should be less volatile than in the delta hedging brought in the previous section. As in the previous case, the whole algorithm was ran 10 times, with 4 rehedges intervals (1, 10, 100, 1000) ```{r delta_gamma_hedging3, echo=FALSE,cache=TRUE,include=F,eval=TRUE} length_<-1:10 full_results<-c() for(i in length_){ option<-option_simulation() results_tmp<-cbind(results(rehedges_interval=c(1,10,100,1000), state_space_matrix=option, delta_gamma_hedging = TRUE), i) full_results%<>%rbind(results_tmp) } full_results%<>%rename(risk_free_option=Ct, hedged_portfolio_value=pnl, hedged_option_value=value_opt1) to_filter<-full_results%>%group_by(i,rehedges_interval)%>% summarize(mean=mean(hedged_portfolio_value))%>% ungroup()%>% filter(between(mean,10,20))%>% mutate(filterr=paste0(i,'_',rehedges_interval))%$%filterr to_filter2<-paste0(full_results$i,'_',full_results$rehedges_interval)[full_results$gamma_to_hedge>quantile(full_results$gamma_to_hedge,0.99)]%>%unique() full_results%<>% mutate(to_filter3=paste0(i,'_',rehedges_interval))%>% filter(to_filter3 %in% to_filter, !(to_filter3 %in% to_filter2)) save(full_results,file='include/full_results_gamma.Rdata') ``` In the following plot, I have included portfolio value as a function of time. The results are more consistent than in the delta hedging case - value of portfolio in all instances smoothly increases over the time. ```{r plot1_gamma, echo=FALSE,eval=T,cache=TRUE} load(file='include/full_results_gamma.Rdata') full_results%>% ggplot(aes(x=t1-time_to_expiration,y=hedged_portfolio_value,colour=as.factor(i)))+ facet_wrap(~rehedges_interval,scales='free_y')+ geom_line()+ theme_economist()+ labs(x = "Time",y='Portfolio value')+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` Legend: Facets include rehedges interval. Each coloured line represents $i^th$ iteration. X axis shows Time in the range of $<0, 1>$. Y axis shows the hedged portfolio value. I have included the following plot, which includes Gamma Ratio, i.e. a ratio between gamma of the first option and gamma of the second option that I used for calculation. As we can see, as time passes this ratio tends to have more variability. ```{r plot2_gamma, echo=FALSE,include=TRUE,eval=T} full_results%>% ggplot(aes(x=t1-time_to_expiration, y=gamma_to_hedge, colour=as.factor(i)))+ facet_wrap(~rehedges_interval,scales='free_y')+ geom_line()+ theme_economist()+ labs(x = "Time",y='Value')+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` The next plot shows how 3 different variables, value of the first option, value of the portfolio, and value of the risk-free option, differ. In all cases, it can be clearly seen that portfolio value has no spikes in contrast to hedged option value. ```{r plot3_gamma, echo=FALSE,eval=T} full_results%>% filter(i<6)%>% melt(id.vars=c('time_to_expiration','rehedges_interval','i'), measure.vars = c('hedged_option_value','hedged_portfolio_value','risk_free_option'))%>% ggplot(aes(x=t1-time_to_expiration,y=value,colour=variable))+ facet_grid(i~rehedges_interval)+ geom_line()+theme_economist()+ labs(x = "Time",y='Value')+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` Legend: Facets include rehedges interval (horizontally) and a number of simulation (vertically). X axis shows Time in the range of $<0, 1>$. Y axis shows the hedged portfolio value. In the following histogram, I have included $\delta$ P&L for Delta-Gamma Hedging portfolios. They are steeper than in delta hedging portfolios what is consistent with logic. ```{r frequency_plot_gamma, echo=FALSE,include=TRUE,eval=T} full_results%>% mutate(delta_pnl=round(delta_pnl,2), delta_pnl_f =cut(delta_pnl, breaks = seq(-10,10,by=0.05)))%>% filter(abs(delta_pnl)<=0.3)%>% group_by(rehedges_interval)%>% mutate(noo=n())%>% ungroup()%>% group_by(delta_pnl_f, rehedges_interval)%>% summarize(count=n()/mean(noo))%>% ggplot(aes(x=delta_pnl_f,y=count))+ facet_wrap(~rehedges_interval)+ geom_bar(stat='identity')+ #coord_cartesian(xlim=c(-0.10,0.10))+ theme_economist()+ theme(axis.text.x = element_text(angle = 90, hjust = 1))+ labs(x = "Delta P&L",y='Frequency') ``` Legend: Facets include rehedges interval. X axis shows $\delta$ PnL on the hedged portfolio. Y axis shows a fraction of all observation in a given bin. Note: Outliers are not included in the following plot. The table below includes all basic statistics for delta P&L I have obtained. ```{r table_of_results_2, echo=FALSE,include=TRUE,eval=T,cache=TRUE} library('knitr') summary_full<-full_results%>% group_by(rehedges_interval)%>% summarize(mean=mean(delta_pnl,na.rm=T)%>%round(4), sd=sd(delta_pnl,na.rm=T)%>%round(4), `0% quantile`=quantile(delta_pnl,0,na.rm=T)%>%round(4), `25% quantile`=quantile(delta_pnl,0.25,na.rm=T)%>%round(4), `50% quantile`=quantile(delta_pnl,0.5,na.rm=T)%>%round(4), `75% quantile`=quantile(delta_pnl,0.75,na.rm=T)%>%round(4), `100% quantile`=quantile(delta_pnl,1,na.rm=T)%>%round(4)) kable(summary_full, format = "latex") ``` ## Conclusion The paper was to show and test how delta and Delta-Gamma Hedging portfolios perform. Results that I have obtained are consistent with the expectations, though I found out that gamma should not be hedged when time to expiration is close to 0 and option is deep in- or out-of-money. In such a scenario, gamma ratio $(\frac{\gamma_1}{\gamma_2})$, which serve as an indicator as to how much of an option and an underlying asset should be bought to hedge the portfolio, can be too high. This fact implies highly unpredictable results.
820f13c206a54820e7bb183d2e896996ed533198
[ "R", "RMarkdown" ]
5
RMarkdown
kwojdalski/option_pricing
7bb2cc5a44649e08fbe213d60c821079c815ed03
3d5320004d042deb6b026dfa231cc3a01d90a79f
refs/heads/master
<repo_name>ErnestoDavidOlivaPerez/el-senor-de-los-anillos<file_sep>/src/main/resources/strings_en.properties new = New Game load = Load language = Language exit = Exit back = Back cancel = Cancel quest = Do you want to overwrite this game? information = Saved progress will be permanently lost game_save = Saved Games spanish = Spanish english = English french = French exit! = Back! sure = Are you sure you want to exit? yes = YES no! = NO!!! name = Name: type = Type: life = Life: armor = Armor: add = Add heroes = Heroes beast = Beasts up = Up down = Down delete = Delete orc = Orc goblin = Goblin elf = Elf hobbit = Hobbit human = Humans life2 = Life armor2 = Armor fight = ˇFIGHT! fight2 = fight between out = scores and_remove = and takes of_life = of life from death = Go Dead! victory_hero = Heroes Victory!! victory_beast = Beasts Victory!! ok = OK want_exit = Do you want to exit to the Main Menu? progress_save = Progress will be saved (: turn = Turn : and = and <file_sep>/src/main/java/com/tokioschool/util/EffectUtil.java package com.tokioschool.util; import javafx.scene.effect.Bloom; import javafx.scene.effect.Reflection; public class EffectUtil { public static Bloom getBloom(double threshold){ Bloom bloom = new Bloom(); bloom.setThreshold(threshold); return bloom; } public static Reflection getReflection(double bottomOpacity, double fraction){ Reflection reflection = new Reflection(); reflection.setBottomOpacity(bottomOpacity); reflection.setFraction(fraction); return reflection; } } <file_sep>/src/main/java/com/tokioschool/database/AppModel.java package com.tokioschool.database; import com.tokioschool.domain.Beast; import com.tokioschool.domain.Hero; import com.tokioschool.util.Filter; import java.io.File; import java.sql.*; import java.util.ArrayList; import java.util.List; public class AppModel { private final String dbName1 = "save1.db"; private final String dbName2 = "save2.db"; private final String dbName3 = "save3.db"; private final String dbLanguage = "language.db"; private int save; private final String contain = "saves"; private Connection connection; private final String sqliteServer = "jdbc:sqlite:"; public AppModel(){ } public void connect() { if (!new File(contain + File.separator + dbLanguage).exists()){ File file = new File(contain); file.mkdir(); try { connection = DriverManager.getConnection(sqliteServer + contain + File.separator + dbLanguage); createTableLanguage(); } catch (SQLException sqlException) { sqlException.printStackTrace(); } } switch (save){ case 1: File myDataBase = new File(contain + File.separator + dbName1); if (myDataBase.exists()) { try { connection = DriverManager.getConnection(sqliteServer + contain + File.separator + dbName1); } catch (SQLException sqle) { sqle.printStackTrace(); } } else { try { connection = DriverManager.getConnection(sqliteServer + contain + File.separator + dbName1); createTableHero(); createTableBeast(); createTableName(); createTableTurn(); } catch (SQLException sqle) { sqle.printStackTrace(); } } break; case 2: myDataBase = new File(contain + File.separator + dbName2); if (myDataBase.exists()) { try { connection = DriverManager.getConnection(sqliteServer + contain + File.separator + dbName2); } catch (SQLException sqle) { sqle.printStackTrace(); } } else { try { connection = DriverManager.getConnection(sqliteServer + contain + File.separator + dbName2); createTableHero(); createTableBeast(); createTableName(); createTableTurn(); } catch (SQLException sqle) { sqle.printStackTrace(); } } break; case 3: myDataBase = new File(contain + File.separator + dbName3); if (myDataBase.exists()) { try { connection = DriverManager.getConnection(sqliteServer + contain + File.separator + dbName3); } catch (SQLException sqle) { sqle.printStackTrace(); } } else { try { connection = DriverManager.getConnection(sqliteServer + contain + File.separator + dbName3); createTableHero(); createTableBeast(); createTableName(); createTableTurn(); } catch (SQLException sqle) { sqle.printStackTrace(); } } break; } } public void disconnect(){ try { connection.close(); } catch (SQLException sqlException) { sqlException.printStackTrace(); } } public void createTableHero(){ String sql = "CREATE TABLE hero(name TEXT, armor INT, life INT, type TEXT, pos INT)"; try { PreparedStatement statement = connection.prepareStatement(sql); statement.execute(); } catch (SQLException throwables) { throwables.printStackTrace(); } } public void createTableBeast(){ String sql = "CREATE TABLE beast(name TEXT, armor INT, life INT, type TEXT, pos INT)"; try { PreparedStatement statement = connection.prepareStatement(sql); statement.execute(); } catch (SQLException throwables) { throwables.printStackTrace(); } } public void createTableName(){ String sql = "CREATE TABLE name(name Text)"; try { PreparedStatement statement = connection.prepareStatement(sql); statement.execute(); }catch (SQLException throwables){ throwables.printStackTrace(); } } public void createTableTurn(){ String sql = "CREATE TABLE turn(turn INT)"; try { PreparedStatement statement = connection.prepareStatement(sql); statement.execute(); } catch (SQLException sqlException) { sqlException.printStackTrace(); } } public void createTableLanguage(){ String sql = "CREATE TABLE language(language text)"; try { PreparedStatement statement = connection.prepareStatement(sql); statement.execute(); saveLanguage("es"); } catch (SQLException sqlException) { sqlException.printStackTrace(); } } public void addHero(Hero hero) throws SQLException { String sql = "INSERT INTO hero(name, armor, life, type, pos) VALUES (?, ?, ?, ?, ?)"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, hero.getName()); statement.setInt(2, hero.getArmor()); statement.setInt(3, hero.getLife()); statement.setString(4, hero.getType().getType()); statement.setInt(5, hero.getPos()); statement.executeUpdate(); } public void addBeast(Beast beast) throws SQLException{ String sql = "INSERT INTO beast(name, armor, life, type, pos) VALUES (?, ?, ?, ?, ?)"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, beast.getName()); statement.setInt(2, beast.getArmor()); statement.setInt(3, beast.getLife()); statement.setString(4, beast.getType().getType()); statement.setInt(5, beast.getPos()); statement.executeUpdate(); } public List<Hero> getHeroes() throws SQLException { List<Hero> heroes = new ArrayList<>(); String sql = "SELECT * FROM hero ORDER BY pos"; PreparedStatement statement = connection.prepareStatement(sql); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()){ if (Filter.getHeroTypeFromComboBox(resultSet.getString(4)) != null){ Hero hero = new Hero(); hero.setName(resultSet.getString(1)); hero.setArmor(resultSet.getInt(2)); hero.setLife(resultSet.getInt(3)); hero.setType(Filter.getHeroTypeFromComboBox(resultSet.getString(4))); hero.setPos(resultSet.getInt(5)); heroes.add(hero); } } return heroes; } public List<Beast> getBeast() throws SQLException{ List<Beast> beasts = new ArrayList<>(); String sql = "SELECT * FROM beast ORDER BY pos"; PreparedStatement statement = connection.prepareStatement(sql); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()){ if (Filter.getBeastTypeFromComboBox(resultSet.getString(4)) != null){ Beast beast = new Beast(); beast.setName(resultSet.getString(1)); beast.setArmor(resultSet.getInt(2)); beast.setLife(resultSet.getInt(3)); beast.setType(Filter.getBeastTypeFromComboBox(resultSet.getString(4))); beast.setPos(resultSet.getInt(5)); beasts.add(beast); } } return beasts; } public String getName() throws SQLException{ String name = ""; String sql = "SELECT * FROM name"; PreparedStatement statement = connection.prepareStatement(sql); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()){ name = resultSet.getString(1); } return name; } public int getTurn() throws SQLException{ int turn = 1; String sql = "SELECT * FROM turn"; PreparedStatement statement = connection.prepareStatement(sql); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()){ turn = resultSet.getInt(1); } return turn; } public String getLanguage() throws SQLException{ connection = DriverManager.getConnection(sqliteServer + contain + File.separator + dbLanguage); String sql = "SELECT * FROM language"; PreparedStatement statement = connection.prepareStatement(sql); ResultSet resultSet = statement.executeQuery(); String language = null; while (resultSet.next()){ language = resultSet.getString(1); } return language; } public void save(List<Hero> heroes, List<Beast> beasts) throws SQLException{ String sqlRefresh = "DELETE FROM hero"; PreparedStatement statement = connection.prepareStatement(sqlRefresh); statement.executeUpdate(); sqlRefresh = "DELETE FROM beast"; statement = connection.prepareStatement(sqlRefresh); statement.execute(); heroes.forEach(hero -> { try { addHero(hero); } catch (SQLException sqlException) { sqlException.printStackTrace(); } }); beasts.forEach(beast -> { try { addBeast(beast); } catch (SQLException sqlException){ sqlException.printStackTrace(); } }); } public void saveName(String name) throws SQLException{ String sqlRefresh = "DELETE FROM name"; PreparedStatement statement = connection.prepareStatement(sqlRefresh); statement.executeUpdate(); String sql = "INSERT INTO name(name) VALUES(?)"; statement = connection.prepareStatement(sql); statement.setString(1, name); statement.executeUpdate(); } public void saveTurn(int turn) throws SQLException{ String sqlRefresh = "DELETE FROM turn"; PreparedStatement statement = connection.prepareStatement(sqlRefresh); statement.executeUpdate(); String sql = "INSERT INTO turn(turn) VALUES(?)"; statement = connection.prepareStatement(sql); statement.setInt(1, turn); statement.executeUpdate(); } public void saveLanguage(String language) throws SQLException{ connection = DriverManager.getConnection(sqliteServer + contain + File.separator + dbLanguage); String sql = "DELETE FROM language"; PreparedStatement statement = connection.prepareStatement(sql); statement.execute(); sql = "INSERT INTO language(language) VALUES (?)"; statement = connection.prepareStatement(sql); statement.setString(1, language); statement.executeUpdate(); } public void reset() throws SQLException{ String sql = "DELETE FROM hero"; PreparedStatement statement = connection.prepareStatement(sql); statement.executeUpdate(); sql = "DELETE FROM beast"; statement = connection.prepareStatement(sql); statement.executeUpdate(); sql = "DELETE FROM name"; statement = connection.prepareStatement(sql); statement.executeUpdate(); sql = "DELETE FROM turn"; statement = connection.prepareStatement(sql); statement.executeUpdate(); } public void setSave(int save){ this.save = save; } public boolean isConnect(){ return new File(contain + File.separator + dbName1).exists() || new File(contain + File.separator + dbName2).exists() || !new File(contain + File.separator + dbName3).exists(); } public boolean isSave1(){ return new File(contain + File.separator + dbName1).exists(); } public boolean isSave2(){ return new File(contain + File.separator + dbName2).exists(); } public boolean isSave3(){ return new File(contain + File.separator + dbName3).exists(); } public boolean isLanguage(){return new File(contain + File.separator + dbLanguage).exists();} } <file_sep>/src/main/java/com/tokioschool/util/BorderUtil.java package com.tokioschool.util; import javafx.scene.layout.*; import javafx.scene.paint.Color; public class BorderUtil { public static Border getBlack(){ return new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, new CornerRadii(15), new BorderWidths(3))); } } <file_sep>/src/main/java/com/tokioschool/components/game/listeners/AppGameActionEvent.java package com.tokioschool.components.game.listeners; import com.tokioschool.AppView; import com.tokioschool.database.AppModel; import com.tokioschool.domain.BeastType; import com.tokioschool.domain.HeroType; import com.tokioschool.domain.Beast; import com.tokioschool.domain.Hero; import com.tokioschool.util.Filter; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.text.Font; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; public class AppGameActionEvent implements EventHandler<ActionEvent> { private final AppView view; private final AppModel model; private final ResourceBundle res; public AppGameActionEvent(AppView view, AppModel model, ResourceBundle res){ this.view = view; this.model = model; this.res = res; } @Override public void handle(ActionEvent actionEvent) { Node node = (Node) actionEvent.getSource(); String userData = node.getUserData().toString(); switch (userData){ case "heroAddButton": String name = view.getAppGameHeroes().getTfName().getText(); int armor = (int) view.getAppGameHeroes().getSliderArmorValue(); int life = (int) view.getAppGameHeroes().getSliderLifeValue(); HeroType heroType = Filter.getHeroTypeFromComboBox(view.getAppGameHeroes().getComboType()); int pos = view.getAppGameHeroes().getListView().getItems().size(); Hero hero = new Hero(); hero.setName(name); hero.setArmor(armor); hero.setLife(life); hero.setType(heroType); hero.setPos(pos); hero.setRes(res); HeroType.HUMAN.refreshLanguage(res); Label label = new Label(hero.toString()); label.setFont(new Font(20)); view.getAppGameHeroes().getListView().getItems().add(label); view.getAppGameHeroes().getListView().getHeroPosDTOS().add(hero); if (!view.getAppGameHeroes().getListView().getItems().isEmpty() && !view.getAppGameBeast().getListView().getItems().isEmpty()) view.getAppGameContainer().getAppGameFight().getFight().setDisable(false); break; case "beastAddButton": name = view.getAppGameBeast().getTfName().getText(); armor = (int) view.getAppGameBeast().getSliderArmorValue(); life = (int) view.getAppGameBeast().getSliderLifeValue(); BeastType beastType = Filter.getBeastTypeFromComboBox(view.getAppGameBeast().getComboType()); pos = view.getAppGameBeast().getListView().getItems().size(); Beast beast = new Beast(); beast.setName(name); beast.setArmor(armor); beast.setLife(life); beast.setType(beastType); beast.setPos(pos); beast.setRes(res); BeastType.GOBLIN.refreshLanguage(res); label = new Label(beast.toString()); label.setFont(new Font(20)); view.getAppGameBeast().getListView().getItems().add(label); view.getAppGameBeast().getListView().getBeastPosDTOS().add(beast); if (!view.getAppGameHeroes().getListView().getItems().isEmpty() && !view.getAppGameBeast().getListView().getItems().isEmpty()) view.getAppGameContainer().getAppGameFight().getFight().setDisable(false); break; case "heroUp": if (view.getAppGameHeroes().getListView().getSelectionModel().getSelectedIndex() > 0){ label = view.getAppGameHeroes().getListView().getSelectionModel().getSelectedItem(); int oldIndex = view.getAppGameHeroes().getListView().getSelectionModel().getSelectedIndex(); int newIndex = oldIndex - 1; ObservableList<Label> observableList = view.getAppGameHeroes().getListView().getItems(); observableList.remove(oldIndex); hero = view.getAppGameHeroes().getListView().getHeroPosDTOS().remove(oldIndex); hero.setPos(newIndex); view.getAppGameHeroes().getListView().getHeroPosDTOS().add(hero.getPos(), hero); label.setText(hero.toString()); observableList.add(newIndex, label); label = view.getAppGameHeroes().getListView().getItems().get(oldIndex); hero = view.getAppGameHeroes().getListView().getHeroPosDTOS().get(oldIndex); hero.setPos(oldIndex); label.setText(hero.toString()); view.getAppGameHeroes().getListView().requestFocus(); view.getAppGameHeroes().getListView().getSelectionModel().select(newIndex); view.getAppGameHeroes().getListView().getFocusModel().focus(newIndex); view.getAppGameHeroes().getListView().scrollTo(newIndex); } break; case "heroDown": if (view.getAppGameHeroes().getListView().getSelectionModel().getSelectedIndex() < view.getAppGameHeroes().getListView().getItems().size() - 1){ label = view.getAppGameHeroes().getListView().getSelectionModel().getSelectedItem(); int oldIndex = view.getAppGameHeroes().getListView().getSelectionModel().getSelectedIndex(); int newIndex = oldIndex + 1; ObservableList<Label> observableList = view.getAppGameHeroes().getListView().getItems(); observableList.remove(oldIndex); hero = view.getAppGameHeroes().getListView().getHeroPosDTOS().remove(oldIndex); hero.setPos(newIndex); view.getAppGameHeroes().getListView().getHeroPosDTOS().add(hero.getPos(), hero); label.setText(hero.toString()); observableList.add(newIndex, label); label = view.getAppGameHeroes().getListView().getItems().get(oldIndex); hero = view.getAppGameHeroes().getListView().getHeroPosDTOS().get(oldIndex); hero.setPos(oldIndex); label.setText(hero.toString()); view.getAppGameHeroes().getListView().requestFocus(); view.getAppGameHeroes().getListView().getSelectionModel().select(newIndex); view.getAppGameHeroes().getListView().getFocusModel().focus(newIndex); view.getAppGameHeroes().getListView().scrollTo(newIndex); } break; case "heroDelete": int index = view.getAppGameHeroes().getListView().getSelectionModel().getSelectedIndex(); int size = view.getAppGameHeroes().getListView().getHeroPosDTOS().size(); for (int i = index; i < size; i++){ hero = view.getAppGameHeroes().getListView().getHeroPosDTOS().get(i); view.getAppGameHeroes().getListView().getHeroPosDTOS().get(i).setPos(hero.getPos() - 1); view.getAppGameHeroes().getListView().getItems().get(i).setText(hero.toString()); } view.getAppGameHeroes().getListView().getHeroPosDTOS().remove(index); view.getAppGameHeroes().getListView().getItems().remove(index); if (view.getAppGameHeroes().getListView().getItems().isEmpty()){ view.getAppGameHeroes().getUpButton().setDisable(true); view.getAppGameHeroes().getDownButton().setDisable(true); view.getAppGameHeroes().getDeleteButton().setDisable(true); } else { view.getAppGameHeroes().getListView().requestFocus(); } if (view.getAppGameHeroes().getListView().getItems().isEmpty() || view.getAppGameBeast().getListView().getItems().isEmpty()) view.getAppGameContainer().getAppGameFight().getFight().setDisable(true); break; case "beastUp": if (view.getAppGameBeast().getListView().getSelectionModel().getSelectedIndex() > 0) { label = view.getAppGameBeast().getListView().getSelectionModel().getSelectedItem(); int oldIndex = view.getAppGameBeast().getListView().getSelectionModel().getSelectedIndex(); int newIndex = oldIndex - 1; ObservableList<Label> observableList = view.getAppGameBeast().getListView().getItems(); observableList.remove(oldIndex); beast = view.getAppGameBeast().getListView().getBeastPosDTOS().remove(oldIndex); beast.setPos(newIndex); view.getAppGameBeast().getListView().getBeastPosDTOS().add(beast.getPos(), beast); label.setText(beast.toString()); observableList.add(newIndex, label); label = view.getAppGameBeast().getListView().getItems().get(oldIndex); beast = view.getAppGameBeast().getListView().getBeastPosDTOS().get(oldIndex); beast.setPos(oldIndex); label.setText(beast.toString()); view.getAppGameBeast().getListView().requestFocus(); view.getAppGameBeast().getListView().getSelectionModel().select(newIndex); view.getAppGameBeast().getListView().getFocusModel().focus(newIndex); view.getAppGameBeast().getListView().scrollTo(newIndex); } break; case "beastDown": if (view.getAppGameBeast().getListView().getSelectionModel().getSelectedIndex() < view.getAppGameBeast().getListView().getItems().size() - 1) { label = view.getAppGameBeast().getListView().getSelectionModel().getSelectedItem(); int oldIndex = view.getAppGameBeast().getListView().getSelectionModel().getSelectedIndex(); int newIndex = oldIndex + 1; ObservableList<Label> observableList = view.getAppGameBeast().getListView().getItems(); observableList.remove(oldIndex); beast = view.getAppGameBeast().getListView().getBeastPosDTOS().remove(oldIndex); beast.setPos(newIndex); view.getAppGameBeast().getListView().getBeastPosDTOS().add(beast.getPos(), beast); label.setText(beast.toString()); observableList.add(newIndex, label); label = view.getAppGameBeast().getListView().getItems().get(oldIndex); beast = view.getAppGameBeast().getListView().getBeastPosDTOS().get(oldIndex); beast.setPos(oldIndex); label.setText(beast.toString()); view.getAppGameBeast().getListView().requestFocus(); view.getAppGameBeast().getListView().getSelectionModel().select(newIndex); view.getAppGameBeast().getListView().getFocusModel().focus(newIndex); view.getAppGameBeast().getListView().scrollTo(newIndex); } break; case "beastDelete": index = view.getAppGameBeast().getListView().getSelectionModel().getSelectedIndex(); size = view.getAppGameBeast().getListView().getBeastPosDTOS().size(); for (int i = index; i < size; i++){ beast = view.getAppGameBeast().getListView().getBeastPosDTOS().get(i); view.getAppGameBeast().getListView().getBeastPosDTOS().get(i).setPos(beast.getPos() - 1); view.getAppGameBeast().getListView().getItems().get(i).setText(beast.toString()); } view.getAppGameBeast().getListView().getBeastPosDTOS().remove(index); view.getAppGameBeast().getListView().getItems().remove(index); if (view.getAppGameBeast().getListView().getItems().isEmpty()){ view.getAppGameBeast().getUpButton().setDisable(true); view.getAppGameBeast().getDownButton().setDisable(true); view.getAppGameBeast().getDeleteButton().setDisable(true); } else { view.getAppGameBeast().getListView().requestFocus(); } if (view.getAppGameHeroes().getListView().getItems().isEmpty() || view.getAppGameBeast().getListView().getItems().isEmpty()) view.getAppGameContainer().getAppGameFight().getFight().setDisable(true); break; case "fight": int countTurn = 1; try { countTurn = model.getTurn(); } catch (SQLException sqlException) { sqlException.printStackTrace(); } int totalHeroes = view.getAppGameHeroes().getListView().getItems().size(); int totalBeast = view.getAppGameBeast().getListView().getItems().size(); int maxFight = totalHeroes; List<Integer> removesHeroes = new ArrayList<>(); List<Integer> removesBeasts = new ArrayList<>(); String textArea; textArea = view.getAppGameContainer().getAppGameFight().getTextArea().getText().concat(res.getString("turn") + countTurn + "\n"); view.getAppGameContainer().getAppGameFight().getTextArea().setText(textArea); if (totalHeroes > totalBeast) maxFight = totalBeast; for (int i = 0; i < maxFight; i++) { hero = view.getAppGameHeroes().getListView().getHeroPosDTOS().get(i); beast = view.getAppGameBeast().getListView().getBeastPosDTOS().get(i); int attackHero; int attackBeast; int heroOldLife = hero.getLife(); int beastOldLife = beast.getLife(); armor = hero.getArmor(); if (hero.getType() == HeroType.ELF && beast.getType() == BeastType.ORC) { attackHero = (int) Math.floor(Math.random() * 100) + 10; attackBeast = (int) Math.floor(Math.random() * 90); hero.setArmor(90 * hero.getArmor() / 100); } else if (hero.getType() == HeroType.HOBBIT && beast.getType() == BeastType.GOBLIN) { attackHero = (int) Math.floor(Math.random() * 100) - 5; attackBeast = (int) Math.floor(Math.random() * 90); } else if (beast.getType() == BeastType.ORC) { attackHero = (int) Math.floor(Math.random() * 100); attackBeast = (int) Math.floor(Math.random() * 90); hero.setArmor(90 * hero.getArmor() / 100); } else { attackHero = (int) Math.floor(Math.random() * 100); attackBeast = (int) Math.floor(Math.random() * 90); } int attackHeroReduceArmor = (int) ((beast.getArmor() / 1.5) * attackHero / 100); int attackBeastReduceArmor = (int) ((hero.getArmor() / 1.5) * attackBeast / 100); beast.setLife(beast.getLife() - (attackHero - attackHeroReduceArmor)); hero.setLife(hero.getLife() - (attackBeast - attackBeastReduceArmor)); hero.setArmor(armor); textArea = view.getAppGameContainer().getAppGameFight().getTextArea().getText().concat( res.getString("fight2") + hero.getName() + " (" + res.getString("life2") + "=" + heroOldLife + " " + res.getString("armor2") + "=" + hero.getArmor() + ") " + res.getString("and") + beast.getName() + " (" + res.getString("life2") + "=" + beastOldLife + " " + res.getString("armor2") + "=" + beast.getArmor() + ")\n" + hero.getName() + " " + res.getString("out") + attackHero + " " + res.getString("and_remove") + (attackHero - attackHeroReduceArmor) + " " + res.getString("of_life") + beast.getName() + "\n" + beast.getName() + " " + res.getString("out") + attackBeast + " " + res.getString("and_remove") + (attackBeast - attackBeastReduceArmor) + " " + res.getString("of_life") + hero.getName() + "\n" ); if (hero.getLife() <= 0) { textArea = textArea.concat(res.getString("death") + hero.getType().getType() + " " + hero.getName() + "!\n"); } if (beast.getLife() <= 0) { textArea = textArea.concat(res.getString("death") + beast.getType().getType() + " " + beast.getName() + "!\n"); } if (beast.getLife() <= 0) { size = view.getAppGameBeast().getListView().getBeastPosDTOS().size(); for (int j = beast.getPos() + 1; j < size; j++) { beast = view.getAppGameBeast().getListView().getBeastPosDTOS().get(j); view.getAppGameBeast().getListView().getItems().get(j).setText(beast.toString()); } removesBeasts.add(i); } else { view.getAppGameBeast().getListView().getBeastPosDTOS().set(beast.getPos(), beast); view.getAppGameBeast().getListView().getItems().get(beast.getPos()).setText(beast.toString()); } if (hero.getLife() <= 0) { size = view.getAppGameHeroes().getListView().getHeroPosDTOS().size(); for (int j = hero.getPos() + 1; j < size; j++) { hero = view.getAppGameHeroes().getListView().getHeroPosDTOS().get(j); view.getAppGameHeroes().getListView().getItems().get(j).setText(hero.toString()); } removesHeroes.add(i); } else { view.getAppGameHeroes().getListView().getHeroPosDTOS().set(hero.getPos(), hero); view.getAppGameHeroes().getListView().getItems().get(hero.getPos()).setText(hero.toString()); } view.getAppGameContainer().getAppGameFight().getTextArea().setText(textArea); view.getAppGameContainer().getAppGameFight().getTextArea().requestFocus(); String text = view.getAppGameContainer().getAppGameFight().getTextArea().getText(); view.getAppGameContainer().getAppGameFight().getTextArea().positionCaret(text.length()); } if (!removesHeroes.isEmpty()){ for (int i = removesHeroes.size(); i > 0; i--){ view.getAppGameHeroes().getListView().getHeroPosDTOS().remove((int) removesHeroes.get(i - 1)); view.getAppGameHeroes().getListView().getItems().remove((int) removesHeroes.get(i - 1)); size = view.getAppGameHeroes().getListView().getHeroPosDTOS().size(); for (int j = removesHeroes.get(i - 1); j < size; j++){ hero = view.getAppGameHeroes().getListView().getHeroPosDTOS().get(j); view.getAppGameHeroes().getListView().getHeroPosDTOS().get(j).setPos(hero.getPos() - 1); } } removesHeroes.clear(); } if (!removesBeasts.isEmpty()){ for (int i = removesBeasts.size(); i > 0; i--){ view.getAppGameBeast().getListView().getBeastPosDTOS().remove((int) removesBeasts.get(i - 1)); view.getAppGameBeast().getListView().getItems().remove((int) removesBeasts.get(i - 1)); size = view.getAppGameBeast().getListView().getBeastPosDTOS().size(); for (int j = removesBeasts.get(i - 1); j < size; j++ ){ beast = view.getAppGameBeast().getListView().getBeastPosDTOS().get(j); view.getAppGameBeast().getListView().getBeastPosDTOS().get(j).setPos(beast.getPos() - 1); } } removesBeasts.clear(); } if (view.getAppGameHeroes().getListView().getItems().isEmpty()){ textArea = textArea.concat("----------" + res.getString("victory_beast") + "----------"); view.getAppGameContainer().getAppGameFight().getTextArea().setText(textArea); } if (view.getAppGameBeast().getListView().getItems().isEmpty()){ textArea = textArea.concat("----------" + res.getString("victory_hero") + "----------"); view.getAppGameContainer().getAppGameFight().getTextArea().setText(textArea); } textArea = textArea.concat("\n"); view.getAppGameContainer().getAppGameFight().getTextArea().setText(textArea); if (view.getAppGameHeroes().getListView().getItems().isEmpty() || view.getAppGameBeast().getListView().getItems().isEmpty()) view.getAppGameContainer().getAppGameFight().getFight().setDisable(true); countTurn++; try { model.saveTurn(countTurn); } catch (SQLException sqlException) { sqlException.printStackTrace(); } break; case "exit": view.getAppGameContainer().getAppGameExitStage().showAndWait(); break; } } } <file_sep>/src/main/resources/strings_es.properties new = Nueva Partida load = Cargar language = Idioma exit = Salir back = Atras cancel = Cancelar quest = Seguro quieres sobreescribir esta patida? information = El progreso guardado se perdera permanentemente game_save = Partidas Guardadas spanish = Español english = Ingles french = Frances exit! = ¡Salir! sure = ¿Esta seguro que desea Salir? yes = SI no! = NO!!! name = Nombre: type = Tipo: life = Vida: armor = Armadura: add = Añadir heroes = Heroes beast = Bestias up = Subir down = Bajar delete = Eliminar orc = Orco goblin = Goblin elf = Elfo hobbit = Hobbit human = Humano life2 = Vida armor2 = Armadura fight = ¡LUCHA! fight2 = lucha entre out = saca and_remove = y le quita of_life = de vida a death = ¡Muere! victory_hero = ¡¡Victoria de los Heroes!! victory_beast = ¡¡Victoria de las Bestias!! ok = Aceptar want_exit = ¿Desea salir al Menu Principal? progress_save = El progreso se guardara (: turn = Turno : and = y <file_sep>/src/main/java/com/tokioschool/components/menu/listeners/AppMenuKeyEvent.java package com.tokioschool.components.menu.listeners; import com.tokioschool.AppView; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.input.KeyEvent; public class AppMenuKeyEvent implements EventHandler<KeyEvent> { private final AppView view; public AppMenuKeyEvent(AppView view){ super(); this.view = view; } @Override public void handle(KeyEvent keyEvent) { Node node = (Node) keyEvent.getSource(); String userData = node.getUserData().toString(); if ("newStageTextField".equals(userData)) { String tfName = view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getTextField().getText(); if (tfName.length() >= 14) { StringBuilder sb = new StringBuilder(tfName); sb.deleteCharAt(tfName.length() - 1); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getTextField().setText(sb.toString()); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getTextField().positionCaret(tfName.length()); } } } } <file_sep>/src/main/resources/strings_fr.properties new = Nouveau jeu load = Charge language = Langage exit = Sortir back = Derriére cancel = Annuler quest = Voulez-vous écraser ce jeu? information = La progression enregistrée sera définitivement perdue game_save = Parties Sauvegardées spanish = Espagnol english = Anglais french = Français exit! = Sortir! sure = ¿Étes-vous sur de vouloir quitter? yes = OUI no! = NON!!! name = Nom: type = Type: life = Vie: armor = Armure: add = Ajouter heroes = Héros beast = Bétes up = Monter down = Descendre delete = Retirer orc = Orc goblin = Goblin elf = Elfe hobbit = Hobbit human = Humain life2 = Vie armor2 = Armure fight = ¡LUTTE! fight2 = combat entre out = obtient un score de and_remove = et prend of_life = de la vie de death = Meurt! victory_hero = Victoire des héros!! victory_beast = Victoire des bétes!! ok = Accepter want_exit = Voulez-vous quitter le menu principal? progress_save = La progression sera enregistrée (: turn = Tour and = et <file_sep>/src/main/java/com/tokioschool/AppController.java package com.tokioschool; import com.tokioschool.components.game.listeners.AppGameActionEvent; import com.tokioschool.components.game.listeners.AppGameKeyEvent; import com.tokioschool.components.game.listeners.AppGameMouseEvent; import com.tokioschool.components.menu.listeners.AppMenuActionEvent; import com.tokioschool.components.menu.listeners.AppMenuKeyEvent; import com.tokioschool.components.menu.listeners.AppMenuMouseEvent; import com.tokioschool.database.AppModel; import java.util.ResourceBundle; public class AppController { private final AppModel model; private AppView view; public AppController(AppModel model){ this.model = model; initComponents(); } private void initComponents(){ } public void initListeners(AppView view, ResourceBundle res){ this.view = view; AppMenuMouseEvent appMenuMouseEvent = new AppMenuMouseEvent(view, model); view.getMenuStart().getLabelButton().setOnMouseClicked(appMenuMouseEvent); view.getMenuStart().getLabelButton().setOnMouseEntered(appMenuMouseEvent); view.getMenuStart().getLabelButton().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getButtonExit().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getButtonExit().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getSave1().getSave().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getSave1().getSave().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getSave1().getSave().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getSave2().getSave().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getSave2().getSave().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getSave2().getSave().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getSave3().getSave().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getSave3().getSave().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getSave3().getSave().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getLabelOkSave().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getLabelOkSave().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getLabelOkSave().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getLabelCancelSave().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getLabelCancelSave().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getLabelCancelSave().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getLabelOkReplace().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getLabelOkReplace().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getLabelOkReplace().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getLabelCancelReplace().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getLabelCancelReplace().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getLabelCancelReplace().setOnMouseClicked(appMenuMouseEvent); view.getMenuLoad().getLabelButton().setOnMouseClicked(appMenuMouseEvent); view.getMenuLoad().getLabelButton().setOnMouseEntered(appMenuMouseEvent); view.getMenuLoad().getLabelButton().setOnMouseExited(appMenuMouseEvent); connectSave(); view.getAppMenuLoad().getBackButton().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuLoad().getBackButton().setOnMouseExited(appMenuMouseEvent); view.getMenuLanguish().getLabelButton().setOnMouseClicked(appMenuMouseEvent); view.getMenuLanguish().getLabelButton().setOnMouseEntered(appMenuMouseEvent); view.getMenuLanguish().getLabelButton().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuLanguish().getImageSpanish().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuLanguish().getImageSpanish().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuLanguish().getImageSpanish().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuLanguish().getImageEnglish().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuLanguish().getImageEnglish().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuLanguish().getImageEnglish().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuLanguish().getImageFrench().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuLanguish().getImageFrench().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuLanguish().getImageFrench().setOnMouseClicked(appMenuMouseEvent); view.getMenuExit().getLabelButton().setOnMouseClicked(appMenuMouseEvent); view.getMenuExit().getLabelButton().setOnMouseEntered(appMenuMouseEvent); view.getMenuExit().getLabelButton().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuLanguish().getBackButton().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuLanguish().getBackButton().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuExit().getImageViewExit().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuExit().getImageViewExit().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuExit().getImageViewExit().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuExit().getOkLabel().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuExit().getOkLabel().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuExit().getOkLabel().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuExit().getCancelLabel().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuExit().getCancelLabel().setOnMouseExited(appMenuMouseEvent); view.getAppMenuContainer().getAppMenuExit().getCancelLabel().setOnMouseClicked(appMenuMouseEvent); AppMenuActionEvent appMenuActionEvent = new AppMenuActionEvent(view); view.getAppMenuLoad().getBackButton().setOnAction(appMenuActionEvent); view.getAppMenuContainer().getAppMenuNew().getButtonExit().setOnAction(appMenuActionEvent); view.getAppMenuContainer().getAppMenuLanguish().getBackButton().setOnAction(appMenuActionEvent); AppMenuKeyEvent appMenuKeyEvent = new AppMenuKeyEvent(view); view.getAppMenuContainer().getAppMenuNew().getAppMenuNewStage().getTextField().setOnKeyTyped(appMenuKeyEvent); AppGameActionEvent appGameActionEvent = new AppGameActionEvent(view, model, res); view.getAppGameHeroes().getAddButton().setOnAction(appGameActionEvent); view.getAppGameBeast().getAddButton().setOnAction(appGameActionEvent); view.getAppGameHeroes().getUpButton().setOnAction(appGameActionEvent); view.getAppGameHeroes().getDownButton().setOnAction(appGameActionEvent); view.getAppGameHeroes().getDeleteButton().setOnAction(appGameActionEvent); view.getAppGameBeast().getUpButton().setOnAction(appGameActionEvent); view.getAppGameBeast().getDownButton().setOnAction(appGameActionEvent); view.getAppGameBeast().getDeleteButton().setOnAction(appGameActionEvent); view.getAppGameContainer().getAppGameFight().getFight().setOnAction(appGameActionEvent); view.getAppGameContainer().getAppGameFight().getExit().setOnAction(appGameActionEvent); AppGameMouseEvent appGameMouseEvent = new AppGameMouseEvent(view, model); view.getAppGameHeroes().getSliderArmor().setOnMouseDragged(appGameMouseEvent); view.getAppGameHeroes().getSliderLife().setOnMouseDragged(appGameMouseEvent); view.getAppGameBeast().getSliderArmor().setOnMouseDragged(appGameMouseEvent); view.getAppGameBeast().getSliderLife().setOnMouseDragged(appGameMouseEvent); view.getAppGameHeroes().getAddButton().setOnMouseEntered(appGameMouseEvent); view.getAppGameHeroes().getAddButton().setOnMouseExited(appGameMouseEvent); view.getAppGameBeast().getAddButton().setOnMouseEntered(appGameMouseEvent); view.getAppGameBeast().getAddButton().setOnMouseExited(appGameMouseEvent); view.getAppGameHeroes().getUpButton().setOnMouseEntered(appGameMouseEvent); view.getAppGameHeroes().getUpButton().setOnMouseExited(appGameMouseEvent); view.getAppGameHeroes().getDeleteButton().setOnMouseEntered(appGameMouseEvent); view.getAppGameHeroes().getDeleteButton().setOnMouseExited(appGameMouseEvent); view.getAppGameHeroes().getDownButton().setOnMouseEntered(appGameMouseEvent); view.getAppGameHeroes().getDownButton().setOnMouseExited(appGameMouseEvent); view.getAppGameBeast().getUpButton().setOnMouseEntered(appGameMouseEvent); view.getAppGameBeast().getUpButton().setOnMouseExited(appGameMouseEvent); view.getAppGameBeast().getDeleteButton().setOnMouseEntered(appGameMouseEvent); view.getAppGameBeast().getDeleteButton().setOnMouseExited(appGameMouseEvent); view.getAppGameBeast().getDownButton().setOnMouseEntered(appGameMouseEvent); view.getAppGameBeast().getDownButton().setOnMouseExited(appGameMouseEvent); view.getAppGameContainer().getAppGameFight().getFight().setOnMouseEntered(appGameMouseEvent); view.getAppGameContainer().getAppGameFight().getFight().setOnMouseExited(appGameMouseEvent); view.getAppGameHeroes().getListView().setOnMouseClicked(appGameMouseEvent); view.getAppGameBeast().getListView().setOnMouseClicked(appGameMouseEvent); view.getAppGameContainer().getAppGameFight().getExit().setOnMouseEntered(appGameMouseEvent); view.getAppGameContainer().getAppGameFight().getExit().setOnMouseExited(appGameMouseEvent); view.getAppGameContainer().getAppGameExitStage().getLabelOk().setOnMouseClicked(appGameMouseEvent); view.getAppGameContainer().getAppGameExitStage().getLabelOk().setOnMouseEntered(appGameMouseEvent); view.getAppGameContainer().getAppGameExitStage().getLabelOk().setOnMouseExited(appGameMouseEvent); view.getAppGameContainer().getAppGameExitStage().getLabelCancel().setOnMouseClicked(appGameMouseEvent); view.getAppGameContainer().getAppGameExitStage().getLabelCancel().setOnMouseEntered(appGameMouseEvent); view.getAppGameContainer().getAppGameExitStage().getLabelCancel().setOnMouseExited(appGameMouseEvent); AppGameKeyEvent appGameKeyEvent = new AppGameKeyEvent(view); view.getAppGameHeroes().getTfName().setOnKeyTyped(appGameKeyEvent); view.getAppGameBeast().getTfName().setOnKeyTyped(appGameKeyEvent); } public void connectSave(){ AppMenuMouseEvent appMenuMouseEvent = new AppMenuMouseEvent(view, model); if (model.isSave1()){ view.getAppMenuLoad().getLoad1().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuLoad().getLoad1().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuLoad().getLoad1().setOnMouseExited(appMenuMouseEvent); } if (model.isSave2()){ view.getAppMenuLoad().getLoad2().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuLoad().getLoad2().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuLoad().getLoad2().setOnMouseExited(appMenuMouseEvent); } if (model.isSave3()){ view.getAppMenuLoad().getLoad3().setOnMouseClicked(appMenuMouseEvent); view.getAppMenuLoad().getLoad3().setOnMouseEntered(appMenuMouseEvent); view.getAppMenuLoad().getLoad3().setOnMouseExited(appMenuMouseEvent); } } } <file_sep>/imagen/.picasa.ini [espada-dardo-frodo.jpg] rotate=rotate(1) <file_sep>/src/main/java/com/tokioschool/components/menu/AppMenuNew.java package com.tokioschool.components.menu; import com.tokioschool.database.AppModel; import com.tokioschool.util.BorderUtil; import com.tokioschool.util.EffectUtil; import com.tokioschool.util.WindowUtil; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.effect.Bloom; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.stage.Stage; import java.sql.SQLException; import java.util.ResourceBundle; public class AppMenuNew extends StackPane { private AppMenuSaves save1, save2, save3; private Button buttonExit; private AppMenuNewStage appMenuNewStage; private final Stage ownerStage; private final AppModel model; private final ResourceBundle res; public AppMenuNew(Stage ownerStage, AppModel model, ResourceBundle res){ super(); this.ownerStage = ownerStage; this.model = model; this.res = res; setPrefWidth(WindowUtil.getDimension().width); setPrefHeight(WindowUtil.getDimension().height); setAlignment(Pos.CENTER); initComponents(); } private void initComponents(){ save1 = new AppMenuSaves(); save1.getSave().setUserData("save1"); if (model.isSave1()){ String name = ""; try { model.setSave(1); model.connect(); name = model.getName(); model.disconnect(); } catch (SQLException sqlException) { sqlException.printStackTrace(); } save1.getSave().setText(name); } save2 = new AppMenuSaves(); save2.getSave().setUserData("save2"); if (model.isSave2()){ String name = ""; try { model.setSave(2); model.connect(); name = model.getName(); model.disconnect(); } catch (SQLException sqlException){ sqlException.printStackTrace(); } save2.getSave().setText(name); } save3 = new AppMenuSaves(); save3.getSave().setUserData("save3"); if (model.isSave3()){ String name = ""; try{ model.setSave(3); model.connect(); name = model.getName(); model.disconnect(); }catch (SQLException sqlException){ sqlException.printStackTrace(); } save3.getSave().setText(name); } HBox hBox1 = new HBox(save1, save2, save3); hBox1.setAlignment(Pos.CENTER); hBox1.setSpacing(40); hBox1.setMaxHeight(400); buttonExit = new Button(res.getString("back")); buttonExit.setFont(new Font("cambria", 50)); buttonExit.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, null, null))); buttonExit.setTextFill(Color.WHITE); buttonExit.setBorder(BorderUtil.getBlack()); buttonExit.setPadding(new Insets(15, 30, 15, 30)); Bloom bloom = EffectUtil.getBloom(0.9); buttonExit.setEffect(bloom); buttonExit.setUserData("backNew"); appMenuNewStage = new AppMenuNewStage(ownerStage, res); HBox hBox2 = new HBox(buttonExit); hBox2.setPadding(new Insets(0, 30, 30, 0)); hBox2.setAlignment(Pos.BOTTOM_RIGHT); getChildren().addAll(hBox2, hBox1); } public Button getButtonExit(){ return buttonExit; } public AppMenuSaves getSave1(){ return save1; } public AppMenuSaves getSave2(){ return save2; } public AppMenuSaves getSave3(){ return save3; } public AppMenuNewStage getAppMenuNewStage(){return appMenuNewStage;} } <file_sep>/src/main/java/com/tokioschool/components/menu/AppMenu.java package com.tokioschool.components.menu; import com.tokioschool.util.BorderUtil; import com.tokioschool.util.EffectUtil; import com.tokioschool.util.FontUtil; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.effect.Bloom; import javafx.scene.effect.DropShadow; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; public class AppMenu extends HBox { private Label labelButton; private final String title; private final String userData; public AppMenu(String title, String userData){ super(); this.title = title; this.userData = userData; setConfigure(); initComponents(); } private void setConfigure(){ setAlignment(Pos.CENTER); } private void initComponents(){ labelButton = new Label(title); labelButton.setUserData(userData); labelButton.setBorder(BorderUtil.getBlack()); FontUtil.labelFontAll("Cambria", FontWeight.NORMAL, FontPosture.ITALIC, 80, Color.WHITE, labelButton); labelButton.setAlignment(Pos.CENTER); labelButton.setMinWidth(600); labelButton.setPadding(new Insets(20)); DropShadow dropShadow = new DropShadow(); dropShadow.setOffsetX(5); dropShadow.setSpread(0.3); Bloom bloom = EffectUtil.getBloom(0.8); bloom.setInput(dropShadow); labelButton.setEffect(bloom); StackPane stackPane = new StackPane(); stackPane.getChildren().addAll(labelButton); getChildren().add(stackPane); } public Label getLabelButton(){return labelButton;} } <file_sep>/src/main/java/com/tokioschool/components/menu/AppMenuLanguage.java package com.tokioschool.components.menu; import com.tokioschool.util.BorderUtil; import com.tokioschool.util.ImageUtil; import com.tokioschool.util.WindowUtil; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.effect.DropShadow; import javafx.scene.image.ImageView; import javafx.scene.layout.Background; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import java.io.IOException; import java.util.ResourceBundle; public class AppMenuLanguage extends StackPane { private ImageView imageSpanish, imageEnglish, imageFrench; private Button backButton; private final ResourceBundle res; public AppMenuLanguage(ResourceBundle res){ super(); this.res = res; initComponents(); } private void initComponents(){ setPrefHeight(WindowUtil.getDimension().height); setPrefWidth(WindowUtil.getDimension().width); setAlignment(Pos.CENTER); try { imageSpanish = ImageUtil.getImageView("spanish.png"); imageSpanish.setUserData("spanish"); imageEnglish = ImageUtil.getImageView("english.png"); imageEnglish.setUserData("english"); imageFrench = ImageUtil.getImageView("french.png"); imageFrench.setUserData("french"); } catch (IOException e) { e.printStackTrace(); } DropShadow dropShadow = new DropShadow(10, Color.BLACK); Label labelSpanish = new Label(res.getString("spanish")); labelSpanish.setFont(Font.font("Cambria", null, null, 50)); labelSpanish.setTextFill(Color.WHITE); labelSpanish.setEffect(dropShadow); VBox vBoxSpanish = new VBox(imageSpanish, labelSpanish); vBoxSpanish.setAlignment(Pos.CENTER); Label labelEnglish = new Label(res.getString("english")); labelEnglish.setFont(Font.font("Cambria", null, null, 50)); labelEnglish.setTextFill(Color.WHITE); labelEnglish.setEffect(dropShadow); VBox vBoxEnglish = new VBox(imageEnglish, labelEnglish); vBoxEnglish.setAlignment(Pos.CENTER); Label labelFrench = new Label(res.getString("french")); labelFrench.setFont(Font.font("Cambria", null, null, 50)); labelFrench.setTextFill(Color.WHITE); labelFrench.setEffect(dropShadow); VBox vBoxFrench = new VBox(imageFrench, labelFrench); vBoxFrench.setAlignment(Pos.CENTER); backButton = new Button(res.getString("back")); backButton.setTranslateX(WindowUtil.getDimension().width / 2.0 - 150); backButton.setTranslateY(WindowUtil.getDimension().height / 2.0 - 100); backButton.setBackground(Background.EMPTY); backButton.setBorder(BorderUtil.getBlack()); backButton.setFont(Font.font("Cambria", null, null, 50)); backButton.setTextFill(Color.WHITE); backButton.setUserData("languageBack"); HBox hBox = new HBox(vBoxSpanish, vBoxEnglish, vBoxFrench); hBox.setAlignment(Pos.CENTER); hBox.setSpacing(100); hBox.setPrefWidth(WindowUtil.getDimension().width); getChildren().addAll(hBox, backButton); } public ImageView getImageSpanish() { return imageSpanish; } public ImageView getImageEnglish() { return imageEnglish; } public ImageView getImageFrench() { return imageFrench; } public Button getBackButton() { return backButton; } } <file_sep>/src/main/java/com/tokioschool/components/game/listeners/AppGameKeyEvent.java package com.tokioschool.components.game.listeners; import com.tokioschool.AppView; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.input.KeyEvent; public class AppGameKeyEvent implements EventHandler<KeyEvent> { private final AppView view; public AppGameKeyEvent(AppView view){ this.view = view; } @Override public void handle(KeyEvent keyEvent) { Node node = (Node) keyEvent.getSource(); String userData = node.getUserData().toString(); switch (userData){ case "heroName": String tfName = view.getAppGameHeroes().getTfName().getText().trim(); if (tfName.contains(" ") || tfName.equals("")){ view.getAppGameHeroes().getAddButton().setDisable(true); view.getAppGameHeroes().getTfName().setStyle("-fx-text-fill: red"); } else { view.getAppGameHeroes().getTfName().setStyle("-fx-text-fill: white"); view.getAppGameHeroes().getAddButton().setDisable(false); } tfName = view.getAppGameHeroes().getTfName().getText(); if (tfName.length() >= 14){ StringBuilder sb = new StringBuilder(tfName); sb.deleteCharAt(tfName.length() - 1); view.getAppGameHeroes().getTfName().setText(sb.toString()); view.getAppGameHeroes().getTfName().positionCaret(tfName.length()); } break; case "beastName": tfName = view.getAppGameBeast().getTfName().getText().trim(); if (tfName.contains(" ") || tfName.equals("")){ view.getAppGameBeast().getAddButton().setDisable(true); view.getAppGameBeast().getTfName().setStyle("-fx-text-fill: red"); } else { view.getAppGameBeast().getTfName().setStyle("-fx-text-fill: white"); view.getAppGameBeast().getAddButton().setDisable(false); } tfName = view.getAppGameBeast().getTfName().getText(); if (tfName.length() >= 14){ StringBuilder sb = new StringBuilder(tfName); sb.deleteCharAt(tfName.length() - 1); view.getAppGameBeast().getTfName().setText(sb.toString()); view.getAppGameBeast().getTfName().positionCaret(tfName.length()); } break; } } } <file_sep>/src/main/java/com/tokioschool/components/game/AppGameExitStage.java package com.tokioschool.components.game; import com.tokioschool.util.BorderUtil; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.effect.DropShadow; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import java.util.ResourceBundle; public class AppGameExitStage extends Stage { private Label labelOk; private Label labelCancel; private ResourceBundle res; public AppGameExitStage(Stage ownerStage, ResourceBundle res){ super(StageStyle.TRANSPARENT); this.res = res; initOwner(ownerStage); initModality(Modality.APPLICATION_MODAL); initComponents(); } private void initComponents(){ labelOk = new Label(res.getString("ok")); labelOk.setBorder(BorderUtil.getBlack()); labelOk.setFont(Font.font("Cambria", FontWeight.NORMAL, FontPosture.REGULAR, 30)); labelOk.setTextFill(Color.WHITE); labelOk.setPadding(new Insets(10)); labelOk.setMinWidth(100); labelOk.setUserData("stageButtonOk"); labelCancel = new Label(res.getString("cancel")); labelCancel.setBorder(BorderUtil.getBlack()); labelCancel.setFont(Font.font("Cambria", FontWeight.NORMAL, FontPosture.REGULAR, 30)); labelCancel.setTextFill(Color.WHITE); labelCancel.setPadding(new Insets(10)); labelCancel.setMinWidth(100); labelCancel.setUserData("stageButtonCancel"); HBox hBox = new HBox(labelOk, labelCancel); hBox.setAlignment(Pos.CENTER); hBox.setSpacing(60); DropShadow dropShadow = new DropShadow(); dropShadow.setOffsetX(2); dropShadow.setRadius(5); dropShadow.setColor(Color.BLACK); Label labelQuest = new Label(res.getString("want_exit")); labelQuest.setFont(Font.font("Cambria", FontWeight.BOLD, FontPosture.ITALIC, 30)); labelQuest.setTextFill(Color.WHITE); labelQuest.setEffect(dropShadow); Label labelInformation = new Label(res.getString("progress_save")); labelInformation.setFont(Font.font("Cambria", FontWeight.BOLD, FontPosture.ITALIC, 20)); labelInformation.setTextFill(Color.WHITE); labelInformation.setEffect(dropShadow); VBox vBox = new VBox(labelQuest, labelInformation, hBox); vBox.setAlignment(Pos.TOP_CENTER); vBox.setBackground(new Background(new BackgroundFill(Color.rgb(193, 202, 238, 0.6), new CornerRadii(15), null))); vBox.setSpacing(30); vBox.setPadding(new Insets(25)); Scene scene = new Scene(vBox, Color.TRANSPARENT); setScene(scene); } public Label getLabelOk(){return labelOk;} public Label getLabelCancel(){return labelCancel;} } <file_sep>/src/main/java/com/tokioschool/domain/HeroType.java package com.tokioschool.domain; import java.util.ResourceBundle; public enum HeroType{ ELF(""), HOBBIT(""), HUMAN(""); String type; HeroType(String type){ this.type = type; } public String getType() { return type; } public void setType(String type) { this.type = type; } public void refreshLanguage(ResourceBundle res){ ELF.setType(res.getString("elf")); HOBBIT.setType(res.getString("hobbit")); HUMAN.setType(res.getString("human")); } }<file_sep>/src/main/java/com/tokioschool/util/WindowUtil.java package com.tokioschool.util; import java.awt.*; public class WindowUtil { public static Dimension getDimension(){ Toolkit t = Toolkit.getDefaultToolkit(); return t.getScreenSize(); } } <file_sep>/src/main/java/com/tokioschool/components/game/AppGameButtonsOfListView.java package com.tokioschool.components.game; import com.tokioschool.util.FontUtil; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.effect.DropShadow; import javafx.scene.layout.*; import javafx.scene.paint.Color; import java.util.ResourceBundle; public class AppGameButtonsOfListView extends HBox { private Button up, down, delete; private final String userData; private final ResourceBundle res; public AppGameButtonsOfListView(String userData, ResourceBundle res){ super(); this.userData = userData; this.res = res; setAlignment(Pos.CENTER); setSpacing(20); initComponents(); } private void initComponents(){ DropShadow dropShadow = new DropShadow(10, Color.WHITE); up = new Button(res.getString("up")); up.setUserData(userData + "Up"); up.setTextFill(Color.WHITE); up.setBackground(Background.EMPTY); up.setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, new CornerRadii(10), new BorderWidths(2)))); up.setEffect(dropShadow); up.setDisable(true); down = new Button(res.getString("down")); down.setUserData(userData + "Down"); down.setTextFill(Color.WHITE); down.setBackground(Background.EMPTY); down.setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, new CornerRadii(10), new BorderWidths(2)))); down.setEffect(dropShadow); down.setDisable(true); delete = new Button(res.getString("delete")); delete.setUserData(userData + "Delete"); delete.setTextFill(Color.WHITE); delete.setBackground(Background.EMPTY); delete.setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, new CornerRadii(10), new BorderWidths(2)))); delete.setEffect(dropShadow); delete.setDisable(true); FontUtil.buttonsFontAll(up, down, delete); getChildren().addAll(up, down, delete); } public Button getUp() { return up; } public Button getDown() { return down; } public Button getDelete() { return delete; } } <file_sep>/src/main/java/com/tokioschool/components/menu/AppMenuNewStage.java package com.tokioschool.components.menu; import com.tokioschool.util.BorderUtil; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.effect.DropShadow; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import java.util.ResourceBundle; public class AppMenuNewStage extends Stage { private TextField textField; private Label labelOkReplace, labelCancelReplace, labelCancelSave, labelOkSave; private Scene sceneSave, sceneReplace; private int isScene, isSave; private final ResourceBundle res; public AppMenuNewStage(Stage ownerStage, ResourceBundle res){ super(StageStyle.TRANSPARENT); this.res = res; initOwner(ownerStage); initModality(Modality.APPLICATION_MODAL); initComponents(); } private void initComponents(){ textField = new TextField(); textField.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, null, null))); textField.setFont(Font.font("Cambria", FontWeight.NORMAL, FontPosture.REGULAR, 30)); textField.setStyle("-fx-text-fill: white"); textField.setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, new CornerRadii(15), new BorderWidths(2), null))); DropShadow dropShadow = new DropShadow(10, Color.WHITE); textField.setEffect(dropShadow); textField.setMaxWidth(350); textField.setUserData("newStageTextField"); labelOkSave = new Label("Ok"); labelOkSave.setBorder(BorderUtil.getBlack()); labelOkSave.setFont(Font.font("Cambria", FontWeight.NORMAL, FontPosture.REGULAR, 30)); labelOkSave.setTextFill(Color.WHITE); labelOkSave.setPadding(new Insets(10)); labelOkSave.setMinWidth(100); labelOkSave.setUserData("newStageButtonOk"); labelCancelSave = new Label(res.getString("cancel")); labelCancelSave.setBorder(BorderUtil.getBlack()); labelCancelSave.setFont(Font.font("Cambria", FontWeight.NORMAL, FontPosture.REGULAR, 30)); labelCancelSave.setTextFill(Color.WHITE); labelCancelSave.setPadding(new Insets(10)); labelCancelSave.setMinWidth(100); labelCancelSave.setUserData("newStageButtonCancel"); HBox hBox = new HBox(labelOkSave, labelCancelSave); hBox.setAlignment(Pos.CENTER); hBox.setSpacing(60); VBox vBox = new VBox(textField, hBox); vBox.setPadding(new Insets(20, 0, 0, 0)); vBox.setAlignment(Pos.TOP_CENTER); vBox.setSpacing(30); vBox.setBackground(new Background(new BackgroundFill(Color.rgb(193, 202, 238, 0.4), new CornerRadii(15), null))); sceneSave = new Scene(vBox, Color.TRANSPARENT); DropShadow dropShadow2 = new DropShadow(); dropShadow2.setOffsetX(2); dropShadow2.setRadius(5); dropShadow2.setColor(Color.BLACK); Label labelQuest = new Label(res.getString("quest")); labelQuest.setFont(Font.font("Cambria", FontWeight.BOLD, FontPosture.ITALIC, 30)); labelQuest.setTextFill(Color.WHITE); labelQuest.setEffect(dropShadow2); Label labelInformation = new Label(res.getString("information")); labelInformation.setFont(Font.font("Cambria", FontWeight.BOLD, FontPosture.ITALIC, 20)); labelInformation.setTextFill(Color.WHITE); labelInformation.setEffect(dropShadow2); labelOkReplace = new Label("Ok"); labelOkReplace.setBorder(BorderUtil.getBlack()); labelOkReplace.setFont(Font.font("Cambria", FontWeight.NORMAL, FontPosture.REGULAR, 30)); labelOkReplace.setTextFill(Color.WHITE); labelOkReplace.setPadding(new Insets(10)); labelOkReplace.setMinWidth(100); labelOkReplace.setUserData("newStageButtonOk"); labelCancelReplace = new Label("Cancelar"); labelCancelReplace.setBorder(BorderUtil.getBlack()); labelCancelReplace.setFont(Font.font("Cambria", FontWeight.NORMAL, FontPosture.REGULAR, 30)); labelCancelReplace.setTextFill(Color.WHITE); labelCancelReplace.setPadding(new Insets(10)); labelCancelReplace.setMinWidth(100); labelCancelReplace.setUserData("newStageButtonCancel"); HBox hBox2 = new HBox(labelOkReplace, labelCancelReplace); hBox2.setAlignment(Pos.CENTER); hBox2.setSpacing(60); VBox vBox2 = new VBox(labelQuest, labelInformation, hBox2); vBox2.setAlignment(Pos.TOP_CENTER); vBox2.setBackground(new Background(new BackgroundFill(Color.rgb(193, 202, 238, 0.4), new CornerRadii(15), null))); vBox2.setSpacing(30); sceneReplace = new Scene(vBox2, Color.TRANSPARENT); } public Label getLabelOkSave(){return labelOkSave;} public Label getLabelCancelSave(){return labelCancelSave;} public Label getLabelOkReplace(){return labelOkReplace;} public Label getLabelCancelReplace(){return labelCancelReplace;} public TextField getTextField(){return textField;} public int getIsScene(){return isScene;} public void sceneSave(){ setHeight(200); setWidth(500); setScene(sceneSave); isScene = 1; } public void sceneReplace(){ setHeight(200); setWidth(600); setScene(sceneReplace); isScene = 2; } public void setIsSave(int save){ isSave = save; } public int getIsSave(){return isSave;} } <file_sep>/src/main/java/com/tokioschool/components/menu/AppMenuExit.java package com.tokioschool.components.menu; import com.tokioschool.util.BorderUtil; import com.tokioschool.util.ImageUtil; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.effect.DropShadow; import javafx.scene.image.ImageView; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import java.io.IOException; import java.util.ResourceBundle; public class AppMenuExit extends Stage { private Label okLabel; private Label cancelLabel; private ImageView imageViewExit; private final ResourceBundle res; public AppMenuExit(Stage ownerStage, ResourceBundle res){ super(StageStyle.TRANSPARENT); this.res = res; initComponents(); initModality(Modality.APPLICATION_MODAL); setHeight(250); setWidth(600); initOwner(ownerStage); } private void initComponents(){ DropShadow dropShadow = new DropShadow(); dropShadow.setSpread(0.5); dropShadow.setOffsetX(5); Label titleLabel = new Label(res.getString("exit!")); titleLabel.setFont(Font.font("Cambria", FontWeight.NORMAL, FontPosture.REGULAR, 30)); titleLabel.setTextFill(Color.WHITE); titleLabel.setEffect(dropShadow); Line line = new Line(5, 5, 5, 5); line.setFill(Color.BLACK); line.setStartX(0); line.setEndX(600); line.setTranslateY(-25); try { imageViewExit = ImageUtil.getImageView("cerrar.png"); imageViewExit.setTranslateX(245); imageViewExit.setUserData("exitImage"); } catch (IOException e) { e.printStackTrace(); } HBox hBox = new HBox(titleLabel,imageViewExit); hBox.setAlignment(Pos.TOP_CENTER); Label infoLabel = new Label(res.getString("sure")); infoLabel.setFont(Font.font("Cambria", FontWeight.BOLD, FontPosture.REGULAR, 40)); infoLabel.setTextFill(Color.WHITE); infoLabel.setEffect(dropShadow); okLabel = new Label(res.getString("yes")); okLabel.setFont(Font.font("Cambria", null, null, 35)); okLabel.setTextFill(Color.WHITE); okLabel.setBorder(BorderUtil.getBlack()); okLabel.setPadding(new Insets(0, 15, 0, 15)); okLabel.setMinWidth(110); dropShadow = new DropShadow(); dropShadow.setSpread(0.2); dropShadow.setOffsetX(5); okLabel.setEffect(dropShadow); okLabel.setUserData("exitOkButton"); cancelLabel = new Label(res.getString("no!")); cancelLabel.setFont(Font.font("Cambria", null, null, 35)); cancelLabel.setTextFill(Color.WHITE); cancelLabel.setBorder(BorderUtil.getBlack()); cancelLabel.setPadding(new Insets(0, 15, 0, 15)); cancelLabel.setMinWidth(110); dropShadow = new DropShadow(); dropShadow.setSpread(0.2); dropShadow.setOffsetX(5); cancelLabel.setEffect(dropShadow); cancelLabel.setUserData("exitCancelButton"); HBox hBox2 = new HBox(okLabel, cancelLabel); hBox2.setAlignment(Pos.CENTER); hBox2.setSpacing(30); hBox2.setPadding(new Insets(0, 0, 20, 0)); VBox container = new VBox(hBox, line, infoLabel, hBox2); container.setSpacing(25); container.setBackground(new Background(new BackgroundFill(Color.rgb(193, 202, 238, 1), new CornerRadii(15), null))); container.setBorder(BorderUtil.getBlack()); container.setAlignment(Pos.CENTER); Scene scene = new Scene(container); scene.setFill(Color.TRANSPARENT); setScene(scene); } public Label getOkLabel() { return okLabel; } public Label getCancelLabel() { return cancelLabel; } public ImageView getImageViewExit() { return imageViewExit; } }
e98acf12d21213c3b8699ce735bc14a185e3d7a6
[ "Java", "INI" ]
20
INI
ErnestoDavidOlivaPerez/el-senor-de-los-anillos
9dc2ac1bc281fdd12efaf39d998af34a57c35e9e
31013d413abb0091245ac8c1daa1af3e3372cd48
refs/heads/master
<repo_name>JVue/biggestbass<file_sep>/app.rb require 'json' require 'sinatra' require 'sinatra/reloader' require 'sinatra/namespace' require_relative 'route_methods/biggestbass' require_relative 'route_methods/user' require_relative 'route_methods/html' require_relative 'route_methods/log' # require rack # require_relative 'secrets' # set port and binding set :bind, '0.0.0.0' set :port, 8080 set :sessions, :expire_after => 1800 # presets - load classes before do @html = HTML.new @bb = BiggestBass.new @log = Log.new end # Endpoints get '/biggestbass' do redirect '/biggestbass/members' if session[:userid] @user_session_status = @html.login_button if session[:userid].nil? @title = "Biggest Bass Leaderboard" @bb_table = @bb.sort_by_weight erb :biggestbass end get '/biggestbass/members' do redirect '/biggestbass' if session[:userid].nil? if session[:userid] @user_session_status = @html.logout_button(session[:userid]) @submit_weight = @html.submit_weight_button(session[:userid]) end @title = "Biggest Bass Leaderboard" @bb_table = @bb.sort_by_weight @bb_history = @bb.history_table erb :biggestbass_members end post '/biggestbass/sessions' do @user = User.new(params['username'], params['password']) if @user.authorized? session[:userid] = @user.name @log.log_action(session[:userid], 'Logged in successfully') redirect '/biggestbass/members' else @log.log_action(params['username'], 'Login failed') redirect '/unauthorized' end end post '/biggestbass/submit' do redirect '/unauthorized' if session[:userid].nil? if params['upgrade_weight'].to_s.empty? @log.log_action(session[:userid], 'Attempted to submit an upgrade with an empty field') redirect '/biggestbass/submission_failed' elsif params['upgrade_weight'].match(/[A-Za-z]/) @log.log_action(session[:userid], 'Attempted to submit an upgrade with letter characters in the field') redirect '/biggestbass/submission_failed' elsif [email protected]_fee_paid?(session[:userid], '$120') @log.log_action(session[:userid], 'Attempted to submit a weight upgrade but failed due to entry fee not paid') redirect '/biggestbass/submission_failed' elsif params['upgrade_weight'].to_s.match(/\d{1,2}\-\d{1,2}/) upgrade_weight = params['upgrade_weight'] @log.log_action(session[:userid], "Submitted an upgrade for #{params['fish_type']} @ #{params['upgrade_weight']}") elsif params['upgrade_weight'].to_s.match(/\d{1,2}\.\d{1,2}/) upgrade_weight = @bb.convert_decimal_to_lbs_oz(params['upgrade_weight']) @log.log_action(session[:userid], "Submitted an upgrade for #{params['fish_type']} @ #{upgrade_weight}") end @bb.update_bass_weight(@log.get_datetime, session[:userid], params['fish_type'], upgrade_weight) redirect '/biggestbass/members' end get '/biggestbass/submission_failed' do redirect '/unauthorized' if session[:userid].nil? @message = @html.weight_upgrade_submission_failed erb :biggestbass_submission_failed end get '/change_password_ui' do redirect '/unauthorized' if session[:userid].nil? @log.log_action(session[:userid], 'Is attempting to change his/her password') erb :change_password_ui end post '/change_password' do redirect '/unauthorized' if session[:userid].nil? @user = User.new(session[:userid], params['old_password']) if !params['old_password'].match(/\w/) || [email protected]? @error_msg = @html.old_password_incorrect @log.log_action(session[:userid], "Tried changing password but received: Error => Old password does NOT match") erb :change_password_ui elsif !params['new_password'].match(/\w/) || !params['new_password2'].match(/\w/) || params['new_password'] != params['<PASSWORD>2'] @error_msg = @html.new_passwords_not_match @log.log_action(session[:userid], "Tried changing password but received: Error => New passwords do NOT match and/or field(s) are empty") erb :change_password_ui elsif params['new_password'] == params['old_password'] @error_msg = @html.new_password_match_old @log.log_action(session[:userid], "Tried changing password but received: Error => New password matches old password") erb :change_password_ui else @user.change_password(params['<PASSWORD>']) @log.log_action(session[:userid], 'Changed password successfully') session[:userid] = nil erb :password_change_successful end end get '/unauthorized' do @message = 'Invalid username / password' erb :unauthorized end get '/logout' do @log.log_action(session[:userid], 'Logged out successfully') session[:userid] = nil redirect '/biggestbass' end <file_sep>/route_methods/html.rb require_relative 'biggestbass' class HTML def login_button <<~HTML <div style="float:right"> <form method="POST" action="/biggestbass/sessions"> Login: <input type="text" placeholder="Enter Username" name="username"> <input type="password" placeholder="Enter <PASSWORD>" name="<PASSWORD>"> <input type="submit" value="Submit"> </form> </div> HTML end def logout_button(user) <<~HTML <p align="right">[Logged in as: #{user}]</p> <div style="float:right"> <form align="right" method="get" action="/change_password_ui"> <button type="submit" name="action" value="submit">Change password</button> <button type="submit" name="action" formmethod="get" formaction="/logout">Logout</button> </form> </div> HTML end def submit_weight_button(user) <<~HTML <p align="left">Have an upgrade <b>#{user}</b>? Submit your <b>bullshit</b> catch below!</p> <p>(Input accepts either forms of weight measurement: lbs-oz (eg: 3-8) OR lbs-decimal (eg: 3.58))</p> <form method="POST" action="/biggestbass/submit"> <input type="radio" name="fish_type" value="largemouth_weight" checked>&nbsp;&nbsp;Largemouth<br> <input type="radio" name="fish_type" value="smallmouth_weight">&nbsp;&nbsp;Smallmouth<br><br> <input type="text" placeholder="eg: 3-8 OR 3.58" name="upgrade_weight"><br> <input type="submit" value="Submit Upgrade"> </form> HTML end def old_password_incorrect <<~HTML <p><font color="red">Error: Old password does NOT match</font></p> HTML end def new_passwords_not_match <<~HTML <p><font color="red">Error: New passwords do NOT match and/or field(s) are empty</font></p> HTML end def new_password_match_old <<~HTML <p><font color="red">Error: New password matches old password</font></p> HTML end def entry_fee_not_paid <<~HTML <p><font color="red">Error: Upgrade submission failed. Entry fee has not been paid.</font></p> HTML end def weight_upgrade_submission_failed <<~HTML <p><b>Reasons may include the following:</b><br> <ul> <li>Your entry fee has not been paid</li> <li>Weight submission field is empty</li> <li>Weight submission field contains letter characters</li> </ul><br> Please review the Global Actions History for more details. </p> HTML end end <file_sep>/route_methods/user.rb require_relative 'postgres' class User attr_reader :name, :password def initialize(name, password) @pg = PostGres.new @name = name @password = <PASSWORD> end def create_user(name, password) @pg.db_insert_data('users', 'name, password', "\'#{name}\', \'#{password}\'") end def authorized?(name = @name) user_info = @pg.db_query_user('users', name) return false if user_info.nil? || user_info.to_s.empty? || user_info.count.zero? return false if user_info['password'] != @password true rescue false end def delete_user(name = @name) delete_table_row('users', 'name', name) end def change_password(<PASSWORD>, name = @name) @pg.update_table_field('users', 'password', <PASSWORD>, 'name', name) end end
78b4ec2c2f901cbe82c44c6a164a31da3341016f
[ "Ruby" ]
3
Ruby
JVue/biggestbass
69c10a9b4f2c3025749834ac9b81ffe7005af0a2
6bbea91e209762d8ffb4bd4926ba29da3f81f31f
refs/heads/master
<file_sep>require './parser.rb' class Interpreter def initialize @evaluator = StringExecutor.new end def print @evaluator.parse("##(equals,1,2,(##(add,2,3)),(##(print_str,hehehey)))") ###(print_str, ##(add, 3 , ##(sub, 2, 1))) @evaluator.parse "##(define,mul3,(#(mul,A,#(mul,B,C))))" @evaluator.parse "##(segment_string,mul3,A,B,C)" @evaluator.parse "##(print_str,#(call,mul3,2,3,4))" @evaluator.parse "##(print_str,#(call,mul3,300,300,10))" end def console str = "" while str != "bye" p @evaluator.parse str if str != "" str = gets.chomp end end def from_file filepath megaline = "" File.open(filepath, "r") do |infile| while (line = infile.gets) megaline += line end end megaline.gsub! /\r\n/, "" megaline.gsub! /\n/, "" megaline.gsub! /\t/, "" instructions = megaline.split /\'/ instructions.each {|str| @evaluator.parse(str) } end end Interpreter.new().print #there will be init #if ARGV.empty? # Interpreter.new().console #else Interpreter.new().from_file("program.tr") Interpreter.new().console #end<file_sep>module Functions def get_marker_symbol i (i + 127).chr end def print_str str puts str nil end def read_str gets.chomp end def nil_value nil end def add x , y x.to_i + y.to_i end def mul x , y x.to_i * y.to_i end def sub x , y x.to_i - y.to_i end def div x , y x.to_i / y.to_i end def concat first, second first.to_s + second.to_s end #comparison def greater first, second, branch_1, branch_2 if first.to_i > second.to_i parse(branch_1) else parse(branch_2) end end def equals first, second, branch_1, branch_2 if first.to_i == second.to_i parse(branch_1) else parse branch_2 end end def less first, second, branch_1, branch_2 if first.to_i < second.to_i parse(branch_1) else parse(branch_2) end end #---------- def define name, string self.forms_array[name.to_sym] = string end def segment_string name, *args i = 1 args.each do |string| self.forms_array[name.to_sym].gsub!(Regexp.new(string) , get_marker_symbol(i)) i += 1 end end def call name , *args temp_string = String.new(self.forms_array[name.to_sym]) i = 1 args.each do |arg| temp_string.gsub!(Regexp.new(get_marker_symbol(i)), arg) i += 1 end temp_string.each_char.inject("") do |accum, char| if char.ord <= 127 accum = accum + char else accum = accum + "##(nil)" end accum end end def trace_on debug true end def trace_off debug false end end<file_sep>def get_char state = `stty -g` `stty raw -echo -icanon isig` STDIN.getc.chr ensure `stty #{state}` end def read_str string = "" while (new_char = get_char) != "'" string += new_char if new_char.ord == 13 puts else print new_char end end string end puts read_str
b761fa8ddad5fd7b1a46ee732fa9caf62c45e781
[ "Ruby" ]
3
Ruby
NikitaTsvetkov/Tractor
a38840c434b56439f3b6c95120489314abecab38
d8ed4e15ebdea2e56659dea32f06ff89bab5b7e7
refs/heads/main
<file_sep>from pokemon import app from pokemon.forms import PokeForm from flask import render_template, request, redirect, url_for, session import numpy as np import pandas as pd import json import pickle import os #function to get the name of the image to fetch... def change_names(name): name = name.replace('.png',"") name = name.lower() name = name.replace('mega ','') temp = '' for i in range(len(name)): if (name[i].isalnum()): temp += name[i] return temp + '.png' #Random Forest Classifier... def run_rf(features): features = [features] location = os.path.join('pokemon', 'pokemon_model') fp_classifier = open(os.path.join(location,'classifier.pkl'),'rb') fp_label = open(os.path.join(location,'labelEnc.pkl'),'rb') fp_onehot = open(os.path.join(location,'onehot.pkl'),'rb') classifier = pickle.load(fp_classifier) labelE = pickle.load(fp_label) onehot = pickle.load(fp_onehot) fp_classifier.close() fp_label.close() fp_onehot.close() features = np.array(onehot.transform(features)) y_pred = classifier.predict(features) y_pred = labelE.inverse_transform(y_pred) return y_pred[0] #To fetch the actual details of a pokemon from the csv file... def get_actual_details(name): location = os.path.join('pokemon', 'pokemon_model') df = pd.read_csv(os.path.join(location, 'pokemon.csv')) pokemon_row = df.loc[ df['Name']==name, ["Type 1", "Type 2", "Attack", "Defense", "Speed"]] fp_minmax = open(os.path.join(location,'min_max.pkl'),'rb') minmax = pickle.load(fp_minmax) pokemon_row.iloc[:,2:] = minmax.transform(pokemon_row.iloc[:,2:]) pokemon_row.iloc[:,2:] = pokemon_row.iloc[:,2:].applymap(lambda x:x*100) fp_minmax.close() pokemon_row = pokemon_row.values data = dict() data['ptype'] = pokemon_row[0][0] data['stype'] = 'No Secondary Type' if pd.isnull(pokemon_row[0][1]) else pokemon_row[0][1] data['attack'] = round(pokemon_row[0][2],2) data['defense'] = round(pokemon_row[0][3],2) data['speed'] = round(pokemon_row[0][4],2) return data #The page containing the form... @app.route("/", methods = ['GET','POST']) def mainpage(): form = PokeForm(stype = "No Secondary Type" ) if request.method == 'POST': data = dict() data['attack'] = str(form.attack.data) data['defense'] = str(form.defense.data) data['speed'] = str(form.speed.data) data['ptype'] = form.ptype.data data['stype'] = form.stype.data session['data'] = json.dumps(data) return redirect(url_for('result')) return render_template('mainpage.html', form = form) #The results are displayed in this page... @app.route('/Results') def result(): if 'data' in session: pData = json.loads(session['data']) session.pop('data') features = [pData['ptype'], pData['stype'], pData['attack'], pData['defense'], pData['speed']] name = run_rf(features) pic = url_for('static', filename = f"Poke_Images/{change_names(name)}") if not os.path.isfile(os.path.join('pokemon', 'static','Poke_Images',change_names(name))): pic = url_for('static', filename = f"Poke_Images/default.png") actual_data = get_actual_details(name) return render_template('results.html', pData=pData, name=name, pic = pic , actual_data= actual_data) else: return redirect(url_for('mainpage')) <file_sep>from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) #replace the secret key... app.config['SECRET_KEY'] = '<KEY>' from pokemon import routes<file_sep>from flask_wtf import FlaskForm from wtforms.fields.html5 import DecimalRangeField from wtforms import SubmitField, SelectField ptypes = ['Grass', 'Fire', 'Water', 'Bug', 'Normal', 'Poison', 'Electric', 'Ground', 'Fairy', 'Fighting', 'Psychic', 'Rock', 'Ghost', 'Ice', 'Dragon', 'Dark', 'Steel', 'Flying'] stypes = ['Poison', 'No Secondary Type', 'Flying', 'Dragon', 'Ground', 'Fairy', 'Grass', 'Fighting', 'Psychic', 'Steel', 'Ice', 'Rock', 'Dark', 'Water', 'Electric', 'Fire', 'Ghost', 'Bug', 'Normal'] class PokeForm(FlaskForm): ptype = SelectField("Primary Type:",choices = ptypes) stype = SelectField("Secondary Type:",choices = stypes) attack = DecimalRangeField('Attack:') speed = DecimalRangeField('Speed:') defense = DecimalRangeField('Defense:') submit = SubmitField("Get Pokemon")<file_sep>import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, LabelEncoder from sklearn.compose import ColumnTransformer from sklearn.ensemble import RandomForestClassifier import random import math import pickle #function for creating fake data... def temp_func(x): opt = random.choice([0,1,2,3]) if opt == 0: #floor operation x = math.floor(x) elif opt == 1: #ceil operation x = math.ceil(x) elif opt == 2: #add some value x = x + random.choice([1,2,3,4,5,6,7]) else: #subtract some value x = x - random.choice([1,2,3,4,5,6,7]) return x #importing dataset pokemon_data = pd.read_csv("pokemon.csv") df = pd.DataFrame() df[["Type 1", "Type 2", "Attack", "Defense", "Speed", "Name"]] = \ pokemon_data.loc[:, ["Type 1", "Type 2", "Attack", "Defense", "Speed", "Name"]] #replacing np.nan with 'No Secondary Type' df["Type 2"] = df["Type 2"].replace(np.nan, "No Secondary Type") #Scaling Attack, Defense, Speed min_max_scaler = MinMaxScaler() df.iloc[:, 2:-1] = min_max_scaler.fit_transform(df.iloc[:, 2:-1]) df.iloc[:,2:-1] = df.iloc[:,2:-1].applymap(lambda x:x*100) #creating fake data using temp_func... temp_df = df.copy() temp_df.iloc[:,2:-1] = temp_df.iloc[:,2:-1].applymap(temp_func) temp_df2 = df.copy() temp_df2.iloc[:,2:-1] = temp_df2.iloc[:,2:-1].applymap(temp_func) temp_df3 = df.copy() temp_df3.iloc[:,2:-1] = temp_df3.iloc[:,2:-1].applymap(temp_func) #concatenating the dataframes... df = pd.concat([df, temp_df, temp_df2, temp_df3]) #X -> Independent variables #y -> Dependent variable X = df.iloc[:,:-1].values y = df.iloc[:,-1].values #Encoding Categorical data: Type 1, Type 2 ct = ColumnTransformer(transformers = [('encoder1', OneHotEncoder(sparse = False ), [0,1])], remainder = "passthrough" ) X = np.array(ct.fit_transform(X)) #Encoding Categorical data: Name le = LabelEncoder() le.fit(y) y = le.transform(y) classifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0) classifier.fit(X, y) #creating pickles classifier_pkl = open("classifier.pkl","wb") minmax_pkl = open("min_max.pkl","wb") onehot_pkl = open("onehot.pkl","wb") labelEnc_pkl = open("labelEnc.pkl","wb") pickle.dump(classifier, classifier_pkl) pickle.dump(min_max_scaler, minmax_pkl) pickle.dump(ct, onehot_pkl) pickle.dump(le, labelEnc_pkl) classifier_pkl.close() minmax_pkl.close() onehot_pkl.close() labelEnc_pkl.close() <file_sep># Pokemon-Predictor-Using-Random-Forrest-Classifier ## Based on the inputs given by the user this web-application predicts the pokemon. ## Instructions to run the web-application 1) Install python 3.6 or above on your device 2) Setup a python virtual environment and activate it.(optional) 3) Install Flask, Flask-WTF, scikit-learn, pandas, numpy. 4) Download the Zip file of the repository and unzip it. 5) Open the project directory and navigate to ./pokemon/pokemon_model/ directory on command line. 6) Run model.py with python. 7) This will create four .pkl files(classifier.pkl, onehot.pkl, min_max.pkl, labelEnc.pkl) in the 'pokemon_model' directory. 8) Note: If you don't run model.py with 'pokemon_model' as you working directory, the .pkl files will be saved in some other directory. Please run the model.py script with 'pokemon_model' as your working directory. 9) Now run main.py in the project directory which will start the server. 10) Open http://localhost:5000 on your browser with the server running. ## Datasets used 1) For data: https://www.kaggle.com/abcsds/pokemon?select=Pokemon.csv 2) For Images: https://www.kaggle.com/arenagrenade/the-complete-pokemon-images-data-set Note: some changes were made to the csv files and also to the filenames, quality of the images to fit the needs of the application.
cbc603b2c2aa1a55f4f75cc6fac8e5fe9906abca
[ "Markdown", "Python" ]
5
Python
PanduAkshay/Pokemon-Predictor-Using-Random-Forrest-Classification
b914b9155c7c6f6230cc3bc7fd2ca65c33451b7b
bee555f6f98fcf5aec3e0daeca34a3032cc907c4
refs/heads/master
<repo_name>burnasheva/gradlew-test<file_sep>/src/main/java/com/test/Test.java package com.test; /** * Created by teng on 2017/7/17. */ public class Test { } <file_sep>/README.md # gradlew-test Build project by gradlew 如果本机没有安装gradle,请执行目录下的gradlew来自动下载编译项目。 <file_sep>/settings.gradle rootProject.name = 'gradlew-test'
471529d4272699d124713b7726c763ff48591c42
[ "Markdown", "Java", "Gradle" ]
3
Java
burnasheva/gradlew-test
fdd75730f7d3047e5991962c3238229444b04df2
909d386fef8e146e3a6df10d69ff07c87f5d4766
refs/heads/main
<file_sep>import threading from tkinter import * import webbrowser import time def wd(mem): def run(): link = entry_label.get() mem.append(link) root = Tk() title_label = Label(root, text="Mini Broswer", pady=10, padx=50) run_button = Button(root, text="Run", padx=10, command=run) entry_label = Entry(root, text="Digite a URL do site que quer abrir", width=100) title_label.grid(row=0, column=0) run_button.grid(row=1, column=1) entry_label.grid(row=1, column=0) root.mainloop() def render(mem): mem_old = mem[-1] while True: if mem[-1] == mem_old: print("Esperando URL...") else: print(f'render( {mem[-1]} )') webbrowser.open_new_tab(mem[-1]) mem_old = mem[-1] break time.sleep(1) memoria = ["nada"] t1 = threading.Thread(target=wd, kwargs=dict(mem=memoria)) t2 = threading.Thread(target=render, kwargs=dict(mem=memoria)) t1.start() t2.start() <file_sep># Sistemas Operacionais ## Integrantes da equipe * <NAME> (18111264) * <NAME> (18111464) ### Instalação do pipenv Execute o comando: `pip install pipenv` ### Instruções para execução 1. Entre no diretório raiz do projeto com o seu terminal 1. Execute o comando: `python -m pipenv shell` 1. Execute o comando: `pipenv install` 1. Entre no diretório da questão e execute o comando: `python q{número da questão}.py` 1. Após a execução das questões remova o ambiente virtual com o comando: `pipenv --rm` 1. Saia do ambiente com o comando: `exit` <file_sep>import time import threading import random as rd from faker import Faker class Crianca: tempo_de_espera = 3 def __init__(self, nome, priority, meta): self.com_bola = False self.pontos = 0 self.meta = meta self.nome = nome self.priority = priority def jogando(self, jogo): while jogo.em_progresso: if jogo.bola_em_uso == False: self.pegar_bola(jogo) if self.pontos >= self.meta: print(f'Fim de jogo! {self.nome} ganhou.') jogo.em_progresso = False break time.sleep(self.tempo_de_espera) self.soltar_bola(jogo) else: time.sleep(1-self.priority) def pegar_bola(self, jogo): jogo.bola_em_uso = True self.com_bola = True self.pontos += 1 print(f'{self.nome}: Peguei a bola! | {self.pontos} Pontos!\n') def soltar_bola(self, jogo): jogo.bola_em_uso = False self.com_bola = False print(f'{self.nome}: Soltei!\n') class Jogo: em_progresso = True bola_em_uso = True def start_game(num_criancas, meta): fake = Faker('pt_BR') parametros_do_jogo = [{'nome': fake.name(), 'prioridade': rd.uniform(0, 1)} for i in range(num_criancas)] print('Parâmetros dos jogadores:') # Criando crianças criancas = [] for parametros in parametros_do_jogo: print(parametros) criancas.append(Crianca(parametros['nome'], parametros['prioridade'], meta)) jogo = Jogo() threads = [] # Atribuindo a cada criança uma thread e iniciando essas threads for c in criancas: t = threading.Thread(target=c.jogando, kwargs=dict(jogo=jogo)) t.start() threads.append(t) # Começando a brincadeira print(f'\nO Jogo começou com {num_criancas} jogadores, e terminará quando algum jogador atingir {meta} pontos.\n') jogo.bola_em_uso = False start_game(num_criancas=10, meta=10) <file_sep>import threading import time class Saldo: def __init__(self, name, value): self.name = name self.value = value self.begin = False def s1(saldo): while True: if saldo.begin: x = saldo.value # print("x: ",x) x = x-200 saldo.value = x # print(f'depositado x : {saldo.value}') break def s2(saldo): while True: if saldo.begin: y = saldo.value y = y-100 # print("y: ",y) saldo.value = y # print(f'depositado y : {saldo.value}') break def d1(saldo): while True: if (saldo.begin): x = saldo.value x = x+100 saldo.value = x break def d2(saldo): while True: if (saldo.begin): y = saldo.value y = y+200 saldo.value = y break saldo_a, saldo_b = Saldo("a", 500), Saldo("b", 900) t1 = threading.Thread(target=s1, kwargs=dict(saldo=saldo_a)) t2 = threading.Thread(target=s2, kwargs=dict(saldo=saldo_a)) t1.start() t2.start() saldo_a.begin = True t3 = threading.Thread(target=d1, kwargs=dict(saldo=saldo_b)) t4 = threading.Thread(target=d2, kwargs=dict(saldo=saldo_b)) t3.start() t4.start() saldo_b.start = True time.sleep(1) print(saldo_a.value, saldo_b.value) <file_sep>from time import sleep import threading as td class Conta: def __init__(self, saldo=0, nome='NOT NAMED'): self.in_use = True self.saldo = saldo self.nome = nome self.historico = [] def depositar(self, valor=0, pessoa='Anonimo'): if valor >= 0: self.saldo += valor print(f'Foi depositado: {valor} por: {pessoa} | saldo da conta {self.nome}: {self.saldo} \n') self.historico.append((pessoa, 'deposito', valor, self.saldo)) confirmation = True else: print(f'Ocorreu um erro na operacao \n') confirmation = False sleep(1) return confirmation def sacar(self, valor=0, pessoa='Anonimo'): if valor > 0 and (self.saldo - valor) >= 0: self.saldo -= valor self.historico.append((pessoa, 'saque', valor, self.saldo)) confirmation = True print(f'Foi sacado: {valor} por: {pessoa} | saldo da conta {self.nome}: {self.saldo} \n') else: print(f'Ocorreu um erro na operacao \n') confirmation = False sleep(1) return confirmation def show_historico(self): for event in self.historico: print(event) class Cliente: def __init__(self, nome): self.nome = nome def tentar_depositar(self, conta, valor=0, n_max_tries=1): while n_max_tries: sleep(2) if not conta.in_use: conta.in_use = True conta.depositar(valor, self.nome) conta.in_use = False break else: print(f'Cliente {self.nome} aguardando...') def tentar_sacar(self, conta, valor=0, n_max_tries=1): while n_max_tries: sleep(2) if not conta.in_use: conta.in_use = True conta.sacar(valor, self.nome) conta.in_use = False break else: print(f'Cliente {self.nome} aguardando...') def script(self, conta1, conta2, valores, max_tries): x, y = valores[0], valores[1] self.tentar_sacar(conta1, x, max_tries) self.tentar_depositar(conta2, y, max_tries) # Criando as entidades do programa conta1 = Conta(500, 'A') conta2 = Conta(900, 'B') cliente1, cliente2 = Cliente('A'), Cliente('B') # Definindo e iniciando as threads com uma função target t1 = td.Thread(target=cliente1.script, kwargs=dict(conta1=conta1, conta2=conta2, valores=[200, 100], max_tries=50)) t2 = td.Thread(target=cliente2.script, kwargs=dict(conta1=conta1, conta2=conta2, valores=[100, 200], max_tries=50)) t1.start() t2.start() # Começando a brincadeira conta1.in_use, conta2.in_use = False, False # Esperando o retorno das threads t1.join() t2.join() # Apresentando os resultados finais print('\n\nLog Conta1') conta1.show_historico() print('------------------') print('Log Conta2') conta2.show_historico() print(f'\nSALDO 1: {conta1.saldo}, SALDO2: {conta2.saldo}')
1f9b9c20254af33e2c33dc0db718983a4e7df44a
[ "Markdown", "Python" ]
5
Python
galerax/SO
b5b7f6f6e93a6b1ce91b8316880ad7ffa2e9f68c
21c3f6d1c872d5ad3b96b79b29998608a60e8d97
refs/heads/master
<repo_name>dehare/doctrine-extension<file_sep>/lib/Dehare/Doctrine/DoctrineExtension.php <?php namespace Dehare\Doctrine; class DoctrineExtension extends ConnectionManager { public function __call($method, $args) { $result = false; $connection = $this->getConnection(); // DBAL config $fetch_methods = array('array', 'all', 'assoc', 'column'); if (strpos(strtolower($method), 'fetch') !== false) { $mtest = str_ireplace('fetch', '', strtolower($method)); if (in_array($mtest, $fetch_methods)) { $dbal = new DBAL($connection); array_unshift($args, $mtest); $result = call_user_func_array(array($dbal, 'fetchAction'), $args); } } elseif (method_exists($this, $method)) { $result = call_user_func_array(array($this, $method), $args); } if (!empty($result)) { return $result; } } /** * Shorthand for SQL query builder * @return object */ public function build($key=null) { $connection = $this->getConnection($key); return $connection->createQueryBuilder(); } }<file_sep>/lib/Dehare/Doctrine/Statement.php <?php namespace Dehare\Doctrine; use Dehare\Exception\InvalidArgumentException as IAE; use Dehare\Silex\Helper\ReflectionHelper; class Statement { const STMT_SELECT = 1, STMT_UPDATE = 2, STMT_INSERT = 3, STMT_DELETE = 4; const PARAM_MATCH = 10, PARAM_DEFAULT = 10, PARAM_RANGE = 11, PARAM_RANGE_MATCH = 12, PARAM_RANGE_BETWEEN = 12, PARAM_LIKE = 13; public $table = null, $columns = array('*'), $conditions = array(), $group = array(), $order = array(), $limit = 0; /** * @var object ReflectionHelper */ private $_reflection; /** * @var string Type of statment * @see self::STMT_* */ private $_type; /** * @var bool Custom build utilized */ private $_custom = false; /** * @var array Parameters used in WHERE statement */ private $_parameters = array(); /** * @var string SQL query string */ private $query = null; /** * @var array Parameter values */ private $values = array(); public function __construct($type=self::STMT_SELECT) { $this->_reflection = new ReflectionHelper($this); $types = $this->_reflection->getProperties(ReflectionHelper::PROPERTY_CONSTANT, 'STMT_'); if (!in_array($type, $types)) { throw IAE::unknownInConstants($this, 'Unknown Statement type "%s". Please supply one of [%s]', array($type), 'STMT_'); } $this->_type = $type; } public function getQuery() { if (!$this->query && !$this->_custom) { $this->build(); } return trim($this->query); } public function getParameters() { if (empty($this->_parameters) && empty($this->values) && !$this->_custom) { $this->build(); } return $this->values; } public function bindParameter($parameter, $value=null, $type=null) { if (empty($value)) { return; } $result = $parameter; switch (true) { case $type == self::PARAM_RANGE && is_array($value): $result .= ' >= ? AND '.$parameter.' <= ?'; break; case $type == self::PARAM_RANGE_MATCH && is_array($value): $result .= ' BETWEEN ? AND ?'; break; case $type == self::PARAM_MATCH && is_array($value): case empty($type) && is_array($value): $params = implode(',', array_fill(0, count($value), '?')); $result .= ' IN ('.$params.')'; break; case $type == self::PARAM_LIKE: $result .= ' LIKE ?'; break; case $type == self::PARAM_MATCH: case empty($type): $result .= ' = ?'; break; default: throw IAE::unknownInConstants($this, 'Unknown Statement parameter type "(%s) %s". Please supply one of [%s]', array(gettype($type), $type), 'PARAM_'); } $this->_parameters[] = $result; } public function bindValue($parameter, $value, $type=null) { if (empty($value)) { return; } switch (true) { case $type == self::PARAM_RANGE && is_array($value): case $type == self::PARAM_RANGE_MATCH && is_array($value): $from = min($value); $to = max($value); $this->values[] = $from; $this->values[] = $to; break; case $type == self::PARAM_MATCH && is_array($value): case empty($type) && is_array($value): foreach($value as $v) { $this->values[] = $v; } break; default: $this->values[] = $value; } } public function buildColumns($columns=array()) { if (empty($this->columns) || !is_array($columns)) { $this->columns = array('*'); } return implode(', ', $this->columns); } public function buildParameters($parameters=array(), $keyword=false, $has_value=true, $seperator=' AND ') { $this->_parameters = array(); $parameter_types = $this->_reflection->getProperties(ReflectionHelper::PROPERTY_CONSTANT, 'PARAM_'); $result = ''; $count = count($parameters); if (!$count) { return; } if ($keyword) { $result .= ' WHERE '; } foreach($parameters as $param=>$value) { if ($has_value) { $parameter_type = null; // determine if value holds parameter type if (is_array($value) && count($value) == 1) { $keys = array_keys($value); if (in_array($keys[0], $parameter_types) && $keys[0] != $values[$keys[0]]) { $value = $value[$keys[0]]; $parameter_type = $keys[0]; } } $this->bindParameter($param, $value, $parameter_type); $this->bindValue($param, $value, $parameter_type); } else { $this->bindParameter($value, null); } } $result .= implode($seperator, $this->_parameters); return $result; } public function buildOrder($order=array(), $keyword=false) { $result = ''; if ($keyword && count($order)) { $result .= ' ORDER BY '; } $fields = array(); foreach($order as $ord) { $field = $ord; $dir = 'ASC'; if (is_array($ord)) { $field = $ord[0]; $dir = $ord[1]; } $fields[] = "$field $dir"; } $result .= $this->buildFields($fields); return $result; } public function buildFields($fields=array(), $seperator=', ') { return implode($seperator, $fields); } public function customBuild() { $this->query = null; $this->_custom = true; switch($this->_type) { case self::STMT_SELECT: $columns = $this->buildColumns($this->columns); $parameters = implode(', ', $this->_parameters); $group = $this->buildFields($this->group); $order = $this->buildOrder($this->order, true); $limit = $this->limit > 0 ? ' LIMIT '.$this->limit : null; $this->query = "SELECT $columns FROM $table $parameters $group $order $limit"; break; case self::STMT_UPDATE: $columns = $this->buildParameters($this->columns, false); $parameters = implode(', ', $this->_parameters); $this->query = "UPDATE $table SET $columns $parameters"; break; default: throw new \InvalidArgumentException('Requested Statement type is not yet supported. Please refer to the default Doctrine library.'); } } private function build() { $this->query = null; $this->values = array(); $this->_parameters = array(); $this->_custom = false; if (empty($this->table)) { throw new \InvalidArgumentException('No table supplied'); } switch($this->_type) { case self::STMT_SELECT: $table = $this->table; $columns = $this->buildColumns($this->columns); $parameters = $this->buildParameters($this->conditions, true); $group = $this->buildFields($this->group); $order = $this->buildOrder($this->order, true); $limit = $this->limit > 0 ? ' LIMIT '.$this->limit : null; $this->query = "SELECT $columns FROM $table $parameters $group $order $limit"; break; case self::STMT_UPDATE: $table = $this->table; $columns = $this->buildParameters($this->columns, false, false, ', '); $parameters = $this->buildParameters($this->conditions, true); $this->query = "UPDATE $table SET $columns $parameters"; break; default: throw new \InvalidArgumentException('Requested Statement type is not yet supported. Please refer to the default Doctrine library.'); } } }<file_sep>/lib/Dehare/Doctrine/ConnectionManager.php <?php namespace Dehare\Doctrine; use \Doctrine\DBAL\DriverManager; use \Doctrine\DBAL\Connection; class ConnectionManager { private $configuration = array(), $connection = array(), $connection_active = null, $pdo_source = array(); /** * Creates new Doctrine connection * * @param string $configuration_key * @return void */ public function connect($configuration_key=null) { if (!$configuration_key) { $keys = array_keys($this->configuration); $configuration_key = $keys[0]; } $config = $this->getConfig($configuration_key); if (strpos($config['driver'], 'pdo_') !== false) { $this->connectPDO($configuration_key); } $connection = DriverManager::getConnection($this->configuration[$configuration_key]); $this->setConnection($configuration_key, $connection); $this->connection_active = $configuration_key; } private function connectPDO($configuration_key) { $config = $this->getConfig($configuration_key); $driver = strtolower(str_replace('pdo_', '', $config['driver'])); $charset = isset($config['charset']) ? ';charset='.$config['charset'] : ''; $pdo = new \PDO($driver.':host='.$config['host'].';dbname='.$config['dbname'].$charset, $config['user'], $config['password']); $this->setConfig($configuration_key, array('pdo'=>$pdo)); $this->pdo_source[$configuration_key] = $pdo; } /** * Get specified connection configuration * @param string $configuration_key * @param boolean $get_all Get all configurations * @return array */ public function getConfig($configuration_key=null, $get_all=false) { if ($get_all) { return $this->configuration; } $this->getActiveConnection($configuration_key); if (isset($this->configuration[$configuration_key])) { return $this->configuration[$configuration_key]; } return false; } /** * Set connection configuration * @param string $name Named key for configuration * @param array $configuration */ public function setConfig($name, $configuration=array()) { $this->configuration[$name] = $configuration; } /** * Gets Doctrine\DBAL\Connection of connections * @param string $key * @return object */ public function getConnection($key=null) { $this->getActiveConnection($key); if (isset($this->connection[$key])) { return $this->connection[$key]; } } public function setConnection($key, Connection $connection) { $this->connection[$key] = $connection; } /** * Gets PDO connection of connections * @param string key * @return object */ public function getSource($key=null) { $this->getActiveConnection($key); if (isset($this->pdo_source[$key])) { return $this->pdo_source[$key]; } } public function setActiveConnection($key) { $this->connection_active = $key; } private function getActiveConnection(&$key) { if (empty($key) && $this->connection_active) { $key = $this->connection_active; } elseif (empty($this->connection_active) && count($this->configuration)) { $keys = array_keys($this->configuration); $key = $keys[0]; } } }<file_sep>/lib/Dehare/Doctrine/DBAL.php <?php namespace Dehare\Doctrine; use \Doctrine\DBAL\Connection; class DBAL { private $conn; public function __construct(Connection $connection) { $this->conn = $connection; } public function fetchAction($method='all') { $args = func_get_args(); $stmt = new Statement(); $stmt->table = !empty($args[1]) ? $args[1] : $stmt->table; $stmt->columns = !empty($args[2]) ? $args[2] : $stmt->columns; $stmt->conditions = !empty($args[3]) ? $args[3] : $stmt->conditions; $stmt->group = !empty($args[4]) ? $args[4] : $stmt->group; $stmt->order = !empty($args[5]) ? $args[5] : $stmt->order; $stmt->limit = !empty($args[6]) ? $args[6] : $stmt->limit; $query = $stmt->getQuery(); $params = $stmt->getParameters(); $result = $this->conn->{'fetch'.ucfirst($method)}($query, $params); return $result; } /** * @internal Use Doctrine\DBAL */ public function updateAction() {} /** * @internal Use Doctrine\DBAL */ public function insertAction() {} /** * @internal Use Doctrine\DBAL */ public function deleteAction() {} }
f66c2412dd38cf873564763fc6bfa7e3bc92f955
[ "PHP" ]
4
PHP
dehare/doctrine-extension
64182b71e8928dbde69e8836727ed9b4263bcd59
a04e649f36fe14d1918d47cdadac18de92a0a7f1
refs/heads/master
<repo_name>MMHK/vue-amd-cli<file_sep>/README.md # Vue-AMD-Cli Create Vue Project By AMD way tools Vue AMD 部署项目工具,此工具会在当前目录下建立整个(Vue + AMD)模式的项目模板。 第一次,会在当前目录下载项目模板,并使用 `bower` 安装所有的项目依赖到`lib`下。然后就可以马上开始编码工作,不需要重新配置环境。 在第一次运行后,在执行`vue-amd-cli` 就会出现交互式的命令脚手架,方便创建 `page` / `component` / `service` 等模板。 # 环境依赖 - 必须已经安装 [NodeJS](https://nodejs.org/zh-cn/) - 必须已经安装 [Git 客户端](https://git-scm.com/download/win) # 安装 ``` npm install vue-amd-cli -g ``` # 运行 ``` vue-amd-cli ``` ## Support VueJS 1.*<file_sep>/index.js #!/usr/bin/env node var fs = require('fs') var process = require('process') var prompt = require('prompt') var colors = require('colors/safe') var path = require('path') var template = require('lodash.template') var git_download = require('download-git-repo') var bower = require('bower') require.extensions['.tpl'] = function (module, filename) { var tmp = '' try { tmp = fs.readFileSync(filename, 'utf8') } catch (e) { console.error(e) } module.exports = tmp } var ROOT_DIR = process.cwd(), TEMPLATE = { html: require('./template/html.tpl'), css: require('./template/css.tpl'), service: template(require('./template/service.tpl')), js: template(require('./template/js.tpl')) } prompt.message = colors.green('vue-amd-cli') prompt.delimiter = colors.green('#') if (fs.existsSync(path.join(ROOT_DIR, 'package.json'))) { // // Start the prompt // prompt.start() init() } else { install() } function install() { prompt.get({ properties: { project_name: { description: colors.green('\n 请输入项目名') } } }, function (err, result) { if (err) { console.log(err) } git_download('MMHK/vue-amd-template', '.', { clone: false }, function (err) { if (err) { console.error(err) return } replaceFile(path.join(ROOT_DIR, 'readme.md.tpl'), { 'project_name': result.project_name }) replaceFile(path.join(ROOT_DIR, 'package.json.tpl'), { 'project_name': result.project_name }) replaceFile(path.join(ROOT_DIR, 'index.html.tpl'), { 'project_name': result.project_name }) replaceFile(path.join(ROOT_DIR, 'bower.json.tpl'), { 'project_name': result.project_name }) bower.commands .install([], { production: true, save: false }, { interactive: true }) .on("log", function (args) { if (args.level == "action" && args.id == "install") { console.log("%s...安装中...", args.message); } }) .on('end', function (installed) { console.log("安装成功!") }) }) }) prompt.start() } function init() { prompt.get({ properties: { type: { description: colors.green('\n 请选择功能: \n 1: 新建组件; \n 2: 新建页面; \n 3: 新建服务 \n') }, name: { description: colors.green('\n 请输入新的模块名: \n') } } }, function (err, result) { if (result.type == 1) { component(result.name) return } if (result.type == 3) { service(result.name) return } else { page(result.name) return } }) } function saveFile(filename, content) { var dir = path.dirname(filename) try { if (!fs.existsSync(dir)) { fs.mkdirSync(dir) } fs.writeFileSync(filename, content) } catch (e) { console.error(e) } } function replaceFile(template_name, args) { try { var file = fs.readFileSync(template_name, 'utf8'), distFile = template_name.replace('.tpl', ''), temp = template(file)(args) saveFile(distFile, temp) fs.unlinkSync(template_name) } catch (e) { console.error(e) } } function page(name) { var fullpath = 'page/' + name if (fs.existsSync(path.join(ROOT_DIR, fullpath + '.js'))) { console.log(colors.red('已经存在page:' + fullpath)) return } saveFile(path.join(ROOT_DIR, fullpath + '.js'), TEMPLATE.js({ filebase: fullpath })) saveFile(path.join(ROOT_DIR, fullpath + '.css'), TEMPLATE.css) saveFile(path.join(ROOT_DIR, fullpath + '.html'), TEMPLATE.html) console.log(colors.green('创建page:' + fullpath + ' 成功!')) } function component(name) { var fullpath = 'component/' + name if (fs.existsSync(path.join(ROOT_DIR, fullpath + '.js'))) { console.log(colors.red('已经存在 component:' + fullpath)) return } saveFile(path.join(ROOT_DIR, fullpath + '.js'), TEMPLATE.js({ filebase: fullpath })) saveFile(path.join(ROOT_DIR, fullpath + '.css'), TEMPLATE.css) saveFile(path.join(ROOT_DIR, fullpath + '.html'), TEMPLATE.html) console.log(colors.green('创建 component:' + fullpath + ' 成功!')) } function service(name) { var fullpath = 'service/' + name if (fs.existsSync(path.join(ROOT_DIR, fullpath + '.js'))) { console.log(colors.red('已经存在 service:' + fullpath)) return } saveFile(path.join(ROOT_DIR, fullpath + '.js'), TEMPLATE.service({ filebase: fullpath })) }
6d87c31a01403459a896b666f0817b938cfdb5ac
[ "Markdown", "JavaScript" ]
2
Markdown
MMHK/vue-amd-cli
8e47b3dd6f6ccfa38acf32b538480e5cae936f06
fdd5c53751c6ffa8225e6a401e71848c2d35d64a
refs/heads/master
<repo_name>chinmaysathe93/Coursera_TensorFlow_in_practice_Specialization<file_sep>/1_Introduction_to_TensorFlow/Code Helper.py !pip install tensorflow==2.0.0-alpha0 activate nlp_course pip install --upgrade tensorflow # ------------------------------------------ Rule of Thumbs : #1 By adding more Neurons we have to do more calculations, slowing down the process,that doesn't #mean it's always a case of 'more is better'. #2 The first layer in your network should be the same shape as your data. #3 The number of neurons in the last layer should match the number of classes you are classifying for. #4 Normalize the Data before inputing # ------------------------------------------ # GRADED FUNCTION: train_mnist_conv def train_mnist_conv(): # Please write your code only where you are indicated. # please do not remove model fitting inline comments. # YOUR CODE STARTS HERE class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): if(logs.get('acc')>0.998): print("\n Reached 99.8% accuracy so cancelling training!") self.model.stop_training = True # YOUR CODE ENDS HERE mnist = tf.keras.datasets.mnist (training_images, training_labels), (test_images, test_labels) = mnist.load_data(path=path) # YOUR CODE STARTS HERE training_images=training_images.reshape(60000, 28, 28, 1) test_images=test_images.reshape(10000, 28, 28, 1) training_images, test_images = training_images / 255.0, test_images / 255.0 callbacks = myCallback() # YOUR CODE ENDS HERE model = tf.keras.models.Sequential([ # YOUR CODE STARTS HERE tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation=tf.nn.relu), tf.keras.layers.Dense(10, activation=tf.nn.softmax) # YOUR CODE ENDS HERE ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # model fitting history = model.fit( # YOUR CODE STARTS HERE training_images, training_labels, epochs=20, callbacks=[callbacks] # YOUR CODE ENDS HERE ) # model fitting return history.epoch, history.history['acc'][-1] # ------------------------------------------ <file_sep>/README.md <h1> Coursera - TensorFlow in Practice Specialization</h1> <a href = "https://www.coursera.org/specializations/tensorflow-in-practice"> <img src="/Tensorflow_Screen.png"></a> <h3> 1. Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning</h3> <h3> 2. Convolutional Neural Networks in TensorFlow</h3> <h3> 3. Natural Language Processing in TensorFlow</h3> <h3> 4. Sequences, Time Series and Prediction</h3>
cca7ae29b60f72bf865fce4471863a03866dafcd
[ "Markdown", "Python" ]
2
Python
chinmaysathe93/Coursera_TensorFlow_in_practice_Specialization
40e0efacca96a00adb2d24cc855cd07223cde056
774f7ec160c77b98710cb01d0ef84582797e93c4
refs/heads/master
<repo_name>lancemitchell/strengthcom<file_sep>/public/js/main.js /* ========================================================================== Strength.com global JS ========================================================================== */ $(document).ready(function(){ // Init Event Handlers - Flyout Panel Events $('#nav-flyout-cart').on('click',function(e){ e.preventDefault(); // Refresh Cart Panel $('#cart-flyout-panel').attr('src', $('#cart-flyout-panel').attr('src')); $('body').toggleClass('nav-flyout-expanded'); $('#links').collapse('hide'); }); $('.flyout-nav-wrapper .nav-flyout-close a').on('click',function(e){ e.preventDefault(); $('body').removeClass('nav-flyout-expanded'); $('#links').collapse('hide'); }); // Init Event Handlers - Navgoco with defaults if ($(".flyout-nav-menu").length) $(".flyout-nav-menu").navgoco({ caret: '&nbsp;<span class="caret"></span>', accordion: true, openClass: 'open', save: true, cookie: { name: 'navgoco', expires: false, path: '/' }, slide: { duration: 300, easing: 'swing' } }); // Initialize shopping cart basket popupover functionality $(".shopping_basket").popover({delay: {show: 0, hide: 4000},content: function() { return shoppingBasketPopupMsg; }}); }); //Document.Ready var shoppingBasketPopupMsg = ''; function showCartPopupMsg( msg ) { shoppingBasketPopupMsg = msg; $('.shopping_basket').popover('toggle'); $('.shopping_basket').popover('toggle'); } function populateInfopanel( execBtn ) { // Flag item active & populate infopanel if (!execBtn.hasClass('active')){ $(execBtn).closest(".product_listings").children(".active").removeClass('active'); $(execBtn).addClass('active'); // Move infopanel into position var infoPanel = $('.prod-detailpanel'); var infoDOMtarget = $(execBtn); if ($(window).width() > 768) { //(Tablet or larger) var execs = $(".product_listings > div:not('.prod-detailpanel')"); var endRowElementIdx = Math.ceil((execs.index( execBtn ) + 1) / 3) * 3; endRowElementIdx = (endRowElementIdx <= execs.length) ? endRowElementIdx : execs.length; infoDOMtarget = execs.eq( endRowElementIdx - 1 ); } infoPanel.insertAfter(infoDOMtarget); // Populate panel with content infoPanel.html($(execBtn).find('.prod-details').html()); // Show panel infoPanel.fadeIn(); // Scroll up to the selected button, so it's visible in viewport $('html, body').animate({ scrollTop: ($(execBtn).offset().top - (($(window).width() > 768) ? 80 : 75)) }, 1000); } else { $(execBtn).removeClass('active'); } } // Make asyncronous JSON call to get Qty of SKUs in Shopping Cart // Expect JSON response on success or error function get_CART_Qty() { // Make Asyncronous AJAX Request var json_URL = "/cart/qty"; var ajaxResponse = $.ajax({ type: "GET", url: json_URL, contentType: "application/json; charset=utf-8", dataType: "json", cache: false }) .done(function( jsonResponse ) { if (jsonResponse.status == 'success') { // Update Basket Counter $('#shopping_basket_counter').html(jsonResponse.basket_qty).fadeIn(); } }); return null; } // Make asyncronous JSON call to add / update SKU in Shopping Cart // Expect JSON response on success or error function update_SKU_in_CART(sku_id, qty) { if ((sku_id === null) || (sku_id == '') || (qty === null) || (qty == '')) { return ''; } // Show busy icon $("button[name='cart_add_" + sku_id + "']").toggleClass('active'); // Make Asyncronous AJAX Request var json_URL = "/cart/update/" + sku_id + "/" + qty; var ajaxResponse = $.ajax({ type: "GET", url: json_URL, contentType: "application/json; charset=utf-8", dataType: "json", cache: false }) .done(function( jsonResponse ) { if (jsonResponse.status == 'success') { // Hide busy icon $("button[name='cart_add_" + jsonResponse.sku_id + "']").toggleClass('active'); // Update Basket Counter $('#shopping_basket_counter').html(jsonResponse.basket_qty); // Refresh Cart Panel $('#cart-flyout-panel').attr('src', $('#cart-flyout-panel').attr('src')); // Show Basket Message showCartPopupMsg( jsonResponse.msg ); } if (jsonResponse.status == 'failure') { // Hide busy icon $("button[name^='cart_add_']").removeClass('active'); // Show Error Message in Basket var ErrMsg = 'Failure Adding Product Item: ' + jsonResponse.msg; showCartPopupMsg( ErrMsg ); } }) .fail(function( jsonResponse ) { // Hide busy icon $("button[name^='cart_add_']").removeClass('active'); // Show Error Message in Basket var ErrMsg = 'Failure Adding Product Item: ' + jsonResponse.responseText; showCartPopupMsg( ErrMsg ); }); return null; } // Make syncronous GET request for new SKU content // Return HTML as response on success or NULL on error function Get_NEW_SKU(sku_id) { if ((sku_id === null) || (sku_id == '')) { return null; } // Make Syncronous AJAX Request var json_URL = "/products/sku/" + sku_id; var ajaxResponse = $.ajax({ type: "GET", url: json_URL, async: false }); // Verify that Response; // (1) is part of a successful HTTP response, no 404 etc // (2) is HTML, by checking first few character for Valid HTML from controller if (ajaxResponse.status == 200 && ajaxResponse.responseText.trim().match("^<!-- HTML-VALID -->")) { if (ajaxResponse.statusText == 'OK') { return ajaxResponse.responseText; } } return null; } <file_sep>/database/seeds/SkuOptsTableSeeder.php <?php use Illuminate\Database\Seeder; // composer require laracasts/testdummy use Laracasts\TestDummy\Factory as TestDummy; class SkuOptsTableSeeder extends Seeder { public function run() { DB::table('sku_opts')->insert([ ['option_id' => '5','sku_id' => '4' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '5','sku_id' => '5' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '5','sku_id' => '7' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '5','sku_id' => '9' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '5','sku_id' => '11' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '6','sku_id' => '3' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '7','sku_id' => '6' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '7','sku_id' => '8' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '7','sku_id' => '10' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '7','sku_id' => '12' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '8','sku_id' => '6' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '8','sku_id' => '7' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '8','sku_id' => '8' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '9','sku_id' => '3' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '9','sku_id' => '4' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '10','sku_id' => '2' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '12','sku_id' => '1' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '12','sku_id' => '9' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '12','sku_id' => '10' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '12','sku_id' => '11' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '12','sku_id' => '12' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '13','sku_id' => '5' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '23','sku_id' => '1' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '23','sku_id' => '2' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '24','sku_id' => '3' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '24','sku_id' => '4' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '25','sku_id' => '5' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '25','sku_id' => '6' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '26','sku_id' => '7' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '26','sku_id' => '8' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '27','sku_id' => '9' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '27','sku_id' => '10' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '28','sku_id' => '11' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ['option_id' => '28','sku_id' => '12' ,'created_at' => new DateTime, 'updated_at' => new DateTime], ]); } } <file_sep>/app/Invoice.php <?php namespace strengthcom; use Illuminate\Database\Eloquent\Model; class Invoice extends Model { protected $fillable = [ 'inv_num', 'inv_total', 'inv_datetime', 'bill_name', 'bill_phone', 'pay_method', 'card_suffix', 'ship_method', 'ship_cost', 'ship_addr', 'ship_city', 'ship_prov', 'ship_country', 'ship_postal', 'bill_addr', 'bill_city', 'bill_prov', 'bill_country', 'bill_postal', 'trans_status', 'trans_num', 'trans_datetime', ]; public function cust() { return $this->belongsTo('strengthcom\Customer', 'customer_id'); } public function skus() { return $this->hasMany('strengthcom\InvSKU'); } } <file_sep>/app/Http/Controllers/CheckoutPayStatusController.php <?php namespace strengthcom\Http\Controllers; use Mail; use Auth; use Event; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\URL; use strengthcom\Jobs\EmailOrderPurchaseInvoiceJob; use strengthcom\Events\InvoiceClosedEvent; use strengthcom\Http\Requests; use strengthcom\User; use strengthcom\SKU; use strengthcom\Option; use strengthcom\Basket; use strengthcom\Customer; use strengthcom\InvSKU; use strengthcom\Invoice; class CheckoutPayStatusController extends Controller { /** * Inform Middleware of the need for Authenticated access to route /checkout/info * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Collect Billing & Shipping info * * GET /checkout/paystatus * * @return \Illuminate\Http\Response */ public function index(Request $request) { $session_num = ShoppingCartController::getSessionNumber(); $user = Auth::user(); $cust = Customer::where('user_id', $user->id)->with( 'ship_addr', 'bill_addr' )->first(); // Validate if user ready for this stage of checkout if ($cust == null) { return redirect('/checkout/info', 301); } $inv = Invoice::where('customer_id', $cust->id) ->with('skus') ->where('trans_status','=','TEMP-PASS') ->orWhere('trans_status','!=','PASS') ->first(); if ($inv == null) { return redirect('/checkout/shipping', 301); } if (!$request->session()->has('payment_info')) { return redirect('/checkout/payment', 301); } if (!$request->session()->has('payment_info.proceed_with_payment')) { return redirect('/checkout/confirm', 301); } // // After Successful order processing, // if (count(session('errors')) > 0) { // Get quantity of SKUs now purchased from Basket table and deduct from stock count in SKU table $basket = Basket::where('session_num', $session_num)->get(); foreach ($basket as $item) { $sku = SKU::find($item->sku_id); $sku->stock_qty -= $item->sku_qty; $sku->save(); } // Store email used for invoicing in customer record, // this could possible be different than what's used for login $cust->email = session('payment_info')['email']; $cust->save(); // Store Shipping / Billing / Payment info in Invoice // Some of which could possible be different than what's in customer account $inv->pay_method = session('payment_info')['paymethod']; $inv->card_suffix = substr(session('payment_info')['card_num'], -4); $inv->bill_name = session('payment_info')['name']; $inv->bill_phone = session('payment_info')['phone']; $inv->ship_addr = $cust->ship_addr->addr; $inv->ship_city = $cust->ship_addr->city; $inv->ship_prov = $cust->ship_addr->prov; $inv->ship_country = $cust->ship_addr->country; $inv->ship_postal = $cust->ship_addr->postal; $inv->bill_addr = session('payment_info')['bill_addr']; $inv->bill_city = session('payment_info')['bill_city']; $inv->bill_prov = session('payment_info')['bill_prov']; $inv->bill_country = session('payment_info')['bill_country']; $inv->bill_postal = session('payment_info')['bill_postal']; $inv->trans_status = 'PASS'; $inv->save(); // Purge basket, Since // (1) customer confirmed Order and invoice items at /checkout/confirm // (2) Records were been moved over to invoices tables earlier in process // (3) Order Payment was successful Basket::where('session_num', $session_num)->delete(); // Delete confidential Payment Information in Session storage session()->forget('payment_info'); // Queue mail Event handler to generate and send email Event::fire(new InvoiceClosedEvent($inv)); return view('checkout.paystatus-success') ->with('order', CheckoutPayStatusController::generateInvoiceOrderData($inv->id)); } else { // Send request out for payment processing return view('checkout.paystatus-processing'); } } /** * Store a newly created resource in storage. * * POST /checkout/paystatus * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // Verify there are no empty fields $validator = Validator::make($request->all(), [ 'trans_status' => 'required|string', 'trans_datetime' => 'required|string', 'trans_num' => 'required|numeric', ]); if ($validator->fails()) { return redirect('checkout/confirm') ->withErrors($validator) ->withInput(); } $session_num = ShoppingCartController::getSessionNumber(); $user = Auth::user(); $cust = Customer::where('user_id', $user->id)->with( 'ship_addr', 'bill_addr' )->first(); $inv = Invoice::where('customer_id', $cust->id) ->where('trans_status','!=','PASS') ->with('skus') ->first(); $basket = Basket::where('session_num', $session_num)->get(); // Transaction Failure Catch-all if ($request->trans_status != 'PASS') { session()->put([ 'payment_info.trans_status' => $request->trans_status, 'payment_info.trans_datetime' => $request->trans_datetime, 'payment_info.trans_num' => $request->trans_num, ]); return redirect('checkout/confirm') ->withErrors(array('msg' => 'Your order payment was declined. Please review your order below and change as required.')) ->withInput(); } // Transaction Successful else { // After Successful order processing, // // Generate customer invoice number & store other invoice related-data $inv->trans_status = 'TEMP-PASS'; $inv->inv_num = date_timestamp_get(date_create()); $inv->trans_datetime = $request->trans_datetime; $inv->trans_num = $request->trans_num; $inv->save(); return redirect('checkout/paystatus') ->withErrors(array('msg' => 'Your order purchase was successfull. Your Invoice below has been emailed to you.')) ->withInput(); } } /** * Assesmble order data for generating Order Invoice for web and email * */ public static function generateInvoiceOrderData($inv_id) { // Validate if user ready for this stage of checkout $inv = Invoice::where('id', $inv_id)->with('skus')->first(); if ($inv == null) { return ([]); } $cust = Customer::where('id', $inv->customer_id)->with( 'ship_addr', 'bill_addr' )->first(); if ($cust == null) { return ([]); } $name = User::where('id', $cust->user_id)->first()->name; // Get Invoice information created by Payment process from Invoice $order['inv_num'] = $inv->inv_num; $order['pay_method'] = $inv->pay_method; $order['card_num_suffix'] = $inv->card_suffix; // Get Shipping / Billing information $order['ship_name'] = $name; $order['ship_phone'] = $cust->phone; $order['bill_name'] = $inv->bill_name; $order['bill_phone'] = $inv->bill_phone; $order['bill_email'] = $cust->email; $order['ship']['ship_addr'] = $inv->ship_addr; $order['ship']['ship_city'] = $inv->ship_city; $order['ship']['ship_prov'] = $inv->ship_prov; $order['ship']['ship_postal'] = $inv->ship_postal; $order['ship']['ship_country'] = $inv->ship_country; $order['bill']['bill_addr'] = $inv->bill_addr; $order['bill']['bill_city'] = $inv->bill_city; $order['bill']['bill_prov'] = $inv->bill_prov; $order['bill']['bill_postal'] = $inv->bill_postal; $order['bill']['bill_country'] = $inv->bill_country; $order['same_as_ship'] = self::array_equal($order['ship'], $order['bill']) ? 'yes' : ''; $shipping_methods = Option::where('cat_name', 'ship_method') ->orderBy('cat_value', 'asc') ->get(['cat_value as name'])->lists('name'); foreach ($shipping_methods as $ship_value) { list($id, $name, $price) = explode(':', $ship_value); if ($inv->ship_method == $id) { $order['ship_method'] = $name; $order['ship_price'] = $price; } } // Get Product items purchased from Invoice SKUs $item_total = 0; $item_qty = 0; $items = []; $baseURL = URL::to('/'); $basePath = public_path(); foreach ($inv->skus as $item) { $item_qty += $item->sku_qty; $item_total += number_format(floatval($item->sku_price) * floatval($item->sku_qty), 2); $items[] = [ 'title' => $item->title, 'desc' => $item->desc, 'qty' => $item->sku_qty, 'price' => $item->sku_price, 'img' => $item->img_url, 'img_path' => str_replace($baseURL, $basePath, $item->img_url), ]; } $order['item_total'] = number_format(floatval($item_total), 2); $order['item_qty'] = $item_qty; $order['inv_total'] = number_format(floatval($item_total) + floatval($order['ship_price']), 2); $order['items'] = $items; return $order; } /** * Compare who arrays of keys in any order and report if values are identical * */ private static function array_equal($a, $b) { return (is_array($a) && is_array($b) && array_diff($a, $b) === array_diff($b, $a)); } } <file_sep>/tests/functional/AdminOptionsTest.php <?php use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use strengthcom\Option; class AdminOptionsTest extends TestCase { use DatabaseTransactions; protected $account_user = '<NAME>'; protected $account_email = '<EMAIL>'; protected $account_passwd = '<PASSWORD>'; protected $test_options = array( array('cat_name' => '_servings', 'cat_value' => '12 bars'), array('cat_name' => '_weight', 'cat_value' => '20g bar'), array('cat_name' => '_flavour', 'cat_value' => 'White Choc Raspberry'), ); public static function setUpBeforeClass() { error_log("---- RESET & SEED DATABASE --------------------------------------------------------------"); passthru("php artisan migrate:reset --env='testing'"); passthru("php artisan migrate --env='testing'"); } /** * testVerifyOption Test Case. * * Add / Edit / Delete / View Options * * @return void */ public function testVerifyOptions() { // Verify DB empty $this->assertEquals(0, DB::table('options')->count()); // Register and verify Options Creation view presented $this->accountRegister(); $this->seePageIs('/admin/options/create') ->see('Create New Category:'); // Create Option $this->call('POST', '/admin/options', array( '_token' => csrf_token(), 'new_option_cat' => $this->test_options[0]['cat_name'], 'new_option_value' => $this->test_options[0]['cat_value'], )); $this->assertRedirectedTo('/admin/options'); // Verify in DB $db_opts = DB::table('options')->get(); $this->assertEquals(1, count($db_opts)); // Lets Update It $newval = 'A new value'; $opt_id = $db_opts[0]->id; $this->call('POST', '/admin/options', array( '_token' => csrf_token(), 'ddlCategoryName' => $opt_id, 'opt_' . $opt_id => $newval, 'opt_update' => 'opt_' . $opt_id, )); // Verify update in DB $db_opts = DB::table('options')->where('id',$opt_id)->first(); $this->assertEquals($this->test_options[0]['cat_name'], $db_opts->cat_name); $this->assertEquals($newval, $db_opts->cat_value); // Add new option to category $this->call('POST', '/admin/options', array( '_token' => csrf_token(), 'ddlCategoryName' => $opt_id, 'opt_create' => 'new_option', 'new_option' => $this->test_options[0]['cat_value'], )); // Verify addition of new option $db_opts = DB::table('options')->get(); $this->assertEquals(2, count($db_opts)); $this->assertEquals($this->test_options[0]['cat_name'], $db_opts[1]->cat_name); $this->assertEquals($this->test_options[0]['cat_value'], $db_opts[1]->cat_value); // Add new category $newcat = 'A new cat'; $this->call('POST', '/admin/options', array( '_token' => csrf_token(), 'ddlCategoryName' => $opt_id, 'new_cat' => $newcat, 'opt_create' => 'new_cat', )); // Verify addition of new category $db_opts = DB::table('options')->get(); $this->assertEquals(3, count($db_opts)); $this->assertEquals('A new cat', $db_opts[2]->cat_name); $this->assertEquals('[New Option]', $db_opts[2]->cat_value); // Delete 2/3 Options $this->call('POST', '/admin/options', array( '_token' => csrf_token(), 'opt_delete' => array($db_opts[0]->id, $db_opts[2]->id), )); // Verify deletion $db_opts = DB::table('options')->get(); $this->assertEquals(1, count($db_opts)); $this->assertEquals($this->test_options[0]['cat_name'], $db_opts[0]->cat_name); $this->assertEquals($this->test_options[0]['cat_value'], $db_opts[0]->cat_value); // Verify view of a specific option $opt_id = $db_opts[0]->id; $this->visit('/admin/options/cat/' . $opt_id) ->see('Admin - Manage Options') ->see('id="create_cat"') ->see('id="add_option"') ->see('id="delete_option"') ->see('>Update</button>'); // Verify redirect on an invalid option $this->visit('/admin/options/cat/999'); $this->assertTrue(ends_with(url()->current(), '/admin/options/cat/'. $opt_id)); // We're ALL DONE! } /** * accountRegister Helper Method. * * Register Test Account * * @return void */ public function accountRegister() { $this->visit('/login') ->see('Sign In') ->click('Create Your Account') ->seePageIs('/register') ->type($this->account_user, 'name') ->type($this->account_email, 'email') ->type($this->account_passwd, '<PASSWORD>') ->type($this->account_passwd, '<PASSWORD>') ->press('Register'); } /** * accountLogin Helper Method. * * Login to Test Account * * @return void */ public function accountLogin() { $this->visit('/login') ->see('Sign In') ->type($this->account_email, 'email') ->type($this->account_passwd, '<PASSWORD>') ->press('Sign in'); } }<file_sep>/app/Http/routes.php <?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ /* -- User Routes */ Route::auth(); Route::get('/', ['uses' => 'ProductsController@index']); Route::get('products/sku/{id}', ['uses' => 'ProductsController@getSKU']); Route::resource('products', 'ProductsController', ['only' => ['index']]); Route::get('cart/update/{id}/{qty}', ['uses' => 'ShoppingCartController@updateCart']); Route::resource('cart', 'ShoppingCartController', ['only' => ['index','show','store']]); Route::get('checkout', ['uses' => 'CheckoutInfoController@goToInfo']); Route::resource('checkout/info', 'CheckoutInfoController', ['only' => ['index','store']]); Route::resource('checkout/shipping', 'CheckoutShippingController', ['only' => ['index','store']]); Route::resource('checkout/payment', 'CheckoutPaymentController', ['only' => ['index','store']]); Route::resource('checkout/confirm', 'CheckoutConfirmController', ['only' => ['index','store']]); Route::resource('checkout/paystatus', 'CheckoutPayStatusController', ['only' => ['index','store']]); /* -- Administrative Routes */ Route::get('/admin', 'AdminController@index'); Route::resource('admin', 'AdminController', ['only' => ['index']]); Route::resource('admin/products', 'AdminProductsController', ['only' => ['index','show','store','create']]); Route::get('admin/options/cat/{id}', ['uses' => 'AdminOptionsController@edit']); Route::resource('admin/options', 'AdminOptionsController', ['only' => ['index','store','create']]); Route::resource('admin/skus', 'AdminSKUsController', ['only' => ['index','show','store','create']]); <file_sep>/app/Listeners/EmailInvoiceOfOrderPurchase.php <?php namespace strengthcom\Listeners; use Mail; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\DispatchesJobs; use strengthcom\Http\Controllers\CheckoutPayStatusController; use strengthcom\Events\InvoiceClosedEvent; use strengthcom\Jobs\EmailOrderPurchaseInvoiceJob; use strengthcom\Invoice; class EmailInvoiceOfOrderPurchase implements ShouldQueue { use DispatchesJobs; /** * Handle the event. * * @param InvoiceClosedEvent $event * @return void */ public function handle(InvoiceClosedEvent $e) { // Dispatch job to handle the creation of email Invoice and sending to user $job = (new EmailOrderPurchaseInvoiceJob($e->inv)); $this->dispatch($job); } } <file_sep>/tests/functional/AdminProductsTest.php <?php use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use strengthcom\Option; use strengthcom\Product; class AdminProductsTest extends TestCase { use DatabaseTransactions; protected $account_user = '<NAME>'; protected $account_email = '<EMAIL>'; protected $account_passwd = '<PASSWORD>'; protected $test_options = array( array('cat_name' => '_servings', 'cat_value' => '12 bars'), array('cat_name' => '_weight', 'cat_value' => '20g bar'), array('cat_name' => '_flavour', 'cat_value' => 'White Choc Raspberry'), ); protected $test_products = array( array('title' => 'MusclePharm Combat Crunch Protein Bar', 'price' => '2.99'), array('title' => 'EnergyFirst Permalean Protein Bar', 'price' => '3.99'), array('title' => 'MuscleMaxx Protein Bar (Box)', 'price' => '15.99'), ); public static function setUpBeforeClass() { error_log("---- RESET & SEED DATABASE --------------------------------------------------------------"); passthru("php artisan migrate:reset --env='testing'"); passthru("php artisan migrate --env='testing'"); } protected function setUp() { parent::setUp(); // Verify DB empty, then create some dummy options // so redirect to product admin occurs $this->assertEquals(0, DB::table('products')->count()); foreach ($this->test_options as $opt) { Option::create(['cat_name' => $opt['cat_name'], 'cat_value' => $opt['cat_value']]); } // Verify creation of options $this->assertEquals(count($this->test_options), count(DB::table('options')->get())); } /** * testVerifyOption Test Case. * * Add / Edit / Delete / View Products * * @return void */ public function testVerifyProducts() { // Register and verify shown is Product Creation view $this->accountRegister(); $this->seePageIs('/admin/products/create'); // Create Product $this->call('POST', '/admin/products', array( '_token' => csrf_token(), 'new_prod_title' => $this->test_products[0]['title'], 'new_prod_price' => $this->test_products[0]['price'], )); $this->assertRedirectedTo('/admin/products'); // Verify in DB $db_prods = DB::table('products')->get(); $this->assertEquals(1, count($db_prods)); // Lets Update both fields $newtitle = 'A new title'; $newprice = '99.99'; $prod_id = $db_prods[0]->id; $this->call('POST', '/admin/products', array( '_token' => csrf_token(), 'ddlProduct' => $prod_id, 'prod_opt' => 'update_prod', 'title' => $newtitle, 'price' => $newprice, )); // Verify update in DB $db_prods = DB::table('products')->where('id', $prod_id)->first(); $this->assertEquals($newtitle, $db_prods->title); $this->assertEquals($newprice, $db_prods->price); // Create 2nd Product $this->call('POST', '/admin/products', array( '_token' => csrf_token(), 'new_prod_title' => $this->test_products[0]['title'], 'new_prod_price' => $this->test_products[0]['price'], )); // Verify DB addition $db_prods = DB::table('products')->get(); $this->assertEquals(2, count($db_prods)); $this->assertEquals($this->test_products[0]['title'], $db_prods[1]->title); $this->assertEquals($this->test_products[0]['price'], $db_prods[1]->price); // Delete a product $this->call('POST', '/admin/products', array( '_token' => csrf_token(), 'prod_opt' => 'delete_prod', 'ddlProduct' => $db_prods[0]->id, )); // Verify deletion $db_prods = DB::table('products')->get(); $this->assertEquals(1, count($db_prods)); $this->assertEquals($this->test_products[0]['title'], $db_prods[0]->title); $this->assertEquals($this->test_products[0]['price'], $db_prods[0]->price); // Verify view of a specific Product $prod_id = $db_prods[0]->id; $this->visit('/admin/products/' . $prod_id) ->see('Admin - Manage Products') ->see('>Add new Product<') ->see('name="update_prod"') ->see('name="delete_prod"'); // Verify redirect on an invalid product $this->visit('/admin/products/999'); $this->assertTrue(ends_with(url()->current(), '/admin/products/'. $prod_id)); // We're ALL DONE! } /** * accountRegister Helper Method. * * Register Test Account * * @return void */ public function accountRegister() { $this->visit('/login') ->see('Sign In') ->click('Create Your Account') ->seePageIs('/register') ->type($this->account_user, 'name') ->type($this->account_email, 'email') ->type($this->account_passwd, '<PASSWORD>') ->type($this->account_passwd, '<PASSWORD>') ->press('Register'); } /** * accountLogin Helper Method. * * Login to Test Account * * @return void */ public function accountLogin() { $this->visit('/login') ->see('Sign In') ->type($this->account_email, 'email') ->type($this->account_passwd, '<PASSWORD>') ->press('Sign in'); } }<file_sep>/app/Http/Controllers/AdminOptionsController.php <?php namespace strengthcom\Http\Controllers; use Illuminate\Database\Eloquent\Collection; use Illuminate\Http\Request; use strengthcom\Option; use strengthcom\Http\Requests; class AdminOptionsController extends Controller { /** * Inform Middleware of the need for Authenticated access to route /checkout/info * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Redirect to the first Options in DB for editing * * GET /admin/options * * @return \Illuminate\Http\Response */ public function index() { $opt_cat_all = Option::distinct('cat_name') ->orderBy('cat_name', 'asc') ->groupBy('cat_name') ->get(); if ($opt_cat_all->isEmpty()) { return redirect('admin/options/create'); } else { $opt_cat_first = $opt_cat_all->first()->id; return redirect('admin/options/cat/' . $opt_cat_first); } } /** * Show a minial form for creating a single new Option * * GET /admin/options/create * * @return \Illuminate\Http\Response */ public function create() { return view('admin.options.create'); } /** * Display Options in a form for editing * * GET /admin/options/cat/:id * * @param int $id * @return \Illuminate\Http\Response */ public function edit($opt_cat_id) { // If ID does not exist in DB, redirect to using first record if (!is_object(Option::find($opt_cat_id))) { return redirect('admin/options'); } // Get lists to populate view $opt_cat = Option::distinct('cat_name') ->orderBy('cat_name', 'asc') ->groupBy('cat_name') ->get(['id','cat_name as name']); $opt_cat_name = Option::find($opt_cat_id)->cat_name; $cat_options = Option::where('cat_name', $opt_cat_name) ->orderBy('id', 'asc') ->get(['id','cat_value as name']); return view('admin.options.edit') ->with('opt_categories', $opt_cat->lists('name', 'id')) ->with('cat_options', $cat_options) ->with('selected_cat_id', $opt_cat_id) ->with('selected_cat_name', $opt_cat_name); } /** * Create, Update, and Delete option values and categories * * POST /admin/options * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // Create new option on empty table if ($request->has('new_option_cat') && $request->has('new_option_value')) { $option = new Option; $option->cat_name = $request->new_option_cat; $option->cat_value = $request->new_option_value; $option->save(); return redirect('admin/options'); } // Delete option elseif ($request->has('opt_delete')) { Option::destroy($request->opt_delete); } // Append new option to table elseif ($request->has('opt_create')) { if ($request->has('ddlCategoryName') && $request->has($request->opt_create)) { // Create new Category // if ($request->opt_create == 'new_cat') { $opt_cat_name = $request->input($request->opt_create); $opt_value = '[New Option]'; } // Create new Option value elseif ($request->opt_create == 'new_option') { $opt_cat_name = Option::find($request->ddlCategoryName)->cat_name; $opt_value = $request->input($request->opt_create); } $option = new Option; $option->cat_name = $opt_cat_name; $option->cat_value = $opt_value; $option->save(); } } // Update existing option in table elseif ($request->has('opt_update')) { if ($request->has('ddlCategoryName') && $request->has($request->opt_update)) { list($opt_code, $opt_id) = explode('_', $request->opt_update); $opt_value = $request->input($request->opt_update); $option = Option::find($opt_id); $option->cat_value = $opt_value; $option->save(); } } $cat_id = $request->input('ddlCategoryName'); return redirect('admin/options/cat/' . $cat_id); } } <file_sep>/app/Option.php <?php namespace strengthcom; use Illuminate\Database\Eloquent\Model; class Option extends Model { protected $fillable = [ 'cat_name', 'cat_value', ]; public function products() { return $this->belongsToMany('strengthcom\Product', 'product_options'); } public function skus() { return $this->belongsToMany('strengthcom\SKU', 'sku_opts', 'option_id', 'sku_id')->withTimestamps(); } } <file_sep>/public/js/demo.css.js /* Parse Queryr strings into Object */ (function($) { $.QueryString = (function(a) { if (a == "") return {}; var b = {}; for (var i = 0; i < a.length; ++i) { var p=a[i].split('='); if (p.length != 2) continue; b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " ")); } return b; })(window.location.search.substr(1).split('&')) })(jQuery); // Dynamically load CSS to page DOM var cssNAV = $.QueryString["nav"] == 'bottom' ? 'css/main-navbar-bottom' : 'css/main-navbar-top'; var cssURL = cssNAV + (( $.QueryString["theme"] != '' && $.QueryString["theme"] != '' && $.isNumeric($.QueryString["theme"])) ? '-theme' + $.QueryString["theme"] + '.css' : '-theme1.css' ); var cssLINK = document.createElement('link'); cssLINK.setAttribute('rel', 'stylesheet'); cssLINK.setAttribute('type', 'text/css'); cssLINK.setAttribute('href', cssURL ); document.getElementsByTagName('head')[0].appendChild( cssLINK ); <file_sep>/database/seeds/UsersTableSeeder.php <?php use Illuminate\Database\Seeder; use strengthcom\User; // composer require laracasts/testdummy use Laracasts\TestDummy\Factory as TestDummy; class UsersTableSeeder extends Seeder { public function run() { User::create([ 'name' => 'admin', 'email' => '<EMAIL>', 'password' => bcrypt('<PASSWORD>') ]); /* User::create([ 'name' => 'lance', 'email' => '<EMAIL>', 'password' => bcrypt('<PASSWORD>') ]); */ } } <file_sep>/app/Http/Controllers/ProductsController.php <?php namespace strengthcom\Http\Controllers; use DB; use Illuminate\Http\Request; use strengthcom\Http\Requests; use strengthcom\SKU; use strengthcom\Product; class ProductsController extends Controller { protected $warnUserOfOutOfStockAtLessThan = '5'; /** * Display a listing of the Products and associated SKUs. * * GET / * * @return \Illuminate\Http\Response */ public function index(Request $request) { if (SKU::count() == 0) { return redirect('admin/skus'); } if ($request->is('/')) { return redirect('products'); } $sku_objs = Product::orderBy('title', 'asc') ->join('skus', 'products.id', '=', 'skus.product_id') ->select(DB::raw("skus.*, products.*, skus.id as sku_id")) ->where('stock_qty','>',0) ->orderBy('title', 'asc') ->orderBy('is_default', 'desc') ->orderBy('opt_label', 'asc') ->get(); if ($sku_objs->isEmpty()) { return redirect('admin/skus'); } // The first sorted SKU for a product must ALWAYS be marked as default!! // Its possible for the default SKU to be out-of-stock and not updated by Admin // So, we mark it default for the next SKU in this product to be listed if (!$sku_objs[0]->is_default) $sku_objs[0]->is_default = true; $prod_all = $alt_skus = []; $idx = 0; $current_pid = $sku_objs[0]->product_id; foreach ($sku_objs as $sku) { // Attach AltSkus to Product Array if ($current_pid != $sku->product_id) { $current_pid = $sku->product_id; $prod_all[$idx]['alt_skus'] = $alt_skus; $alt_skus = []; $idx += 1; // The first sorted SKU for a product must ALWAYS be marked as default!! // Its possible for the default SKU to be out-of-stock and not updated by Admin // So, we mark it default for the next SKU in this product to be listed if (!$sku->is_default) $sku->is_default = true; } // Populate Product with data from Default-SKU if ($sku->is_default) { // Create Qty selection dropdown values for ($i = 1, $qty_select=[]; $i <= $sku->stock_qty; $i++) { $qty_select[$i] = $i; } $prod_all[$idx]['prod_id'] = $sku->product_id; $prod_all[$idx]['prod_title'] = $sku->title; $prod_all[$idx]['img_url'] = $sku->img_url; $prod_all[$idx]['opt_label'] = $sku->opt_label; $prod_all[$idx]['desc'] = $sku->desc; $prod_all[$idx]['sku_id'] = $sku->sku_id; $prod_all[$idx]['sku_total'] = $sku->sku_total; $prod_all[$idx]['stock_qty'] = $sku->stock_qty; $prod_all[$idx]['qty_select'] = $qty_select; // Create array of default sku options $sku_opts = SKU::find($sku->sku_id)->options() ->orderBy('id', 'desc') ->get(['cat_value as name']) ->lists('name'); $prod_all[$idx]['sku_options'] = $sku_opts->toArray(); } // Create array of alternate SKUs for user to choose from else { $alt_skus[] = [ 'id' => $sku->sku_id, 'label' => $sku->opt_label ]; } } if (!empty($alt_skus)) { $prod_all[$idx]['alt_skus'] = $alt_skus; } return view('products.index') ->with('prod_all', $prod_all) ->with('qty_warn_threshold', $this->warnUserOfOutOfStockAtLessThan); } /** * Process request for HTML rendering of a SKU on the Products page * when user selects a different SKU from select dropdown * * GET /products/sku/{id} * * @param int $id * @return \Illuminate\Http\Response (NULL on ID Not Found) */ public function getSKU($sku_id) { $sku = SKU::find($sku_id); if ($sku == null) return ''; $sku->load([ 'product', 'product.skus' => function ($q) { $q->where('stock_qty','>',0)->orderBy('opt_label', 'asc'); }, 'options' => function ($q) { $q->orderBy('id', 'desc'); } ]); // Create array of default sku options foreach ($sku->options as $option) { $sku_options[] = $option->cat_value; } // Ensure that QTY select is at least 2x the current Qty's in basket for ($i = 1, $qty_select=[]; $i <= $sku->stock_qty; $i++) $qty_select[$i] = $i; //Create view Product Array $prod_arr = [ 'prod_id' => $sku->product_id, 'prod_title' => $sku->product->title, 'img_url' => $sku->img_url, 'opt_label' => $sku->opt_label, 'desc' => $sku->desc, 'sku_id' => $sku->id, 'sku_total' => $sku->sku_total, 'stock_qty' => $sku->stock_qty, 'sku_options' => $sku_options, 'qty_select' => $qty_select, ]; // Create array of alternate SKUs for user to choose from $alt_skus = []; foreach ($sku->product->skus as $alt_sku) { if ($alt_sku->id == $sku_id) continue; $alt_skus[] = [ 'id' => $alt_sku->id, 'label' => $alt_sku->opt_label ]; } if (!empty($alt_skus)) $prod_arr['alt_skus'] = $alt_skus; // Return HTML fragment return view('partials.product_item') ->with('prod', $prod_arr) ->with('qty_warn_threshold', $this->warnUserOfOutOfStockAtLessThan); } } <file_sep>/tests/functional/ShoppingCartControllerTest.php <?php use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use strengthcom\Basket; class ShoppingCartControllerTest extends TestCase { use DatabaseTransactions; use WithoutMiddleware; public static function setUpBeforeClass() { error_log("---- RESET & SEED DATABASE --------------------------------------------------------------"); passthru("php artisan migrate:reset --env='testing'"); passthru("php artisan migrate --env='testing' --seed"); } /** * testVerifySKUsToAdd Test Case. * * Ensure there are products to Add to Basket * * @return void */ public function testVerifySKUsToAdd() { // Look for a SKU after DB seeding on Product listings page $this->visit('/products') ->see('Shop our Products') ->see('EnergyFirst Permalean Protein Bar') ->see('MusclePharm Combat Crunch Protein Bar') ->see('MuscleMaxx Protein Bar (Box)') ->see('QuestBar Protein Bar (Box)'); // Verify no SKUs in shopping cart $this->json('GET', '/cart/qty') ->seeJson([ 'basket_qty' => '0', 'status' => 'success', 'msg' => '0 Product Items in basket', ]); } /** * testAddSKUsToCartViaAJAX Test Case. * * Add SKUs of varying quantities and methods to Cart using AJAX methods * * @depends testVerifySKUsToAdd * * @return void */ public function testAddSKUsToCartViaAJAX() { // Add SKU 'EnergyFirst Permalean Protein Bar' with quantity 1 to basket $this->json('GET', '/cart/update/1/1') ->seeJson([ 'sku_id' => '1', 'sku_qty' => '1', 'basket_qty' => '1', 'status' => 'success', 'msg' => 'Product Item added or updated in Cart', ]); // Increment count in basket of same SKU 'EnergyFirst Permalean Protein Bar' $this->json('GET', '/cart/update/1/1') ->seeJson([ 'sku_id' => '1', 'sku_qty' => '1', 'basket_qty' => '2', 'status' => 'success', 'msg' => 'Product Item added or updated in Cart', ]); // Add to basket, an additional SKU 'MusclePharm Combat Crunch Protein Bar', with QTY 3 $this->json('GET', '/cart/update/3/2') ->seeJson([ 'sku_id' => '3', 'sku_qty' => '2', 'basket_qty' => '4', 'status' => 'success', 'msg' => 'Product Item added or updated in Cart', ]); } /** * testManageCartViaPOST Test Case. * * Add / Update /Delete Products in Cart using form POST operation * * @depends testAddSKUsToCartViaAJAX * * @return void */ public function testManageCartViaPOST() { $this->testAddSKUsToCartViaAJAX(); // Submit QTY update in Cart for SKU, 'MusclePharm Combat Crunch Protein Bar' $response = $this->call('POST', '/cart', array( 'sku_qty-3' => '6', 'delete_sku' => '', )); $this->assertRedirectedTo('/cart'); // Verify updated QTY items in cart, post UPDATE $this->json('GET', '/cart/qty') ->seeJson([ 'basket_qty' => '8', 'status' => 'success', 'msg' => '8 Product Items in basket', ]); // Submit DELETE in Cart for SKU, 'EnergyFirst Permalean Protein Bar' $response = $this->call('POST', '/cart', array( 'sku_qty-1' => '1', 'delete_sku' => '1', )); $this->assertRedirectedTo('/cart'); // Verify updated QTY items in cart, post DELETE $this->json('GET', '/cart/qty') ->seeJson([ 'basket_qty' => '6', 'status' => 'success', 'msg' => '6 Product Items in basket', ]); // Verify missing SKU item,'EnergyFirst Permalean Protein Bar' in cart, post DELETE $this->visit('/cart') ->dontSee('EnergyFirst Permalean Protein Bar'); } }<file_sep>/app/InvSKU.php <?php namespace strengthcom; use Illuminate\Database\Eloquent\Model; class InvSKU extends Model { protected $table = 'inv_skus'; protected $fillable = [ 'invoice_id', 'title', 'desc', 'sku_qty', 'sku_price', 'img_url', ]; public function invoice() { return $this->belongsTo('strengthcom\Invoice'); } } <file_sep>/app/SKU.php <?php namespace strengthcom; use Illuminate\Database\Eloquent\Model; class SKU extends Model { protected $table = 'skus'; protected $fillable = [ 'opt_label', 'img_url', 'desc', 'sku_total', 'stock_qty', ]; public function product() { return $this->belongsTo('strengthcom\Product'); } public function options() { return $this->belongsToMany('strengthcom\Option', 'sku_opts', 'sku_id', 'option_id')->withTimestamps(); } public function baskets() { return $this->hasMany('strengthcom\Basket'); } } <file_sep>/database/seeds/ProductsTableSeeder.php <?php use Illuminate\Database\Seeder; // composer require laracasts/testdummy use Laracasts\TestDummy\Factory as TestDummy; class ProductsTableSeeder extends Seeder { public function run() { DB::table('products')->insert([ ['title' => 'MusclePharm Combat Crunch Protein Bar', 'price' => '2.99', 'created_at' => new DateTime, 'updated_at' => new DateTime], ['title' => 'EnergyFirst Permalean Protein Bar', 'price' => '2.99', 'created_at' => new DateTime, 'updated_at' => new DateTime], ['title' => 'MuscleMaxx Protein Bar (Box)', 'price' => '15.99', 'created_at' => new DateTime, 'updated_at' => new DateTime], ['title' => 'QuestBar Protein Bar (Box)', 'price' => '15.45', 'created_at' => new DateTime, 'updated_at' => new DateTime], /* ['title' => 'MusclePharm Combat Crunch Protein Bar', 'price' => '2.99', 'def_sku_id' => '3', 'created_at' => new DateTime, 'updated_at' => new DateTime], ['title' => 'EnergyFirst Permalean Protein Bar', 'price' => '2.99', 'def_sku_id' => '1', 'created_at' => new DateTime, 'updated_at' => new DateTime], ['title' => 'MuscleMaxx Protein Bar (Box)', 'price' => '15.99', 'def_sku_id' => '5', 'created_at' => new DateTime, 'updated_at' => new DateTime], ['title' => 'QuestBar Protein Bar (Box)', 'price' => '15.45', 'def_sku_id' => '9', 'created_at' => new DateTime, 'updated_at' => new DateTime], ['title' => '', 'price' => '0.00', 'created_at' => new DateTime, 'updated_at' => new DateTime], ['title' => '', 'price' => '0.00', 'created_at' => new DateTime, 'updated_at' => new DateTime], */ ]); } } <file_sep>/app/Http/Controllers/CheckoutPaymentController.php <?php namespace strengthcom\Http\Controllers; use Auth; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use strengthcom\Http\Requests; use strengthcom\User; use strengthcom\Option; use strengthcom\Customer; use strengthcom\Invoice; class CheckoutPaymentController extends Controller { /** * Inform Middleware of the need for Authenticated access to route /checkout/info * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Collect Billing & Shipping info * * GET /checkout/payment * * @return \Illuminate\Http\Response */ public function index() { $session_num = ShoppingCartController::getSessionNumber(); $user = Auth::user(); $cust = Customer::where('user_id', $user->id)->with( 'bill_addr' )->first(); // Validate if user ready for this stage of checkout if ($cust == null) { return redirect('/checkout/info'); } $inv = Invoice::where('customer_id', $cust->id) ->where('trans_status','!=','PASS') ->with('skus') ->first(); if ($inv == null) { return redirect('/checkout/shipping'); } // Collect Customer information $payArr = [ 'paymethod' => '', 'card_num' => '', 'visa_exp_month' => '', 'visa_exp_year' => '', 'visa_exp_cvv' => '', 'name' => $user->name, 'email' => $cust->email ? $cust->email : $user->email, 'phone' => $cust->phone, 'bill_addr' => $cust->bill_addr->addr, 'bill_city' => $cust->bill_addr->city, 'bill_prov' => $cust->bill_addr->prov, 'bill_postal' => $cust->bill_addr->postal, 'bill_country' => $cust->bill_addr->country, ]; if (session()->has('payment_info')) { $this->populate_array_with_keys($payArr, [ 'name', 'email', 'phone', 'paymethod', 'card_num', 'visa_exp_month', 'visa_exp_year', 'visa_exp_cvv', 'bill_addr', 'bill_city', 'bill_prov', 'bill_postal', 'bill_country'], session('payment_info')); } // Create Dropdowns $prov_list = Option::where('cat_name', 'prov_state') ->orderBy('cat_value', 'asc') ->get(['id','cat_value as name'])->lists('name', 'name'); $country_list = Option::where('cat_name', 'countries') ->get(['id','cat_value as name'])->lists('name', 'name'); // Create Credit Card MM for ($i = 1, $month_list=[]; $i <= 12; $i++) { $mm = sprintf("%'.02d", $i); $month_list[$mm] = $mm; } // Create Credit Card YY for ($i = 16, $year_list=[]; $i <= 26; $i++) { $yy = sprintf("%'.02d", $i); $year_list[$yy] = $yy; } return view('checkout.payment') ->with('country_list', $country_list) ->with('prov_list', $prov_list) ->with('month_list', $month_list) ->with('year_list', $year_list) ->with('pay', $payArr); } /** * Populate Array with values from Data Array if found * * [Array to populate] * [array of keys to look for in Request & Session] * [Data Array to search for key] * */ private function populate_array_with_keys(&$Arr, $keys, $data) { if (is_array($Arr) && is_array($data)) { if (is_array($keys)) { foreach ($keys as $key) { if (array_has($data, $key)) $Arr[$key] = $data[$key]; } } else { if (array_has($data, $keys)) $Arr[$keys] = $data[$keys]; } } } /** * Store a newly created resource in storage. * * POST /checkout/payment * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // Verify there are no empty fields $validator = Validator::make($request->all(), [ 'paymethod' => 'required|string', 'email' => 'required_if:paymethod,visa|string', 'name' => 'required_if:paymethod,visa|string', 'card_num' => 'required_if:paymethod,visa|numeric', 'visa_exp_month' => 'required_if:paymethod,visa|numeric', 'visa_exp_year' => 'required_if:paymethod,visa|numeric', 'visa_exp_cvv' => 'required_if:paymethod,visa|numeric', 'bill_country' => 'required_if:paymethod,visa|string', 'bill_addr' => 'required_if:paymethod,visa|string', 'bill_city' => 'required_if:paymethod,visa|alpha', 'bill_prov' => 'required_if:paymethod,visa|string', 'bill_postal' => 'required_if:paymethod,visa|string', ]); if ($validator->fails()) { return redirect('checkout/payment') ->withErrors($validator) ->withInput(); } // Store new info to Customer Invoice $user = Auth::user(); $cust = Customer::where('user_id', $user->id)->first(); $inv = Invoice::where('customer_id', $cust->id) ->where('trans_status','!=','PASS') ->first(); $inv->pay_method = $request->paymethod; $inv->save(); // Store payment info into session to be passed to /checkout/confirm stage session([ 'payment_info' => [ 'paymethod' => $request->paymethod, 'name' => $request->name, 'email' => $request->email, 'phone' => $request->phone, 'card_num' => $request->card_num, 'visa_exp_month' => $request->visa_exp_month, 'visa_exp_year' => $request->visa_exp_year, 'visa_exp_cvv' => $request->visa_exp_cvv, 'bill_country' => $request->bill_country, 'bill_addr' => $request->bill_addr, 'bill_city' => $request->bill_city, 'bill_prov' => $request->bill_prov, 'bill_postal' => $request->bill_postal, ] ]); return redirect('checkout/confirm'); } } <file_sep>/app/Http/Controllers/CheckoutShippingController.php <?php namespace strengthcom\Http\Controllers; use Auth; use DB; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use strengthcom\Http\Requests; use strengthcom\User; use strengthcom\Option; use strengthcom\Basket; use strengthcom\Customer; use strengthcom\Invoice; use strengthcom\InvSKU; class CheckoutShippingController extends Controller { /** * Inform Middleware of the need for Authenticated access to route /checkout/info * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Collect Billing & Shipping info * * GET /checkout/shipping * * @return \Illuminate\Http\Response */ public function index() { $session_num = ShoppingCartController::getSessionNumber(); $user = Auth::user(); $cust = Customer::where('user_id', $user->id)->with( 'ship_addr' )->first(); // Validate if user ready for this stage of checkout if ($cust == null) { return redirect('/checkout/info'); } // Assemble Customer Shipping information $cust_ship = $user->name . ', ' . $cust->ship_addr->addr . ', ' . $cust->ship_addr->city . ', ' . $cust->ship_addr->prov . ', ' . $cust->ship_addr->postal . ', ' . $cust->ship_addr->country; // Get count of SKUs in Basket $basket = Basket::where('session_num', $session_num)->with([ 'sku' => function ($q) { $q->orderBy('id', 'desc'); }, 'sku.product' ])->get(); $shipping_method = Option::where('cat_name', 'ship_method') ->orderBy('cat_value', 'asc') ->get(['cat_value as name'])->lists('name'); $inv = Invoice::where('customer_id', $cust->id) ->where('trans_status','!=','PASS') ->first(); $cust_ship_method = ''; foreach ($shipping_method as $ship_value) { list($id, $name, $price) = explode(':', $ship_value); $ship_methods[] = [ 'id' => $id, 'name' => $name, 'price' => $price ]; if ($inv != null && $inv->ship_method == $id) $cust_ship_method = $id; } $basket_qty = 0; $basket_total = 0; $skus_all = []; foreach ($basket as $item) { $basket_qty += $item->sku_qty; $basket_total += ($item->sku->sku_total * $item->sku_qty); $skus_all[] = [ 'id' => $item->sku->id, 'title' => $item->sku->product->title, 'label' => $item->sku->opt_label, 'desc' => $item->sku->desc, 'qty' => $item->sku_qty, 'price' => $item->sku->sku_total, 'img' => $item->sku->img_url, ]; } $basket_arr = [ 'cust_ship' => $cust_ship, 'basket_total' => $basket_total, 'basket_qty' => $basket_qty, 'cust_ship_method' => $cust_ship_method, 'shipping_methods' => $ship_methods, 'items' => $skus_all, ]; if (!count($basket_arr['items'])) { return redirect('/products'); } else { return view('checkout.shipping') ->with('cust', $basket_arr); } } /** * Store a newly created resource in storage. * * POST /checkout/shipping * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // Verify there are no empty fields $validator = Validator::make($request->all(), [ 'shipmethod' => 'required|string', 'ship_cost' => 'required|numeric', 'basket_total' => 'required|numeric', 'skus' => 'required|array', ]); if ($validator->fails()) { return redirect('checkout/shipping') ->withErrors($validator) ->withInput(); } // Validation passed: lets store this info $user = Auth::user(); $cust = Customer::where('user_id', $user->id)->first(); $inv = Invoice::where('customer_id', $cust->id) ->where('trans_status','!=','PASS') ->first(); // Create Invoice if ($inv == null) { $inv = new Invoice; } // Update Invoice $inv->ship_cost = $request->ship_cost; $inv->ship_method = $request->shipmethod; $inv->inv_total = $request->basket_total; $inv->inv_datetime = Carbon::now(); $inv->cust()->associate($cust); $inv->save(); // Purge stale InvoiceSKU records InvSKU::where('invoice_id', $inv->id)->delete(); // Create InvoiceSKU records foreach ($request->skus as $sku) { InvSKU::firstOrCreate([ 'invoice_id' => $inv->id, 'title' => $sku['title'], 'desc' => $sku['desc'], 'sku_qty' => $sku['qty'], 'sku_price' => number_format($sku['price'], 2), 'img_url' => $sku['img'], ]); } return redirect('checkout/payment'); } } <file_sep>/app/Http/Controllers/AdminSKUsController.php <?php namespace strengthcom\Http\Controllers; use DB; use Illuminate\Http\Request; use strengthcom\SKU; use strengthcom\Product; use strengthcom\Option; use strengthcom\Http\Requests; class AdminSKUsController extends Controller { protected $publicImgRelPath = '/uploads/images'; protected $warnUserOfOutOfStockAtLessThan = '5'; /** * Inform Middleware of the need for Authenticated access to route /checkout/info * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Redirect to the first Product in DB for editing * * GET /admin/skus * * @return \Illuminate\Http\Response */ public function index() { $sku_all = SKU::join('products', 'products.id', '=', 'skus.product_id') ->select(DB::raw("skus.*, products.*, skus.id as id")) ->orderBy('title', 'asc') ->orderBy('is_default', 'desc') ->get(); if ($sku_all->isEmpty()) { return redirect('admin/skus/create'); } else { $sku_first = $sku_all->first()->id; return redirect('admin/skus/' . $sku_first); } } /** * Show a minial form for creating a single new Product * * GET /admin/skus/create * * @return \Illuminate\Http\Response */ public function create() { // Validate if system ready for this stage $prod_db = Product::orderBy('title', 'asc')->get(); if ($prod_db->isEmpty()) { return redirect('admin/products/create'); } foreach ($prod_db as $prod) { $prod_code = $prod->id . ':' . $prod->price; $prod_all[$prod_code] = $prod->title; } $opt_all = Option::where('cat_name','like','\_%') ->orderBy('cat_name', 'asc') ->orderBy('id', 'asc') ->get(); foreach ($opt_all as $option) { $prod_options[$option->cat_name][$option->id] = $option->cat_value; } $basePath = public_path() . $this->publicImgRelPath; foreach (scandir($basePath) as $file) { if ($file == '.' || $file == '..' || is_dir("$basePath/$file")) continue; $uploaded_imgs[ asset($this->publicImgRelPath . "/" . $file) ] = $file; } return view('admin.skus.create') ->with('prod_all', $prod_all) ->with('prod_options', $prod_options) ->with('sku_options', []) ->with('base_url_path', asset($this->publicImgRelPath)) ->with('uploaded_imgs', $uploaded_imgs); } /** * Display Products in a form for editing * * GET /admin/skus/{id} * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // If ID does not exist in DB, redirect to using first record $skus = SKU::join('products', 'products.id', '=', 'skus.product_id') ->select(DB::raw("skus.*, products.*, skus.id as id")) ->orderBy('title', 'asc') ->orderBy('is_default', 'desc') ->get(); // If ID does not exist in DB, redirect to using first record if (!is_object(SKU::find($id)) || $skus->isEmpty()) { return redirect('admin/skus'); } // Create list of SKU names (Combination of Product title & Option Labels) $prod_all = []; foreach ($skus as $s) { $skus_all[$s->id] = $s->title . ' - ' . $s->opt_label . ($s->is_default ? ' (Default)' : '') . ($s->stock_qty <= 0 ? ' [OUT OF STOCK]' : ($s->stock_qty <= $this->warnUserOfOutOfStockAtLessThan ? ' [LOW ON STOCK]' : '')); // Create Products List array (Combining prod_id and prod_price in dropdown key) $prod_code = $s->product_id . ':' . $s->price; if (!array_has($prod_all, $prod_code)) $prod_all[$prod_code] = $s->title; } // Create Products Options List array $opt_all = Option::where('cat_name','like','\_%') ->orderBy('cat_name', 'asc') ->orderBy('id', 'asc') ->get(); foreach ($opt_all as $option) { $prod_options[$option->cat_name][$option->id] = $option->cat_value; } // Scan public image directory for list of image files $basePath = public_path() . $this->publicImgRelPath; foreach (scandir($basePath) as $file) { if ($file == '.' || $file == '..' || is_dir("$basePath/$file")) continue; $uploaded_imgs[ asset($this->publicImgRelPath . "/" . $file) ] = $file; } // Create SKU Options List array $skuObj = $skus->filter(function($sku) use ($id) { return $sku->id == $id; })->first(); $sku_options = $skuObj->options()->orderBy('id', 'desc')->get(['id','cat_value as name'])->lists('name', 'id'); return view('admin.skus.edit') ->with('skus_all', $skus_all) ->with('prod_all', $prod_all) ->with('prod_options', $prod_options) ->with('base_url_path', asset($this->publicImgRelPath)) ->with('uploaded_imgs', $uploaded_imgs) ->with('prod_code', $skuObj->product_id . ':' . $skuObj->product->price) ->with('opt_label', $skuObj->opt_label) ->with('sku_options', $sku_options) ->with('sku_id', $skuObj->id) ->with('sku_desc', $skuObj->desc) ->with('sku_total', $skuObj->sku_total) ->with('stock_qty', $skuObj->stock_qty) ->with('img_url', $skuObj->img_url) ->with('def_sku_checked', ($skuObj->is_default ? 'checked="checked"' : '' )); } /** * Create, Update, and Delete products * * POST /admin/skus * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // Delete SKU if ($request->has('delete_sku')) { list($prod_id, $prod_price) = explode(':', $request->prod_id); $sku_count = DB::table('skus')->where('product_id', $prod_id)->count(); $sku = SKU::find($request->sku_id); // Since more than one SKU for this product, make sure another SKU is marked as default if($sku->is_default && $sku_count > 1) { $next_sku = DB::table('skus')->where('product_id',$prod_id)->whereNotIn('id', [$sku->id])->first(); DB::table('skus')->where('id', $next_sku->id)->update(['is_default' => true]); } SKU::destroy($request->delete_sku); return redirect('admin/skus'); } // Process uploaded files if ($request->has('img_name') && $request->img_name != '' && $request->hasFile('img_upload') && $request->file('img_upload')->isValid() && $request->img_name == $request->file('img_upload')->getClientOriginalName()) { $request->file('img_upload')->move(public_path() . $this->publicImgRelPath, $request->img_name); } // Update existing SKU if ($request->has('sku_id')) { list($prod_id, $prod_price) = explode(':', $request->prod_id); // Save SKU Model $sku = SKU::find($request->sku_id); $sku->product_id = $prod_id; $sku->img_url = $request->img_url; $sku->opt_label = $request->opt_label; $sku->desc = $request->sku_desc; $sku->sku_total = $request->sku_total; $sku->stock_qty = $request->stock_qty; // Update Product Model with a default SKU, if its the first or user requests it $sku_count = DB::table('skus')->where('product_id', $prod_id)->where('stock_qty','>',0)->count(); if ($sku_count <= 1 || ($sku_count && $request->has('def_sku'))) { DB::table('skus')->where('product_id', $prod_id)->where('is_default', true)->update(['is_default' => false]); $sku->is_default = true; } // Do not make this SKU default AND there are multiple SKUs for this product elseif($sku->is_default) { $sku->is_default = false; // Since more than one SKU for this product, make sure another SKU is marked as default if ($sku_count) { $next_sku = DB::table('skus')->where('product_id',$prod_id)->whereNotIn('id', [$sku->id])->first(); DB::table('skus')->where('id', $next_sku->id)->update(['is_default' => true]); } } // If the stock count is zero, then it cannot be the default if ($sku->stock_qty <= 0 && $sku->is_default && $sku_count > 1) { $sku->is_default = false; $next_sku = DB::table('skus')->where('product_id',$prod_id)->whereNotIn('id', [$sku->id])->first(); DB::table('skus')->where('id', $next_sku->id)->update(['is_default' => true]); } $sku->save(); // Update the many-to-many DB SKU Options relationship if ($request->has('sku_opts')) { $sku->options()->detach(); $sku->options()->attach($request->sku_opts); } } // Create new SKU else { // Save SKU Model list($prod_id, $prod_price) = explode(':', $request->prod_id); $sku = new SKU; $sku->product_id = $prod_id; $sku->img_url = $request->img_url; $sku->opt_label = $request->opt_label; $sku->desc = $request->sku_desc; $sku->sku_total = $request->sku_total; $sku->stock_qty = $request->stock_qty; // Update Product Model with a default SKU, if its the first or user requests it $sku_count = DB::table('skus')->where('product_id', $prod_id)->count(); if ($sku_count <= 1 || ($sku_count && $request->has('def_sku'))) { DB::table('skus')->where('product_id',$prod_id)->update(['is_default' => false]); $sku->is_default = true; } // Do not make this SKU default AND there are multiple SKUs for this product elseif($sku->is_default) { $sku->is_default = false; // Since more than one SKU for this product, make sure another SKU is marked as default if ($sku_count) { $next_sku = DB::table('skus')->where('product_id',$prod_id)->whereNotIn('id', [$sku->id])->first(); DB::table('skus')->where('id', $next_sku->id)->update(['is_default' => true]); } } $sku->save(); // Create the many-to-many DB SKU Options relationship if ($request->has('sku_opts')) { $sku->options()->attach($request->sku_opts); } } return redirect('admin/skus/' . $sku->id); } } <file_sep>/app/Customer.php <?php namespace strengthcom; use Illuminate\Database\Eloquent\Model; class Customer extends Model { protected $fillable = [ 'addr_ship_id', 'addr_bill_id', 'phone', 'user_id', ]; public function invoices() { return $this->hasMany('strengthcom\Invoice'); } public function ship_addr() { return $this->belongsTo('strengthcom\Address', 'addr_ship_id'); } public function bill_addr() { return $this->belongsTo('strengthcom\Address', 'addr_bill_id'); } public function user() { return $this->belongsTo('strengthcom\User'); } } <file_sep>/app/Basket.php <?php namespace strengthcom; use Illuminate\Database\Eloquent\Model; class Basket extends Model { protected $fillable = [ 'session_num', 'sku_id', 'sku_qty', ]; public function sku() { return $this->belongsTo('strengthcom\SKU'); } } <file_sep>/tests/functional/AdminSKUsTest.php <?php use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use strengthcom\Product; use strengthcom\Option; use strengthcom\SKU; class AdminSKUsTest extends TestCase { use DatabaseTransactions; protected $account_user = '<NAME>'; protected $account_email = '<EMAIL>'; protected $account_passwd = '<PASSWORD>'; protected $test_options = array( array('cat_name' => '_flavour', 'cat_value' => 'White Choc Raspberry'), array('cat_name' => '_flavour', 'cat_value' => 'Choc Cookie Dough'), array('cat_name' => '_weight', 'cat_value' => '20g bar'), array('cat_name' => '_servings', 'cat_value' => '12 bars'), ); protected $test_products = array( array('title' => 'MusclePharm Combat Crunch Protein Bar', 'price' => '2.99'), array('title' => 'EnergyFirst Permalean Protein Bar', 'price' => '3.99'), array('title' => 'MuscleMaxx Protein Bar (Box)', 'price' => '15.99'), ); protected $test_SKU = array( array( 'p_id' => '1', 'p_price' => '2.99', 'sku_opts' => array('3','1'), 'opt_label' => 'White Choc Raspberry, 20g bar', 'sku_desc' => 'This is a sample', 'sku_total' => '2.99', 'stock_qty' => '10', 'img_url' => 'http://strengthcom.dev/uploads/images/bars-EnergyFirst-Permalean-Chocoholic-Cookie-Dough-12-bars.png', 'base_url_path' => 'http://strengthcom.dev/uploads/images', 'img_name' => 'bars-EnergyFirst-Permalean-Chocoholic-Cookie-Dough-12-bars.png', 'img_path' => '/uploads/images/bars-EnergyFirst-Permalean-Chocoholic-Cookie-Dough-12-bars.png', ), array( 'p_id' => '1', 'p_price' => '3.99', 'sku_opts' => array('3','2'), 'opt_label' => 'Choc Cookie Dough, 20g bar', 'sku_desc' => 'This is 2nd SKU', 'sku_total' => '3.99', 'stock_qty' => '5', 'img_url' => 'http://strengthcom.dev/uploads/images/box-MuscleMaxx-Peanut-Butter-Dream-12-bars', 'base_url_path' => 'http://strengthcom.dev/uploads/images', 'img_name' => 'box-MuscleMaxx-Peanut-Butter-Dream-12-bars', 'img_path' => '/uploads/images/box-MuscleMaxx-Peanut-Butter-Dream-12-bars.png', ), ); public static function setUpBeforeClass() { error_log("---- RESET & SEED DATABASE --------------------------------------------------------------"); passthru("php artisan migrate:reset --env='testing'"); passthru("php artisan migrate --env='testing'"); } protected function setUp() { parent::setUp(); // Verify DB empty $this->assertEquals(0, DB::table('options')->count()); $this->assertEquals(0, DB::table('products')->count()); $this->assertEquals(0, DB::table('skus')->count()); // Then create some dummy options & products so redirect to SKUs admin occurs foreach ($this->test_options as $opt) { Option::create(['cat_name' => $opt['cat_name'], 'cat_value' => $opt['cat_value']]); } // Verify creation of options $this->assertEquals(count($this->test_options), count(DB::table('options')->get())); // Create dummy products foreach ($this->test_products as $prod) { Product::create(['title' => $prod['title'], 'price' => $prod['price']]); } } /** * testVerifyOption Test Case. * * Add / Edit / Delete / View Products * * @return void */ public function testVerifySKUs() { // Register and verify shown is SKU creation view $this->accountRegister(); $this->seePageIs('/admin/skus/create'); // Create SKU $this->call('POST', '/admin/skus', array( '_token' => csrf_token(), 'prod_id' => $this->test_SKU[0]['p_id'] . ':' . $this->test_SKU[0]['p_price'], 'sku_opts' => $this->test_SKU[0]['sku_opts'], 'opt_label' => $this->test_SKU[0]['opt_label'], 'sku_desc' => $this->test_SKU[0]['sku_desc'], 'sku_total' => $this->test_SKU[0]['sku_total'], 'stock_qty' => $this->test_SKU[0]['stock_qty'], 'img_url' => $this->test_SKU[0]['img_url'], 'base_url_path' => $this->test_SKU[0]['base_url_path'], 'img_name' => $this->test_SKU[0]['img_name'], )); $this->assertRedirectedTo('/admin/skus/1'); // Verify SKU Added to DB $db_skus = DB::table('skus')->get(); $this->assertEquals(1, count($db_skus)); // Verify the SKU options added $SkuOptions = SKU::find($db_skus[0]->id)->options()->get()->toArray(); $this->assertEquals(2, count($SkuOptions)); $this->assertEquals($this->test_SKU[0]['sku_opts'][0], $SkuOptions[1]['id']); $this->assertEquals($this->test_SKU[0]['sku_opts'][1], $SkuOptions[0]['id']); // Lets Update fields $newdesc = 'A new description'; $newprice = '99.99'; $newopt_id = '4'; $sku_id = $db_skus[0]->id; $this->call('POST', '/admin/skus', array( '_token' => csrf_token(), 'sku_id' => $sku_id, 'prod_id' => $this->test_SKU[0]['p_id'] . ':' . $this->test_SKU[0]['p_price'], 'def_sku' => 'on', 'sku_opts' => array_add($this->test_SKU[0]['sku_opts'], 2, $newopt_id), 'opt_label' => $this->test_SKU[0]['opt_label'], 'sku_desc' => $newdesc, 'sku_total' => $newprice, 'stock_qty' => $this->test_SKU[0]['stock_qty'], 'img_url' => $this->test_SKU[0]['img_url'], 'base_url_path' => $this->test_SKU[0]['base_url_path'], 'img_name' => $this->test_SKU[0]['img_name'], )); // Verify the SKU options added $SkuOptions = SKU::find($db_skus[0]->id)->options()->get()->toArray(); $this->assertEquals(3, count($SkuOptions)); $this->assertEquals($this->test_SKU[0]['sku_opts'][0], $SkuOptions[1]['id']); $this->assertEquals($this->test_SKU[0]['sku_opts'][1], $SkuOptions[0]['id']); $this->assertEquals($newopt_id, $SkuOptions[2]['id']); // Verify update in DB $db_skus = DB::table('skus')->where('id', $sku_id)->first(); $this->assertEquals($newdesc, $db_skus->desc); $this->assertEquals($newprice, $db_skus->sku_total); // Create 2nd SKU on same Product $this->call('POST', '/admin/skus', array( '_token' => csrf_token(), 'def_sku' => 'on', 'prod_id' => $this->test_SKU[1]['p_id'] . ':' . $this->test_SKU[0]['p_price'], 'sku_opts' => $this->test_SKU[1]['sku_opts'], 'opt_label' => $this->test_SKU[1]['opt_label'], 'sku_desc' => $this->test_SKU[1]['sku_desc'], 'sku_total' => $this->test_SKU[1]['sku_total'], 'stock_qty' => $this->test_SKU[1]['stock_qty'], 'img_url' => $this->test_SKU[1]['img_url'], 'base_url_path' => $this->test_SKU[1]['base_url_path'], 'img_name' => $this->test_SKU[1]['img_name'], )); // Verify DB addition + new SKU is the ONLY default $db_skus = DB::table('skus')->get(); $this->assertEquals(2, count($db_skus)); $this->assertTrue(!$db_skus[0]->is_default && $db_skus[1]->is_default); //2nd is new default, first was unselected as default // Delete a product $this->call('POST', '/admin/skus', array( '_token' => csrf_token(), 'delete_sku' => $db_skus[1]->id, 'prod_id' => $this->test_SKU[1]['p_id'] . ':' . $this->test_SKU[0]['p_price'], 'sku_id' => $db_skus[1]->id, )); // Verify deletion $old_shu_id = $db_skus[0]->id; $db_skus = DB::table('skus')->get(); $this->assertEquals(1, count($db_skus)); $this->assertEquals($old_shu_id, $db_skus[0]->id); $this->assertTrue($db_skus[0]->is_default == '1'); //1st is now default // Verify view of a specific SKU $sku_id = $db_skus[0]->id; $this->visit('/admin/skus/' . $sku_id) ->see('Admin - Manage SKUs') ->see('>Add SKU<') ->see('id="update_create_sku"') ->see('id="delete_sku"'); // Verify redirect on an invalid product $this->visit('/admin/skus/999'); $this->assertTrue(ends_with(url()->current(), '/admin/skus/'. $sku_id)); // We're ALL DONE! } /** * accountRegister Helper Method. * * Register Test Account * * @return void */ public function accountRegister() { $this->visit('/login') ->see('Sign In') ->click('Create Your Account') ->seePageIs('/register') ->type($this->account_user, 'name') ->type($this->account_email, 'email') ->type($this->account_passwd, '<PASSWORD>') ->type($this->account_passwd, '<PASSWORD>') ->press('Register'); } /** * accountLogin Helper Method. * * Login to Test Account * * @return void */ public function accountLogin() { $this->visit('/login') ->see('Sign In') ->type($this->account_email, 'email') ->type($this->account_passwd, '<PASSWORD>') ->press('Sign in'); } }<file_sep>/tests/functional/ProductsControllerTest.php <?php use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class ProductsControllerTest extends TestCase { use DatabaseTransactions; public static function setUpBeforeClass() { error_log("---- RESET & SEED DATABASE --------------------------------------------------------------"); passthru("php artisan migrate:reset --env='testing'"); passthru("php artisan migrate --env='testing' --seed"); } /** * testVerifyProductItemDisplays Test Case. * * Verify product item display's on the Products page * and will be populated by new Product Item HTML when javascript dropdowns change * * @return void */ public function testVerifyProductItemDisplays() { error_log("---- VERIFY PRODUCT ITEM --------------------------------------------------------------"); // Look for a product from DB seeding on Product listings page $this->visit('/products') ->see('Shop our Products') ->see('<!-- PRODUCT ITEM -->') ->see('EnergyFirst Permalean Protein Bar') ->see('CDN 3.99') ->see('Delicious and Nutritious tasting treat in a bar of goodness') ->see('<img alt="EnergyFirst Permalean Protein Bar"'); error_log("---- VERIFY PRODUCT SELECTION CHANGE --------------------------------------------------------------"); // Emulate product selection change (from javascript dropdown) via a GET /products/sku/:id request $this->visit('/products/sku/4') ->see('MusclePharm Combat Crunch Protein Bar') ->see('CDN 12.99') ->see('Wow! Delicious and Nutritious tasting treat in a bar of goodness') ->see('<img alt="MusclePharm Combat Crunch Protein Bar"'); } }<file_sep>/app/Events/Event.php <?php namespace strengthcom\Events; abstract class Event { // } <file_sep>/app/Http/Controllers/ShoppingCartController.php <?php namespace strengthcom\Http\Controllers; use DB; use Illuminate\Http\Request; use Webpatser\Uuid\Uuid; use strengthcom\Http\Requests; use strengthcom\SKU; use strengthcom\Product; use strengthcom\Basket; class ShoppingCartController extends Controller { protected static $SessionKeyName = 'cart_session_number'; /** * Display listing of SKUs in shopping cart. * * GET /cart * * @return \Illuminate\Http\Response */ public function index() { // Get max SKU QTY in Basket $session_num = $this->getSessionNumber(); // Get count of SKUs in Basket $basket = Basket::where('session_num', $session_num)->with([ 'sku' => function ($q) { $q->orderBy('id', 'desc'); }, 'sku.product' ])->get(); $basket_qty = 0; $basket_total = 0; $skus_all = []; foreach ($basket as $item) { $basket_qty += $item->sku_qty; $basket_total += ($item->sku->sku_total * $item->sku_qty); // Ensure that QTY select is at least 2x the current Qty's in basket // (Up to the max stock available for this SKU) for ($i = 1, $qty_select=[]; $i <= $item->sku->stock_qty; $i++) $qty_select[$i] = $i; $skus_all[] = [ 'id' => $item->sku->id, 'product_title' => $item->sku->product->title, 'qty' => $item->sku_qty, 'price' => $item->sku->sku_total, 'label' => $item->sku->opt_label, 'img_url' => $item->sku->img_url, 'qty_select' => $qty_select, ]; } $basket_arr = [ 'basket_total' => $basket_total, 'basket_qty' => $basket_qty, 'skus' => $skus_all ]; return view('products.cart')->with('cart', $basket_arr); } /** * Return JSON response with SKU quantity in basket * * GET /cart/{opt} * * @param int $opt * @return \Illuminate\Http\Response */ public function show($opt) { if ($opt == 'qty') { $session_num = $this->getSessionNumber(); // Get the sum of SKU QTY's in Basket $basket_qty = Basket::where('session_num', $session_num)->sum('sku_qty'); // Return JSON response $jsonResponse = [ 'basket_qty' => ($basket_qty == '' ? '0' : $basket_qty), 'status' => 'success', 'msg' => "$basket_qty Product Items in basket" ]; return response()->json($jsonResponse); } return ''; } /** * Process request for adding / updating a SKU in Shopping Basket * * GET /cart/update/{id}/{qty} * * @param int $id * @param int $qty * @return \Illuminate\Http\Response (JSON) */ public function updateCart($sku_id, $qty) { $session_num = $this->getSessionNumber(); // Validate input if (!is_numeric($qty) || $qty <= 0) return response()->json(['status' => 'failure', 'msg' => 'SKU Qty must be 1 or greater']);; $sku = SKU::find($sku_id); if ($sku == null) return response()->json(['status' => 'failure', 'msg' => 'SKU Does not exist']);; $sku = Basket::where(['session_num' => $session_num, 'sku_id' => $sku_id])->first(); // Create SKU in basket if ($sku == null) { Basket::create([ 'session_num' => $session_num, 'sku_id' => $sku_id, 'sku_qty' => $qty, ]); } // If it exists, increment it's quantity else { $sku->sku_qty += $qty; $sku->save(); } // Get the sum of SKU QTY's in Basket $basket_qty = Basket::where('session_num', $session_num)->sum('sku_qty'); // Return JSON response $jsonResponse = [ 'sku_id' => $sku_id, 'sku_qty' => $qty, 'basket_qty' => $basket_qty, 'status' => 'success', 'msg' => "Product Item added or updated in Cart" ]; return response()->json($jsonResponse); } /** * Store a newly created resource in storage. * * POST /cart * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $session_num = $this->getSessionNumber(); // Process Delete operation if ($request->delete_sku) { Basket::where('session_num', $session_num) ->where('sku_id', $request->delete_sku) ->delete(); } // Process Qty Update operation else { $basket = Basket::where('session_num', $session_num)->with('sku')->get(); $new_qty_lookup = []; foreach ($request->all() as $field_name => $field_value) { if (starts_with($field_name, 'sku_qty-')) { list($dump, $sku_id) = explode('-', $field_name); $new_qty_lookup[$sku_id] = $field_value; } } foreach ($basket as $item) { if (array_key_exists($item->sku->id, $new_qty_lookup) && $item->sku_qty != $new_qty_lookup[$item->sku->id]) { $item->sku_qty = $new_qty_lookup[$item->sku->id]; $item->save(); } } } return redirect('cart'); } public static function getSessionNumber() { if (session()->has(self::$SessionKeyName)) { // Use UUID stored in Session under $SessionKeyName $UUID = session(self::$SessionKeyName); } else { // Create UUID for Shopping basket session_num column $UUID_Obj = Uuid::generate(4); $UUID = $UUID_Obj->string; session([self::$SessionKeyName => $UUID]); } return $UUID; } } <file_sep>/tests/functional/CheckoutTest.php <?php use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use Carbon\Carbon; class CheckoutTest extends TestCase { use DatabaseTransactions; protected $account_user = '<NAME>'; protected $account_email = '<EMAIL>'; protected $account_passwd = '<PASSWORD>'; public static function setUpBeforeClass() { error_log("---- RESET & SEED DATABASE --------------------------------------------------------------"); passthru("php artisan migrate:reset --env='testing'"); passthru("php artisan migrate --env='testing' --seed"); } protected function setUp() { parent::setUp(); Session::start(); } /** * testVerifyLoginLogout Test Case. * * Login / Logout validation * * @return void */ public function testVerifyLoginLogout() { // Register and verify logged in but redirected to products when attempting to checkout $this->accountRegister(); $this->visit('/checkout') ->seePageIs('/products'); // Logout and log back in $this->click('Logout') ->visit('/checkout') ->see('Sign In'); $this->accountLogin(); $this->visit('/checkout') ->seePageIs('/products') ->click('Logout'); } /** * testCheckoutProcess Test Case. * * Proceed through checkout process * * @depends testVerifyLoginLogout * * @return void */ public function testCheckoutInfo() { // Populate cart with items to purchase $this->populateCart(); // Register and login $this->accountRegister(); $this->visit('/checkout') ->seePageIs('/checkout/info'); // Step 1: Fill-in shipping / billing info $this->type('4164574537', 'phone') ->type('72 Kop Rd', 'ship_addr') ->type('Etobicoke', 'ship_city') ->type('Ontario', 'ship_prov') ->type('Canada', 'ship_country') ->type('L7N2G6', 'ship_postal') ->type('72 Kop Rd', 'bill_addr') ->type('Etobicoke', 'bill_city') ->type('Ontario', 'bill_prov') ->type('Canada', 'bill_country') ->type('L7N2G6', 'bill_postal') ->type('Ontario', 'bill_prov') ->check('same_as_ship') ->press('Next') ->seePageIs('/checkout/shipping'); // Verify in DB $db_cust = DB::table('customers')->get(); $this->assertEquals(1, count($db_cust)); $this->assertTrue($db_cust[0]->addr_ship_id == $db_cust[0]->addr_bill_id); //Same as option created single address // Step 2: Specify Shipping Method $ship_method_name = 'UPS'; $ship_method_price = '14.99'; $this->type($ship_method_price, 'ship_cost'); $this->select($ship_method_name, 'shipmethod') ->press('Next') ->seePageIs('/checkout/payment'); // Verify in DB $db_inv = DB::table('invoices')->get(); $this->assertEquals(1, count($db_inv)); $this->assertEquals($ship_method_name, $db_inv[0]->ship_method); $this->assertEquals($ship_method_price, $db_inv[0]->ship_cost); // Step 3: Specify Payment Method $pay_method_value = 'visa'; $this->select($pay_method_value, 'paymethod'); $this->type('CC Tester', 'name') ->type('111111111', 'phone') ->type('<EMAIL>', 'email') ->type('12313122123', 'card_num') ->type('01', 'visa_exp_month') ->type('16', 'visa_exp_year') ->type('558', 'visa_exp_cvv') ->type('12 Test St', 'bill_addr') ->type('Toronto', 'bill_city') ->type('Alberta', 'bill_prov') ->type('Canada', 'bill_country') ->type('N9D2H7', 'bill_postal') ->press('Next') ->seePageIs('/checkout/confirm'); // Verify saved info in Session $this->assertSessionHas('payment_info'); // Step 4: Confirm Order $this->see('Your Order Items') ->press('Place your order') ->seePageIs('/checkout/paystatus'); // Step 5: Fake Payment processing $this->see('Please wait while we process your order') ->type('PASS','trans_status') ->type(Carbon::now(),'trans_datetime') ->type('1234567890','trans_num') ->press('Proceed') ->seePageIs('/checkout/paystatus'); // Verify in DB $db_inv = DB::table('invoices')->get(); $this->assertEquals(1, count($db_inv)); $this->assertEquals('111111111', $db_inv[0]->bill_phone); $this->assertEquals('PASS', $db_inv[0]->trans_status); $this->assertEquals('1234567890', $db_inv[0]->trans_num); $this->assertEquals('Alberta', $db_inv[0]->bill_prov); $this->assertEquals('12 Test St', $db_inv[0]->bill_addr); $this->assertEquals('72 Kop Rd', $db_inv[0]->ship_addr); $this->assertEquals('L7N2G6', $db_inv[0]->ship_postal); $this->assertEquals('UPS', $db_inv[0]->ship_method); // Verify that email was queued for transmission // We're ALL DONE! } /** * populateCart Helper Method * * Add Products to Cart so we can cash them out * * @return void */ public function populateCart() { // Add SKU 'EnergyFirst Permalean Protein Bar' with quantity 1 to basket $this->json('GET', '/cart/update/1/1') ->seeJson([ 'sku_id' => '1', 'sku_qty' => '1', 'basket_qty' => '1', 'status' => 'success', 'msg' => 'Product Item added or updated in Cart', ]); // Increment count in basket of same SKU 'EnergyFirst Permalean Protein Bar' $this->json('GET', '/cart/update/1/1') ->seeJson([ 'sku_id' => '1', 'sku_qty' => '1', 'basket_qty' => '2', 'status' => 'success', 'msg' => 'Product Item added or updated in Cart', ]); // Add to basket, an additional SKU 'MusclePharm Combat Crunch Protein Bar', with QTY 3 $this->json('GET', '/cart/update/3/2') ->seeJson([ 'sku_id' => '3', 'sku_qty' => '2', 'basket_qty' => '4', 'status' => 'success', 'msg' => 'Product Item added or updated in Cart', ]); } /** * accountRegister Helper Method. * * Register Test Account * * @return void */ public function accountRegister() { $this->visit('/login') ->see('Sign In') ->click('Create Your Account') ->seePageIs('/register') ->type($this->account_user, 'name') ->type($this->account_email, 'email') ->type($this->account_passwd, '<PASSWORD>') ->type($this->account_passwd, '<PASSWORD>') ->press('Register'); } /** * accountLogin Helper Method. * * Login to Test Account * * @return void */ public function accountLogin() { $this->visit('/login') ->see('Sign In') ->type($this->account_email, 'email') ->type($this->account_passwd, '<PASSWORD>') ->press('Sign in'); } }<file_sep>/app/Http/Controllers/AdminProductsController.php <?php namespace strengthcom\Http\Controllers; use Illuminate\Http\Request; use strengthcom\Http\Requests; use strengthcom\Product; use strengthcom\Option; class AdminProductsController extends Controller { /** * Inform Middleware of the need for Authenticated access to route /checkout/info * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Redirect to the first Product in DB for editing * * GET /admin/products * * @return \Illuminate\Http\Response */ public function index() { // Validate if system ready for this stage if (Option::all()->isEmpty()) { return redirect('admin/options/create'); } // Get Products, if they exist $prod_all = Product::all(); if ($prod_all->isEmpty()) { return redirect('admin/products/create'); } else { $prod_first = $prod_all->first()->id; return redirect('admin/products/' . $prod_first); } } /** * Show a minial form for creating a single new Product * * GET /admin/products/create * * @return \Illuminate\Http\Response */ public function create() { // Validate if system ready for this stage if (Option::all()->isEmpty()) { return redirect('admin/options/create'); } return view('admin.products.create'); } /** * Display Products in a form for editing * * GET /admin/products/{id} * * @param int $id * @return \Illuminate\Http\Response */ public function show($prod_id) { // If ID does not exist in DB, redirect to using first record if (!is_object(Product::find($prod_id))) { return redirect('admin/products'); } // If ID does not exist in DB, redirect to using first record if (!is_object(Product::find($prod_id))) { return redirect('admin/products'); } // Get lists to populate view $prod_all = Product::orderBy('title', 'asc')->get(); $prod = Product::find($prod_id); return view('admin.products.edit') ->with('prod_all', $prod_all->lists('title', 'id')) ->with('selected_prod_id', $prod_id) ->with('prod', $prod); } /** * Create, Update, and Delete products * * POST /admin/products * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // Create new product on empty table if ($request->has('new_prod_title') && $request->has('new_prod_price')) { $option = new Product; $option->title = $request->new_prod_title; $option->price = $request->new_prod_price; $option->save(); return redirect('admin/products'); } // // Perform product operation based on value of "prod_opt" if ($request->has('prod_opt')) { // UPDATE Operation if ($request->prod_opt == 'update_prod') { $product = Product::find($request->ddlProduct); $product->title = $request->title; $product->price = $request->price; $product->save(); return redirect('admin/products/' . $request->ddlProduct); } // DELETE Operation elseif ($request->prod_opt == 'delete_prod') { Product::destroy($request->ddlProduct); return redirect('admin/products'); } } } } <file_sep>/readme.md # Laravel PHP Framework Hello Enjoy playing with my Laravel Project. It's uploaded here, for you to download and install into you local Vagrant sandbox VM Contact me at <EMAIL> if you have issues with the installation instruction below ## Installation 1. git clone this repository source into a working Vagrant VM > > rm -rf database/migrations/*_create_password_resets_table.php > > rm -rf database/migrations/*_create_users_table.php > > git remote add upstream https://github.com/lancemitchell/LaravelProject > > git fetch upstream > > git merge upstream/master > > git status > > git checkout remotes/upstream/master -- [files] > > git commit -m <Msg> > 2. Update Laravel installation with latest updates from __composer.json__ dependancies and flush caches of old code > composer update > > composer dump-autoload > > composer dump-auto > > php artisan cache:clear > > php artisan config:clear 3. Configure MYSQL database 4. In project root, configure your own .env file with you Ubuntu specifics 5. In project root, use the supplied __laravel-worker.conf__ file to configure the Supervisor process monitor for email queue process management > sudo apt-get install supervisor > > edit 'laravel-worker.conf' with your project path > > cp laravel-worker.conf /etc/supervisor/conf.d > > sudo supervisorctl reread > > sudo supervisorctl update > > sudo supervisorctl start laravel-worker:* > > In __.env__, change the __QUEUE_DRIVER__ setting from __sync__ to __database__ 6. Initialize the database schema, and seed it with working data > php migrate:install > > php artisan migrate:reset; > > php artisan migrate --seed > 7. Configure your PC hosts file to point to you vagrant VM 8. Open a browser to project web root 9. Enjoy shopping 10. To explore the Administration backend, login and click "Administration" in nav <file_sep>/app/Address.php <?php namespace strengthcom; use Illuminate\Database\Eloquent\Model; class Address extends Model { protected $fillable = [ 'addr', 'city', 'prov', 'country', 'postal', ]; public function ship_cust() { return $this->hasOne('strengthcom\Customer', 'addr_ship_id'); } public function bill_cust() { return $this->hasOne('strengthcom\Customer', 'addr_bill_id'); } } <file_sep>/database/migrations/2016_04_11_063423_create_invoices_table.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateInvoicesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('invoices', function (Blueprint $table) { $table->increments('id'); $table->integer('customer_id')->unsigned(); $table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade'); $table->char('inv_num', 100); $table->decimal('inv_total', 8, 2); $table->dateTime('inv_datetime'); $table->string('bill_name'); $table->char('bill_phone', 20); $table->char('pay_method', 10); $table->char('card_suffix', 5); $table->char('ship_method', 50); $table->decimal('ship_cost', 8, 2); $table->string('ship_addr'); $table->char('ship_city', 100); $table->char('ship_prov', 100); $table->char('ship_country', 100); $table->char('ship_postal', 10); $table->string('bill_addr'); $table->char('bill_city', 100); $table->char('bill_prov', 100); $table->char('bill_country', 100); $table->char('bill_postal', 10); $table->char('trans_status', 10); $table->char('trans_num', 100); $table->dateTime('trans_datetime'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('invoices'); } } <file_sep>/app/Jobs/EmailOrderPurchaseInvoiceJob.php <?php namespace strengthcom\Jobs; use Mail; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Mail\Mailer; use Illuminate\Contracts\Bus\SelfHandling; use Illuminate\Contracts\Queue\ShouldQueue; use strengthcom\Http\Controllers\CheckoutPayStatusController; use strengthcom\Jobs\Job; use strengthcom\Invoice; class EmailOrderPurchaseInvoiceJob extends Job implements SelfHandling, ShouldQueue { use InteractsWithQueue, SerializesModels; protected $inv; /** * Create a new job instance. * * @return void */ public function __construct(Invoice $invoice) { $this->inv = $invoice; } /** * Execute the job. * * @return void */ public function handle() { // Generate Invoice from DB $order = CheckoutPayStatusController::generateInvoiceOrderData($this->inv->id); // Email Invoice to user Mail::send('emails.invoice', ['order' => $order], function ($msg) use ($order) { $msg->from('<EMAIL>', 'Strength.com App'); $msg->to($order['bill_email'], $order['ship_name']) ->subject('Your Order#' . $order['inv_num'] . ' Invoice'); }); } } <file_sep>/app/Product.php <?php namespace strengthcom; use Illuminate\Database\Eloquent\Model; class Product extends Model { protected $fillable = [ 'title', 'price', ]; public function skus() { return $this->hasMany('strengthcom\SKU'); } public function options() { return $this->belongsToMany('strengthcom\Option', 'product_options'); } } <file_sep>/app/Http/Controllers/CheckoutConfirmController.php <?php namespace strengthcom\Http\Controllers; use Auth; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use strengthcom\Http\Requests; use strengthcom\User; use strengthcom\Option; use strengthcom\Basket; use strengthcom\Customer; use strengthcom\Invoice; use strengthcom\InvSKU; class CheckoutConfirmController extends Controller { /** * Inform Middleware of the need for Authenticated access to route /checkout/info * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Collect Billing & Shipping info * * GET /checkout/confirm * * @return \Illuminate\Http\Response */ public function index(Request $request) { $session_num = ShoppingCartController::getSessionNumber(); $user = Auth::user(); $cust = Customer::where('user_id', $user->id)->with( 'ship_addr', 'bill_addr' )->first(); // Validate if user ready for this stage of checkout if ($cust == null) { return redirect('/checkout/info'); } $inv = Invoice::where('customer_id', $cust->id) ->where('trans_status','!=','PASS') ->with('skus') ->first(); if ($inv == null) { return redirect('/checkout/shipping'); } if (!$request->session()->has('payment_info')) { return redirect('/checkout/payment'); } // Get Shipping / Billing information $order['name'] = $user->name; $order['email'] = $user->email; $order['phone'] = $cust->phone; $order['ship']['ship_addr'] = $cust->ship_addr->addr; $order['ship']['ship_city'] = $cust->ship_addr->city; $order['ship']['ship_prov'] = $cust->ship_addr->prov; $order['ship']['ship_postal'] = $cust->ship_addr->postal; $order['ship']['ship_country'] = $cust->ship_addr->country; $order['bill']['bill_addr'] = session('payment_info')['bill_addr'] ? session('payment_info')['bill_addr'] : $cust->bill_addr->addr; $order['bill']['bill_city'] = session('payment_info')['bill_city'] ? session('payment_info')['bill_city'] : $cust->bill_addr->city; $order['bill']['bill_prov'] = session('payment_info')['bill_prov'] ? session('payment_info')['bill_prov'] : $cust->bill_addr->prov; $order['bill']['bill_postal'] = session('payment_info')['bill_postal'] ? session('payment_info')['bill_postal'] : $cust->bill_addr->postal; $order['bill']['bill_country'] = session('payment_info')['bill_country'] ? session('payment_info')['bill_country'] : $cust->bill_addr->country; $order['same_as_ship'] = $this->array_equal($order['ship'], $order['bill']) ? 'yes' : ''; $shipping_methods = Option::where('cat_name', 'ship_method') ->orderBy('cat_value', 'asc') ->get(['cat_value as name'])->lists('name'); foreach ($shipping_methods as $ship_value) { list($id, $name, $price) = explode(':', $ship_value); if ($inv->ship_method == $id) { $order['ship_method'] = $name; $order['ship_price'] = $price; } } // Get Payment Information from Session $order['paymethod'] = session('payment_info')['paymethod']; $order['card_num_suffix'] = substr(session('payment_info')['card_num'], -4); $order['email'] = session('payment_info')['email']; // Get Product Item Information $basket = Basket::where('session_num', $session_num)->with([ 'sku' => function ($q) { $q->orderBy('id', 'desc'); }, 'sku.product' ])->get(); $item_total = 0; $item_qty = 0; $items = []; foreach ($basket as $item) { $item_qty += $item->sku_qty; $item_total += ($item->sku->sku_total * $item->sku_qty); $items[] = [ 'id' => $item->sku->id, 'title' => $item->sku->product->title, 'label' => $item->sku->opt_label, 'desc' => $item->sku->desc, 'qty' => $item->sku_qty, 'price' => $item->sku->sku_total, 'img' => $item->sku->img_url, ]; } $order['item_total'] = number_format(floatval($item_total), 2); $order['item_qty'] = $item_qty; $order['inv_total'] = number_format(floatval($item_total) + floatval($order['ship_price']), 2); $order['items'] = $items; return view('checkout.confirm') ->with('order', $order); } /** * Store a newly created resource in storage. * * POST /checkout/confirm * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // Verify there are no empty fields $validator = Validator::make($request->all(), [ 'placeOrderButton' => 'required|string', ]); if ($validator->fails()) { return redirect('checkout/confirm') ->withErrors($validator) ->withInput(); } // Validation passed: lets store this info $user = Auth::user(); $cust = Customer::where('user_id', $user->id)->first(); $inv = Invoice::where('customer_id', $cust->id) ->where('trans_status','!=','PASS') ->first(); $inv->inv_datetime = Carbon::now(); $inv->trans_datetime = Carbon::now(); $inv->save(); $inv_sku_count = InvSKU::where('invoice_id', $inv->id)->count(); if ($inv->inv_total > 0 && $inv_sku_count <= 0) { //Send error back to /checkout/shipping to resave Invoice SKU items return redirect('checkout/shipping') ->withErrors(array('reconfirm' => 'Please reconfirm your order and proceed through Checkout.')) ->withInput(); } // Update Payement info, with acceptance of user to proceed session()->put('payment_info.proceed_with_payment', 'yes'); return redirect('checkout/paystatus'); } /** * Compare who arrays of keys in any order and report if values are identical * */ private function array_equal($a, $b) { return (is_array($a) && is_array($b) && array_diff($a, $b) === array_diff($b, $a)); } } <file_sep>/database/migrations/2016_04_11_063432_create_inv_skus_table.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateInvSkusTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('inv_skus', function (Blueprint $table) { $table->increments('id'); $table->integer('invoice_id')->unsigned(); $table->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade'); $table->string('title', 255); $table->longText('desc'); $table->integer('sku_qty'); $table->decimal('sku_price', 8, 2); $table->text('img_url'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('inv_skus'); } } <file_sep>/app/Http/Controllers/CheckoutInfoController.php <?php namespace strengthcom\Http\Controllers; use Auth; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use strengthcom\Http\Requests; use strengthcom\User; use strengthcom\Option; use strengthcom\Basket; use strengthcom\Customer; use strengthcom\Address; class CheckoutInfoController extends Controller { /** * Inform Middleware of the need for Authenticated access to route /checkout/info * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Redirect to collecting Address info (1st stage of fullfillment process) at /checkout/info * * GET /checkout * * @return \Illuminate\Http\Response */ public function goToInfo() { return redirect('checkout/info'); } /** * Collect Billing & Shipping info * * GET /checkout/info * * @return \Illuminate\Http\Response */ public function index() { // Validate if user ready for this stage of checkout $session_num = ShoppingCartController::getSessionNumber(); $items_in_basket = Basket::where('session_num', $session_num)->count(); if (!$items_in_basket) { return redirect('/products'); } $user = Auth::user(); $customer = Customer::where('user_id', $user->id)->with( 'ship_addr', 'bill_addr' )->first(); $prov_list = Option::where('cat_name', 'prov_state') ->get(['id','cat_value as name'])->lists('name', 'name'); $country_list = Option::where('cat_name', 'countries') ->get(['id','cat_value as name'])->lists('name', 'name'); // Evaluate if Shipping & Billing have the same values if ($customer == null) { $same_as_ship = 'yes'; } else { $ship_addr = array_except($customer->ship_addr->toArray(), ['id','created_at','updated_at']); $bill_addr = array_except($customer->bill_addr->toArray(), ['id','created_at','updated_at']); $same_as_ship = $customer != null && $this->array_equal($ship_addr, $bill_addr) ? 'yes' : ''; } // Pass data to View $customerArr = [ 'name' => $user->name, 'phone' => $customer == null ? '' : $customer->phone, 'ship_addr' => $customer == null ? '' : $customer->ship_addr->addr, 'ship_city' => $customer == null ? '' : $customer->ship_addr->city, 'ship_prov' => $customer == null ? '' : $customer->ship_addr->prov, 'ship_country' => $customer == null ? '' : $customer->ship_addr->country, 'ship_postal' => $customer == null ? '' : $customer->ship_addr->postal, 'bill_addr' => $customer == null ? '' : $customer->bill_addr->addr, 'bill_city' => $customer == null ? '' : $customer->bill_addr->city, 'bill_prov' => $customer == null ? '' : $customer->bill_addr->prov, 'bill_country' => $customer == null ? '' : $customer->bill_addr->country, 'bill_postal' => $customer == null ? '' : $customer->bill_addr->postal, 'same_as_ship' => $same_as_ship, ]; return view('checkout.info') ->with('cust', $customerArr) ->with('prov_list', $prov_list) ->with('country_list', $country_list); } /** * Store a newly created resource in storage. * * POST /checkout/info * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // Verify there are no empty fields $validator = Validator::make($request->all(), [ 'name' => 'required|string', 'phone' => 'required|numeric', 'ship_addr' => 'required|string', 'ship_city' => 'required|string', 'ship_prov' => 'required|string', 'ship_country' => 'required|string', 'ship_postal' => 'required|string', 'bill_addr' => 'required|string', 'bill_city' => 'required|string', 'bill_prov' => 'required|string', 'bill_country' => 'required|string', 'bill_postal' => 'required|string', ]); if ($validator->fails()) { return redirect('checkout/info') ->withErrors($validator) ->withInput(); } // Validation passed: lets store this info $user = Auth::user(); $user->name = $request->name; $user->save(); $cust = Customer::where('user_id', $user->id)->with( 'ship_addr', 'bill_addr' )->first(); $ship_addr = [ 'addr' => $request->ship_addr, 'city' => $request->ship_city, 'prov' => $request->ship_prov, 'country' => $request->ship_country, 'postal' => $request->ship_postal, ]; $bill_addr = [ 'addr' => $request->bill_addr, 'city' => $request->bill_city, 'prov' => $request->bill_prov, 'country' => $request->bill_country, 'postal' => $request->bill_postal, ]; // Update Session Payment info with updated Billing Information if (session()->has('payment_info')) { session()->put([ 'payment_info.bill_addr' => $request->bill_addr, 'payment_info.bill_city' => $request->bill_city, 'payment_info.bill_prov' => $request->bill_prov, 'payment_info.bill_postal' => $request->bill_postal, 'payment_info.bill_country' => $request->bill_country, ]); } // Create Customer if ($cust == null) { $cust = new Customer; $ship_address = Address::firstOrCreate($ship_addr); $bill_address = Address::firstOrCreate($bill_addr); $cust->ship_addr()->associate($ship_address); $cust->bill_addr()->associate($bill_address); $cust->user()->associate($user); $cust->phone = $request->phone; $cust->save(); } // Update Customer else { // Addresses should be the same but they DON'T have the same values if ($cust->addr_ship_id == $cust->addr_bill_id && !$this->array_equal($ship_addr, $bill_addr)) { // Split out Billing and Shipping address into seperate records $bill_address = Address::firstOrCreate($bill_addr); $cust->bill_addr()->associate($bill_address); } elseif ($cust->addr_ship_id == $cust->addr_bill_id) { // Only save Shippping, as they both point to the same DB record $cust->ship_addr->addr = $request->ship_addr; $cust->ship_addr->city = $request->ship_city; $cust->ship_addr->prov = $request->ship_prov; $cust->ship_addr->country = $request->ship_country; $cust->ship_addr->postal = $request->ship_postal; } else { // Update seperate Biling and Shipping records $cust->ship_addr->addr = $request->ship_addr; $cust->ship_addr->city = $request->ship_city; $cust->ship_addr->prov = $request->ship_prov; $cust->ship_addr->country = $request->ship_country; $cust->ship_addr->postal = $request->ship_postal; $cust->bill_addr->addr = $request->bill_addr; $cust->bill_addr->city = $request->bill_city; $cust->bill_addr->prov = $request->bill_prov; $cust->bill_addr->country = $request->bill_country; $cust->bill_addr->postal = $request->bill_postal; } $cust->phone = $request->phone; $cust->update(); $cust->ship_addr->update(); $cust->bill_addr->update(); } return redirect('checkout/shipping'); } /** * Compare who arrays of keys in any order and report if values are identical * */ private function array_equal($a, $b) { return (is_array($a) && is_array($b) && array_diff($a, $b) === array_diff($b, $a)); } } <file_sep>/app/Http/Controllers/AdminController.php <?php namespace strengthcom\Http\Controllers; use Illuminate\Http\Request; use strengthcom\Http\Requests; class AdminController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * GET /admin * * @return \Illuminate\Http\Response */ public function index(Request $request) { $admin_menus = [ ['url' => '/admin/products', 'name' => 'Edit Products'], ['url' => '/admin/options', 'name' => 'Edit Options'], ['url' => '/admin/skus', 'name' => 'Edit SKUs'], ]; if ($request->has('user_session')) { if ($request->user_session == 'view') { if (session()->has('payment_info')) dd(session('payment_info')); else dd("NO USER SESSION DATA"); } elseif ($request->user_session == 'clear') if (session()->has('payment_info')) session()->forget('payment_info'); return redirect(url()->previous()); } return view('admin.index')->with('admin_menus', $admin_menus); } }
75726ab87ee34bbd7160d454611531ce9810e127
[ "JavaScript", "Markdown", "PHP" ]
37
JavaScript
lancemitchell/strengthcom
5e8f5b9388aec1a6347cc2234747342b69b907cb
daab11b197314b9993f24ade4d044cf4a3dda3cf
refs/heads/master
<file_sep>from MyMainPackage import some_main_script from MyMainPackage.SubPackage import mysubscript from mymodule import my_func some_main_script.report_main() my_func() <file_sep>def cap_text(text): ''' Input: Una cadena Output: La cadena capitalizada ''' return text.title() <file_sep>def my_func(): print("Hey Estoy en my modulo.py") <file_sep>def report_main(): print("Hey Estoy en some_main_script in main package")<file_sep>def func(): print("func() en one.PY") def function(): pass def function2(): pass print("Top level en one.py") if __name__ == "__main__": print("one.py esta siendo ejecuutado directamente") # Correr el script function() function2() else: print("one.py ha sido importado") <file_sep>def sub_report(): print("Hey Soy una funcion dentro de mysubscript")<file_sep>import one print("Top level en two.py") one.func() if __name__ == "__main__": print("two.py esta corriendo directamente") else: print("two.py ha sido importado") <file_sep># Complete-Python-Bootcamp-Go-from-zero-to-hero-in-Python-3 Python course
b431b252bea8a48f5ce72f8b8dc1eb8f05ac4407
[ "Markdown", "Python" ]
8
Python
FrancisFerriEPN/Complete-Python-Bootcamp-Go-from-zero-to-hero-in-Python-3
75d20264f0e1fbc67aaff6176a53b5bd25a5a280
35f8ed96dd6bc5f655948907bb6097bff0913aaa
refs/heads/master
<file_sep># meeting-calendar A simple JS app to show the meeting events for the day. # input The input to the function will be an array of meeting objects with the time of the beginning and end specified in minutes after 9 AM. For example, [{ id : 123, start : 120 end : 150 }] specifies a meeting starting at 11 AM and ending at 11.30 AM. Returns the array of the meetings with the width of each meeting, as well as the CSS attributes for its position. (top and left) # Live Demo: https://rawgit.com/spratap124/meeting-calendar/master/index.html <file_sep>function getRandomColor() { var colors = ["#673AB7","#4CAF50","#F9A825","#e53935","#0091EA","#009688"] var color = colors[Math.floor(Math.random() * colors.length)]; return color; } function creatTimeline(tl) { var i = 0; while (i < tl.length) { var divEl = document.createElement('div'); divEl.style.width = '50px'; divEl.style.height = '120px'; divEl.style.border = '0px solid yellow'; divEl.innerHTML = tl[i]; var timeLine = document.getElementById('timeline'); timeLine.appendChild(divEl); i++; } } function todaysDate(){ var monthArr = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; var dt = new Date(); var date = dt.getDate(); var month = monthArr[dt.getMonth()]; var year = dt.getFullYear(); var today = date +"-"+month+"-"+year; var dateContainer = document.getElementById('date'); dateContainer.innerHTML = today; } function makeCurrentTimeLine(){ var dt = new Date(); var hr = dt.getHours(); var min = dt.getMinutes(); var timeLine = document.getElementById("currentTimeLine"); var timeHolder = document.getElementById('timeHolder'); if(hr> 9 && hr<=20){ // dont let it cross after 9pm min = min.toString().length<2? "0"+min : min; var top = (hr-9)*120 + min*2 +60; var time = hr+":"+ min; timeLine.style.top = top+'px'; timeHolder.innerHTML = time; } else{ timeLine.style.display = 'none' } } function appendEventDivs(eventArr) { var i = 0; while (i < eventArr.length) { var eventEl = document.createElement('div'); eventEl.className = 'event'; eventEl.style.height = eventArr[i].height; eventEl.style.top = eventArr[i].top; eventEl.style.background = eventArr[i].color; eventEl.style.width = eventArr[i].width; eventEl.style.left = eventArr[i].left; eventEl.innerHTML = 'Meeting' + eventArr[i].id; var cl = document.getElementById('calendar'); cl.appendChild(eventEl); i++; } } function collidesWith(a, b) { return a.end > b.start && a.start < b.end; } function checkCollision(eventArr) { for (var i = 0; i < eventArr.length; i++) { eventArr[i].cols = []; eventArr[i].colsBefore=[]; for (var j = 0; j < eventArr.length; j++) { if (collidesWith(eventArr[i], eventArr[j])) { eventArr[i].cols.push(j); if(i>j) eventArr[i].colsBefore.push(j); //also list which of the conflicts came before } } } return eventArr; } function updateEvents(eventArr) { eventArr = checkCollision(eventArr); var arr=eventArr.slice(0); //clone the array for(var i=0; i<arr.length; i++){ var el=arr[i]; el.color = getRandomColor(); el.height = (el.end - el.start) * 2 + 'px'; el.top = (el.start) * 2 + 'px'; if(i>0 && el.colsBefore.length>0){ //check column if not the first event and the event has collisions with prior events if(arr[i-1].column>0){ //if previous event wasn't in the first column, there may be space to the left of it for(var j=0;j<arr[i-1].column;j++){ //look through all the columns to the left of the previous event if(el.colsBefore.indexOf(i-(j+2))===-1){ //the current event doesn't collide with the event being checked... el.column=arr[i-(j+2)].column; //...and can be put in the same column as it } } if(typeof el.column==='undefined') el.column=arr[i-1].column+1; //if there wasn't any free space, but it ito the right of the previous event }else{ var column=0; for(var j=0;j<el.colsBefore.length;j++){ //go through each column to see where's space... if(arr[el.colsBefore[el.colsBefore.length-1-j]].column==column) column++; } el.column=column; } }else el.column=0; } //We need the column for every event before we can determine the appropriate width and left-position, so this is in a different for-loop: for(var i=0; i<arr.length; i++){ arr[i].totalColumns=0; if(arr[i].cols.length>1){ //if event collides var conflictGroup=[]; //store here each column in the current event group var conflictingColumns=[]; //and here the column of each of the events in the group addConflictsToGroup(arr[i]); function addConflictsToGroup(a){ for(k=0;k<a.cols.length;k++){ if(conflictGroup.indexOf(a.cols[k])===-1){ //don't add same event twice to avoid infinite loop conflictGroup.push(a.cols[k]); conflictingColumns.push(arr[a.cols[k]].column); addConflictsToGroup(arr[a.cols[k]]); //check also the events this event conflicts with } } } arr[i].totalColumns=Math.max.apply(null, conflictingColumns); //set the greatest value as number of columns } arr[i].width=(600/(arr[i].totalColumns+1))+'px'; arr[i].left=(600/(arr[i].totalColumns+1)*arr[i].column)+'px'; } return arr; } function getEvents (eventArr) { eventArr.sort(function(a, b) { return a.start - b.start; }); eventArr = updateEvents(eventArr); appendEventDivs(eventArr); return eventArr; }; var timeline = ['9AM', '10AM', '11AM', '12PM', '1PM', '2PM', '3PM', '4PM', '5PM', '6PM', '7PM', '8PM']; var events = [{ id: 123, start: 60, end: 150 }, { id: 124, start: 540, end: 570 }, { id: 125, start: 555, end: 600 }, { id: 128, start: 585, end: 660 }, { id: 129, start: 590, end: 610 }]; function main(){ // draw calendar creatTimeline(timeline); todaysDate(); getEvents(events); //move the current time line after every 1 min; setInterval(makeCurrentTimeLine,1000); } main();
0d9e538913bb7f00f2910580881e45a5fd6767ce
[ "Markdown", "JavaScript" ]
2
Markdown
spratap124/meeting-calendar
13d44a632249abaa844df53e5a8387719a50da2b
5fe13288bdd8afb1873ffe29ceecf7da621c4461
refs/heads/master
<file_sep>import Leaflet from 'leaflet'; import mapMarkerImg from '../images/mapIcon/logo.png'; const mapIcon = Leaflet.icon({ iconUrl: mapMarkerImg, iconSize: [100, 100], iconAnchor: [50, 100], popupAnchor: [0, -75] }) export default mapIcon;
c7683a2a31e70359b6c711492177902840430dcc
[ "TypeScript" ]
1
TypeScript
SostenisVinicius/tcc
50b47abeeed22aeec165c3102195e8251371732a
654bcd0f186cfef45353ced1ea5a896ec454b595
refs/heads/master
<repo_name>KickButtowski80/i_t_view_tool<file_sep>/lib/i_t_view_tool.rb require "i_t_view_tool/version" require "i_t_view_tool/renderer" module ITViewTool end
2f8d0a9abfce112b375bf2d8d8f291c5512beb6e
[ "Ruby" ]
1
Ruby
KickButtowski80/i_t_view_tool
b9b7dee74c02edb73f63aac6ff3ac6692d6e626a
c2f84360e7edac72bf03f7011b7279edbf5449dd
refs/heads/master
<repo_name>alinilopes/LaFontaine<file_sep>/LaFontaine/assets/js/src/app.js (function ($) { var updateProgress = $('#UpdateProgress'); var prm = Sys.WebForms.PageRequestManager.getInstance(); //prm.add_initializeRequest(onRequestInitialize);//Criado antes do início do processamento da solicitação assíncrona. prm.add_beginRequest(onRequestBegin);//Executa antes do processamento do postbak //prm.add_pageLoaded(onRequestEnd); //Executa após o conteúdo da página ser atualizado .Executa Antes prm.add_endRequest(onRequestEnd);//Executa depois de um post-assíncrono terminar e o controle foi retornado ao navegador //Evento Document Ready $(document).on("ready", onDocumentReady); //Evento Document keydown $(document).on("keydown", onDocumentKeydown); function onDocumentKeydown(e) { //Se clicar em ESC if (e.keyCode == 27) { //Fecha todas as notify PNotify.removeAll(); //Fecha a modal se aberta var modalPopUp = $(".modalPopUp"); modalPopUp.each(function () { var modal = $(this); if (modal.is(":visible")) { var closeModal = modal.find(".close-modal"); if (closeModal.length > 0) { //console.log(closeModal.attr("data-id")); __doPostBack(closeModal.attr("data-id"), ''); } else { var parentId = modal.parent().attr("id"); $('#' + parentId).modal('hide'); } //closeModal.trigger("click"); //closeModal.click(); }; }) } } //function onRequestInitialize() { //} function onRequestBegin() { //Fecha todas as notify PNotify.removeAll(); } function onDocumentReady(e) { Main(); } function onRequestEnd() { //Método que habilita o botão clicado, ele pode estar fora do update panel var disabledElements = $("[clicked='true']"); if (disabledElements.length > 0) { disabledElements.each(function () { var element = $(this); element.prop('disabled', false); element.removeAttr("clicked"); }); } //-------------------------------------------------------------------------- Main(); } function Main() { var jDocument = $(document); var jWindow = $(window); var fileinput = $(".fileinput"); var datepicker = $('.datepicker'); var checkbox = $('.checkbox'); var radio = $('.radio'); //var tooltipTop = $(".tooltip-top"); var tooltipTop = $("[data-tooltip]"); var tabsScrollable = $(".tabs-scrollable"); //plugins instance holders var numberInput = $("input.number"); var floatingLabels = $("[rel='float-label']"); var tooltip = $("[data-toggle='tooltip']"); var drawer = $(".drawer"); var bgParallax = $(".bgParallax"); var startPointAnimation = $(".startPointAnimation"); var animatedElement = $(".animatedElement"); var animsition = $(".animsition"); var btnReturn = $(".btn-return"); var btnTop = $(".btn-scroll-top"); var cep = $('.cep'); var cpf = $(".cpf"); var cnpj = $(".cnpj"); var cpfCnpj = $(".cpf-cnpj"); var telefone = $(".telefone"); var data = $(".data"); var hora = $(".hora"); var dataHora = $(".data-hora"); var numberformatter = $("[data-formatter='numberformatter']"); var datagrid = $(".datagrid"); var html = $("html"); var navToggle = $('.nav-toggle'); var sidebarToggle = $('.sidebar-toggle'); var sidebar = $('.sidebar'); var $navigationDrawerToggle = $("[rel='drawer']"); var carousel = $('.carousel'); var animate = $("[data-animate]"); animate.css('visibility', 'hidden'); var animatePositionStart = $("[data-position-animate]"); var fixedSidebar = $('.fixed-sidebar'); var collapseSelector = '[data-toggle="collapse-next"]', colllapsibles = $('.sidebar .collapse').collapse({ toggle: false }), toggledClass = 'aside-collapsed', $body = $('body'), phone_mq = 768; // media querie var fixedMenu = GetCookie("fixedMenu") if (fixedMenu == null) fixedMenu = 0; var numberInputKeyPress = Rx.Observable.fromEvent(numberInput, "keypress"); var numberInputKeyPressSubscription = numberInputKeyPress.forEach( function (e) { var theEvent = e || window.event; var key = theEvent.keyCode || theEvent.which; key = String.fromCharCode(key); var regex = /[0-9]|\./; if (!regex.test(key)) { theEvent.returnValue = false; if (theEvent.preventDefault) theEvent.preventDefault(); } }, function (err) { throw err; }, function () { numberInputKeyPressSubscription.dispose(); } ); cep.mask("00000-000"); telefone.mask("(99) 99999-9999", { onKeyPress: function (val, e, field, options) { var mask = (val.replace(/\D/g, '').length == 11) ? '(00) 00000-0000' : '(00) 0000-00000'; $('.telefone').mask(mask, options); } }); hora.mask('00:00'); hora.blur(function () { var field = $(this)[0]; if (field.value == "") return true; field.value = field.value.toString().replace(" ", ":"); var obj; if (field.value.substring(0, 2) > 23) { alert(unescape("Hora invalida")); // SetaFocus(field.id); field.value = ' '; setTimeout(function () { SetaFocus(field.id); field.value = ''; }, 0); return false; } if (field.value.substring(3, 5) > 59) { alert(unescape("Minutos invalidos")); // SetaFocus(field.id); field.value = ' '; setTimeout(function () { SetaFocus(field.id); field.value = ''; }, 0); return false; } if (field.value.substring(2, 3) != ":") { alert(unescape("Separador invalido,Ex: 20:56")); //SetaFocus(field.id); field.value = ' '; setTimeout(function () { SetaFocus(field.id); field.value = ''; }, 0); return false; } // IMPEDE QUE SAIA DO CAMPO DE HORA SEM A FORMATAÇÃO CERTA if (field.value.length != 5) { alert(unescape("Formato%20de%20hora%20inv%E1lido.%20\nExemplo:%2020:56")); //SetaFocus(field.id); field.value = ' '; setTimeout(function () { SetaFocus(field.id); field.value = ''; }, 0); return false; } }); data.mask('00/00/0000'); dataHora.mask("00/00/0000 00:00"); cpfCnpj.mask('00.000.000/0000-00', { onKeyPress: function (val, e, field, options) { var mask = (val.replace(/[^\d]+/g, "").length > 11) ? '00.000.000/0000-00' : '000.000.000-000'; var lbl = (val.replace(/[^\d]+/g, "").length > 11) ? 'CNPJ' : 'CPF'; $('.cpf-cnpj').mask(mask, options); $('.lbl-cpf-cnpj').html(lbl); } }); cpf.mask('000.000.000-00'); cnpj.mask('00.000.000/0000-00'); numberformatter.blur(function () { var field = $(this); if (field.val() != "") { var data_focus = field.attr('data_focus'); var _casasDecimais = 0; if (data_focus != null) { var _data = data_focus.split('-'); _casasDecimais = _data[4]; } var _format = "#,##0."; var TotalCasas = 8; if (_casasDecimais == 1) { _format = _format + "0" TotalCasas = TotalCasas - 1; } else if (_casasDecimais == 2) { _format = _format + "00" TotalCasas = TotalCasas - 1; } else if (_casasDecimais > 2) { _format = _format + "00"; TotalCasas = TotalCasas - 2; } for (var i = 0; i < TotalCasas; i++) { _format = _format + "#"; } field.parseNumber({ format: _format, locale: "br" }); field.formatNumber({ format: _format, locale: "br" }); } }); floatingLabels.floatlabel({ labelClass: "label-color" }); tooltip.tooltip({ container: 'body' }); animsition.animsition({ inClass: 'fade-in-left', outClass: 'fade-out-left', inDuration: 1500, outDuration: 800, linkElement: '.animsition-link', loading: true, loadingParentElement: 'body', //animsition wrapper element loadingClass: 'animsition-loading', loadingInner: '', // e.g '<img src="loading.svg" />' timeout: true, timeoutCountdown: 10, onLoadEvent: true, browser: ['animation-duration', '-webkit-animation-duration'], overlay: false, overlayClass: 'animsition-overlay-slide', overlayParentElement: 'body', transition: function (url) { window.location.href = url; } }); btnTop.on("click", function (e) { e.preventDefault(); var body = $("html, body"); body.stop().animate({ scrollTop: 0 }, '800', 'swing'); }); btnReturn.on("click", function (e) { e.preventDefault(); console.log(window.history); window.history.back(); }); fixedSidebar.on("click", function (e) { e.preventDefault(); var date = new Date(); date.setTime(date.getTime() + (1000 * 24 * 60 * 60 * 1000)) if (fixedMenu == 0) { fixedMenu = 1; var $this = $(this); navToggle.off("mouseenter"); sidebar.off("mouseleave"); notify("", "Menu fixo!", "success"); } else { fixedMenu = 0; initFixedMenu(); notify("", "Menu dinâmico!", "success"); } if (fixedMenu == 1) { $body.addClass(toggledClass) } else { $body.removeClass(toggledClass) } SetCookie("fixedMenu", fixedMenu, date) }); sidebarToggle.off("click").on("click", function (e) { if (sidebar.is(":visible") == true) { sidebar.velocity({ left: '-255px' }, { duration: 300, display: 'none' }); } else { sidebar.css('display', 'block').velocity({ left: '0px' }, { duration: 300, display: 'block' }); } }); initFixedMenu(); function initFixedMenu() { if (fixedMenu == 0) { navToggle.on("mouseenter", function (e) { sidebar.css('display', 'block').velocity({ left: '0px' }, { duration: 300, display: 'block' }); }); sidebar.on("mouseleave", function (e) { /* Solution - Ocorria de executar o mouseleave ao clicar nos itens do menu, o menu era fechado, sem o mouse ter saído da div. Bug no Chrome*/ if (e.relatedTarget == null) return; /************/ sidebar.velocity({ left: '-255px', }, { duration: 300, display: "none" }); }); } } jDocument .on('click', collapseSelector, function (e) { e.preventDefault(); //if ($(window).width() > phone_mq && // $body.hasClass(toggledClass)) return; // ...then open just the one we want var $target = $(this).siblings('ul'); var $targetParent = $target.parent().parent(); // Try to close all of the collapse areas first if ($targetParent.has("ul").hasClass("in") == true) { colllapsibles.not($targetParent).collapse('hide'); } else { colllapsibles.collapse('hide'); } $target.collapse('show'); }); jDocument.on('click.card', '.card', function (e) { //if ($(this).find('> .card-reveal').length) { if ($(e.target).is($('.card-reveal .card-title')) || $(e.target).is($('.card-reveal .card-title i'))) { // Make Reveal animate down and display none $(this).find('.card-reveal').velocity( { translateY: 0 }, { duration: 225, queue: false, easing: 'easeInOutQuad', complete: function () { $(this).css({ display: 'none' }); } } ); } else if ($(e.target).is($('.card .activator')) || $(e.target).is($('.card .activator i'))) { $(e.target).closest('.card').css('overflow', 'hidden'); $(this).find('.card-reveal').css({ display: 'block' }).velocity("stop", false).velocity({ translateY: '-100%' }, { duration: 300, queue: false, easing: 'easeInOutQuad' }); } $('.card-reveal').closest('.card').css('overflow', 'hidden'); }); // jQuery reverse $.fn.reverse = [].reverse; fileinput.fileinput({ overwriteInitial: true, showUpload: false, showPreview: false, browseLabel: 'Selecionar Arquivo', //browseIcon: '<i class="fa fa-file-o"></i>&nbsp;', browseClass: 'btn btn-warning', removeLabel: '', removeIcon: '<i class="glyphicon glyphicon-remove"></i>' }); fileinput.on('change', function (event) { $(".fileinput-charge").removeClass('hidden') }); fileinput.on('fileclear', function (event) { $(".fileinput-charge").addClass('hidden') }); datepicker.r9datepicker(); checkbox.r9checkbox(); radio.r9radiobuttonlist(); tooltipTop.TooltipTop(); tabsScrollable.r9tabsscrollable(); padrao(); carousel.carousel({ pause: null }); //Evento Window Scroll jWindow.off("scroll").on("scroll", onWindowScroll); function onWindowScroll(e) { bgParallax.each(function () { var $obj = $(this); var yPos = -($(window).scrollTop() / $obj.attr('data-speed')); var bgpos = '50% ' + yPos + 'px'; $obj.css('background-position', bgpos); }); animate.each(function () { var $obj = $(this); var offset = $obj.offset(); var scroll_start = $(window).scrollTop(); animatePositionStart = $obj.attr("data-position-animate") if (scroll_start > offset.top - (window.screen.availHeight * (animatePositionStart / 10))) { var animationName = $obj.attr("data-animate") $obj.addClass("animated " + animationName); $obj.css('visibility', 'visible'); } }); btnScroll(); }; btnScroll(); function btnScroll() { var scrollDistance = $(this).scrollTop(); if (scrollDistance > 180) { btnTop.show(); } else { btnTop.hide(); } } function onWindowResize(e) { initNavigation(); }; $(".toggle-navigation i").off("click").on("click", function (e) { e.preventDefault(); $icon = $(this); if ($icon.parent().parent().has("ul")) e.preventDefault(); if ($icon.parent().hasClass("active")) { // hide $icon.parent().removeClass("active"); $icon.parent().removeClass("active").parent().removeClass("active").removeClass("clicked"); $icon.parent().next("ul").slideUp(350, function () { }); //$icon.html("expand_more"); $icon.removeClass("fa fa-close") $icon.addClass("fa fa-chevron-down") } else { // show $icon.parent().next("ul").slideDown(350); $icon.parent().addClass("active").parent().addClass("clicked"); //$icon.html("close"); $icon.removeClass("fa fa-chevron-down") $icon.addClass("fa fa-close") } return false; }); function initNavigation() { var body = $("body"); } initNavigation(); datagrid.DataGrid(); /* Nice-Scroll*/ html.niceScroll({ scrollspeed: 100, //scrolling speed mousescrollstep: 38, //scrolling speed with mouse wheel (pixel) cursorwidth: 5, //largura do cursor cursorborder: 0, //borda do cursor cursorcolor: '#333', //cor do cursor cursorborderradius: 0, //border radius in pixel for cursor autohidemode: true, // how hide the scrollbar works, possible values: //true (hide when no scrolling), cursor (only cursor hidden), false (do not hide), leave (hide only if pointer leaves content), hidden (hide always), scroll (show only on scroll) zindex: 999999999, horizrailenabled: false, //nicescroll can manage horizontal scroll }); } })(jQuery); <file_sep>/LaFontaine/gulpfile.js var gulp = require("gulp"), gutil = require("gulp-util"), concat = require("gulp-concat"), sass = require("gulp-sass"), minifyCss = require("gulp-minify-css"), rename = require("gulp-rename"), uglify = require("gulp-uglify"), imagemin = require('gulp-imagemin'), cache = require('gulp-cache'), del = require('del'), sourcemaps = require("gulp-sourcemaps"), jsPath = "./assets/js/", scripts = { vendor: { jquery: jsPath + "vendor/jquery-3.0.0.min.js", bootstrap: jsPath + "vendor/bootstrap.min.js", }, src: { globals: jsPath + "src/globals.js", app: jsPath + "src/app.js", }, getScripts: function () { var scriptsArray = []; for (var key in scripts) { if (!scripts.hasOwnProperty(key)) continue; var obj = scripts[key]; for (var script in obj) { if (!obj.hasOwnProperty(script)) continue; scriptsArray.push(obj[script]); } } return scriptsArray; } }, scriptsJquery = { vendor: { jquery: jsPath + "vendor/jquery.min.js", }, getScripts: function () { var scriptsArray = []; for (var key in scriptsJquery) { if (!scriptsJquery.hasOwnProperty(key)) continue; var obj = scriptsJquery[key]; for (var script in obj) { if (!obj.hasOwnProperty(script)) continue; scriptsArray.push(obj[script]); } } return scriptsArray; } }; gulp.task("default", ['build']); gulp.task("build", ['clean:dist', 'sass', 'js']); gulp.task("sass", function (done) { del.sync('./assets/dist/css'); gulp.src("./assets/scss/style.scss") .pipe(sass()) .on("error", sass.logError) .pipe(gulp.dest("./assets/dist/css/")) .pipe(minifyCss({ keepSpecialComments: 0 })) .pipe(rename({ extname: ".min.css" })) .pipe(gulp.dest("./assets/dist/css/")) .on("end", done) }); gulp.task('js', function () { del.sync('./assets/dist/js'); return gulp.src(scripts.getScripts()) .pipe(sourcemaps.init()) .pipe(concat('scripts.js')) .pipe(gulp.dest('./assets/dist/js/')) .pipe(uglify()) .pipe(rename({ extname: ".min.js" })) .pipe(sourcemaps.write()) .pipe(gulp.dest('./assets/dist/js/')); }); gulp.task('clean:dist', function () { return del.sync('./assets/dist'); }); gulp.task('clean:cache', function (callback) { return cache.clearAll(callback) })<file_sep>/LaFontaine/Home.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace LaFontaine { public partial class Home : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void lnkEmpresas_Click(object sender, EventArgs e) { Response.Redirect("~/ERP360.aspx"); } protected void lnkAgronegocio_Click(object sender, EventArgs e) { Response.Redirect("~/ERPAgro.aspx"); } protected void lnkMobile_Click(object sender, EventArgs e) { Response.Redirect("~/ERP360.aspx"); } protected void lnkFiscal_Click(object sender, EventArgs e) { Response.Redirect("~/1Clic.aspx"); } protected void lnkCRM_Click(object sender, EventArgs e) { Response.Redirect("~/ERP360.aspx"); } protected void lnkCloudComputing_Click(object sender, EventArgs e) { Response.Redirect("~/ERP360.aspx"); } protected void lnkECommerce_Click(object sender, EventArgs e) { Response.Redirect("~/ECommerce.aspx"); } protected void lnkCertificado_Click(object sender, EventArgs e) { Response.Redirect("~/Certificacao.aspx"); } } }<file_sep>/LaFontaine/Global.asax.cs using System; using System.Web; using System.Web.Routing; namespace LaFontaine { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { // Code that runs on application startup // RegisterRoutes(RouteTable.Routes); } public static void RegisterRoutes(RouteCollection route) { route.Ignore("{resource}.axd/{*pathInfo}"); route.RouteExistingFiles = true; route.MapPageRoute("", "", "~/Home.aspx"); route.MapPageRoute("Home", "Home", "~/Home.aspx"); route.MapPageRoute("ListagemProdutos", "ListagemProdutos", "~/ListagemProdutos.aspx"); route.MapPageRoute("PaginaNaoEncontrada", "PaginaNaoEncontrada", "~/Erro/PaginaNaoEncontrada.aspx"); } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }<file_sep>/README.md # LaFontaine E-Commerce desenvolvido na disciplina de Interfaces Web da Pós Graduação em Desenvolvimento Web e Mobile da UPF <file_sep>/LaFontaine/MasterPage.Master.cs using System; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Collections.Generic; namespace LaFontaine { public partial class MasterPage : System.Web.UI.MasterPage { protected void Page_Init(object sender, EventArgs e) { } protected void master_Page_PreLoad(object sender, EventArgs e) { } protected void Page_Load(object sender, EventArgs e) { } private void ValorPadrao() { } } }
950ce9a30e1d85036f9e878d21e8825a7269a250
[ "JavaScript", "C#", "Markdown" ]
6
JavaScript
alinilopes/LaFontaine
2f281ab49622535aaf3ba61e5cb1a46c591d9189
f306728b3901cec147d39abf32ef2112adc8832d
refs/heads/master
<file_sep>from IPython.parallel.apps.winhpcjob import * import tempfile import pickle # just execute this file in python to create the xml file for the cluster (in ./analysis/cluster), which one then can manually submit through the HPC Job Manager def cluster_setup(i, python_path, home, t, work_dir, tempdir): t.work_directory = work_dir #t.std_out_file_path = r'cluster\log\cluster_out%d.txt' % i #t.std_err_file_path = r'cluster\log\cluster_err%d.txt' % i t.std_out_file_path = tempdir + r'\out%d.txt' % i t.std_err_file_path = tempdir + r'\err%d.txt' % i #t.std_out_file_path = r'out%d.txt' % i #t.std_err_file_path = r'err%d.txt' % i #if not os.path.exists(t.std_out_file_path): os.makedirs(t.std_out_file_path) #if not os.path.exists(t.std_err_file_path): os.makedirs(t.std_err_file_path) t.environment_variables['PYTHONPATH'] = python_path t.environment_variables['HOME'] = home print "cluster python_path=%s" % python_path def create(user, models, orders, degrees, GP_likelihoods, adaboost_learning_rates=None, adaboost_num_estimators=None, adaboost_max_depths=None, adaboost_CV=False, exp_name=None, learn_options=None): job = WinHPCJob() job.job_name = 'CRISPR.%s' % exp_name if user == 'fusi': job.username = 'REDMOND\\fusi' elif user =='jennl': job.username = 'REDMOND\\jennl' else: raise Exception("ensure you are using the right username, then add a clause here") job.priority = 'Normal' job.min_nodes = 1 job.max_nodes = 5000 job.min_cores = 1 job.max_cores = 5000 if job.username == 'REDMOND\\fusi': remote_dir = r'\\fusi1\crispr2\analysis\cluster\results' work_dir = r"\\FUSI1\crispr2\analysis" #working dir wherever you put it, even off the cluster python = r'\\fusi1\crispr\python.exe' #this will not get copied, but used in-place python_path = r'\\fusi1\crispr\lib\site-packages\;\\fusi1\crispr2\analysis' home = r"\\fusi1\CLUSTER_HOME" elif job.username == 'REDMOND\\jennl': remote_dir = r"\\GCR\Scratch\RR1\jennl\CRISPR" work_dir = r'\\jennl2\D$\Source\CRISPR\analysis' python = r'\\fusi1\crispr\python.exe' python_path = r'\\fusi1\crispr\lib\site-packages\;\\jennl2\D$\Source\CRISPR\analysis' home = r"\\fusi1\CLUSTER_HOME" # print "workdir=%s" % work_dir # print "python=%s" % python # print "python_path=%s" % python_path # generate random dir in results directory tempdir = tempfile.mkdtemp(prefix='cluster_experiment_', dir=remote_dir) print "Created directory: %s" % str(tempdir) # dump learn_options with open(tempdir+'/learn_options.pickle', 'wb') as f: pickle.dump(learn_options, f) i = 0 for model in models: if model in ['L1', 'L2', 'linreg', 'doench', 'logregL1', 'RandomForest', 'SVC']: for order in orders: t = WinHPCTask() t.task_name = 'CRISPR_task' t.command_line = python + ' cli_run_model.py %s --order %d --output-dir %s --exp-name %s' % (model, order, tempdir, exp_name) cluster_setup(i, python_path, home, t, work_dir, tempdir) t.min_nodes = 1 # t.min_cores = 1 # t.max_cores = 100 job.add_task(t) i += 1 elif model in ['AdaBoost']: for order in orders: for learning_rate in adaboost_learning_rates: for num_estimators in adaboost_num_estimators: for max_depth in adaboost_max_depths: t = WinHPCTask() t.task_name = 'CRISPR_task' t.command_line = python + ' cli_run_model.py %s --order %d --output-dir %s --adaboost-learning-rate %f --adaboost-num-estimators %d --adaboost-max-depth %d --exp-name %s' % (model, order, tempdir, learning_rate, num_estimators, max_depth, exp_name) if adaboost_CV: t.command_line += " --adaboost-CV" cluster_setup(i, python_path, home, t, work_dir, tempdir) t.min_nodes = 1 job.add_task(t) i += 1 elif model in ['GP']: for likelihood in GP_likelihoods: for degree in degrees: t = WinHPCTask() t.task_name = 'CRISPR_task' t.command_line = python + ' cli_run_model.py %s --order 1 --weighted-degree %s --output-dir %s --likelihood %s --exp-name %s' % (model, degree, tempdir, likelihood, exp_name) cluster_setup(i, python_path, home, t, work_dir, tempdir) t.min_nodes = 1 # t.min_cores = 1 # t.max_cores = 100 job.add_task(t) i += 1 else: t = WinHPCTask() t.task_name = 'CRISPR_task' t.command_line = python + ' cli_run_model.py %s --output-dir %s' % (model, tempdir) cluster_setup(i, python_path, home, t, work_dir, tempdir) t.min_cores = 1 t.max_cores = 1 job.add_task(t) i += 1 clust_filename = 'cluster_job.xml' job.write(tempdir+'/'+clust_filename) return tempdir, job.username, clust_filename <file_sep>import azimuth import azimuth.model_comparison import numpy as np import unittest import pandas import os dirname, filename = os.path.split(os.path.abspath(__file__)) class SavedModelTests(unittest.TestCase): """ This unit test checks that the predictions for 1000 guides match the predictions we expected in Nov 2016. This unit test can fail due to randomness in the model (e.g. random seed, feature reordering). """ def test_predictions_nopos(self): df = pandas.read_csv(os.path.join(dirname, '1000guides.csv'), index_col=0) predictions = azimuth.model_comparison.predict(np.array(df['guide'].values), None, None) self.assertTrue(np.allclose(predictions, df['truth nopos'].values, atol=1e-3)) def test_predictions_pos(self): df = pandas.read_csv(os.path.join(dirname, '1000guides.csv'), index_col=0) predictions = azimuth.model_comparison.predict(np.array(df['guide'].values), np.array(df['AA cut'].values), np.array(df['Percent peptide'].values)) self.assertTrue(np.allclose(predictions, df['truth pos'].values, atol=1e-3)) if __name__ == '__main__': unittest.main()
cfb53350611955c8cd608991531fda108ab79065
[ "Python" ]
2
Python
neelarka/Azimuth
b7902aa49e0a5e394ede442062ff0eb56468f9ad
3442fe37a98ff9689a1552241459a26f7f9c5f6b
refs/heads/master
<file_sep>package com.actitime.qa.testcases; import java.io.IOException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.actitime.qa.base.TestBase; import com.actitime.qa.pages.LoginPage; import com.actitime.qa.pages.TimeTrackPage; import com.actitime.qa.pages.UsersPage; import com.actitime.qa.util.TestUtil; public class UsersPageTest extends TestBase { LoginPage loginPage; TimeTrackPage timeTrackPage; UsersPage usersPage; public UsersPageTest() { super(); } @BeforeMethod public void setUp() { initialization(); loginPage = new LoginPage(); timeTrackPage = loginPage.login(prop.getProperty("username"), prop.getProperty("password")); usersPage = timeTrackPage.gotoUsersPage(); } @Test public void createNewUserTest() throws InvalidFormatException, IOException { usersPage.clickNewUser(); //enter details int noOfUsers = TestUtil.noOfValues("Sheet1"); for(int row=1; row<=noOfUsers; row++) { String first = TestUtil.readDataFromExcel("Sheet1", row, 0); usersPage.enterFirstName(first); String last = TestUtil.readDataFromExcel("Sheet1", row, 1); usersPage.enterLastName(last); String email = TestUtil.readDataFromExcel("Sheet1", row, 2); usersPage.enteremail(email); String department = TestUtil.readDataFromExcel("Sheet1", row, 3); usersPage.selectDept(department); //usersPage.saveAndSendInvitation(); //usersPage.inviteOneMoreUser(); } //usersPage.closeAddUser(); } //@AfterMethod }
cc4622a7cb58762bad7e8daa44360ab7d4f27144
[ "Java" ]
1
Java
ushapmgithub/ActiTime_2020
22dfc99c2b5c6cc2f9bd4fffc919113c9b462b3c
ca4f2c65a4efb9266e04e3d98a30266f1a46e1bf
refs/heads/master
<repo_name>kerimtumkaya/2018-Data-Science-Bowl<file_sep>/aug/_augment2.py import os import sys import argparse import tqdm import uuid import cv2 # To read and manipulate images import numpy as np import pandas as pd import tensorflow as tf from utils.oper_utils2 \ import normalize_imgs, trsf_proba_to_binary, \ normalize_masks, imgs_to_grayscale, invert_imgs from utils.image_utils import read_image, read_mask from tqdm import tqdm RANDOM_SEED = 54989 FLAGS = None def read_images_and_gt_masks () : train_ids = next(os.walk(FLAGS.train_dir))[1] images = [] masks = [] for n, id_ in tqdm(enumerate(train_ids), total=len(train_ids)): path = FLAGS.train_dir + id_ image_ = read_image(path + '/images/' + id_ + '.png', target_size=(FLAGS.img_size, FLAGS.img_size)) # mask_ = read_mask(path + '/masks/', # target_size=(FLAGS.img_size, FLAGS.img_size)) mask_ = read_image(path + '/gt_mask/' + id_ + '.png', color_mode=cv2.IMREAD_GRAYSCALE, target_size=(FLAGS.img_size, FLAGS.img_size)) images.append(image_) masks.append(tf.expand_dims(mask_, -1)) images = np.array(images) masks = np.array(masks) return images, masks # def read_test () : # test_ids = next(os.walk(FLAGS.test_dir))[1] # x_test = [] # # for n, id_ in tqdm(enumerate(test_ids), total=len(test_ids)): # path = FLAGS.test_dir + id_ # image_ = read_image(path + '/images/' + id_ + '.png', # target_size=(FLAGS.img_size, FLAGS.img_size)) # # x_test.append(image_) # # x_test = np.array(x_test) # # return x_test def normalize(data, type_=1): """Normalize data.""" if type_ == 0: # Convert pixel values from [0:255] to [0:1] by global factor data = data.astype(np.float32) / data.max() if type_ == 1: # Convert pixel values from [0:255] to [0:1] by local factor div = data.max(axis=tuple(np.arange(1, len(data.shape))), keepdims=True) div[div < 0.01 * data.mean()] = 1. # protect against too small pixel intensities data = data.astype(np.float32) / div if type_ == 2: # Standardisation of each image data = data.astype(np.float32) / data.max() mean = data.mean(axis=tuple(np.arange(1, len(data.shape))), keepdims=True) std = data.std(axis=tuple(np.arange(1, len(data.shape))), keepdims=True) data = (data - mean) / std return data def normalize_imgs(data): """Normalize images.""" return normalize(data, type_=1) def invert_imgs(imgs, cutoff=.5): '''Invert image if mean value is greater than cutoff.''' imgs = np.array(list(map(lambda x: 1. - x if np.mean(x) > cutoff else x, imgs))) return normalize_imgs(imgs) # return imgs def imgs_to_grayscale(imgs): # imgs = tf.reshape(imgs, [-1, 256, 256, 3]) '''Transform RGB images into grayscale spectrum.''' if imgs.shape[3] == 3: # imgs = normalize_imgs(np.expand_dims(np.mean(imgs, axis=3), axis=3)) imgs = np.expand_dims(np.mean(imgs, axis=3), axis=3) return imgs # Normalize all images and masks. There is the possibility to transform images # into the grayscale sepctrum and to invert images which have a very # light background. def preprocess_raw_data(x_train, grayscale=False, invert=False): """Preprocessing of images and masks.""" # Normalize images and masks # x_train = normalize_imgs(x_train) # print('Images normalized.') if grayscale: # Remove color and transform images into grayscale spectrum. x_train = imgs_to_grayscale(x_train) print('Images transformed into grayscale spectrum.') if invert: # Invert images, such that each image has a dark background. x_train = invert_imgs(x_train) print('Images inverted to remove light backgrounds.') return x_train def write_image(images, masks): train_ids = next(os.walk(FLAGS.train_dir))[1] for n, id_ in tqdm(enumerate(train_ids), total=len(train_ids)): image_ = images[n, :, :, :] mask_ = masks[n, :, :, :] randomString = str(uuid.uuid4()).replace("-", "") new_id = FLAGS.aug_prefix + id_[:10] + randomString os.mkdir(FLAGS.train_dir + new_id) os.mkdir(FLAGS.train_dir + new_id + '/images/') os.mkdir(FLAGS.train_dir + new_id + '/gt_mask/') cv2.imwrite(FLAGS.train_dir + new_id + '/images/' + new_id + '.png', image_) cv2.imwrite(FLAGS.train_dir + new_id + '/gt_mask/' + new_id + '.png', mask_) def write_image2(images, masks): train_ids = next(os.walk(FLAGS.train_dir))[1] for n, id_ in tqdm(enumerate(train_ids), total=len(train_ids)): image_ = images[n, :, :, :] mask_ = masks[n, :, :, :] randomString = str(uuid.uuid4()).replace("-", "") new_id = FLAGS.aug_prefix + id_[:10] + randomString os.mkdir(FLAGS.train_dir + new_id) os.mkdir(FLAGS.train_dir + new_id + '/images/') os.mkdir(FLAGS.train_dir + new_id + '/gt_mask/') cv2.imwrite(FLAGS.train_dir + new_id + '/images/' + new_id + '.png', image_) cv2.imwrite(FLAGS.train_dir + new_id + '/gt_mask/' + new_id + '.png', mask_) def image_augmentation(image, seed): """Returns (maybe) augmented images` (1) Random flip (left <--> right) (2) Random flip (up <--> down) (3) Random brightness (4) Random hue Args: image (3-D Tensor): Image tensor of (H, W, C) mask (3-D Tensor): Mask image tensor of (H, W, 1) Returns: image: Maybe augmented image (same shape as input `image`) mask: Maybe augmented mask (same shape as input `mask`) """ maybe_flipped = tf.image.random_flip_left_right(image, seed=seed) maybe_flipped = tf.image.random_flip_up_down(image, seed=seed) if image.shape[2] == 3: image = tf.image.random_brightness(image, 0.7, seed=seed) image = tf.image.random_hue(image, 0.3, seed=seed) return image # def make_aug_dir(): # randomString = str(uuid.uuid4()).replace("-", "") # _new = FLAGS.aug_prefix + randomString # # return _new def main(_): images, masks = read_images_and_gt_masks() # images = preprocess_raw_data(images, grayscale=True, invert=False) image_list = [] mask_list = [] for idx, img in enumerate(images): seed = np.random.randint(RANDOM_SEED) _image = image_augmentation(images[idx], seed) _mask = image_augmentation(masks[idx], seed) image_list.append(_image) mask_list.append(_mask) images = np.array(image_list) masks = np.array(mask_list) write_image(images, masks) # x_test = read_test() # x_test = imgs_to_grayscale(x_test) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--train_dir', default='../../../dl_data/nucleus/stage1_train/', type=str, help="Train Data directory") # parser.add_argument( # '--aug_dir', # default='../../../dl_data/nucleus/aug_stage1_train', # type=str, # help="Augmentation train Data directory") parser.add_argument( '--test_dir', default='../../../dl_data/nucleus/stage1_test', type=str, help="Test data directory") parser.add_argument( '--img_size', type=int, default=256, help="Image height and width") parser.add_argument( '--aug_prefix', default='_aug_', type=str, help="prefix name of augmentation") parser.add_argument( '--aug_count', type=int, default=2, help="Count of augmentation") FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
0eddf1abf5606cd96d869bef1585aac64ca60572
[ "Python" ]
1
Python
kerimtumkaya/2018-Data-Science-Bowl
09ea69c702f1fb405c3995cba1889b1306143831
4e9cac5adce0cb7e2fef0ecb568cf4ce6f3d942f
refs/heads/master
<file_sep>using System.Collections.Generic; namespace ML.Lib.Classification { public class ClassifiedObject<T> { public string Classification { get; set; } //Classification of this object public List<T> Properties { get; set; } //all properties of this object public string Label { get; set; } //A human readable ID of this particular object public ClassifiedObject() { Properties = new List<T>(); } } }<file_sep>using System.Collections.Generic; namespace softsets { public class IdentifiedObject { public List<string> properties = new List<string>(); public string id; } }<file_sep>using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace softsets { class Program { static void Main(string[] args) { List<IdentifiedObject> objects = new List<IdentifiedObject>(); string[] data = File.ReadAllLines(args[0]); List<string> properties = data[0].Split(',').ToList(); for(int i = 1; i < data.Length; i++) { string[] tokens = data[i].Split(" "); IdentifiedObject obj = new IdentifiedObject(); objects.Add(obj); obj.id = tokens[0]; for(int j = 1; j < tokens.Length; j++) { if(tokens[j] == "1") { obj.properties.Add(properties[j-1]); } } /* Console.Write("Loaded: " + obj.id + " that is: "); foreach(string p in obj.properties) { Console.Write(p + " "); } Console.WriteLine();*/ } List<ClassifierInfo> parameters = new List<ClassifierInfo>(); data = File.ReadAllLines(args[1]); foreach(string d in data) { string[] tokens = d.Split(','); ClassifierInfo i = new ClassifierInfo(tokens[0], Convert.ToDouble(tokens[1])); parameters.Add(i); } List<ClassifierInfo> results = Classifier.Classify(objects, parameters); results.ForEach(x=> Console.WriteLine(x.label + " w:" + x.match)); Console.WriteLine("Best match: " + results.OrderByDescending(x=>x.match).ToList()[0].label); } } } <file_sep>using System; using System.Collections.Generic; namespace NeuralNetwork { public class HighestHitTest : ITestStrategy { private Network network; private double minDelta; public double MinDelta { get { return minDelta; } set { minDelta = value; } } private double recentPercentage; public HighestHitTest(Network network, double minDelta = 0.001) { this.network = network; this.minDelta = minDelta; } public double Test(double[][] inputs, double[][] expectedOutputs) { double hitPercentage = 0; int hits = 0; List<double> outputs = new List<double>(); for (int i = 0; i < inputs.Length; i++) { network.PushInputValues(inputs[i]); outputs = network.GetOutput(); if (outputs.MaxAt() == expectedOutputs[i].MaxAt()) hits++; } hitPercentage = (double)hits / (double)inputs.Length; recentPercentage = hitPercentage; Console.WriteLine($"Hit percentage : {Math.Round(hitPercentage * 100.0, 2)}%"); return hitPercentage; } public bool CheckHalt() { return recentPercentage < minDelta; } } }<file_sep>using System.Collections.Generic; namespace ML.Lib.Neuron { public class InputNeuron : INeuron { public List<IConnection> OutcomingConnections { get; set; } //Unused values public List<IConnection> IncomingConnections { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } public double PreviousPartialDerivate { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } public double LastOutputValue { get {return OutputtingValue;} set {throw new System.Exception();}} public double LastInputValue { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } public IActivationFunction ActivationFunction { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } //Set this value to input values public double OutputtingValue { get; set; } public InputNeuron() { OutcomingConnections = new List<IConnection>(); } public double CalculateOutput() { return OutputtingValue; } public void PushToOutput(double d) { foreach (IConnection output in OutcomingConnections) { output.Output = d; } } } }<file_sep>using ML.Lib.Classification; using ML.Lib; using System.Collections.Generic; using System; using System.Linq; namespace KNN { public class Classifier { //Original data double[][] dataArr; public Func<double[], double[], double> DistanceMethod; public Classifier() { DistanceMethod = Distance; } //data object input to be evaluated //k - how many closest neighbours will be taken into consideration public void Classify(ClassifiedObject<double> input, List<ClassifiedObject<double>> data, int k) { //Get amount of minimum dimensions int dim = data.Max(x => x.Properties.Count); if (dim < input.Properties.Count) dim = input.Properties.Count; //create data array double[][] dataArr = new double[data.Count + 1][]; for (int i = 0; i < dataArr.Length; i++) { dataArr[i] = new double[dim]; } //fill data array for (int i = 0; i < data.Count; i++) { for (int j = 0; j < data[i].Properties.Count; j++) { dataArr[i][j] = data[i].Properties[j]; } } //put last element as an input for (int i = 0; i < input.Properties.Count; i++) { dataArr.Last()[i] = input.Properties[i]; } //Normalize data to 0-1 range for (int i = 0; i < dataArr[0].Length; i++) { double[] col = dataArr.GetColumn(i); Normalizator.Normalize(col, 0.0, 1.0); dataArr.SetColumn(col, i); } double[] distances = new double[data.Count]; //Calculate distances for (int i = 0; i < distances.Length; i++) { distances[i] = DistanceMethod(dataArr.Last(), dataArr[i]); } int[] minimalIndexes = FindKMin(distances, k); Dictionary<string, int> classesHistogram = new Dictionary<string, int>(); //classification histogram //Gather classes foreach (int min in minimalIndexes) { if (!classesHistogram.ContainsKey(data[min].Classification)) { classesHistogram.Add(data[min].Classification, 1); } else { classesHistogram[data[min].Classification]++; } } //Find maximum value and get key input.Classification = classesHistogram.Aggregate((x, y) => x.Value > y.Value ? x : y).Key; } //returns indexes of k closest neighbours int[] FindKMin(double[] distances, int k) { double[] min = new double[k]; int[] minIndex = new int[k]; for (int i = 0; i < k; i++) { minIndex[i] = 0; min[i] = double.PositiveInfinity; } for (int i = 0; i < distances.Length; i++) { for (int j = 0; j < k; j++) { if (min[j] > distances[i]) { min[j] = distances[i]; minIndex[j] = i; break; } } } return minIndex; } double Distance(double[] a, double[] b) { if (a.Length != b.Length) throw new ArgumentException("Arrays are not of the same length"); double distance = 0.0; for (int dim = 0; dim < a.Length; dim++) { distance += Math.Pow(a[dim] - b[dim], 2); } distance = Math.Sqrt(distance); return distance; } } }<file_sep>using System.Collections.Generic; namespace BasicClassifier { public class Classifier { public static List<ClassifierInfo> Classify(List<IdentifiedObject> input, List<ClassifierInfo> parameters) { List<ClassifierInfo> result = new List<ClassifierInfo>(); foreach (IdentifiedObject obj in input) { ClassifierInfo r = new ClassifierInfo(); r.label = obj.id; foreach (ClassifierInfo i in parameters) { if (obj.properties.Exists(x=> x == i.label)) { r.match += i.match; } } result.Add(r); } return result; } } public struct ClassifierInfo { public double match; public string label; public ClassifierInfo(string _label, double _match) { match = _match; label = _label; } } }<file_sep> namespace ML.Lib.Fuzzy { public class SugenoExpectedValue { public string label; public double value; } }<file_sep>using System; namespace ML.Lib.Fuzzy { //Example Fuzzifier that uses gaussian function public class GaussianFuzzifier : IFuzzifier { public string Label { get; set; } private double m, sigma; public GaussianFuzzifier(double m, double sigma, string Label) { this.m = m; this.sigma = sigma; this.Label = Label; } public double Fuzzify(double x) { return Math.Exp(-((x - m) * (x - m)) / (2.0 * sigma * sigma)); } } }<file_sep>using System; namespace ML.Lib.Fuzzy { public class TrapezoidFuzzifier : IFuzzifier { public string Label { get; set; } private double a, b, c, d; public TrapezoidFuzzifier(double a, double b, double c, double d, string Label) { this.a = a; this.b = b; this.c = c; this.d = d; this.Label = Label; } public double Fuzzify(double x) { if (x <= a) return 0; if (x > a && x <= b) return (x - a) / (b - a); if (x > b && x < c) return 1; if (x >= c && x <= d) return (d - x) / (d - c); return 0; } } }<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting; using ML.Lib.Image; using System; using System.IO; using System.Diagnostics; using System.Drawing; namespace ML.Lib.Tests { [Ignore] [TestClass] public class FilterTests { [TestMethod] public void GaussianFilterCtorTest() { GaussianFilter filter = new GaussianFilter(Math.Sqrt(2), 5, 5); } [TestMethod] public void GaussianFilterTest() { GaussianFilter filter = new GaussianFilter(Math.Sqrt(2), 5, 5); Bitmap b = new Bitmap("Resources/test_image1.jpg"); // filter.UseFilter(b); } } } <file_sep>namespace ML.Lib.Neuron { //Common interface for all neural networks public interface INetwork { void Train(double[][] input, double[][] expectedValues, int epochs); //Train network according to given inputs and expected values double[] Calculate(double[] input); // Calculate output of network given the input } }<file_sep>namespace ML.Lib { public struct PointInt2D { public int x; public int y; public PointInt2D(int nx, int ny) { x = nx; y = ny; } public static PointInt2D operator +(PointInt2D lh) { return lh; } public static PointInt2D operator -(PointInt2D lh) { return new PointInt2D(-lh.x, -lh.y); } public static PointInt2D operator +(PointInt2D lh, PointInt2D rh) { return new PointInt2D(lh.x + rh.x, lh.y + rh.y); } public static PointInt2D operator -(PointInt2D lh, PointInt2D rh) { return lh + (-rh); } public override string ToString() { return x.ToString() + " " + y.ToString(); } } }<file_sep>using System; using System.Drawing; using System.Collections.Generic; using ML.Lib; namespace ML.Lib.Image { //Performs sift operation on an image public class SIFT { private static readonly int octaves = 4; private static readonly int blurLevels = 5; public static double sigmaFactor = 1.6; public static double sigmaMultiplier = Math.Sqrt(2); public static double scaleChange = 0.5; //Scale change between octaves public static double intensityTreshold = 130; //treshold that must be exceeded by keypoint to become eligable public static double curvatureTreshold = 14; public static int collectionRadiusPerOctave = (int)(3.0 * sigmaFactor); public static int orientationBins = 36; public static int histogramSmoothingPasses = 4; public static double histogramEligableTreshold = 0.8; private static Bitmap grayBlured; public static Bitmap Perform(Bitmap input) { Console.WriteLine("SIFT running..."); //Convert input to grayscale Bitmap gray = BitmapUtils.ConvertToGrayscale(input); //resize picture to be 2x size to detect highest spacial frequencies gray = BitmapUtils.Resize(gray, 2.0); //Build scale pyramid Console.WriteLine("SIFT: Building gaussian pyramid..."); List<List<Bitmap>> scales = BuildGaussianPyramid(gray, octaves, blurLevels); Console.WriteLine("SIFT: Building DoG octaves..."); List<List<Bitmap>> dogs = CreateDoGs(scales); Console.WriteLine("SIFT: Finding keypoint candidates..."); List<Keypoint> keypointCandidates = FindKeypoints(dogs); Console.WriteLine("Keypoint Candidates found: " + keypointCandidates.Count); //Perform tests ContrastTest(keypointCandidates); EdgeTest(keypointCandidates); AssignKeypointParameters(keypointCandidates, scales); AdjustForDoubleSize(keypointCandidates); //Adjust coordinates to compensate for doubling image size in the begining Pen p = Pens.Red; Bitmap result = new Bitmap(input); Console.WriteLine("Keypoints left: " + keypointCandidates.Count); foreach (SIFT.Keypoint c in keypointCandidates) { Point2D transformedCoords = c.coords; //Transform coords if (c.octave != 0) { transformedCoords = new Point2D(c.coords.x * (Math.Pow(1 / SIFT.scaleChange, c.octave)), c.coords.y * (Math.Pow(1 / SIFT.scaleChange, c.octave))); } BitmapUtils.DrawSIFTFeature(result, p, new PointF((float)transformedCoords.x, (float)transformedCoords.y), new PointF((float)(transformedCoords.x + c.scale * 10 * Math.Cos(c.orientation * 10 * (Math.PI / 180))), (float)(transformedCoords.y + c.scale * 10 * Math.Sin(c.orientation * 10 * (Math.PI / 180))))); } return result; } //Build pyramid composed of public static List<List<Bitmap>> BuildGaussianPyramid(Bitmap gray, int numberOfOctaves, int numberOfBlurLevels) { //First create DoG (Diffrence of Gaussians Image) by filtering input with two Gaussian Filters //The blur levels are following: sigma*k^(2*octave_num + layer_num) //And then substructing results from each other GaussianFilter filter = new GaussianFilter(sigmaFactor, 5, 5); List<List<Bitmap>> octaves = new List<List<Bitmap>>(); grayBlured = filter.UseFilter(gray); Bitmap current = new Bitmap(gray); double scale = 1.0; int currentSigmaMulPower = 0; for (int i = 0; i < numberOfOctaves; i++) { //shrink to half a size octaves.Add(new List<Bitmap>()); octaves[i].Add(current); //Add current, base level of this octave for (int j = 0; j < numberOfBlurLevels - 1; j++) { //blur bitmap filter = new GaussianFilter(sigmaFactor * Math.Pow(sigmaMultiplier, currentSigmaMulPower + j), 5, 5); current = filter.UseFilter(current); octaves[i].Add(current); } scale *= scaleChange; currentSigmaMulPower += 2; current = BitmapUtils.Resize(gray, scale); //resize last image in previous level and use it as a base in the next level filter = new GaussianFilter(sigmaFactor * Math.Pow(sigmaMultiplier, currentSigmaMulPower), 5, 5); current = filter.UseFilter(current); } return octaves; } public static List<List<Bitmap>> CreateDoGs(List<List<Bitmap>> octaves) { List<List<Bitmap>> result = new List<List<Bitmap>>(); for (int i = 0; i < octaves.Count; i++) { result.Add(new List<Bitmap>()); for (int j = 0; j < octaves[i].Count - 1; j++) { result[i].Add(BitmapUtils.Subtract(octaves[i][j], octaves[i][j + 1])); } } return result; } //This method finds subpixel minima/maxima public static List<Keypoint> FindKeypoints(List<List<Bitmap>> DoGs) { List<Keypoint> candidates = new List<Keypoint>(); int octaveNumber = 0; foreach (List<Bitmap> octave in DoGs) //octave axis { for (int i = 1; i < octave.Count - 1; i++) // for each middle layer { for (int j = 1; j < octave[i].Width - 1; j++) //pixel X axis, ignore edges { for (int k = 1; k < octave[i].Height - 1; k++) //pixel Y axis, ignore edges { if (IsPixelEligable(octave, i, j, k)) { candidates.Add(new Keypoint(j, k, i, octaveNumber, octave[i])); } } } } octaveNumber++; } return candidates; } private static bool IsPixelEligable(List<Bitmap> currentOctave, int currentLevel, int currentX, int currentY) { return (CheckForMaximum(currentOctave,currentLevel, currentX, currentY) || CheckForMinimum(currentOctave,currentLevel, currentX, currentY)); } private static bool CheckForMaximum(List<Bitmap> currentOctave, int currentLevel, int currentX, int currentY) { int val = currentOctave[currentLevel].GetPixel(currentX, currentY).R; for (int i = -1; i < 2; i++) //scale axis { for (int j = -1; j < 2; j++) // x axis { for (int k = -1; k < 2; k++) //y axis { if (val < currentOctave[currentLevel + i].GetPixel(currentX + j, currentY + k).R) { return false; } } } } return true; } private static bool CheckForMinimum(List<Bitmap> currentOctave, int currentLevel, int currentX, int currentY) { int val = currentOctave[currentLevel].GetPixel(currentX, currentY).R; for (int i = -1; i < 2; i++) //scale axis { for (int j = -1; j < 2; j++) // x axis { for (int k = -1; k < 2; k++) //y axis { if (val > currentOctave[currentLevel + i].GetPixel(currentX + j, currentY + k).R) { return false; } } } } return true; } private static void CalculateSubPixelCoords(List<Keypoint> keypoints, List<List<Bitmap>> DoGs) { } //Reject keypoint pixels that are below treshold intensity public static void ContrastTest(List<Keypoint> keypoints) { int count = keypoints.Count; Console.WriteLine("ContrastTest: Running..."); //Console.WriteLine(Math.Abs((int)k.underlayingBitmap.GetPixel((int)k.coords.x, (int)k.coords.y).R - 128)); //keypoints.RemoveAll(k => CalculateContrastBlob(k, 1, 1) < intensityTreshold); keypoints.RemoveAll(k => k.GetPixel().R < intensityTreshold); Console.WriteLine("ContrastTest: Excluded - " + (count - keypoints.Count) + " keypoints"); } //Calculates contrast base around the area around keypoint private static double CalculateContrastBlob(Keypoint keypoint, int range, double falloff) { double pixelVal = 0; for (int i = -range; i < range + 1; i++) { for (int j = -range; j < range + 1; j++) { if (i + keypoint.intCoords.x < 0 || i + keypoint.intCoords.x >= keypoint.underlayingBitmap.Width || j + keypoint.intCoords.y < 0 || j + keypoint.intCoords.y >= keypoint.underlayingBitmap.Height) continue; Color pixel = keypoint.underlayingBitmap.GetPixel(i + keypoint.intCoords.x, j + keypoint.intCoords.y); pixelVal += pixel.R / (Math.Abs(range + 1) * falloff); //further pixels are worth less } } pixelVal /= range * range; //Console.WriteLine(pixelVal); return pixelVal; } //Reject keypoints that are on edge public static void EdgeTest(List<Keypoint> keypoints) { Console.WriteLine("EdgeTest running..."); int count = keypoints.Count; for (int i = 0; i < keypoints.Count; i++) { Keypoint k = keypoints[i]; PointInt2D intCoords = k.intCoords; //dxx double dxx = (k.underlayingBitmap.GetPixel(intCoords.x + 1, intCoords.y).R - 2 * k.underlayingBitmap.GetPixel(intCoords.x, intCoords.y).R + k.underlayingBitmap.GetPixel(intCoords.x - 1, intCoords.y).R); //dyy double dyy = (k.underlayingBitmap.GetPixel(intCoords.x, intCoords.y + 1).R - 2 * k.underlayingBitmap.GetPixel(intCoords.x, intCoords.y).R + k.underlayingBitmap.GetPixel(intCoords.x, intCoords.y - 1).R); //dxy also dyx from derivative theorem double dxy = (k.underlayingBitmap.GetPixel(intCoords.x + 1, intCoords.y + 1).R - k.underlayingBitmap.GetPixel(intCoords.x - 1, intCoords.y + 1).R - k.underlayingBitmap.GetPixel(intCoords.x + 1, intCoords.y - 1).R + k.underlayingBitmap.GetPixel(intCoords.x - 1, intCoords.y - 1).R) / 4.0; double trace = dxx + dyy; double determinant = dxx * dxy - dyy * dxy; /* negative determinant -> curvatures have different signs; reject feature */ if (determinant <= 0) { keypoints.Remove(k); i--; continue; } double check = (trace * trace) / determinant; // Console.WriteLine(check + " VS " + ((curvatureTreshold + 1.0) * (curvatureTreshold + 1.0) / curvatureTreshold).ToString()); //If check is bigger then curvature then reject it if (check >= (curvatureTreshold + 1.0) * (curvatureTreshold + 1.0) / curvatureTreshold) { keypoints.Remove(k); i--; } } Console.WriteLine("EdgeTest: Excluded - " + (count - keypoints.Count) + " keypoints"); } //Calculates derivative around a pixel private static Point3D Derivative3D(List<Bitmap> dogOctave, PointInt3D pixelCoord) { double dx = (dogOctave[pixelCoord.z].GetPixel(pixelCoord.x + 1, pixelCoord.y).R - dogOctave[pixelCoord.z].GetPixel(pixelCoord.x - 1, pixelCoord.y).R) / 2.0; double dy = (dogOctave[pixelCoord.z].GetPixel(pixelCoord.x, pixelCoord.y + 1).R - dogOctave[pixelCoord.z].GetPixel(pixelCoord.x, pixelCoord.y - 1).R) / 2.0; double dz = (dogOctave[pixelCoord.z + 1].GetPixel(pixelCoord.x, pixelCoord.y).R - dogOctave[pixelCoord.z - 1].GetPixel(pixelCoord.x, pixelCoord.y).R) / 2.0; return new Point3D(dx, dy, dz); } //Calculates hessian matrix out of octave around given pixel //used for calculating subpixel maxima/minima coords // dxx dxy dxz // dyx dyy dyz // dzx dzy dzz private static double[][] Hessian3D(List<Bitmap> dogOctave, PointInt3D pixelCoord) { double[][] result = new double[3][]; for (int i = 0; i < 3; i++) { result[i] = new double[3]; } double kernelPixel = dogOctave[pixelCoord.z].GetPixel(pixelCoord.x, pixelCoord.y).R; //dxx double dxx = (dogOctave[pixelCoord.z].GetPixel(pixelCoord.x + 1, pixelCoord.y).R - 2 * kernelPixel + dogOctave[pixelCoord.z].GetPixel(pixelCoord.x - 1, pixelCoord.y).R) / 4.0; //dyy double dyy = (dogOctave[pixelCoord.z].GetPixel(pixelCoord.x, pixelCoord.y + 1).R - 2 * kernelPixel + dogOctave[pixelCoord.z].GetPixel(pixelCoord.x, pixelCoord.y - 1).R) / 4.0; //dzz double dzz = (dogOctave[pixelCoord.z + 1].GetPixel(pixelCoord.x, pixelCoord.y).R - 2 * kernelPixel + dogOctave[pixelCoord.z - 1].GetPixel(pixelCoord.x, pixelCoord.y - 1).R) / 4.0; //dxy also dyx from derivative theorem double dxy = (dogOctave[pixelCoord.z].GetPixel(pixelCoord.x + 1, pixelCoord.y + 1).R - dogOctave[pixelCoord.z].GetPixel(pixelCoord.x - 1, pixelCoord.y + 1).R - dogOctave[pixelCoord.z].GetPixel(pixelCoord.x + 1, pixelCoord.y - 1).R + dogOctave[pixelCoord.z].GetPixel(pixelCoord.x - 1, pixelCoord.y - 1).R) / 4.0; //dxz also dzx from derivative theorem double dxz = (dogOctave[pixelCoord.z + 1].GetPixel(pixelCoord.x + 1, pixelCoord.y).R - dogOctave[pixelCoord.z + 1].GetPixel(pixelCoord.x - 1, pixelCoord.y).R - dogOctave[pixelCoord.z - 1].GetPixel(pixelCoord.x + 1, pixelCoord.y).R + dogOctave[pixelCoord.z - 1].GetPixel(pixelCoord.x - 1, pixelCoord.y).R) / 4.0; //dyz also dzy from derivative theorem double dyz = (dogOctave[pixelCoord.z + 1].GetPixel(pixelCoord.x, pixelCoord.y + 1).R - dogOctave[pixelCoord.z + 1].GetPixel(pixelCoord.x, pixelCoord.y - 1).R - dogOctave[pixelCoord.z - 1].GetPixel(pixelCoord.x, pixelCoord.y + 1).R + dogOctave[pixelCoord.z - 1].GetPixel(pixelCoord.x, pixelCoord.y - 1).R) / 4.0; result[0][0] = dxx; result[0][1] = dxy; result[0][2] = dxz; result[1][0] = dxy; result[1][1] = dyy; result[1][2] = dyz; result[2][0] = dxz; result[2][1] = dyz; result[2][2] = dzz; return result; } private double[][] Invert33Matrix(double[][] m) { double[][] result = new double[3][]; for (int i = 0; i < 3; i++) result[i] = new double[3]; // computes the inverse of a matrix m double det = m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]); double invdet = 1 / det; result[0][0] = (m[1][1] * m[2][2] - m[2][1] * m[1][2]) * invdet; result[0][1] = (m[0][2] * m[2][1] - m[0][1] * m[2][2]) * invdet; result[0][2] = (m[0][1] * m[1][2] - m[0][2] * m[1][1]) * invdet; result[1][0] = (m[1][2] * m[2][0] - m[1][0] * m[2][2]) * invdet; result[1][1] = (m[0][0] * m[2][2] - m[0][2] * m[2][0]) * invdet; result[1][2] = (m[1][0] * m[0][2] - m[0][0] * m[1][2]) * invdet; result[2][0] = (m[1][0] * m[2][1] - m[2][0] * m[1][1]) * invdet; result[2][1] = (m[2][0] * m[0][1] - m[0][0] * m[2][1]) * invdet; result[2][2] = (m[0][0] * m[1][1] - m[1][0] * m[0][1]) * invdet; return result; } //Calculates and assings keypoint magnitude and orientation public static void AssignKeypointParameters(List<Keypoint> keypoints, List<List<Bitmap>> initialSmooth) { for (int a = 0; a < keypoints.Count; a++) { Keypoint k = keypoints[a]; int r = ((octaves - k.octave) * collectionRadiusPerOctave) + 2; //"radius" is simply square size double[] histogram = new double[36]; double exp_denom = sigmaFactor * sigmaFactor * 2.0; //build histogram for (int i = -r; i <= r; i++) { for (int j = -r; j <= r; j++) { if (i + k.coords.x < 0 || j + k.coords.y < 0 || i + k.coords.x > k.underlayingBitmap.Width || j + k.coords.y > k.underlayingBitmap.Height) continue; double dx = (double)initialSmooth[k.octave][1].GetPixel(k.intCoords.x + 1, k.intCoords.y).R - (double)initialSmooth[k.octave][1].GetPixel(k.intCoords.x - 1, k.intCoords.y).R; double dy = (double)initialSmooth[k.octave][1].GetPixel(k.intCoords.x, k.intCoords.y + 1).R - (double)initialSmooth[k.octave][1].GetPixel(k.intCoords.x, k.intCoords.y - 1).R; double magnitude = Math.Sqrt(dx * dx + dy * dy); double orientation = Math.Atan2(dy, dx) * (180.0 / Math.PI); orientation = orientation + 180; double w = Math.Exp(-(i * i + j * j) / exp_denom); int binID = (int)(Math.Round(orientation) / (360.0 / (double)orientationBins)); binID = (binID < orientationBins) ? binID : 0; histogram[binID] += w * magnitude; } } //Calculate scale k.orientation = histogram.MaxAt(); k.scale = Math.Pow(1/scaleChange, k.octave); // Console.WriteLine(k.orientation); } } public static void AdjustForDoubleSize(List<Keypoint> keypoints) { foreach (Keypoint k in keypoints) { k.coords = new Point2D(k.coords.x / 2.0, k.coords.y / 2.0); k.scale /= 2.0; } } public class Keypoint { public Point2D coords; // x -> Pixel X axis, Y-> Pixel Y Axis, Z -> Octave Axis public PointInt2D intCoords { get { return new PointInt2D((int)coords.x, (int)coords.y); } } public double scale; public double orientation; public int octave; public int layer; public readonly Bitmap underlayingBitmap; //Underlaying bitmap in which this keypoint was created; public Keypoint(int x, int y, int layer, int octave, Bitmap underlayingBitmap) { coords = new Point2D(x, y); scale = 0; orientation = 0; this.octave = octave; this.layer = layer; this.underlayingBitmap = underlayingBitmap; } //Creates deep copy of a keypoint public Keypoint(Keypoint k) { coords = new Point2D(coords.x, coords.y); scale = k.scale; orientation = k.orientation; octave = k.octave; layer = k.layer; underlayingBitmap = k.underlayingBitmap; } //Gets pixel from underlying bitmap public Color GetPixel() { return underlayingBitmap.GetPixel(intCoords.x, intCoords.y); } public Color GetPixel(PointInt2D offset) { return underlayingBitmap.GetPixel(intCoords.x + offset.x, intCoords.y + offset.y); } } } } <file_sep>using System; using System.Diagnostics; namespace ML.Lib.Image { public class GaussianFilter : Filter { private double _deviation; //Creates gaussian filter public GaussianFilter(double deviation, int width, int height) { _deviation = deviation; filterData = new double[width][]; for (int i = 0; i < width; i++) { filterData[i] = new double[height]; } Point2D pivot = new Point2D(width / 2, height/2); for (int i = 0; i < width; i++) { for(int j = 0; j < height; j++) { filterData[i][j] = GaussianFunction(pivot, new Point2D(i,j)); } } } private double GaussianFunction(Point2D pivot, Point2D current) { return GaussianFunction(pivot - current); } private double GaussianFunction(Point2D distance) { return Math.Exp( -((Math.Pow(distance.x, 2) + Math.Pow(distance.y, 2)) / (2 * Math.Pow(_deviation, 2)))) / (2 * Math.PI * _deviation * _deviation); } public override string ToString() { string result = ""; foreach (var d in filterData) { foreach (var c in d) { result += c.ToString() + " "; } result += "\n"; } return result; } } }<file_sep>using System.Collections.Generic; namespace BayesClassifier { public class ClassifiedObject { public string Classification { get; set; } //Classification of this object public List<string> Properties { get; set; } //all properties of this object public string Label { get; set; } //A human readable ID public ClassifiedObject() { Properties = new List<string>(); } } }<file_sep>namespace ML.Lib.Neuron { //A special kind of connection //To this connection Network pushes it's input values public class InputConnection : IConnection { public double Weight { get { return 1; } set{} } public double PreviousWeight { get { return 1; } } public double Output { get; set; } public double GetOutput() { return Output; } public void UpdateWeight(double newWeight) { throw new System.NotImplementedException(); } public INeuron To => throw new System.NotImplementedException(); public INeuron From => throw new System.NotImplementedException(); } }<file_sep>namespace ML.Lib.Neuron { //Function that changes incoming input public interface IInputFunction<T> { double Perform(T input); } }<file_sep>namespace ML.Lib.Neuron { public interface IActivationFunction { //The "Output" function of a neuron //In normal-case scenario should receive input from IInputFunction double Perform(double input); //Performs first derivative //used in optimalization of a network double PerformDerivative(double input); } }<file_sep>using System.Drawing; using System; using System.Drawing.Imaging; using System.Linq; namespace ML.Lib.Image { public static class BitmapUtils { //Subtructs one bitmap from another, given that both of them are of the same size and dimension public static Bitmap Subtract(this Bitmap lh, Bitmap rh) { if (lh.Width != rh.Width || lh.Height != rh.Height) throw new ArgumentException("Bitmap are not of the same size"); Bitmap result = new Bitmap(lh); int maxDiff = int.MinValue; int minDiff = int.MaxValue; int[][][] data = new int[3][][]; for (int i = 0; i < 3; i++) { data[i] = new int[lh.Width][]; for (int j = 0; j < lh.Width; j++) { data[i][j] = new int[lh.Height]; } } for (int i = 0; i < lh.Width; i++) { for (int j = 0; j < lh.Height; j++) { Color currentPixel = result.GetPixel(i, j); Color currentRHPixel = rh.GetPixel(i, j); data[0][i][j] = currentPixel.R - currentRHPixel.R; data[1][i][j] = currentPixel.G - currentRHPixel.G; data[2][i][j] = currentPixel.B - currentRHPixel.B; if (data[0][i][j] > maxDiff) maxDiff = data[0][i][j]; if (data[1][i][j] > maxDiff) maxDiff = data[1][i][j]; if (data[2][i][j] > maxDiff) maxDiff = data[2][i][j]; if (data[0][i][j] < minDiff) minDiff = data[0][i][j]; if (data[1][i][j] < minDiff) minDiff = data[1][i][j]; if (data[2][i][j] < minDiff) minDiff = data[2][i][j]; } } //Normalize data for (int i = 0; i < 3; i++) { for (int j = 0; j < lh.Width; j++) { for (int k = 0; k < lh.Height; k++) { data[i][j][k] = (data[i][j][k] - minDiff)*(int)(255.0/(double)(maxDiff - minDiff)); } } } for (int j = 0; j < lh.Width; j++) { for (int k = 0; k < lh.Height; k++) { result.SetPixel(j, k, Color.FromArgb(data[0][j][k], data[1][j][k], data[2][j][k])); } } return result; } public static Bitmap ConvertToGrayscale(Bitmap bitmap) { Bitmap b = new Bitmap(bitmap); for (int i = 0; i < b.Width; i++) { for (int j = 0; j < b.Height; j++) { Color c = b.GetPixel(i, j); byte g = (byte)((c.R + c.B + c.G) / 3); b.SetPixel(i, j, Color.FromArgb(g, g, g)); } } return b; } //Resize using bilinear interpolation public static Bitmap Resize(Bitmap m, double factor) { int nwidth = (int)(m.Width * factor); int nheight = (int)(m.Height * factor); // C# Bitmap result = new Bitmap(nwidth, nheight); using (Graphics g = Graphics.FromImage(result)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear; g.DrawImage(m, 0, 0, nwidth, nheight); } return result; } // Draw arrow heads or tails for the // segment from p1 to p2. public static void DrawSIFTFeature(Bitmap b, Pen pen, PointF p1, PointF p2) { using (Graphics g = Graphics.FromImage(b)) { // Draw the shaft. g.DrawLine(pen, p1, p2); int length = (int)Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2)) * 2; g.DrawEllipse(pen, (int)p1.X - (length / 2), (int)p1.Y - (length / 2), length, length); } } } }<file_sep>using System; using System.Diagnostics; using System.Drawing; namespace ML.Lib.Image { //Describes basic 2D filter public class Filter { public double[][] filterData { get; set; } public int Height { get; set; } public int Width { get; set; } public Filter() { } public Filter(double[][] FilterData) { filterData = FilterData; } public Bitmap UseFilter(Bitmap input) { Bitmap map = new Bitmap(input.Width, input.Height); int Length = filterData.Length / 2; for (int i = 0; i < input.Width; i++) { for (int j = 0; j < input.Height; j++) { double maskSum = 0; double R = 0; double B = 0; double G = 0; for (int k = -Length; k < Length + 1; k++) { for (int g = -Length; g < Length + 1; g++) { if (k + i < 0 || k + i >= input.Width || g + j < 0 || g + j >= input.Height) continue; Color filterPixel = input.GetPixel(k + i, g + j); maskSum += filterData[k + Length][g + (Length)]; R += filterPixel.R * filterData[k + (Length)][g + (Length)]; B += filterPixel.B * filterData[k + (Length)][g + (Length)]; G += filterPixel.G * filterData[k + (Length)][g + (Length)]; } } if (maskSum == 0) maskSum = 1; R = R / maskSum; B = B / maskSum; G = G /maskSum; if (R < 0) R = 0; if (R > 255) R = 255; if (G < 0) G = 0; if (G > 255) G = 255; if (B < 0) B = 0; if (B > 255) B = 255; Color newColor = Color.FromArgb(Convert.ToInt32(R), Convert.ToInt32(G), Convert.ToInt32(B)); map.SetPixel(i, j, newColor); } } return map; } } } <file_sep>using System; using System.IO; using NeuralNetwork; namespace neural { class Program { static void Main(string[] args) { if (args.Length > 0) { if (!File.Exists(args[0])) TrainNew(); Network net = new Network(4, new int[] { 4, 4, 4, 4 }, 2); net.LoadWeights(File.ReadAllLines(args[0])); double[][][] data = Loader.Load("data.csv"); //Final test, take test set and test correctness HighestHitTest t = new HighestHitTest(net); t.Test(data[2], data[3]); } else { TrainNew(); } } static void TrainNew() { //Net with 6 layers Network net = new Network(4, new int[] { 4, 4, 4, 4 }, 2); // net.testStrategy = new HighestHitTest(net); double[][][] data = Loader.Load("data.csv"); net.Train(data, 3000); //Final test, take test set and test correctness HighestHitTest t = new HighestHitTest(net); t.Test(data[2], data[3]); } } } <file_sep>using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using ML.Lib.Fuzzy; namespace ML.Lib.Tests { [TestClass] public class SugenoTests { [TestMethod] public void SugenoTest() { Sugeno sugenoSystem = new Sugeno(); FuzzifierGroup sunlightGroup = new FuzzifierGroup("sunlight"); sunlightGroup.Fuzzifiers.Add(new TrapezoidFuzzifier(0, 0.0, 0.2, 0.3, "niskie")); sunlightGroup.Fuzzifiers.Add(new TriangleFuzzifier(0.2, 0.5, 0.8, "średnie")); sunlightGroup.Fuzzifiers.Add(new TrapezoidFuzzifier(0.6, 0.8, 1.0, 1.0, "duże")); sugenoSystem.FuzzifierGroups.Add(sunlightGroup); FuzzifierGroup pollutionGroup = new FuzzifierGroup("pollution"); pollutionGroup.Fuzzifiers.Add(new TrapezoidFuzzifier(0, 0, 0.2, 0.3, "niskie")); pollutionGroup.Fuzzifiers.Add(new TriangleFuzzifier(0.1, 0.4, 0.7, "średnie")); pollutionGroup.Fuzzifiers.Add(new TrapezoidFuzzifier(0.5, 0.7, 1.0, 1.0, "duże")); sugenoSystem.FuzzifierGroups.Add(pollutionGroup); sugenoSystem.Rules.Add(new SugenoRule(SugenoRule.AND, "sunlight", "niskie", "pollution", "niskie")); sugenoSystem.Rules.Add(new SugenoRule(SugenoRule.AND, "sunlight", "niskie", "pollution", "średnie")); sugenoSystem.Rules.Add(new SugenoRule(SugenoRule.AND, "sunlight", "niskie", "pollution", "duże")); sugenoSystem.Rules.Add(new SugenoRule(SugenoRule.AND, "sunlight", "średnie", "pollution", "niskie")); sugenoSystem.Rules.Add(new SugenoRule(SugenoRule.AND, "sunlight", "średnie", "pollution", "średnie")); sugenoSystem.Rules.Add(new SugenoRule(SugenoRule.AND, "sunlight", "średnie", "pollution", "duże")); sugenoSystem.Rules.Add(new SugenoRule(SugenoRule.AND, "sunlight", "duże", "pollution", "niskie")); sugenoSystem.Rules.Add(new SugenoRule(SugenoRule.AND, "sunlight", "duże", "pollution", "średnie")); sugenoSystem.Rules.Add(new SugenoRule(SugenoRule.AND, "sunlight", "duże", "pollution", "duże")); sugenoSystem.expectedValues.Add(new SugenoExpectedValue() { value = 0.6, label = "OK" }); sugenoSystem.expectedValues.Add(new SugenoExpectedValue() { value = 0.3, label = "BAD" }); sugenoSystem.expectedValues.Add(new SugenoExpectedValue() { value = 0.1, label = "VERY BAD" }); sugenoSystem.expectedValues.Add(new SugenoExpectedValue() { value = 0.8, label = "GOOD" }); sugenoSystem.expectedValues.Add(new SugenoExpectedValue() { value = 0.5, label = "OK" }); sugenoSystem.expectedValues.Add(new SugenoExpectedValue() { value = 0.2, label = "BAD" }); sugenoSystem.expectedValues.Add(new SugenoExpectedValue() { value = 1.0, label = "VERY GOOD" }); sugenoSystem.expectedValues.Add(new SugenoExpectedValue() { value = 0.7, label = "GOOD" }); sugenoSystem.expectedValues.Add(new SugenoExpectedValue() { value = 0.3, label = "BAD" }); List<SugenoInput> inputs = new List<SugenoInput>(); inputs.Add(new SugenoInput("Warszawa", new Dictionary<string, double>() { ["sunlight"] = 0.6, ["pollution"] = 0.3 })); inputs.Add(new SugenoInput("Kraków", new Dictionary<string, double>() { ["sunlight"] = 1.0, ["pollution"] = 0.1 })); inputs.Add(new SugenoInput("Gdańsk", new Dictionary<string, double>() { ["sunlight"] = 0.9, ["pollution"] = 0.9 })); inputs.Add(new SugenoInput("Wrocław", new Dictionary<string, double>() { ["sunlight"] = 0.8, ["pollution"] = 0.7 })); inputs.Add(new SugenoInput("Katowice", new Dictionary<string, double>() { ["sunlight"] = 0.3, ["pollution"] = 0.1 })); inputs.Add(new SugenoInput("Poznań", new Dictionary<string, double>() { ["sunlight"] = 0.7, ["pollution"] = 0.6 })); inputs.Add(new SugenoInput("Gliwice", new Dictionary<string, double>() { ["sunlight"] = 0.3, ["pollution"] = 0.1 })); inputs.ForEach(x => Console.WriteLine("Living standards for " + x.Label + " are " + sugenoSystem.Compile(x))); } } }<file_sep>namespace ML.Lib.Fuzzy { public interface IFuzzifier { string Label { get; set; } double Fuzzify(double x); } }<file_sep>using System; namespace ML.Lib { public static class ComparableUtils { public static T Bound<T>(T t, T min, T max) where T : IComparable<T> { if (t.CompareTo(max) > 0) return max; if (t.CompareTo(min) < 0) return min; return t; } } }<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting; using ML.Lib.Image; using System; using System.IO; using System.Diagnostics; using System.Drawing; using System.Collections.Generic; namespace ML.Lib.Tests { [TestClass] [Ignore] public class SIFTTests { static List<List<Bitmap>> octaves = null; static List<List<Bitmap>> DoGs = null; static List<SIFT.Keypoint> candidates = null; static Bitmap original; [TestMethod] public void Test() { // Bitmap b = new Bitmap("Resources/test_image1.jpg"); // SIFT.Perform(b).Save("doggo.png"); } [TestMethod] public void TestPyramidBuilding() { Bitmap b = new Bitmap("../../../Resources/butterfly.jpg"); original = b; b = BitmapUtils.ConvertToGrayscale(b); b = BitmapUtils.Resize(b, 2.0); //resize image 2x times to include highest spacial frequencies GaussianFilter filter = new GaussianFilter(2, 5, 5); b = filter.UseFilter(b); octaves = SIFT.BuildGaussianPyramid(b, 4, 5); int i = 0; int j = 0; foreach (List<Bitmap> level in octaves) { foreach (Bitmap bm in level) { bm.Save("../../../TestGeneratedFiles/Blur/SIFT_TEST_" + i + "_" + j + ".png"); j++; } j = 0; i++; } } [TestMethod] public void TestDoGCreation() { DoGs = SIFT.CreateDoGs(octaves); int i = 0; int j = 0; foreach (List<Bitmap> level in DoGs) { foreach (Bitmap bm in level) { bm.Save("../../../TestGeneratedFiles/DoGs/DoG_TEST_" + i + "_" + j + ".png"); j++; } i++; j = 0; } } [TestMethod] public void TestFindKeypoints() { candidates = SIFT.FindKeypoints(DoGs); Bitmap currentBitmap = null; int currentOctave = -1; int currentLayer = -1; foreach (SIFT.Keypoint c in candidates) { if (c.octave != currentOctave || c.layer != currentLayer) { currentBitmap?.Save("../../../TestGeneratedFiles/KeypointCandidates/points" + currentOctave + "_" + currentLayer + ".png"); currentBitmap = new Bitmap(c.underlayingBitmap); //copy underlaying bitmap currentOctave = c.octave; currentLayer = c.layer; } currentBitmap.SetPixel((int)c.coords.x, (int)c.coords.y, Color.White); } } [TestMethod] public void TestContrastTest() { int co = candidates.Count; SIFT.ContrastTest(candidates); Debug.WriteLine("Test: " + (co - candidates.Count).ToString() + " rejected"); Bitmap currentBitmap = null; int currentOctave = -1; int currentLayer = -1; foreach (SIFT.Keypoint c in candidates) { if (c.octave != currentOctave || c.layer != currentLayer) { currentBitmap?.Save("../../../TestGeneratedFiles/AfterContrastTest/points" + currentOctave + "_" + currentLayer + ".png"); currentBitmap = new Bitmap(c.underlayingBitmap); //copy underlaying bitmap currentOctave = c.octave; currentLayer = c.layer; } currentBitmap.SetPixel((int)c.coords.x, (int)c.coords.y, Color.White); } } [TestMethod] public void TestEdgeTest() { int co = candidates.Count; SIFT.EdgeTest(candidates); Debug.WriteLine("Test: " + (co - candidates.Count).ToString() + " rejected"); Bitmap currentBitmap = null; int currentOctave = -1; int currentLayer = -1; foreach (SIFT.Keypoint c in candidates) { if (c.octave != currentOctave || c.layer != currentLayer) { currentBitmap?.Save("../../../TestGeneratedFiles/AfterEdgeTest/points" + currentOctave + "_" + currentLayer + ".png"); currentBitmap = new Bitmap(c.underlayingBitmap); //copy underlaying bitmap currentOctave = c.octave; currentLayer = c.layer; } currentBitmap.SetPixel((int)c.coords.x, (int)c.coords.y, Color.White); } } [TestMethod] public void TestAssignParameters() { SIFT.AssignKeypointParameters(candidates, octaves); Bitmap currentBitmap = null; int currentOctave = -1; int currentLayer = -1; Pen p = Pens.White; foreach (SIFT.Keypoint c in candidates) { if (c.octave != currentOctave || c.layer != currentLayer) { currentBitmap?.Save("../../../TestGeneratedFiles/AfterAssignParameters/points" + currentOctave + "_" + currentLayer + ".png"); currentBitmap = new Bitmap(c.underlayingBitmap); //copy underlaying bitmap currentOctave = c.octave; currentLayer = c.layer; } BitmapUtils.DrawSIFTFeature(currentBitmap, p, new PointF((float)c.coords.x, (float)c.coords.y), new PointF((float)(c.coords.x + c.scale * 10 * Math.Cos(c.orientation * 10 * (Math.PI / 180))), (float)(c.coords.y + c.scale * 10 * Math.Sin(c.orientation * 10 * (Math.PI / 180))))); } } [TestMethod] public void FinalizeResult() { Pen p = Pens.Red; SIFT.AdjustForDoubleSize(candidates); foreach (SIFT.Keypoint c in candidates) { Point2D transformedCoords = c.coords; //Transform coords if (c.octave != 0) { transformedCoords = new Point2D(c.coords.x * (Math.Pow(1 / SIFT.scaleChange, c.octave)), c.coords.y * (Math.Pow(1 / SIFT.scaleChange, c.octave))); } BitmapUtils.DrawSIFTFeature(original, p, new PointF((float)transformedCoords.x, (float)transformedCoords.y), new PointF((float)(transformedCoords.x + c.scale * 10 * Math.Cos(c.orientation * 10 * (Math.PI / 180))), (float)(transformedCoords.y + c.scale * 10 * Math.Sin(c.orientation * 10 * (Math.PI / 180))))); } original.Save("../../../TestGeneratedFiles/last.png"); } } } <file_sep>using System; namespace ML.Lib { public struct Point2D { public double x; public double y; public Point2D(double nx, double ny) { x = nx; y = ny; } //Calculates cartesian distance public static double Distance(Point2D a, Point2D b) { return Math.Sqrt(Math.Pow(b.x - a.x, 2) + Math.Pow(b.y - a.y, 2)); } public static Point2D operator +(Point2D lh) { return lh; } public static Point2D operator -(Point2D lh) { return new Point2D(-lh.x, -lh.y); } public static Point2D operator +(Point2D lh, Point2D rh) { return new Point2D(lh.x + rh.x, lh.y + rh.y); } public static Point2D operator -(Point2D lh, Point2D rh) { return lh + (-rh); } public override string ToString() { return x.ToString() + " " + y.ToString(); } } }<file_sep>using System.Collections.Generic; using System; using System.Linq; namespace ML.Lib.Fuzzy { public class Sugeno { //Collection of user determined fuzzifiers used in fuzzifying process //each dictionary key is equvialent to the input index number List<FuzzifierGroup> fuzzifierGroups = new List<FuzzifierGroup>(); public List<FuzzifierGroup> FuzzifierGroups { get { return fuzzifierGroups; } } //Collection of user determined truthValues together with their respective IDs List<TruthValueGroup> truthValuesGroups = new List<TruthValueGroup>(); public List<TruthValueGroup> TruthValuesGroups { get { return truthValuesGroups; } } List<SugenoRule> rules = new List<SugenoRule>(); public List<SugenoRule> Rules { get { return rules; } } public List<SugenoExpectedValue> expectedValues = new List<SugenoExpectedValue>(); public Sugeno() { } //Performs fuzzy-system operations //IMPORTANT: order of inputs is used for using appropiate groups of fuzzifiers public double Compile(SugenoInput input) { TruthValuesGroups.Clear(); double result = 0; foreach (FuzzifierGroup fuzzGroup in FuzzifierGroups) { TruthValueGroup currentGroup = new TruthValueGroup(fuzzGroup.GroupName); TruthValuesGroups.Add(currentGroup); foreach (IFuzzifier f in fuzzGroup.Fuzzifiers) { currentGroup.valuePairs.Add(f.Label, f.Fuzzify(input.values[fuzzGroup.GroupName])); } } List<double> ruleValues = new List<double>(); // Contains values of appropiate rules foreach (SugenoRule rule in rules) { double val1 = TruthValuesGroups.Find(x => x.GroupID == rule.truthValueGroupIDs[0]).valuePairs[rule.truthValueIDs[0]]; double val2 = TruthValuesGroups.Find(x => x.GroupID == rule.truthValueGroupIDs[1]).valuePairs[rule.truthValueIDs[1]]; ruleValues.Add(rule.ruleMethod(val1, val2)); } double decision = 0; for (int i = 0; i < expectedValues.Count; i++) { decision += ruleValues[i] * expectedValues[i].value; } double tmp = 0; for (int i = 0; i < ruleValues.Count; i++) { tmp += ruleValues[i]; } result = decision / tmp; return result; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; namespace ML.Lib.Neuron { public class SimpleNetwork : INetwork { //Contains input layer all hidden layers and an output layer public List<Layer> Layers { get; set; } public double LearningRate { get; set; } public static System.Random rnd = new System.Random(); //initialize network sizes.Length layers //each layer has int size assigned public SimpleNetwork(IEnumerable<int> sizes) { Layers = new List<Layer>(); LearningRate = 0.05; //Create input layer Layer inputLayer = new Layer(); Layers.Add(inputLayer); for (int i = 0; i < sizes.ToList()[0]; i++) { inputLayer.Neurons.Add(new InputNeuron()); } foreach (int size in sizes.Skip(1)) { Layer l = new Layer(); Layers.Add(l); //Create layer of "size" neurons for (int i = 0; i < size; i++) { l.Neurons.Add(new SimpleNeuron()); } } ReconnectNetwork(); } public SimpleNetwork() { } public void Train(double[][] input, double[][] expectedValues, int epochs) { //Cost function: 1/2n SUM_i (expected_i - output_i)^2 //Cost for one training example C = 1/n SUM_i C_i //C_i = 1/2 ||(expected - output)^2|| (|| <- norm operation sum all in vector) //============================================================================= //Error in output layer Er^L_j = nabla C / nabla A^L_j * activationFuncDerivative(z^L_J) //Where z -> weighted input to the given layer's Lth jth Neuron //a -> Activation (output) of Layer's Lth jth Neuron //================================================================= //Error in the next layers Er^L = weight_prev_layer * error_prev_layer * activationFuncDerivative(z^L) //================================ //The Backpropagation Algorithm //================================ /* For each epoch For each training example: 1. Feedforward for given input from training example Save information about each weighted input to each neuron and about each activation for every neuron 2. Calculate Output Layer Error 3. Backpropagate error, For each Layer from preLastOne to second one: Compute Error for every weight using error from previous layer 4. Gradient(direction) is given by multiplying error of neuron and activation from next layer that it's connected to 5. Gradient Descent using Gradients move weights in the right direction. */ double[][] errors = new double[Layers.Count][]; for (int i = 0; i < Layers.Count; i++) { errors[i] = new double[Layers[i].Neurons.Count]; } for (int i = 0; i < epochs; i++) { //For each input set for (int j = 0; j < input.Length; j++) { //Calculate current net iteration double[] currentOutputs = Calculate(input[j]); //Calculate errors for output layer for (int k = 0; k < Layers.Last().Neurons.Count; k++) { INeuron currentNeuron = Layers.Last().Neurons[k]; double currentError = (currentOutputs[k] - expectedValues[j][k]) * currentNeuron.ActivationFunction.PerformDerivative(currentNeuron.LastInputValue); errors[Layers.Count - 1][k] = currentError; } //Once we have output layer errors calculated, we can use them to calculate next layers errors for (int k = Layers.Count - 2; k > 0; k--) { for (int l = 0; l < Layers[k].Neurons.Count; l++) { errors[k][l] = 0; for (int m = 0; m < Layers[k + 1].Neurons.Count; m++) { errors[k][l] += errors[k + 1][m] * Layers[k + 1].Neurons[m].IncomingConnections[l].Weight; } errors[k][l] *= Layers[k].Neurons[l].ActivationFunction.PerformDerivative(Layers[k].Neurons[l].LastInputValue); } } //Now, when we have calculated all of errors for each neuron in our net //We can perform weight update, the order does not matter as we already calculated everything needed for (int k = Layers.Count - 1; k > 0; k--) { for (int l = 0; l < Layers[k].Neurons.Count; l++) { for (int m = 0; m < Layers[k - 1].Neurons.Count; m++) { double grad = errors[k][l] * Layers[k-1].Neurons[m].LastOutputValue * 2 * LearningRate; //Update weight Layers[k].Neurons[l].IncomingConnections[m].UpdateWeight(-grad); } } } } } } public double[] Calculate(double[] input) { if (input.Length != Layers[0].Neurons.Count) throw new ArgumentException("Expected input of length: " + Layers[0].Neurons.Count + "| got: " + input.Length); //push values onto input connections for (int i = 0; i < input.Length; i++) { if (!(Layers[0].Neurons[i] is InputNeuron inputNeuron)) throw new Exception("Other neurons than InputNeurons were found in input layer"); inputNeuron.OutputtingValue = input[i]; } //propagate values forward foreach (Layer l in Layers) { foreach (INeuron n in l.Neurons) { //Calculate output of given neuron... double currVal = n.CalculateOutput(); //... and then push that output value to all of Outcoming connection of this neuron n.PushToOutput(currVal); } } double[] result = new double[Layers.Last().Neurons.Count]; //pack values from last layer for (int i = 0; i < Layers.Last().Neurons.Count; i++) { result[i] = Layers.Last().Neurons[i].CalculateOutput(); } return result; } //Connects each layer with next one private void ReconnectNetwork() { for (int backLayer = 0; backLayer < Layers.Count - 1; backLayer++) { foreach (INeuron back in Layers[backLayer].Neurons) { foreach (INeuron front in Layers[backLayer + 1].Neurons) { Connection c = new Connection(back, front, rnd.NextDouble() * (0.5 + 0.5) - 0.5); back.OutcomingConnections.Add(c); front.IncomingConnections.Add(c); } } } } public string Dump() { string result = "Weights:"; for (int i = 0; i < Layers.Count; i++) { result += "Layer#" + i + "\n"; for (int j = 0; j < Layers[i].Neurons.Count; j++) { result += "Neuron#" + j; for (int k = 0; k < Layers[i].Neurons[j].OutcomingConnections.Count; k++) { result += "|" + Layers[i].Neurons[j].OutcomingConnections[k].Weight + "|"; } result += "\n"; } } return result; } } }<file_sep>namespace softsets { public static class Loader { } }<file_sep>using System.Collections.Generic; namespace ML.Lib.Fuzzy { public class SugenoInput { public string Label; public Dictionary<string, double> values; public SugenoInput(string label) { Label = label; values = new Dictionary<string, double>(); } public SugenoInput(string label, Dictionary<string, double> values) { Label = label; this.values = new Dictionary<string, double>(values); } } }<file_sep>using System; using System.IO; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ML.Lib.Neuron { [TestClass] public class NeuralTests { [TestMethod] public void ConstructorTest() { int[] layerSizes = new int[] { 10, 4, 4, 2 }; SimpleNetwork net = new SimpleNetwork(layerSizes); //Check if input connections were connected correctly //And check if first layer has correct amount of Outcoming connections foreach (INeuron n in net.Layers[0].Neurons) { Assert.AreEqual(layerSizes[1], n.OutcomingConnections.Count); } //Check amount of neurons in each hidden layer and in output layer Assert.AreEqual(layerSizes[0], net.Layers[0].Neurons.Count); Assert.AreEqual(layerSizes[1], net.Layers[1].Neurons.Count); Assert.AreEqual(layerSizes[2], net.Layers[2].Neurons.Count); //Check amount of connections for (int i = 1; i < layerSizes.Length - 1; i++) { foreach (INeuron n in net.Layers[i].Neurons) { Assert.AreEqual(layerSizes[i - 1], n.IncomingConnections.Count); Assert.AreEqual(layerSizes[i + 1], n.OutcomingConnections.Count); } } //Check connections to the last layer foreach (INeuron n in net.Layers.Last().Neurons) { Assert.AreEqual(layerSizes[layerSizes.Length - 2], n.IncomingConnections.Count); } } [TestMethod] public void TestCalculate() { int[] layerSizes = new int[] { 1,1,1 }; SimpleNetwork net = new SimpleNetwork(layerSizes); net.Layers[0].Neurons[0].OutcomingConnections[0].Weight = 1; double[] output = net.Calculate(new double[] { 1.0 }); Assert.AreEqual(0.675, output[0], 0.01); } [TestMethod] public void TestMassCalculate() { int[] layerSizes = new int[] { 4, 4, 4, 3 }; SimpleNetwork net = new SimpleNetwork(layerSizes); string[] lines = File.ReadAllLines("Resources/irisDataset.csv"); double[][] results = new double[lines.Length - 1][]; for (int i = 1; i < lines.Length; i++) { string[] tokens = lines[i].Split("|"); results[i - 1] = new double[4]; results[i - 1][0] = Convert.ToDouble(tokens[0]); results[i - 1][1] = Convert.ToDouble(tokens[1]); results[i - 1][2] = Convert.ToDouble(tokens[2]); } foreach (double[] res in results) { double[] output = net.Calculate(res); } } [TestMethod] public void TestTrain() { int[] layerSizes = new int[] { 4, 10, 3 }; SimpleNetwork net = new SimpleNetwork(layerSizes); string[] lines = File.ReadAllLines("Resources/irisDataset.csv"); double[][] results = new double[lines.Length - 1][]; double[][] expectedValues = new double[lines.Length - 1][]; for (int i = 1; i < lines.Length; i++) { string[] tokens = lines[i].Split("|"); results[i - 1] = new double[4]; expectedValues[i - 1] = new double[3]; results[i - 1][0] = Convert.ToDouble(tokens[0]); results[i - 1][1] = Convert.ToDouble(tokens[1]); results[i - 1][2] = Convert.ToDouble(tokens[2]); results[i - 1][3] = Convert.ToDouble(tokens[3]); expectedValues[i - 1][0] = Convert.ToDouble(tokens[4]); expectedValues[i - 1][1] = Convert.ToDouble(tokens[5]); expectedValues[i - 1][2] = Convert.ToDouble(tokens[6]); } net.Train(results, expectedValues, 1000); int s = 0; foreach (double[] res in results) { double[] output = net.Calculate(res); Console.WriteLine("Sample #" + s + "|setosa prob.: " + output[0] + "|versicolor prob.: " + output[1] + "|virginica prob.:" + output[2]); s++; } Console.WriteLine(net.Dump()); } } }<file_sep>namespace ML.Lib.Neuron { public interface IConnection { INeuron To {get;} INeuron From {get;} double Weight {get;set;} double PreviousWeight{get;} double Output {get;set;} void UpdateWeight(double delta); } }<file_sep>using System.IO; using System.Collections.Generic; using System; using ML.Lib; namespace task1 { public class Data { double[][] rawData; public void Load(string path, string delim) { string[] lines = File.ReadAllLines(path); rawData = new double[lines.Length][]; for(int i = 0; i < lines.Length; i++) { string[] tokens = lines[i].Split(delim); double[] buff = new double[tokens.Length]; for(int j = 0; j < tokens.Length; j++) { buff[j] = Convert.ToDouble(tokens[j]); } rawData[i] = buff; } } public void Save(string path) { using(StreamWriter writer = new StreamWriter(File.OpenWrite(path))) { foreach(double[] arr in rawData) { string currentLine = ""; foreach(double d in arr) { currentLine += d + "|"; } writer.WriteLine(currentLine); } } } public void Shuffle() { Shuffler.Shuffle(rawData); } //Normalizes whole data array column wise public void Normalize() { for(int i = 0; i < rawData[0].Length; i++) { rawData.SetColumn(Normalizator.Normalize(rawData.GetColumn(i),0.0,1.0), i); } } } } <file_sep>namespace ML.Lib.Neuron { public class Connection : IConnection { private INeuron from; private INeuron to; public INeuron To { get { return to; } } public INeuron From { get { return from; } } public double Weight { get; set; } public double Output { get; set; } public double PreviousWeight { get; set; } public Connection() { } public Connection(INeuron from, INeuron to, double Weight) { this.from = from; this.to = to; this.Weight = Weight; } public void UpdateWeight(double delta) { PreviousWeight = Weight; Weight += delta; } } } <file_sep>using System; namespace ML.Lib.Fuzzy { public class TriangleFuzzifier : IFuzzifier { public string Label { get; set; } private double a, b, c; public TriangleFuzzifier(double a, double b, double c, string Label) { this.a = a; this.b = b; this.c = c; this.Label = Label; } public double Fuzzify(double x) { if ((a < x) && (x <= b)) return (x - a) / (b - a); if ((b < x) && (x < c)) return (c - x) / (c - b); return 0; } } }<file_sep>using System.Collections.Generic; namespace ML.Lib.Neuron { public class SimpleNeuron : INeuron { public IActivationFunction ActivationFunction { get; set; } public IInputFunction<List<IConnection>> InputFunction { get; set; } public List<IConnection> IncomingConnections { get; set; } public List<IConnection> OutcomingConnections { get; set; } public double LastOutputValue {get;set;} public double LastInputValue {get;set;} public double PreviousPartialDerivate { get; set; } public SimpleNeuron() { ActivationFunction = new SigmoidActivationFunction(); InputFunction = new WeightedSumInputFunction(); IncomingConnections = new List<IConnection>(); OutcomingConnections = new List<IConnection>(); } //Calculates output of this neuron public double CalculateOutput() { LastInputValue = InputFunction.Perform(IncomingConnections); LastOutputValue = ActivationFunction.Perform(LastInputValue); return LastOutputValue; } //Pushes value d to Output property of Outcoming Connections public void PushToOutput(double d) { foreach (IConnection output in OutcomingConnections) { output.Output = d; } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; namespace NeuralNetwork { public class Network { static double LearningRate = 0.01; internal List<Layer> Layers; internal double[][] ExpectedResult; double[][] differences; public ITestStrategy testStrategy; public bool TestHaltEnabled { get; set; } public bool TestingEnabled { get; set; } public Network(int numInputNeurons, int[] hiddenLayerSizes , int numOutputNeurons, bool testHaltEnabled = false, bool testingEnabled = true, string path = null) { Console.WriteLine("\n Building neural network..."); if (numInputNeurons < 1 || hiddenLayerSizes.Length < 1 || numOutputNeurons < 1) throw new Exception("Incorrect Network Parameters"); this.testStrategy = new MeanErrorTest(this); this.TestHaltEnabled = testHaltEnabled; this.TestingEnabled = testingEnabled; Layers = new List<Layer>(); AddFirstLayer(numInputNeurons); for (int i = 0; i < hiddenLayerSizes.Length; i++) AddNextLayer(new Layer(hiddenLayerSizes[i])); AddNextLayer(new Layer(numOutputNeurons)); differences = new double[Layers.Count][]; for (int i = 1; i < Layers.Count; i++) differences[i] = new double[Layers[i].Neurons.Count]; if (File.Exists(path)) { Console.WriteLine(" Loading weights..."); string[] lines = File.ReadAllLines(path); if (lines.Length != Synapse.SynapsesCount) Console.WriteLine(" Incorrect input file."); else LoadWeights(lines); } } private void AddFirstLayer(int inputneuronscount) { Layer inputlayer = new Layer(inputneuronscount); foreach (Neuron neuron in inputlayer.Neurons) neuron.AddInputSynapse(0); Layers.Add(inputlayer); } private void AddNextLayer(Layer newlayer) { Layer lastlayer = Layers[Layers.Count - 1]; lastlayer.ConnectLayers(newlayer); Layers.Add(newlayer); } public void PushInputValues(double[] inputs) { if (inputs.Length != Layers[0].Neurons.Count) throw new Exception("Incorrect Input Size"); for (int i = 0; i < inputs.Length; i++) Layers[0].Neurons[i].PushValueOnInput(inputs[i]); } public void PushExpectedValues(double[][] expectedvalues) { if (expectedvalues[0].Length != Layers[Layers.Count - 1].Neurons.Count) throw new Exception("Incorrect Expected Output Size"); ExpectedResult = expectedvalues; } public List<double> GetOutput() { List<double> output = new List<double>(); for (int i = 0; i < Layers.Count; i++) Layers[i].CalculateOutputOnLayer(); foreach (Neuron neuron in Layers[Layers.Count - 1].Neurons) output.Add(neuron.OutputValue); return output; } /// <summary> /// Trains network with given data /// </summary> /// <param name="data"> /// [0] -> Input Data to be evaluated /// [1] -> Expected Output Data /// [2] -> Test Input Data /// [3] -> Test Output Data</param> /// <param name="epochCount"></param> public void Train(double[][][] data, int epochCount) { double[][] inputs = data[0], expectedOutputs = data[1]; double[][] testInputs = data[2], testOutputs = data[3]; PushExpectedValues(expectedOutputs); Console.WriteLine(" Training neural network..."); for (int i = 0; i < epochCount; i++) { List<double> outputs = new List<double>(); for (int j = 0; j < inputs.Length; j++) { PushInputValues(inputs[j]); outputs = GetOutput(); ChangeWeights(outputs, j); } if (TestingEnabled == true) { testStrategy.Test(testInputs, testOutputs); if (testStrategy.CheckHalt() && TestHaltEnabled == true) break; } } SaveWeights(@"weights.txt"); } public void RandomizeWeights() { foreach (Layer l in Layers) { l.RandomizeWeights(); } } private void CalculateDifferences(List<double> outputs, int row) { for (int i = 0; i < Layers[Layers.Count - 1].Neurons.Count; i++) differences[Layers.Count - 1][i] = (ExpectedResult[row][i] - outputs[i]) * Functions.BipolarDifferential(Layers[Layers.Count - 1].Neurons[i].InputValue); for (int k = Layers.Count - 2; k > 0; k--) for (int i = 0; i < Layers[k].Neurons.Count; i++) { differences[k][i] = 0; for (int j = 0; j < Layers[k + 1].Neurons.Count; j++) differences[k][i] += differences[k + 1][j] * Layers[k + 1].Neurons[j].Inputs[i].Weight; differences[k][i] *= Functions.BipolarDifferential(Layers[k].Neurons[i].InputValue); } } private void ChangeWeights(List<double> outputs, int row) { CalculateDifferences(outputs, row); for (int k = Layers.Count - 1; k > 0; k--) for (int i = 0; i < Layers[k].Neurons.Count; i++) for (int j = 0; j < Layers[k - 1].Neurons.Count; j++) Layers[k].Neurons[i].Inputs[j].Weight += LearningRate * 2 * differences[k][i] * Layers[k - 1].Neurons[j].OutputValue; } public void SaveWeights(string path) { List<string> tmp = ReadWeights(); File.WriteAllLines(path, tmp); } public void LoadWeights(string[] lines) { try { int i = 0; foreach (Layer layer in Layers) foreach (Neuron neuron in layer.Neurons) foreach (Synapse synapse in neuron.Inputs) synapse.Weight = Double.Parse(lines[i++]); } catch (Exception e) { Console.WriteLine(" Incorrect input file"); } } private List<string> ReadWeights() { List<string> tmp = new List<string>(); foreach (Layer layer in Layers) foreach (Neuron neuron in layer.Neurons) foreach (Synapse synapse in neuron.Inputs) tmp.Add(synapse.Weight.ToString()); return tmp; } } }<file_sep>using System; namespace ML.Lib { public struct Point3D { public double x; public double y; public double z; public Point3D(double nx, double ny, double nz) { x = nx; y = ny; z = nz; } //Calculates cartesian distance public static double Distance(Point3D a, Point3D b) { return Math.Sqrt(Math.Pow(b.x - a.x, 2) + Math.Pow(b.y - a.y, 2) + Math.Pow(b.z - a.z, 2)); } public static Point3D operator +(Point3D lh) { return lh; } public static Point3D operator -(Point3D lh) { return new Point3D(-lh.x, -lh.y, -lh.z); } public static Point3D operator +(Point3D lh, Point3D rh) { return new Point3D(lh.x + rh.x, lh.y + rh.y, lh.z + rh.z); } public static Point3D operator -(Point3D lh, Point3D rh) { return lh + (-rh); } public override string ToString() { return x.ToString() + " " + y.ToString(); } } }<file_sep>using System; using System.Collections.Generic; namespace ML.Lib.Neuron { //Holds list of neurons public class Layer { public List<INeuron> Neurons{get;set;} public Layer() { Neurons = new List<INeuron>(); } } }<file_sep>using System.Linq; using System.Collections.Generic; namespace ML.Lib.Neuron { public class WeightedSumInputFunction : IInputFunction<List<IConnection>> { public double Perform(List<IConnection> input) { return input.Select(x => x.Weight * x.Output).Sum(); } } } <file_sep>using System; using ML.Lib.Classification; using System.IO; using System.Collections.Generic; namespace KNN { class Program { static void Main(string[] args) { List<ClassifiedObject<double>> objects = new List<ClassifiedObject<double>>(); string[] lines = File.ReadAllLines("data1.txt"); foreach(string s in lines) { string[] tokens = s.Split(" "); ClassifiedObject<double> o = new ClassifiedObject<double>(); o.Classification = tokens[0]; for(int i = 1; i < tokens.Length; i++) { o.Properties.Add(Convert.ToDouble(tokens[i])); } objects.Add(o); } ClassifiedObject<double> inputObj = new ClassifiedObject<double>(); inputObj.Classification = "None"; inputObj.Properties.Add(4.5); inputObj.Properties.Add(4.5); Classifier c = new Classifier(); c.Classify(inputObj, objects, 4); Console.WriteLine(inputObj.Classification); } } } <file_sep>using System; using System.IO; using ML.Lib.Neuron; namespace NeuralDemo { class Program { static void Main(string[] args) { int[] layerSizes = new int[] { 4, 10, 3 }; SimpleNetwork net = new SimpleNetwork(layerSizes); string[] lines = File.ReadAllLines("Resources/irisDataset.csv"); double[][] results = new double[lines.Length - 1][]; double[][] expectedValues = new double[lines.Length - 1][]; for (int i = 1; i < lines.Length; i++) { string[] tokens = lines[i].Split("|"); results[i - 1] = new double[4]; expectedValues[i - 1] = new double[3]; results[i - 1][0] = Convert.ToDouble(tokens[0]); results[i - 1][1] = Convert.ToDouble(tokens[1]); results[i - 1][2] = Convert.ToDouble(tokens[2]); results[i - 1][3] = Convert.ToDouble(tokens[3]); expectedValues[i - 1][0] = Convert.ToDouble(tokens[4]); expectedValues[i - 1][1] = Convert.ToDouble(tokens[5]); expectedValues[i - 1][2] = Convert.ToDouble(tokens[6]); } net.Train(results, expectedValues, 1000); int s = 0; foreach (double[] res in results) { double[] output = net.Calculate(res); Console.WriteLine("Sample #" + s + "|setosa: " + output[0] + "|versicolor: " + output[1] + "|virginica:" + output[2]); s++; } Console.WriteLine(net.Dump()); } } } <file_sep>using System.Collections.Generic; using System.Linq; using ML.Lib; namespace BayesClassifier { public class Classifier { List<ClassifiedObject> _currentDataset; //Raw data Dictionary<string, List<ClassifiedObject>> _classes = new Dictionary<string, List<ClassifiedObject>>(); //Segragated data by Class List<List<string>> _possibleValues = new List<List<string>>(); //Contains list of unique values in given column public void LoadDataset(List<ClassifiedObject> input, int props) //Loads and enumerates given dataset { _currentDataset = new List<ClassifiedObject>(input); for (int i = 0; i < props; i++) { _possibleValues.Add(new List<string>()); } foreach (ClassifiedObject o in input) { if (!_classes.ContainsKey(o.Classification)) { _classes.Add(o.Classification, new List<ClassifiedObject>() { o }); } else { _classes[o.Classification].Add(o); } for (int i = 0; i < o.Properties.Count; i++) //For each of current row-column { if (!_possibleValues[i].Contains(o.Properties[i])) _possibleValues[i].Add(o.Properties[i]); } } } public void Classify(ClassifiedObject input, double probMod = 0) { double[][] probabilities = new double[_classes.Count][]; double[] results = new double[_classes.Count]; for(int i = 0; i < results.Length; i++) results[i] = (double)_classes.ElementAt(i).Value.Count / (double)_currentDataset.Count; //Probability of being in _classes[i] - class for (int i = 0; i < probabilities.Length; i++) { probabilities[i] = new double[input.Properties.Count]; //All properties + probability of being in a class } for (int i = 0; i < _classes.Count; i++) //Chooses class { for (int j = 0; j < input.Properties.Count; j++) //Chooses property COLUMN in given class { //add all cases in class[i] that have property[j] probabilities[i][j] = _classes.ElementAt(i).Value.FindAll(x => x.Properties.Exists(y => y == input.Properties[j])).Count; //TODO: this is awful if (probabilities[i][j] == 0) //solve for zero { probabilities[i][j] = probMod / (_classes.ElementAt(i).Value.Count + probMod * _possibleValues[j].Count); } else { probabilities[i][j] /= _classes.ElementAt(i).Value.Count; } results[i] *= probabilities[i][j]; //product of probabilities of being in _classes[i] class and having property j } } input.Classification = _classes.ElementAt(results.MaxAt()).Key; } } } <file_sep>using System.Collections.Generic; namespace ML.Lib.Neuron { //Common interface for neurons in networks //Neuron is a smallest work unit in a network public interface INeuron { List<IConnection> IncomingConnections { get; set; } List<IConnection> OutcomingConnections { get; set; } IActivationFunction ActivationFunction {get;set;} double PreviousPartialDerivate { get; set; } double LastOutputValue {get;set;} double LastInputValue {get;set;} double CalculateOutput(); void PushToOutput(double d); } }<file_sep>using System; using System.Collections.Generic; namespace ML.Lib.Fuzzy { public class FuzzifierGroup { public List<IFuzzifier> Fuzzifiers; public string GroupName; public FuzzifierGroup(IEnumerable<IFuzzifier> fuzzifiers, string groupName) { GroupName = groupName; Fuzzifiers = new List<IFuzzifier>(fuzzifiers); } public FuzzifierGroup(string groupName) { GroupName = groupName; Fuzzifiers = new List<IFuzzifier>(); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using ML.Lib; namespace iris_classifier { public class Program { static void Main(string[] args) { string[] lines = File.ReadAllLines(args[0]); double[][] data = new double[lines.Length][]; List<string> names = new List<string>(); //species names //Data loading for (int i = 0; i < lines.Length; i++) { string l = lines[i]; //current line string[] tokens = l.Split(","); int dataRowLength = tokens.Length + 2; data[i] = new double[dataRowLength]; //we need to store 2 additional doubles signifying species if (!names.Contains(tokens[tokens.Length - 1])) names.Add(tokens[tokens.Length - 1]); for (int j = 0; j < dataRowLength - 3; j++) { data[i][j] = Convert.ToDouble(tokens[j]); } data[i][tokens.Length - 1 + names.IndexOf(tokens[tokens.Length - 1])] = 1.0; } //Data normalization for (int i = 0; i < data[0].Length - 2; i++) { data.SetColumn(Normalizator.Normalize(data.GetColumn(i), 0.0, 1.0), i); } Shuffler.Shuffle(data); for (int i = 0; i < data.Length; i++) { for (int j = 0; j < data[i].Length; j++) { Console.Write("|" + data[i][j] + "|---"); } Console.WriteLine(); } } } } <file_sep>using System.Collections.Generic; namespace ML.Lib.Fuzzy { public class TruthValueGroup { public string GroupID; public Dictionary<string, double> valuePairs; public TruthValueGroup(string groupID) { GroupID = groupID; valuePairs = new Dictionary<string, double>(); } } }<file_sep>using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace task1 { public class Graphics { public Bitmap UseFilter(double[][] filter, Bitmap input) { BasicMatrixFilter f = new BasicMatrixFilter(filter); return f.Operate(input); } } } <file_sep>using System; namespace ML.Lib.Neuron { public class SigmoidActivationFunction : IActivationFunction { public double Perform(double input) { return 1 / (1 + Math.Exp(-input)); } public double PerformDerivative(double input) { return Perform(input) * (1 - Perform(input)); } } }<file_sep>namespace ML.Lib { public struct PointInt3D { public int x; public int y; public int z; public PointInt3D(int nx, int ny, int nz) { x = nx; y = ny; z = nz; } public static PointInt3D operator +(PointInt3D lh) { return lh; } public static PointInt3D operator -(PointInt3D lh) { return new PointInt3D(-lh.x, -lh.y, -lh.z); } public static PointInt3D operator +(PointInt3D lh, PointInt3D rh) { return new PointInt3D(lh.x + rh.x, lh.y + rh.y, lh.z + rh.z); } public static PointInt3D operator -(PointInt3D lh, PointInt3D rh) { return lh + (-rh); } public override string ToString() { return x.ToString() + " " + y.ToString() + " " + z.ToString(); } } }<file_sep>using System; using System.Drawing; namespace task1 { class Program { static void Main(string[] args) { Graphics graphics = new Graphics(); Bitmap b = graphics.UseFilter( new double[][] { new double[] {-1.0,-1.0,-1.0}, new double[]{-1.0, 8.0,-1.0}, new double[]{-1.0, -1.0,-1.0}, }, new Bitmap("Resources/cat3.jpg")); b.Save("newCat3.jpg"); Data d = new Data(); d.Load("Resources/irisdataset.csv", "|"); d.Shuffle(); d.Normalize(); d.Save("newIris.csv"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.IO; namespace BayesClassifier { class Program { static void Main(string[] args) { //load data file List<ClassifiedObject> objects = new List<ClassifiedObject>(); string[] lines = File.ReadAllLines(args[0]); foreach(string l in lines) { string[] tokens = l.Split(" "); ClassifiedObject o = new ClassifiedObject(); o.Label = tokens[0]; o.Classification = tokens[1]; for(int i = 2; i < tokens.Length; i++) { o.Properties.Add(tokens[i]); } objects.Add(o); } ClassifiedObject objectToClassify = new ClassifiedObject() { Label="XD", Properties={"DESZCZOWO", "CHŁODNO", "MOCNY"}, Classification=null}; Classifier c = new Classifier(); c.LoadDataset(objects, 3); c.Classify(objectToClassify,1.0); Console.WriteLine( "Object: " + objectToClassify.Label + " has been classified as: " + objectToClassify.Classification); } } } <file_sep>To start the program type dotnet run data_file_name search_parameters_file Compiled using dotnetcore 3.1<file_sep>using System; using System.Collections.Generic; namespace ML.Lib.Fuzzy { //Represents node of a tree of rules public class SugenoRule { public Func<double, double, double> ruleMethod = AND; public string[] truthValueGroupIDs; public string[] truthValueIDs; public SugenoRule(Func<double, double, double> ruleMethod, string variableNameA, string valueA, string variableNameB, string valueB) { truthValueIDs = new string[2]; truthValueGroupIDs = new string[2]; truthValueIDs[0] = valueA; truthValueIDs[1] = valueB; truthValueGroupIDs[0] = variableNameA; truthValueGroupIDs[1] = variableNameB; this.ruleMethod = ruleMethod; } public static double AND(double a, double b) { return Math.Min(a,b); } public static double OR(double a, double b) { return Math.Max(a,b); } public static double NOT(double a, double _ = 0) { return 1 - a; } } }
e3655d4108591ad9d29c327e58933e3ada21b9dc
[ "Markdown", "C#" ]
55
C#
Madoxen/SSI
a49631ff97dd655d6d7e6e7501213ad176ea3e0a
efde693be127b2f33bbcbdcb3f951743c7b432aa
refs/heads/main
<file_sep>import React, { Component } from 'react' import axios from 'axios' import User from './User' import SearchUsers from './SearchUsers' export class Users extends Component { state = { users: [] } getUsers = () => { axios.get('https://api.github.com/users') .then(response => { //console.table(response.data) this.setState({ users: response.data }) }) } componentDidMount () { this.getUsers() } searchFromGit = (data) => { if(data !== '') { axios.get("https://api.github.com/search/users?q="+data) .then(response => { this.setState({ users: response.data.items }) }) } } render() { return ( <div> <div className="row"> <div className="col-md-12 mb-2"> <SearchUsers getUserResults={this.searchFromGit} /> </div> </div> <div className="row"> {this.state.users.map( user => ( <div className="col-md-4 my-2" key={user.id}> <User user={user} /> </div> ))} </div> </div> ) } } export default Users
caff37c0d479b32d9fa7db5779471ee4642750b9
[ "JavaScript" ]
1
JavaScript
Zerka1982/git-engine
e74c594b15b666d46cf46d22637e21c98427afbc
79f3ad9286ee7ca075f6d3856e0035f830b1a434
refs/heads/master
<repo_name>nish-d/wav2mp3<file_sep>/README.md # wav2mp3 ## Usage ./convertWav2mp3.bash <input_file_path> <output_file_path> Example: ./convertWav2mp3.bash "C:\Users\Music\a.wav" "C:\Users\Music\b" ./changeSampleRate.bash <input_file_path> <output_file_path> <sample_rate> Example: ./changeSampleRate.bash "C:\Users\Music\a.wav" "C:\Users\Music\b" 16000 <file_sep>/changeSampleRate.bash #!/bin/bash cp $1 $2 $3 ffmpeg -i "$1" -ar $3 "$2.wav"<file_sep>/convertWav2Mp3.bash #!/bin/bash cp $1 $2 ffmpeg -i "$1" -f mp3 "$2.mp3"
4d823e1bed766efc444656c841b7140166452554
[ "Markdown", "Shell" ]
3
Markdown
nish-d/wav2mp3
9e782649e3276fde99db4ec1e82922235ed15916
fcf585e97e5612fac893279471b650de9c2014ed
refs/heads/master
<repo_name>pandeyroshan/Project-Manager<file_sep>/entries/models.py from django.db import models from model_utils import choices from django.utils import timezone # Create your models here. class Entry(models.Model): title = models.CharField(max_length=200) ROSHAN = '<NAME>' BHARAT = '<NAME>' authors = [(ROSHAN, '<NAME>'),(BHARAT, '<NAME>')] author = models.CharField(max_length=20,choices=authors,default=ROSHAN) text= models.TextField() date_posted = models.DateTimeField(default=timezone.now()) def __str__(self): return self.title class Meta: verbose_name_plural = 'Entries' <file_sep>/entries/migrations/0008_auto_20190802_1721.py # Generated by Django 2.1.5 on 2019-08-02 11:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('entries', '0007_auto_20190801_2027'), ] operations = [ migrations.AlterField( model_name='entry', name='author', field=models.CharField(choices=[('RP', '<NAME>'), ('BH', '<NAME>')], default='RP', max_length=2), ), ] <file_sep>/entries/views.py from django.shortcuts import render, redirect from .models import Entry from .forms import EntryForm from django.core.mail import send_mail from django.conf import settings # Create your views here. def index(request): entries = Entry.objects.order_by('-date_posted') ##Entry.objects.all().delete() ## UnComment this to flush the database context = {'entries' : entries} return render(request,'entries/index.html',context) def add(request): if request.method == 'POST': form = EntryForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = EntryForm() context = { 'form' : form } return render(request,'entries/add.html',context) def sendReport(request): LastInsertedData = Entry.objects.all().last() subject = LastInsertedData.title message = LastInsertedData.text+' \n \n \nBY- '+LastInsertedData.author email_from = settings.EMAIL_HOST_USER recipient_list = ['<EMAIL>','<EMAIL>'] send_mail( subject, message, email_from, recipient_list ) entries = Entry.objects.order_by('-date_posted') context = { 'entries' : entries} return render(request,'entries/index.html',context) <file_sep>/entries/urls.py from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('', views.index,name='index'), path('add/',views.add,name='add'), path('sendReport/',views.sendReport,name='sendReport'), ]
4b98949214942486b4d6e64fd7a0551dd986e720
[ "Python" ]
4
Python
pandeyroshan/Project-Manager
022508361116e0686ac00baffe5d2776e5bcb1bf
7a1215a991cab9aca8754b698d0be6cd1c9addd2
refs/heads/master
<file_sep>/* * Copyright (c) 2015 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.demigodsrpg.util.datasection; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.model.Filters; import org.bson.Document; import java.util.*; import java.util.concurrent.TimeUnit; @SuppressWarnings("ResultOfMethodCallIgnored") public abstract class AbstractMongoRegistry<T extends Model> implements Registry<T> { protected final Cache<String, T> REGISTERED_DATA; protected final MongoCollection<Document> COLLECTION; protected final boolean UUID_KEYS; public AbstractMongoRegistry(MongoCollection<Document> collection, int expireMins, boolean uuidKeys) { COLLECTION = collection; if (expireMins > 0) { REGISTERED_DATA = CacheBuilder.newBuilder().concurrencyLevel(4).expireAfterAccess(expireMins, TimeUnit.MINUTES) .build(); } else { REGISTERED_DATA = CacheBuilder.newBuilder().concurrencyLevel(4).build(); } UUID_KEYS = uuidKeys; } public Optional<T> fromKey(String key) { if (!REGISTERED_DATA.asMap().containsKey(key)) { loadFromDb(key); } return Optional.ofNullable(REGISTERED_DATA.asMap().getOrDefault(key, null)); } public T register(T value) { REGISTERED_DATA.put(value.getKey(), value); saveToDb(value.getKey()); return value; } public T put(String key, T value) { REGISTERED_DATA.put(key, value); saveToDb(key); return value; } public void remove(String key) { REGISTERED_DATA.asMap().remove(key); COLLECTION.deleteOne(Filters.eq("key", key)); } public void saveToDb(String key) { Optional<Document> loaded = documentFromDb(key); if (REGISTERED_DATA.asMap().containsKey(key)) { Model model = REGISTERED_DATA.asMap().get(key); if (loaded.isPresent()) { COLLECTION.deleteMany(Filters.eq("key", key)); } Document document = mapToDocument(model.serialize()); document.put("key", key); COLLECTION.insertOne(document); } } @SuppressWarnings("unchecked") public void loadFromDb(String key) { Document document = COLLECTION.find(Filters.eq("key", key)).first(); if (document != null) { REGISTERED_DATA.put(key, fromDataSection(key, new MJsonSection(document))); } } public Optional<Document> documentFromDb(String key) { Document document = COLLECTION.find(Filters.eq("key", key)).first(); if (document != null) { return Optional.of(document); } return Optional.empty(); } @SuppressWarnings("ConstantConditions") public Map<String, T> loadAllFromDb() { MongoCursor<Document> cursor = COLLECTION.find().iterator(); try { while (cursor.hasNext()) { Document document = cursor.next(); String key = document.getString("key"); if (key != null) { try { if (UUID_KEYS) UUID.fromString(key); REGISTERED_DATA.put(key, fromDataSection(key, new MJsonSection(document))); } catch (Exception oops) { oops.printStackTrace(); } } } } finally { cursor.close(); } return REGISTERED_DATA.asMap(); } public void purge() { REGISTERED_DATA.asMap().clear(); COLLECTION.drop(); } @Override public Map<String, T> getRegisteredData() { return REGISTERED_DATA.asMap(); } // -- UTILITY METHODS -- // public static Document mapToDocument(Map<String, Object> map) { Document document = new Document(); for (Map.Entry<String, Object> entry : map.entrySet()) { if (entry.getValue() instanceof Map) { document.put(entry.getKey(), mapToDocument((Map) entry.getValue())); } else { document.put(entry.getKey(), entry.getValue()); } } return document; } public static Map<String, Object> documentToMap(Document document) { Map<String, Object> map = new HashMap<>(); for (Map.Entry<String, Object> entry : document.entrySet()) { if (entry.getValue() instanceof Document) { map.put(entry.getKey(), documentToMap((Document) entry.getValue())); } else { map.put(entry.getKey(), entry.getValue()); } } return map; } } <file_sep>package com.demigodsrpg.util.datasection; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.File; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; /** * Object representing a section of a json file. */ @SuppressWarnings("unchecked") public class FJsonSection extends HashMap<String, Object> implements DataSection { // -- CONSTRUCTORS -- // /** * Default constructor. */ private FJsonSection() { } /** * Constructor accepting default data. * * @param data Default data. */ public FJsonSection(Map<String, Object> data) { if (data != null) { clear(); putAll(data); } else { throw new NullPointerException("Section data cannot be null, is this a valid section?"); } } // -- UTILITY METHODS -- // /** * Save this section to a json file. * * @param dataFile The file to hold the section data. * @return Save success or failure. */ public boolean save(File dataFile) { try { Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); String json = gson.toJson(this, Map.class); PrintWriter writer = new PrintWriter(dataFile); writer.print(json); writer.close(); return true; } catch (Exception oops) { oops.printStackTrace(); } return false; } /** * Save this section to a json file in a pretty format. * * @param dataFile The file to hold the section data. * @return Save success or failure. */ public boolean savePretty(File dataFile) { try { Gson gson = new GsonBuilder().setPrettyPrinting().enableComplexMapKeySerialization().create(); String json = gson.toJson(this, Map.class); PrintWriter writer = new PrintWriter(dataFile); writer.print(json); writer.close(); return true; } catch (Exception oops) { oops.printStackTrace(); } return false; } // -- GETTERS -- // public FJsonSection getSectionNullable(String s) { try { FJsonSection section = new FJsonSection(); section.putAll((Map) get(s)); return section; } catch (Exception ignored) { } return null; } // -- MUTATORS -- // public FJsonSection createSection(String s) { FJsonSection section = new FJsonSection(); put(s, section); return section; } public FJsonSection createSection(String s, Map<String, Object> map) { FJsonSection section = new FJsonSection(); section.putAll(map); put(s, section); return section; } @Override public FJsonSection toFJsonSection() { return this; } @Override public MJsonSection toMJsonSection() { return new MJsonSection(this); } } <file_sep>package me.hqm.privatereserve.command.member; import com.demigodsrpg.command.BaseCommand; import com.demigodsrpg.command.CommandResult; import me.hqm.privatereserve.PrivateReserve; import me.hqm.privatereserve.util.RegionUtil; import org.bukkit.ChatColor; import org.bukkit.command.*; import org.bukkit.entity.Player; public class SpawnCommand extends BaseCommand { @Override protected CommandResult onCommand(CommandSender sender, Command command, String[] args) { if (command.getName().equals("spawn")) { if (sender instanceof ConsoleCommandSender) { return CommandResult.PLAYER_ONLY; } if (PrivateReserve.PLAYER_R.isVisitorOrExpelled(((Player) sender).getUniqueId())) { sender.sendMessage(ChatColor.YELLOW + "Currently you are just a " + ChatColor.GRAY + ChatColor.ITALIC + "visitor" + ChatColor.YELLOW + ", ask for an invite on Discord!"); return CommandResult.QUIET_ERROR; } ((Player) sender).teleport(RegionUtil.spawnLocation()); sender.sendMessage(ChatColor.YELLOW + "Warped to spawn."); } return CommandResult.SUCCESS; } } <file_sep>package me.hqm.privatereserve.runnable; import me.hqm.privatereserve.Setting; import org.bukkit.*; // Based on https://github.com/magnusulf/LongerDays public class TimeRunnable implements Runnable { // The amount of moon phases minus one private final static int MOON_PHASES = 7; public static long DAY_LENGTH_TICKS = 24000; private int counter = 0; @Override public void run() { counter++; for (World w : Bukkit.getServer().getWorlds()) { this.worldChangeTime(w); } } @SuppressWarnings("ConstantConditions") private void worldChangeTime(World world) { // Not all worlds needs to get time changed if (Setting.TIME_MULTIPLIER_WORLDS.contains(world.getName())) { if (world.getGameRuleValue(GameRule.DO_DAYLIGHT_CYCLE)) { // Here the counter is used. // If the multiplier is 3, the time would NOT be set back // one out of three times. Thus making the day three times longer if (counter % getMultiplier(world) != 0) { // Here we actually change the time world.setTime(world.getTime() - 1); // To keep the moon phase in sync, we have to change the time a few times. // We can't change it a whole day (24000 ticks). Because then the moon phase is not changed. for (int i = 0; i < MOON_PHASES; i++) { world.setTime(world.getTime() - 1); } // Because the time was changed slightly in the above code, keeping track of the moon phase. // We have to change it back world.setTime(world.getTime() + MOON_PHASES); } } } } public static int getMultiplier(World world) { long time = world.getTime(); if (isDay(time)) { return Setting.DAYLIGHT_MULTIPLIER; } return Setting.NIGHT_MULTIPLIER; } public static boolean isDay(long time) { return time < (DAY_LENGTH_TICKS / 2); } } <file_sep>package me.hqm.privatereserve.tag; import com.demigodsrpg.chitchat.tag.PlayerTag; import me.hqm.privatereserve.PrivateReserve; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.*; import org.bukkit.entity.Player; public class TrustedTag extends PlayerTag { private TextComponent trusted; public TrustedTag() { trusted = new TextComponent("["); trusted.setColor(ChatColor.DARK_GRAY); TextComponent middle = new TextComponent("T"); middle.setColor(ChatColor.DARK_AQUA); trusted.addExtra(middle); trusted.addExtra("]"); trusted.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Trusted").color(ChatColor.DARK_AQUA).create())); trusted.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/memberhelp TRUSTED")); } @Override public TextComponent getComponentFor(Player player) { if (!PrivateReserve.PLAYER_R.isAlternate(player.getUniqueId()) && PrivateReserve.PLAYER_R.isTrusted(player.getUniqueId())) { return trusted; } return ChatTag.EMPTY; } @Override public String getName() { return "trusted"; } @Override public int getPriority() { return 2; } } <file_sep>package me.hqm.privatereserve.registry.file; import me.hqm.privatereserve.model.RelationalDataModel; import me.hqm.privatereserve.registry.RelationalDataRegistry; public class FRelationalDataRegistry extends AbstractReserveFileRegistry<RelationalDataModel> implements RelationalDataRegistry { public FRelationalDataRegistry() { super(NAME, 0); } } <file_sep>package me.hqm.privatereserve.registry.mongo; import com.demigodsrpg.util.datasection.AbstractMongoRegistry; import com.mongodb.client.MongoDatabase; import me.hqm.privatereserve.model.LockedBlockModel; import me.hqm.privatereserve.registry.LockedBlockRegistry; public class MLockedBlockRegistry extends AbstractMongoRegistry<LockedBlockModel> implements LockedBlockRegistry { public MLockedBlockRegistry(MongoDatabase database) { super(database.getCollection(NAME), 0, true); } } <file_sep>package me.hqm.privatereserve.tag; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.chat.ComponentSerializer; public class ChatTag { public static final TextComponent NEW_LINE = new TextComponent(ComponentSerializer.parse("{text: \"\n\"}")); public static final TextComponent EMPTY = new TextComponent(); public static final AdminTag ADMIN_TAG = new AdminTag(); public static final TrustedTag TRUSTED_TAG = new TrustedTag(); public static final AlternateTag ALTERNATE_TAG = new AlternateTag(); public static final VisitorTag VISITOR_TAG = new VisitorTag(); public static final ReserveChatNameTag NAME_TAG = new ReserveChatNameTag(); } <file_sep>package me.hqm.privatereserve.registry.mongo; import com.demigodsrpg.util.datasection.AbstractMongoRegistry; import com.mongodb.client.MongoDatabase; import me.hqm.privatereserve.model.PlayerModel; import me.hqm.privatereserve.registry.PlayerRegistry; public class MPlayerRegistry extends AbstractMongoRegistry<PlayerModel> implements PlayerRegistry { public MPlayerRegistry(MongoDatabase database) { super(database.getCollection(NAME), 0, true); } } <file_sep>/* * Copyright 2015 Demigods RPG * Copyright 2015 <NAME> * Copyright 2015 <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. */ package me.hqm.privatereserve.registry; import com.demigodsrpg.util.datasection.DataSection; import com.demigodsrpg.util.datasection.Registry; import me.hqm.privatereserve.model.RelationalDataModel; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public interface RelationalDataRegistry extends Registry<RelationalDataModel> { String NAME = "data"; default void put(String row, String column, String value) { put0(row, column, value); } default void put(String row, String column, boolean value) { put0(row, column, value); } default void put(String row, String column, Number value) { put0(row, column, value); } default void put0(String row, String column, Object value) { // Remove the value if it exists already remove(row, column); // Create and save the timed value RelationalDataModel timedData = new RelationalDataModel(); timedData.generateId(); timedData.setDataType(RelationalDataModel.DataType.PERSISTENT); timedData.setRow(row); timedData.setColumn(column); timedData.setValue(value); register(timedData); } /* * Timed value */ default void put(String row, String column, Object value, long time, TimeUnit unit) { // Remove the value if it exists already remove(row, column); // Create and save the timed value RelationalDataModel timedData = new RelationalDataModel(); timedData.generateId(); timedData.setDataType(RelationalDataModel.DataType.TIMED); timedData.setRow(row); timedData.setColumn(column); timedData.setValue(value); timedData.setExpiration(unit, time); register(timedData); } default boolean contains(String row, String column) { return find(row, column) != null; } default Object get(String row, String column) { return find(row, column).getValue(); } default long getExpiration(String row, String column) throws NullPointerException { return find(row, column).getExpiration(); } default RelationalDataModel find(String row, String column) { if (findByRow(row) == null) return null; for (RelationalDataModel data : findByRow(row)) { if (data.getColumn().equals(column)) return data; } return null; } default Set<RelationalDataModel> findByRow(final String row) { return getRegisteredData().values().stream().filter(model -> model.getRow().equals(row)) .collect(Collectors.toSet()); } default void remove(String row, String column) { if (find(row, column) != null) remove(find(row, column).getKey()); } /** * Clears all expired timed value. */ default void clearExpired() { getRegisteredData().values().stream() .filter(model -> RelationalDataModel.DataType.TIMED.equals(model.getDataType()) && model.getExpiration() <= System.currentTimeMillis()).map(RelationalDataModel::getKey). collect(Collectors.toList()).forEach(this::remove); } @Override default RelationalDataModel fromDataSection(String stringKey, DataSection data) { return new RelationalDataModel(stringKey, data); } } <file_sep>package me.hqm.privatereserve.listener; import com.demigodsrpg.chitchat.Chitchat; import me.hqm.privatereserve.PrivateReserve; import me.hqm.privatereserve.model.PlayerModel; import me.hqm.privatereserve.util.RegionUtil; import net.md_5.bungee.api.ChatColor; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.*; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import java.util.Optional; public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.LOWEST) public void onJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (PrivateReserve.PLAYER_R.isVisitor(player.getUniqueId())) { Optional<PlayerModel> maybeThem = PrivateReserve.PLAYER_R.fromName(player.getName()); if (maybeThem.isPresent()) { PrivateReserve.PLAYER_R.remove(maybeThem.get().getKey()); PrivateReserve.PLAYER_R.invite(player, maybeThem.get().getInvitedFrom()); player.teleport(RegionUtil.spawnLocation()); Chitchat.sendTitle(player, 10, 80, 10, ChatColor.YELLOW + "Celebrate!", ChatColor.GREEN + "You were invited! Have fun!"); return; } if (player.hasPermission("privatereserve.admin") || player.isWhitelisted()) { Bukkit.getScheduler().scheduleSyncDelayedTask(PrivateReserve.PLUGIN, new Runnable() { @Override public void run() { PrivateReserve.PLAYER_R.inviteSelf(player); player.kickPlayer(ChatColor.GREEN + "Sorry, you weren't invited yet. Please rejoin."); } }, 20); return; } if (!RegionUtil.visitingContains(player.getLocation())) { try { player.teleport(RegionUtil.visitingLocation()); } catch (NullPointerException oops) { oops.printStackTrace(); } } player.sendMessage(ChatColor.YELLOW + "Currently you are just a " + ChatColor.GRAY + ChatColor.ITALIC + "visitor" + ChatColor.YELLOW + ", ask for an invite on Discord!"); } else { Optional<PlayerModel> maybeThem = PrivateReserve.PLAYER_R.fromPlayer(event.getPlayer()); if (maybeThem.isPresent()) { PlayerModel model = maybeThem.get(); model.setLastKnownName(event.getPlayer().getName()); model.buildNameTag(); } if (RegionUtil.spawnContains(player.getLocation()) || RegionUtil.visitingContains(player.getLocation())) { try { player.teleport(RegionUtil.spawnLocation()); } catch (NullPointerException oops) { oops.printStackTrace(); } } } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerMove(PlayerMoveEvent event) { Player player = event.getPlayer(); if (PrivateReserve.PLAYER_R.isVisitorOrExpelled(player.getUniqueId())) { if (!RegionUtil.visitingContains(event.getTo())) { Chitchat.sendTitle(player, 10, 60, 10, ChatColor.GREEN + "Sorry!", ChatColor.RED + "Only invited members are allowed there."); try { player.teleport(RegionUtil.visitingLocation()); } catch (NullPointerException oops) { oops.printStackTrace(); } } } } } <file_sep>package me.hqm.privatereserve.tag; import com.demigodsrpg.chitchat.tag.PlayerTag; import me.hqm.privatereserve.PrivateReserve; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.*; import org.bukkit.entity.Player; public class AlternateTag extends PlayerTag { public static String DISPLAY_TAG = org.bukkit.ChatColor.DARK_GRAY + "[" + org.bukkit.ChatColor.GRAY + org.bukkit.ChatColor.ITALIC + "A" + org.bukkit.ChatColor.DARK_GRAY + "]"; private TextComponent alternate; public AlternateTag() { alternate = new TextComponent("["); alternate.setColor(ChatColor.DARK_GRAY); TextComponent middle = new TextComponent("A"); middle.setColor(ChatColor.GRAY); middle.setItalic(true); alternate.addExtra(middle); alternate.addExtra("]"); alternate.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Alt Account").color(ChatColor.GRAY).create())); } @Override public TextComponent getComponentFor(Player player) { if (PrivateReserve.PLAYER_R.isAlternate(player.getUniqueId())) { return alternate; } return ChatTag.EMPTY; } @Override public String getName() { return "alternate"; } @Override public int getPriority() { return 2; } } <file_sep>package me.hqm.privatereserve; import com.demigodsrpg.chitchat.util.LibraryHandler; import org.bukkit.plugin.java.JavaPlugin; public class PrivateReservePlugin extends JavaPlugin { // -- LIBRARY HANDLER -- // private static LibraryHandler LIBRARIES; // -- BUKKIT ENABLE/DISABLE METHODS -- // @Override public void onEnable() { // Config getConfig().options().copyDefaults(true); saveConfig(); // Get and load the libraries LIBRARIES = new LibraryHandler(this); // MongoDB if (Setting.MONGODB_PERSISTENCE) { LIBRARIES.addMavenLibrary(LibraryHandler.MAVEN_CENTRAL, Depends.ORG_MONGO, Depends.MONGODB, Depends.MONGODB_VER); } // Enable new PrivateReserve(this); } @Override public void onDisable() { PrivateReserve.RESERVE_CHAT.disable(); } } <file_sep>package me.hqm.privatereserve.registry.file; import me.hqm.privatereserve.model.PlayerModel; import me.hqm.privatereserve.registry.PlayerRegistry; public class FPlayerRegistry extends AbstractReserveFileRegistry<PlayerModel> implements PlayerRegistry { public FPlayerRegistry() { super(NAME, 0); } } <file_sep>package me.hqm.privatereserve.tag; import com.demigodsrpg.chitchat.tag.DefaultPlayerTag; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.*; public class AdminTag extends DefaultPlayerTag { public AdminTag() { super("admin-tag", "reservechat.admin", admin(), 5); } static TextComponent admin() { TextComponent admin = new TextComponent("["); admin.setColor(ChatColor.DARK_GRAY); TextComponent middle = new TextComponent("A"); middle.setColor(ChatColor.DARK_RED); admin.addExtra(middle); admin.addExtra("]"); admin.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Visiting").color(ChatColor.GREEN).create())); admin.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Administrator"). color(net.md_5.bungee.api.ChatColor.DARK_RED).create())); return admin; } } <file_sep>package com.demigodsrpg.util.datasection; import java.util.Map; import java.util.Optional; public interface Registry<T extends Model> { Optional<T> fromKey(String key); T register(T value); T put(String key, T value); void remove(String key); @Deprecated void saveToDb(String key); void loadFromDb(String key); Map<String, T> loadAllFromDb(); void purge(); T fromDataSection(String key, DataSection section); @Deprecated Map<String, T> getRegisteredData(); }
dc73625005dee224a55d7d0d392b9b36142729a0
[ "Java" ]
16
Java
HmmmQuestionMark/PrivateReserve
e449ce02c9f05adaef54bf4ecedfafd9c7269eb9
f64de389562462e404aa7b3e90cca9955035914e
refs/heads/main
<repo_name>slimcoin-project/slm-pywallet<file_sep>/README.md # slm-pywallet Pywallet script for Slimcoin and helper script to check addresses in a block explorer. ## pywallet Requires Python 2. Uses the following version: https://github.com/joric/pywallet/blob/master/pywallet.py Licenses: See pywallet.py. Pywallet code was released into the public domain. **Usage** ```python2 pywallet.py [options] Options: --version show program's version number and exit -h, --help show this help message and exit --dumpwallet dump wallet in json format --importprivkey=KEY import private key from vanitygen --datadir=DATADIR wallet directory (defaults to bitcoin default) --testnet use testnet subdirectory and address type --password=<PASSWORD> password for the encrypted wallet Dependencies: bsddb (python 2.7.2 msi includes bsddb by default) Links: http://www.python.org/ftp/python/2.7.2/python-2.7.2.msi ``` ## cryptoidlookup.py Allows to look up addresses at the Cryptoid explorer. Prints out addresses for which transactions are found. Uses some code snippets from pypeerassets (https://github.com/PeerAssets/pypeerassets). License: BSD 3-clause (see LICENSE file) Requires Python 3. Usage: ``` python3 cryptoidlookup.py [options] file Options: -v Verbose mode (prints transactions and addresses without transactions) -s start_position Allows to start at a certain position of the address list (e.g. if the block explorer stops responding) ``` <file_sep>/cryptoidlookup.py from typing import cast, Union import json, time, sys from urllib.request import Request, urlopen from http.client import HTTPResponse """This script looks up to cryptoid to look which addresses of a pywallet dump have transactions in it. Requires python 3. Without options it just print out addresses it finds transactions for. Uses some code snippets of pypeerassets (BSD 3-Clause License) Source: https://github.com/PeerAssets/pypeerassets (c) PeerAssets project 2019 Options: -v - Verbose (shows transactions)""" COIN="slm" EXPLORER_URL = 'https://chainz.cryptoid.info/explorer/' EXPLORER_API = 'https://chainz.cryptoid.info/{}/api.dws'.format(COIN) def get_url(url: str) -> Union[dict, int, float, str]: '''Perform a GET request for the url and return a dictionary parsed from the JSON response.''' request = Request(url, headers={"User-Agent": "pywalletlookup"}) response = cast(HTTPResponse, urlopen(request)) if response.status != 200: raise Exception(response.reason) return json.loads(response.read().decode()) def listtransactions(address: str) -> list: query = 'address.summary.dws?coin={net}&id={addr}'.format( net=COIN, addr=address, ) response = cast(dict, get_url(EXPLORER_URL + query)) return [tx[1].lower() for tx in response["tx"]] def getdump(filename: str) -> dict: with open(filename, "r") as f: walletdump = json.load(f) return walletdump def main(args): verbose = True if "-v" in args else False start = args[args.index("-s") + 1] if "-s" in args else 0 wdump = getdump(args[1]) try: addresslist = wdump["keys"][start:] except KeyError: print("No addresses found in this wallet dump.") return for item in addresslist: address = item.get("addr") if verbose: print("Looking up address:", address) try: txes = listtransactions(address) except KeyError: txes = {} if len(txes) == 0: if verbose: print("Address", address, "without transactions.") else: if verbose: print("Address with {} transactions: {}".format(len(txes), address)) print(txes) else: print(address) time.sleep(10) if __name__ == "__main__": main(sys.argv)
7b2624de93d67460109ca76eaf04058ab4e2f077
[ "Markdown", "Python" ]
2
Markdown
slimcoin-project/slm-pywallet
b7dc0d3ad9dde4fd1781ff4ff1e13763d2a582a1
0f1d59519d141bfa3da2dfac3393037d5c0c1bb0
refs/heads/master
<repo_name>Pitarou/coach-a-aptitude-test<file_sep>/SortSelectionTest.java import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Arrays; /** * Test behaviour of class SortSelection. * * @author <NAME> * @version 2014-07-10 */ public class SortSelectionTest { private SortSelection ss; int[] array1; int[] array3; int[] array4; int[] arrayRepeats; int[] arrayExampleGivenInSpecification; /** * Default constructor for test class SortSelectionTest */ public SortSelectionTest() { } /** * Sets up the test fixture. * * Called before every test case method. */ @Before public void classSetUp() { this.ss = new SortSelection(); this.array1 = new int[]{1}; this.array3 = new int[]{1,2,3}; this.array4 = new int[]{4, 3, 2, 1}; this.arrayRepeats = new int[] {1,2,1,2,1,2,1}; this.arrayExampleGivenInSpecification = new int[] {1, 4, 2, 3, 5, 8, 6, 9, 8, 0}; } /** * Tears down the test fixture. * * Called after every test case method. */ @After public void tearDown() { } @Test public void arrayWithOneElement() { assertEquals(this.ss.select(array1, 0), 1); } @Test public void arrayAlreadySorted() { assertEquals(this.ss.select(array3, 0), 3); assertEquals(this.ss.select(array3, 1), 2); assertEquals(this.ss.select(array3, 2), 1); } @Test public void arrayNotAlreadySorted() { assertEquals(this.ss.select(array4, 0), 4); assertEquals(this.ss.select(array4, 3), 1); } @Test public void arrayHasRepeatedElements() { assertEquals(this.ss.select(arrayRepeats, 2), 2); assertEquals(this.ss.select(arrayRepeats, 3), 1); } @Test public void checkThatOriginalArrayDoesNotChange() { this.ss.select(array4, 0); assertTrue(Arrays.equals(array4, new int[] {4, 3, 2, 1})); this.ss.select(array3, 0); assertTrue(Arrays.equals(array3, new int[] {1, 2, 3})); } @Test public void rankLessThanZero() { assertEquals(this.ss.select(array3, -1), 3); } @Test public void rankTooHigh() { assertEquals(this.ss.select(array3, 10), 1); } @Test public void exampleGivenInSpecification() { assertEquals(this.ss.select(arrayExampleGivenInSpecification, 2), 8); } } <file_sep>/SortSelection.java /** * Implementation of IntegerSelection that uses Java's Array sort. * * @author <NAME> * @version 2014-07-10 */ import java.util.Arrays; public class SortSelection implements IntegerSelection { public int select(int[] array, int rank) { if (rank < 0) { rank = 0; } else if (rank >= array.length) { rank = array.length - 1; } int[] a = array.clone(); Arrays.sort(a); return a[a.length - 1 - rank]; } } <file_sep>/README.md Coach A Java Programming Aptitude Test ====================================== <NAME> 2014-10-07 Requirements ============ > Given a non-empty array of integers please return Nth biggest integer in that array. > > please implement the following interface: > > public interface IntegerSelection { > int select(int[] array, int rank); > //rank = 0 is biggest integer, 1 is second biggest and so on. > } > > Example: > input: > SELECT RANK=2 FROM [1, 4, 2, 3, 5, 8, 6, 9, 8, 0] > output: > 8 Implementation Notes ==================== What are all those extra files? ------------------------------- In the `/doc` directory you can find the Javadoc documentation. The `.ctxt` and `package.bluej` files are used by my IDE. You can ignore them. Error handling -------------- The specification clearly states that the list will be non-empty, so I have made no attempt to handle empty lists. The type signature for the interface suggests that my code should not raise exceptions. I have therefore decided to handle out-of-range values by raising or lowering them to the nearest acceptable value. E.g. if *rank* is -10, it is treated as 0. If *rank* is 10 and *array* is {1, 3, 2}, *rank* is treated as 2 (*array.length - 1*) Algorithm --------- * time complexity: O(*n* log *n*) * space complexity: O(*n*) where *n* is the size of the array. This is "the simplest solution that can possibly work". My code: - copies the array (so that the original array will not be affected) - sorts the copied array, from lowest to highest - returns the element at index *array.length - rank - 1* This is *not* the most efficient algorithm, and it would not be suitable for performance-sensitive code.
166b43fe1b8b475c865619dda74cffbc07a77b32
[ "Markdown", "Java" ]
3
Java
Pitarou/coach-a-aptitude-test
92f610348c76c6e5e76b3486a779b9c25d0b6145
6616e2dda302060f6cfbc45bcfa16768125db342
refs/heads/main
<file_sep>document.querySelector( "header" ).innerHTML = `<h1 class="header__h1">Headerやで</h1>`;
4a46f04dc029bc7ed6bffe3b16049627fcbd45ca
[ "JavaScript" ]
1
JavaScript
Hoshitter1/component-end
f790e172d57c31260bdff6e570db0adba0417aba
64ea72a14fef5f33862724ba8cd44d220b52c328
refs/heads/master
<repo_name>bertair7/cpe102project<file_sep>/entities.py import point import worldmodel import actions import image_store import random class Entity(object): def __init__(self, name, imgs): self.name = name self.imgs = imgs self.current_img = 0 def get_images(self): return self.imgs def get_image(self): return self.imgs[self.current_img] def get_name(self): return self.name class InGrid(Entity): def __init__(self, name, position, imgs): super(InGrid, self).__init__(name, imgs) self.position = position def set_position(self, point): self.position = point def get_position(self): return self.position class NonBackground(InGrid): def __init__(self, name, position, imgs): super(NonBackground, self).__init__(name, position, imgs) self.pending_actions = [] def remove_pending_action(self, action): if hasattr(self, "pending_actions"): self.pending_actions.remove(action) def add_pending_action(self, action): if hasattr(self, "pending_actions"): self.pending_actions.append(action) def get_pending_actions(self): if hasattr(self, "pending_actions"): return self.pending_actions else: return [] def clear_pending_actions(self): if hasattr(self, "pending_actions"): self.pending_actions = [] def next_image(self): self.current_img = (self.current_img + 1) % len(self.imgs) class Moving(NonBackground): def __init__(self, name, position, rate, imgs): super(Moving, self).__init__(name, position, imgs) self.rate = rate def next_position(self, world, dest_pt): horiz = sign(dest_pt.x - self.position.x) new_pt = point.Point(self.position.x + horiz, self.position.y) if horiz == 0 or world.is_occupied(new_pt): vert = sign(dest_pt.y - self.position.y) new_pt = point.Point(self.position.x, self.position.y + vert) if vert == 0 or world.is_occupied(new_pt): new_pt = point.Point(self.position.x, self.position.y) return new_pt def get_rate(self): return self.rate class Miner(Moving): def __init__(self, name, resource_limit, position, rate, imgs, animation_rate): super(Miner, self).__init__(name, position, rate, imgs) self.resource_limit = resource_limit self.animation_rate = animation_rate def set_resource_count(self, n): self.resource_count = n def get_resource_count(self): return self.resource_count def get_resource_limit(self): return self.resource_limit def get_animation_rate(self): return self.animation_rate def _schedule(self, world, ticks, i_store): actions.schedule_action(world, self, actions.create_miner_action(world, self, i_store), ticks + self.get_rate()) actions.schedule_animation(world, self) class Background(Entity): def next_image(self): self.current_img = (self.current_img + 1) % len(self.imgs) class MinerNotFull(Miner): def __init__(self, name, resource_limit, position, rate, imgs, animation_rate): super(MinerNotFull, self).__init__(name, resource_limit, position, rate, imgs, animation_rate) self.resource_count = 0 def miner_to_ore(self, world, ore): entity_pt = self.get_position() if not ore: return ([entity_pt], False) ore_pt = ore.get_position() if adjacent(entity_pt, ore_pt): self.set_resource_count(1 + self.get_resource_count()) actions.remove_entity(world, ore) return ([ore_pt], True) else: new_pt = self.next_position(world, ore_pt) return (world.move_entity(self, new_pt), False) class MinerFull(Miner): def __init__(self, name, resource_limit, position, rate, imgs, animation_rate): super(MinerFull, self).__init__(name, resource_limit, position, rate, imgs, animation_rate) self.resource_count = resource_limit def miner_to_smith(self, world, smith): entity_pt = self.get_position() if not smith: return ([entity_pt], False) smith_pt = smith.get_position() if adjacent(entity_pt, smith_pt): smith.set_resource_count(smith.get_resource_count() + self.get_resource_count()) self.set_resource_count(0) return ([], True) else: new_pt = self.next_position(world, smith_pt) return (world.move_entity(self, new_pt), False) class Vein(Moving): def __init__(self, name, rate, position, imgs, resource_distance=1): super(Vein, self).__init__(name, position, rate, imgs) self.resource_distance = resource_distance def get_resource_distance(self): return self.resource_distance def _create_ore(self, world, name, pt, ticks, i_store): ore = Ore(name, pt, image_store.get_images(i_store, 'ore'), random.randint(actions.ORE_CORRUPT_MIN, actions.ORE_CORRUPT_MAX)) ore._schedule(world, ticks, i_store) return ore def _schedule(self, world, ticks, i_store): actions.schedule_action(world, self, actions.create_vein_action(world, self, i_store), ticks + self.get_rate()) class Ore(NonBackground): def __init__(self, name, position, imgs, rate=5000): super(Ore, self).__init__(name, position, imgs) self.rate = rate def get_rate(self): return self.rate def _create_blob(self, world, name, pt, rate, ticks, i_store): blob = OreBlob(name, pt, rate, image_store.get_images(i_store, 'blob'), random.randint(actions.BLOB_ANIMATION_MIN, actions.BLOB_ANIMATION_MAX) * actions.BLOB_ANIMATION_RATE_SCALE) blob._schedule(world, ticks, i_store) return blob def _schedule(self, world, ticks, i_store): actions.schedule_action(world, self, actions.create_ore_transform_acti on(world, self, i_store), ticks + self.get_rate()) class Blacksmith(NonBackground): def __init__(self, name, position, imgs, resource_limit, rate, resource_distance=1): super(Blacksmith, self).__init__(name, position, imgs) self.resource_limit = resource_limit self.resource_count = 0 self.rate = rate self.resource_distance = resource_distance def get_rate(self): return self.rate def set_resource_count(self, n): self.resource_count = n def get_resource_count(self): return self.resource_count def get_resource_limit(self): return self.resource_limit def get_resource_distance(self): return self.resource_distance class Obstacle(InGrid): pass class OreBlob(Moving): def __init__(self, name, position, rate, imgs, animation_rate): super(OreBlob, self).__init__(name, position, rate, imgs) self.animation_rate = animation_rate def get_animation_rate(self): return self.animation_rate def _create_quake(self, world, pt, ticks, i_store): quake = Quake("quake", pt, image_store.get_images(i_store, 'quake'), actions.QUAKE_ANIMATION_RATE) quake._schedule(world, ticks) return quake def _schedule(self, world, ticks, i_store): actions.schedule_action(world, self, actions.create_ore_blob_action(world, self, i_store), ticks + self.get_rate()) actions.schedule_animation(world, self) def blob_to_vein(self, world, vein): entity_pt = self.get_position() if not vein: return ([entity_pt], False) vein_pt = vein.get_position() if adjacent(entity_pt, vein_pt): actions.remove_entity(world, vein) return ([vein_pt], True) else: new_pt = self.next_position(world, vein_pt) old_entity = world.get_tile_occupant(new_pt) if isinstance(old_entity, Ore): actions.remove_entity(world, old_entity) return (world.move_entity(self, new_pt), False) class Quake(NonBackground): def __init__(self, name, position, imgs, animation_rate): super(Quake, self).__init__(name, position, imgs) self.animation_rate = animation_rate def get_animation_rate(self): return self.animation_rate def _schedule(self, world, ticks): actions.schedule_animation(world, self, actions.QUAKE_STEPS) actions.schedule_action(world, self, actions.create_entity_death_actio n(world, self), ticks + actions.QUAKE_DURATION) def sign(x): if x < 0: return -1 elif x > 0: return 1 else: return 0 def adjacent(pt1, pt2): return ((pt1.x == pt2.x and abs(pt1.y - pt2.y) == 1) or (pt1.y == pt2.y and abs(pt1.x - pt2.x) == 1)) def get_image(entity): return entity.imgs[entity.current_img] # This is a less than pleasant file format , but structured based on # material covered in course. Something like JSON would be a # significant improvement. def entity_string(entity): if isinstance(entity, MinerNotFull): return ' '.join(['miner', entity.name, str(entity.position.x), str(entity.position.y), str(entity.resource_limit), str(entity.rate), str(entity.animation_rate)]) elif isinstance(entity, Vein): return ' '.join(['vein', entity.name, str(entity.position.x), str(entity.position.y), str(entity.rate), str(entity.resource_distance)]) elif isinstance(entity, Ore): return ' '.join(['ore', entity.name, str(entity.position.x), str(entity.position.y), str(entity.rate)]) elif isinstance(entity, Blacksmith): return ' '.join(['blacksmith', entity.name, str(entity.position.x), str(entity.position.y), str(entity.resource_limit), str(entity.rate), str(entity.resource_distance)]) elif isinstance(entity, Obstacle): return ' '.join(['obstacle', entity.name, str(entity.position.x), str(entity.position.y)]) else: return 'unknown' <file_sep>/actions.py import entities import worldmodel import pygame import math import point import image_store BLOB_RATE_SCALE = 4 BLOB_ANIMATION_RATE_SCALE = 50 BLOB_ANIMATION_MIN = 1 BLOB_ANIMATION_MAX = 3 ORE_CORRUPT_MIN = 20000 ORE_CORRUPT_MAX = 30000 QUAKE_STEPS = 10 QUAKE_DURATION = 1100 QUAKE_ANIMATION_RATE = 100 VEIN_SPAWN_DELAY = 500 VEIN_RATE_MIN = 8000 VEIN_RATE_MAX = 17000 def create_miner_not_full_action(world, entity, i_store): def action(current_ticks): entity.remove_pending_action(action) entity_pt = entity.get_position() ore = world.find_nearest(entity_pt, entities.Ore) (tiles, found) = entity.miner_to_ore(world, ore) new_entity = entity if found: new_entity = try_transform_miner(world, entity, try_transform_miner_not_full) schedule_action(world, new_entity, create_miner_action(world, new_entity, i_store), current_ticks + new_entity.get_rate()) return tiles return action def create_miner_full_action(world, entity, i_store): def action(current_ticks): entity.remove_pending_action(action) entity_pt = entity.get_position() smith = world.find_nearest(entity_pt, entities.Blacksmith) (tiles, found) = entity.miner_to_smith(world, smith) new_entity = entity if found: new_entity = try_transform_miner(world, entity, try_transform_miner_full) schedule_action(world, new_entity, create_miner_action(world, new_entity, i_store), current_ticks + new_entity.get_rate()) return tiles return action def create_ore_blob_action(world, entity, i_store): def action(current_ticks): entity.remove_pending_action(action) entity_pt = entity.get_position() vein = world.find_nearest(entity_pt, entities.Vein) (tiles, found) = entity.blob_to_vein(world, vein) next_time = current_ticks + entity.get_rate() if found: quake = entity._create_quake(world, tiles[0], current_ticks, i_store) world.add_entity(quake) next_time = current_ticks + entity.get_rate() * 2 schedule_action(world, entity, create_ore_blob_action(world, entity, i_store), next_time) return tiles return action def find_open_around(world, pt, distance): for dy in range(-distance, distance + 1): for dx in range(-distance, distance + 1): new_pt = point.Point(pt.x + dx, pt.y + dy) if (world.within_bounds(new_pt) and (not world.is_occupied(new_pt))): return new_pt return None def create_vein_action(world, entity, i_store): def action(current_ticks): entity.remove_pending_action(action) open_pt = find_open_around(world, entity.get_position(), entity.get_resource_distance()) if open_pt: ore = entity._create_ore(world, "ore - " + entity.get_name() + " - " + str(current_ticks), open_pt, current_ticks, i_store) world.add_entity(ore) tiles = [open_pt] else: tiles = [] schedule_action(world, entity, create_vein_action(world, entity, i_store), current_ticks + entity.get_rate()) return tiles return action def try_transform_miner_full(world, entity): new_entity = entities.MinerNotFull( entity.get_name(), entity.get_resource_limit(), entity.get_position(), entity.get_rate(), entity.get_images(), entity.get_animation_rate()) return new_entity def try_transform_miner_not_full(world, entity): if entity.resource_count < entity.resource_limit: return entity else: new_entity = entities.MinerFull( entity.get_name(), entity.get_resource_limit(), entity.get_position(), entity.get_rate(), entity.get_images(), entity.get_animation_rate()) return new_entity def try_transform_miner(world, entity, transform): new_entity = transform(world, entity) if entity != new_entity: clear_pending_actions(world, entity) world.remove_entity_at(entity.get_position()) world.add_entity(new_entity) schedule_animation(world, new_entity) return new_entity def create_miner_action(world, entity, image_store): if isinstance(entity, entities.MinerNotFull): return create_miner_not_full_action(world, entity, image_store) else: return create_miner_full_action(world, entity, image_store) def create_animation_action(world, entity, repeat_count): def action(current_ticks): entity.remove_pending_action(action) entity.next_image() if repeat_count != 1: schedule_action(world, entity, create_animation_action(world, entity, max(repeat_count - 1, 0)), current_ticks + entity.get_animation_rate()) return [entity.get_position()] return action def create_entity_death_action(world, entity): def action(current_ticks): entity.remove_pending_action(action) pt = entity.get_position() remove_entity(world, entity) return [pt] return action def create_ore_transform_action(world, entity, i_store): def action(current_ticks): entity.remove_pending_action(action) blob = entity._create_blob(world, entity.get_name() + " -- blob", entity.get_position(), entity.get_rate() // BLOB_RATE_SCALE, current_ticks, i_store) remove_entity(world, entity) world.add_entity(blob) return [blob.get_position()] return action def remove_entity(world, entity): for action in entity.get_pending_actions(): world.unschedule_action(action) entity.clear_pending_actions() world.remove_entity(entity) def schedule_action(world, entity, action, time): entity.add_pending_action(action) world.schedule_action(action, time) def schedule_animation(world, entity, repeat_count=0): schedule_action(world, entity, create_animation_action(world, entity, repeat_count), entity.get_animation_rate()) def clear_pending_actions(world, entity): for action in entity.get_pending_actions(): world.unschedule_action(action) entity.clear_pending_actions()
b7225d0f5eb7659cdcb729c78f15d7c2ed2e0da7
[ "Python" ]
2
Python
bertair7/cpe102project
bd9517e7c0e688e8d7e3f09ac563b582ce201424
cfd3ae1dc025807df18ec380de645ad2fd655ee9
refs/heads/master
<file_sep> import java.util.ArrayList; import java.util.Scanner; /** * Created by vb on 21.3.2016 г.. */ public class CharacterMultiplier { private static int multiplyCharacter(String[] input) { int sum=0; String longer; String shorter ; int diff= input[0].length()-input[1].length(); if (diff>0) { longer = input[0]; shorter =input[1]; } else{ longer=input[1]; shorter=input[0]; } for (int i = 0; i <shorter.length() ; i++) { sum+=shorter.charAt(i)*longer.charAt(i); } if (diff!=0){ for (int i =longer.length()-Math.abs(diff); i <longer.length() ; i++) { sum += longer.charAt(i); } } return sum; } public static void main(String[] args) { System.out.print("Enter two strings:"); Scanner console = new Scanner(System.in); String[] input = console.nextLine().split(" "); int result = multiplyCharacter(input); System.out.println(result); } } <file_sep>import java.io.Serializable; /** * Created by vb on 28.3.2016 г.. */ public class CustomObject implements Serializable{ public String Name; public int NumberStudents; public CustomObject(String name,int numberStudents){ this.Name=name; this.NumberStudents =numberStudents; } } <file_sep>import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * Created by vb on 27.3.2016 г.. */ public class SumLines { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new FileReader("lines.txt"))){ String line; while ((line=reader.readLine())!= null){ int sum =0; for (char s : line.toCharArray()) { sum+=s; } System.out.println(sum); } } catch (IOException ioex){ System.out.print(ioex); } } } <file_sep>import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; /** * Created by vb on 28.3.2016 г.. */ public class CountAllWords { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Enter string:"); String[] input = console.nextLine().split("\\W+"); System.out.print(input.length); } } <file_sep>import java.util.Arrays; import java.util.Scanner; /** * Created by vb on 28.3.2016 г.. */ public class SortArrayOfNumbers { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Enter number n: "); int n = console.nextInt(); int[] numbers= new int[n]; for (int i = 0; i < n; i++) { numbers[i]=console.nextInt(); } Arrays.sort(numbers); for (int number : numbers) { System.out.print(number+" "); } } } <file_sep>import java.util.Scanner; /** * Created by vb on 21.3.2016 г.. */ public class HitTheTarget { private static void findPairs(int desireSum) { for (int i = 1; i <= 20; i++) { for (int j = 1; j <= 20; j++) { if (i + j == desireSum) { System.out.printf("%d+%d=%d\n\r", i, j, desireSum); } if (i - j == desireSum) { System.out.printf("%d-%d=%d\n\r", i, j, desireSum); } } } } public static void main(String[] args) { System.out.println("Enter desired sum :"); Scanner console = new Scanner(System.in); int desireSum=console.nextInt(); findPairs(desireSum); } } <file_sep>import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * Created by vb on 28.3.2016 г.. */ public class ZipArchive { public static void main(String[] args) { File zipped= new File("text-files.zip"); File[] files = new File[]{new File("lines.txt") , new File("words.txt"),new File("picture.jpg")}; for (File file : files) { String zipEntryName = file.getPath(); ZipEntry zipEntry = new ZipEntry(zipEntryName); try (FileInputStream inputStream = new FileInputStream(file)) { try (ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(zipped,true))) { zipStream.putNextEntry(zipEntry); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0){ zipStream.write(buffer, 0, length);} zipStream.closeEntry(); } } catch (IOException ioex) { System.out.print(ioex); } } } } <file_sep>import java.util.Scanner; /** * Created by vb on 19.3.2016 г.. */ public class RectangleArea { public static void main(String[] args) { System.out.print("Enter rectangle sides separated by space :"); Scanner sc = new Scanner(System.in); String[] input = sc.nextLine().split(" "); int width =Integer.parseInt( input[0]); int height = Integer.parseInt(input[1]); System.out.printf("Rectangle area:%s",width*height); } } <file_sep>import java.io.*; import java.util.ArrayList; import java.util.Scanner; /** * Created by vb on 27.3.2016 г.. */ public class SaveCustomObjectInAFile { public static void main(String[] args) { CustomObject javaBasic = new CustomObject("JavaBasic", 300); CustomObject cSharpBasic = new CustomObject("CSharpBasic", 1800); CustomObject hcq = new CustomObject("HQC", 300); CustomObject cSharpAdvance = new CustomObject("cSharpAdvance", 1800); ArrayList<CustomObject> allCurses = new ArrayList<>(); try (ObjectOutputStream fos = new ObjectOutputStream(new FileOutputStream("course.save"))) { fos.writeObject(javaBasic); fos.writeObject(cSharpBasic); fos.writeObject(hcq); fos.writeObject(cSharpAdvance); } catch (IOException ex) { System.out.print(ex); } try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("course.save"))) { while (true) { allCurses.add((CustomObject) ois.readObject()); } } catch (EOFException eofx) { for (CustomObject curse : allCurses) { System.out.println(String.format("Name : %s\n\rStudents: %d", curse.Name, curse.NumberStudents)); } } catch (IOException ex) { System.out.print(ex); } catch (ClassNotFoundException cnfex) { System.out.print("cnfex"); } } } <file_sep>import java.util.ArrayList; import java.util.Scanner; /** * Created by vb on 22.4.2016 г.. */ public class Problem1 { public static void main(String[] args) { Scanner console = new Scanner(System.in); String[] resourceField = console.nextLine().split(" "); int paths = console.nextInt(); int maxCollect = 0; for (int i = 0; i < paths; i++) { ArrayList<Integer>colectedIndex=new ArrayList<>(); int collected = 0; int start = console.nextInt(); int step = console.nextInt(); while (true) { String[] res = resourceField[start % resourceField.length].split("_"); if (colectedIndex.contains(start % resourceField.length)){ if (collected > maxCollect) { maxCollect = collected; } break; }else if (res[0].equals("stone")|| res[0].equals("gold")|| res[0].equals("food") || res[0].equals("wood")){ if(res.length==1){ collected+=1; }else { collected += Integer.parseInt(res[1]); } colectedIndex.add(start % resourceField.length); } start += step; } } System.out.print(maxCollect); }} <file_sep>import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; /** * Created by vb on 29.3.2016 г.. */ public class CombineListsOfLetters { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Enter first character sequence separated by space:"); ArrayList<Character> firstList= new ArrayList<Character>(); ArrayList<Character> buffer =new ArrayList<>(); for (char c : console.nextLine().toCharArray()) { firstList.add(c); } System.out.print("Enter second character sequence separated by space:"); ArrayList<Character> secondList= new ArrayList<Character>(); for (char c : console.nextLine().toCharArray()) { secondList.add(c); } for (Character character : secondList) { if (!firstList.contains(character)){ buffer.add(character); } } firstList.addAll(buffer); for (Character character : firstList) { System.out.print(character+" "); } } } <file_sep>import java.util.Scanner; /** * Created by vb on 30.3.2016 г.. */ public class CalculateNFac { public static void main(String[] args) { System.out.print("Enter number: "); Scanner console = new Scanner(System.in); int number = console.nextInt(); int result = calculateFactorial(number); System.out.println(number + "!=" + result); } private static int calculateFactorial(int n) { int result; if (n == 1) return 1; result = calculateFactorial(n - 1) * n; return result; } } <file_sep>import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by vb on 6.4.2016 г.. */ public class StartsAndEndsWithCapitalLetter { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Enter text: "); String text = console.nextLine(); Pattern pattern = Pattern.compile("\\b[A-Z]([a-zA-z]+)?[A-Z]\\b"); Matcher match = pattern.matcher(text); while (match.find()){ System.out.print(match.group()+" "); } } } <file_sep>import java.awt.*; import java.util.*; import java.util.List; import java.util.stream.Collectors; import static java.util.Collections.*; /** * Created by vb on 4.4.2016 г.. */ public class SortArrayWithStreamAPI { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Eneter integer array: " ); Integer[] input = Arrays.stream(console.nextLine().split(" ")).mapToInt(Integer::parseInt) .sorted() .boxed().toArray(Integer[]::new ); System.out.print("Eneter sorting order : " ); console = new Scanner(System.in); if (console.nextLine().equals("Ascending")){ for (int i : input) { System.out.print(i+ " "); } } else{ Collections.reverse(Arrays.asList(input)); for (int i : input) { System.out.print(i+ " "); } } } } <file_sep>import java.util.*; /** * Created by vb on 29.3.2016 г.. */ public class MostFrequentWord { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Enter text: "); String[] allWords = console.nextLine().toLowerCase().split("\\W+"); TreeMap<Integer,TreeSet<String>> wordCount = new TreeMap<>(Collections.reverseOrder()); for (String word : allWords) { int count=0; for (String allWord : allWords) { if (word.equals(allWord)){ count++; } } if (!wordCount.containsKey(count)){ wordCount.put(count,new TreeSet<>()); } wordCount.get(count).add(word); } for (String s : wordCount.firstEntry().getValue()) { System.out.printf("%s -> %d times%n",s,wordCount.firstEntry().getKey()); } } } <file_sep>import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by vb on 6.4.2016 г.. */ public class CountAllWords { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Enter text: "); String[] input = console.nextLine().split("\\W+"); System.out.print(input.length); } } <file_sep>import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.stream.Collectors; /** * Created by vb on 4.4.2016 г.. */ public class FilterArray { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Enter number(Desired min Lenght):"); int desireMinLenght= console.nextInt(); System.out.print("Enter text:"); console=new Scanner(System.in); String[] input = console.nextLine().split(" "); Arrays.stream(input) .filter(s->s.length()>=desireMinLenght).map(s->s+=" ").forEach(System.out::print); } } <file_sep>import java.util.*; /** * Created by vb on 28.3.2016 г.. */ public class LongestIncreasingSequence { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Enter integers separated bu space:"); String[] input = console.nextLine().split(" "); int[] inputNumbers = Arrays.stream(input).mapToInt(Integer::parseInt).toArray(); ArrayList<ArrayList<Integer>> allSequences =new ArrayList<>(); ArrayList<Integer> seq = new ArrayList<>(); seq.add(inputNumbers[0]); for (int i = 0; i < inputNumbers.length - 1; i++) { if (inputNumbers[i]<inputNumbers[i + 1]) { seq.add(inputNumbers[i + 1]); } else { allSequences.add(new ArrayList<Integer>(seq)); seq.clear(); seq.add(inputNumbers[i + 1]); } } allSequences.add(new ArrayList<Integer>(seq)); for (ArrayList en : allSequences) { for (Integer integer :(ArrayList<Integer>)en) { System.out.print(integer+" "); } System.out.println(); } int max = 0; for (int i = 1; i < allSequences.size(); i++) { if (allSequences.get(i).size()>allSequences.get(max).size()){ max=i; } } System.out.print("Longest : "); for (Integer integer : allSequences.get(max)) { System.out.print(integer+" "); } } } <file_sep>import java.util.*; /** * Created by vb on 29.3.2016 г.. */ public class CardsFrequencies { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Enter card: "); String[] cards = console.nextLine().split("\\W+"); double cardCount = cards.length; LinkedHashMap<String, Double> wordCount = new LinkedHashMap<>(); for (String card : cards) { int count = 0; for (String allCard : cards) { if (card.equals(allCard)) { count++; } } if (!wordCount.containsKey(card)) { wordCount.put(card, (count / cardCount) * 100); } } for (String cardFace : wordCount.keySet()) { System.out.printf("%s -> %.2f%s %n", cardFace, wordCount.get(cardFace), "%"); } } }
74a150eb3e33a69405ab4ba23489cf92b551713c
[ "Java" ]
19
Java
valiobar/Java
3106fb0a36959841f2306e8f4f5fcc7ac169cc67
243fb86a98a86e6373ea6db140f05c185850738c
refs/heads/master
<repo_name>jluismorav/restful-spring-mybatis-hazelcast<file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/servicios/AbstractServicio.java package co.com.xoftix.spaservicios.servicios; import java.util.List; /** * * @author jmoraxoftix * * @param <T> */ public abstract class AbstractServicio<T> implements IServicio<T> { @Override public T actualizar(T entidad) throws Exception { throw new UnsupportedOperationException("Metodo no implementado "); } @Override public List<T> consultar(T entidad) throws Exception { throw new UnsupportedOperationException("Metodo no implementado "); } @Override public T eliminar(T entidad) throws Exception { throw new UnsupportedOperationException("Metodo no implementado "); } @Override public T guardar(T entidad) throws Exception { throw new UnsupportedOperationException("Metodo no implementado "); } @Override public List<T> consultar(T entidad, int desde, int hasta) throws Exception { throw new UnsupportedOperationException("Metodo no implementado"); //To change body of generated methods, choose Tools | Templates. } } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/servicios/ge/IPobladoServicio.java package co.com.xoftix.spaservicios.servicios.ge; import co.com.xoftix.spaservicios.entidades.ge.Poblado; import co.com.xoftix.spaservicios.servicios.IServicio; /** * * @author jmoraxoftix */ public interface IPobladoServicio extends IServicio<Poblado> { } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/entidades/ge/UnidadReceptora.java package co.com.xoftix.spaservicios.entidades.ge; import java.io.Serializable; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class UnidadReceptora implements Serializable { /** * */ private static final long serialVersionUID = 4938127937025747156L; private Long id; private String nombre; private Long idPoblado; private String codigo; private Long idEspecialidadServicio; private Long idTipoOficina; private Long idInstitucion; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public Long getIdPoblado() { return idPoblado; } public void setIdPoblado(Long idPoblado) { this.idPoblado = idPoblado; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public Long getIdEspecialidadServicio() { return idEspecialidadServicio; } public void setIdEspecialidadServicio(Long idEspecialidadServicio) { this.idEspecialidadServicio = idEspecialidadServicio; } public Long getIdTipoOficina() { return idTipoOficina; } public void setIdTipoOficina(Long idTipoOficina) { this.idTipoOficina = idTipoOficina; } public Long getIdInstitucion() { return idInstitucion; } public void setIdInstitucion(Long idInstitucion) { this.idInstitucion = idInstitucion; } } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/servicios/ge/impl/CorregimientoServicioImpl.java package co.com.xoftix.spaservicios.servicios.ge.impl; import co.com.xoftix.spaservicios.entidades.ge.Corregimiento; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import co.com.xoftix.spaservicios.mapper.ge.CorregimientoMapper; import co.com.xoftix.spaservicios.servicios.AbstractServicio; import co.com.xoftix.spaservicios.servicios.ge.ICorregimientoServicio; import org.apache.ibatis.session.RowBounds; @Service @Transactional public class CorregimientoServicioImpl extends AbstractServicio<Corregimiento> implements ICorregimientoServicio { @Autowired private CorregimientoMapper corregimientoMapper; @Override public List<Corregimiento> consultar(Corregimiento entidad) throws Exception { return corregimientoMapper.consultar(entidad); } @Override public List<Corregimiento> consultar(Corregimiento entidad, int desde, int hasta) throws Exception { return corregimientoMapper.consultar(entidad, new RowBounds(desde, hasta)); } } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/entidades/nc/NoticiaCriminal.java package co.com.xoftix.spaservicios.entidades.nc; import java.io.Serializable; import java.util.Date; public class NoticiaCriminal implements Serializable { /** * */ private static final long serialVersionUID = 2410872440049639238L; private Long id; private String numero; private Long idUnidadreceptora; private Long idProvincia; private Long idDistrito; private Long idCorregimiento; private Long idPoblado; private Long idBarriada; private String lugarOcurrencia; private Date fechaInicial; private Date fechaFinal; private Date fechaConocimiento; private String relatoHechos; private String refExp; private String nombreRemitente; private String cargoRemitente; private Date fechaRemite; private Date fechaHoraRegistro; private Long estimacionCuantia; private String observacionCambioEstado; private Long idSedePrimerInterviniente; private Long idOficinaAtiendeCaso; private Long estimacionDano; private Long idMensaje; private String idR2Police; private Long idEstadoNoticia; private Long idTipoNoticia; private Long idModoOperacion; private Long idInstitucion; private Long idTipoPrimerInterviniente; private Long idEspecialidadServicio; private Long idRemitente; private Long idFinalizador; private Date fechaHoraFinal; private String referencia; private Boolean manual; private Boolean esNoticiaCriminal; private Long idOrigen; private Boolean tipoNoticiaFormal; private Date fechaInforme; public void setNumero(String numero) { this.numero = numero; } public String getNumero() { return numero; } public void setIdUnidadreceptora(Long idUnidadreceptora) { this.idUnidadreceptora = idUnidadreceptora; } public Long getIdUnidadreceptora() { return idUnidadreceptora; } public void setIdProvincia(Long idProvincia) { this.idProvincia = idProvincia; } public Long getIdProvincia() { return idProvincia; } public void setIdDistrito(Long idDistrito) { this.idDistrito = idDistrito; } public Long getIdDistrito() { return idDistrito; } public void setIdCorregimiento(Long idCorregimiento) { this.idCorregimiento = idCorregimiento; } public Long getIdCorregimiento() { return idCorregimiento; } public void setIdPoblado(Long idPoblado) { this.idPoblado = idPoblado; } public Long getIdPoblado() { return idPoblado; } public void setIdBarriada(Long idBarriada) { this.idBarriada = idBarriada; } public Long getIdBarriada() { return idBarriada; } public void setLugarOcurrencia(String lugarOcurrencia) { this.lugarOcurrencia = lugarOcurrencia; } public String getLugarOcurrencia() { return lugarOcurrencia; } public void setFechaInicial(Date fechaInicial) { this.fechaInicial = fechaInicial; } public Date getFechaInicial() { return fechaInicial; } public void setFechaFinal(Date fechaFinal) { this.fechaFinal = fechaFinal; } public Date getFechaFinal() { return fechaFinal; } public void setFechaConocimiento(Date fechaConocimiento) { this.fechaConocimiento = fechaConocimiento; } public Date getFechaConocimiento() { return fechaConocimiento; } public void setRelatoHechos(String relatoHechos) { this.relatoHechos = relatoHechos; } public String getRelatoHechos() { return relatoHechos; } public void setRefExp(String refExp) { this.refExp = refExp; } public String getRefExp() { return refExp; } public void setNombreRemitente(String nombreRemitente) { this.nombreRemitente = nombreRemitente; } public String getNombreRemitente() { return nombreRemitente; } public void setCargoRemitente(String cargoRemitente) { this.cargoRemitente = cargoRemitente; } public String getCargoRemitente() { return cargoRemitente; } public void setFechaRemite(Date fechaRemite) { this.fechaRemite = fechaRemite; } public Date getFechaRemite() { return fechaRemite; } public void setFechaHoraRegistro(Date fechaHoraRegistro) { this.fechaHoraRegistro = fechaHoraRegistro; } public Date getFechaHoraRegistro() { return fechaHoraRegistro; } public void setEstimacionCuantia(Long estimacionCuantia) { this.estimacionCuantia = estimacionCuantia; } public Long getEstimacionCuantia() { return estimacionCuantia; } public void setObservacionCambioEstado(String observacionCambioEstado) { this.observacionCambioEstado = observacionCambioEstado; } public String getObservacionCambioEstado() { return observacionCambioEstado; } public void setIdSedePrimerInterviniente(Long idSedePrimerInterviniente) { this.idSedePrimerInterviniente = idSedePrimerInterviniente; } public Long getIdSedePrimerInterviniente() { return idSedePrimerInterviniente; } public void setIdOficinaAtiendeCaso(Long idOficinaAtiendeCaso) { this.idOficinaAtiendeCaso = idOficinaAtiendeCaso; } public Long getIdOficinaAtiendeCaso() { return idOficinaAtiendeCaso; } public void setEstimacionDano(Long estimacionDano) { this.estimacionDano = estimacionDano; } public Long getEstimacionDano() { return estimacionDano; } public void setIdMensaje(Long idMensaje) { this.idMensaje = idMensaje; } public Long getIdMensaje() { return idMensaje; } public void setIdR2Police(String idR2Police) { this.idR2Police = idR2Police; } public String getIdR2Police() { return idR2Police; } public void setIdEstadoNoticia(Long idEstadoNoticia) { this.idEstadoNoticia = idEstadoNoticia; } public Long getIdEstadoNoticia() { return idEstadoNoticia; } public void setIdTipoNoticia(Long idTipoNoticia) { this.idTipoNoticia = idTipoNoticia; } public Long getIdTipoNoticia() { return idTipoNoticia; } public void setIdModoOperacion(Long idModoOperacion) { this.idModoOperacion = idModoOperacion; } public Long getIdModoOperacion() { return idModoOperacion; } public void setIdInstitucion(Long idInstitucion) { this.idInstitucion = idInstitucion; } public Long getIdInstitucion() { return idInstitucion; } public void setIdTipoPrimerInterviniente(Long idTipoPrimerInterviniente) { this.idTipoPrimerInterviniente = idTipoPrimerInterviniente; } public Long getIdTipoPrimerInterviniente() { return idTipoPrimerInterviniente; } public void setIdEspecialidadServicio(Long idEspecialidadServicio) { this.idEspecialidadServicio = idEspecialidadServicio; } public Long getIdEspecialidadServicio() { return idEspecialidadServicio; } public void setIdRemitente(Long idRemitente) { this.idRemitente = idRemitente; } public Long getIdRemitente() { return idRemitente; } public void setIdFinalizador(Long idFinalizador) { this.idFinalizador = idFinalizador; } public Long getIdFinalizador() { return idFinalizador; } public void setFechaHoraFinal(Date fechaHoraFinal) { this.fechaHoraFinal = fechaHoraFinal; } public Date getFechaHoraFinal() { return fechaHoraFinal; } public void setReferencia(String referencia) { this.referencia = referencia; } public String getReferencia() { return referencia; } public void setManual(Boolean manual) { this.manual = manual; } public Boolean getManual() { return manual; } public void setEsNoticiaCriminal(Boolean esNoticiaCriminal) { this.esNoticiaCriminal = esNoticiaCriminal; } public Boolean getEsNoticiaCriminal() { return esNoticiaCriminal; } public void setIdOrigen(Long idOrigen) { this.idOrigen = idOrigen; } public Long getIdOrigen() { return idOrigen; } public Boolean getTipoNoticiaFormal() { return tipoNoticiaFormal; } public void setTipoNoticiaFormal(Boolean tipoNoticiaFormal) { this.tipoNoticiaFormal = tipoNoticiaFormal; } public Date getFechaInforme() { return fechaInforme; } public void setFechaInforme(Date fechaInforme) { this.fechaInforme = fechaInforme; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } }<file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/servicios/ge/ICorregimientoServicio.java package co.com.xoftix.spaservicios.servicios.ge; import co.com.xoftix.spaservicios.entidades.ge.Corregimiento; import co.com.xoftix.spaservicios.servicios.IServicio; /** * * @author jmoraxoftix */ public interface ICorregimientoServicio extends IServicio<Corregimiento> { } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/mapper/ge/CorregimientoMapper.java package co.com.xoftix.spaservicios.mapper.ge; import co.com.xoftix.spaservicios.entidades.ge.Corregimiento; import co.com.xoftix.spaservicios.mapper.IMapper; /** * * @author jmoraxoftix */ public interface CorregimientoMapper extends IMapper<Corregimiento> { } <file_sep>/README.md # restful-spring-mybatis-hazelcast Arquetipo configurado en maven integrando Jersy-Spring-mybatis-hazelcast <file_sep>/SPAMicroServicios/src/main/java/co/com/xoftix/spamicroservicios/util/GeneradorRespuestas.java package co.com.xoftix.spamicroservicios.util; import javax.ws.rs.core.Response; /** * Clase que tiene como responsabilidad generar las respuestas a las solicitudes * de los RESTFul * * @author jmoraxoftix * */ public class GeneradorRespuestas { private static Response construirRespuesta(Object object, Response.Status status) { Respuesta respuesta = new Respuesta(); respuesta.setStatus(status); respuesta.setInformacion(object); return Response.status(status).entity(respuesta).build(); } public static Response respuestaOK(Object respuesta) { return construirRespuesta(respuesta, Response.Status.OK); } public static Response respuestaINTERNAL_SERVER_ERROR(Object respuesta) { return construirRespuesta(respuesta, Response.Status.INTERNAL_SERVER_ERROR); } } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/servicios/ge/IProvinciaServicio.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 co.com.xoftix.spaservicios.servicios.ge; import co.com.xoftix.spaservicios.entidades.ge.Provincia; import co.com.xoftix.spaservicios.servicios.IServicio; /** * * @author jmoraxoftix */ public interface IProvinciaServicio extends IServicio<Provincia> { } <file_sep>/SPAMicroServicios/src/main/java/co/com/xoftix/spamicroservicios/restful/TipoIdentificacionRESTFul.java package co.com.xoftix.spamicroservicios.restful; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import co.com.xoftix.spamicroservicios.util.GeneradorRespuestas; import co.com.xoftix.spaservicios.entidades.ds.TipoIdentificacion; import co.com.xoftix.spaservicios.servicios.ds.ITipoIdentificacionServicio; /** * * @author jmoraxoftix * */ @Path("/tipoIdentificacion") @Component public class TipoIdentificacionRESTFul { @Autowired private ITipoIdentificacionServicio iTipoIdentificacionServicio; @GET @Path("/consultar") @Produces(MediaType.APPLICATION_JSON) public Response consultar() { try { TipoIdentificacion tipoIdentificacion = new TipoIdentificacion(); List<TipoIdentificacion> tipoIdentificacions = iTipoIdentificacionServicio .consultar(tipoIdentificacion); return GeneradorRespuestas.respuestaOK(tipoIdentificacions); } catch (Exception e) { return GeneradorRespuestas.respuestaINTERNAL_SERVER_ERROR(e); } } } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/mapper/ds/NivelEducativoMapper.java package co.com.xoftix.spaservicios.mapper.ds; import co.com.xoftix.spaservicios.entidades.ds.NivelEducativo; import co.com.xoftix.spaservicios.mapper.IMapper; public interface NivelEducativoMapper extends IMapper<NivelEducativo> { } <file_sep>/PaginacionXoftix/src/main/java/co/com/xoftix/paginacionxoftix/PageList.java package co.com.xoftix.paginacionxoftix; import java.util.ArrayList; import java.util.Collection; /** * * 包含“分页”信息的List * * <p>要得到总页数请使用 toPaginator().getTotalPages();</p> * * @author badqiu * @author miemiedev */ public class PageList<E> extends ArrayList<E> { private static final long serialVersionUID = 1412759446332294208L; private Paginator paginator; public PageList() {} public PageList(Collection<? extends E> c) { super(c); } public PageList(Collection<? extends E> c,Paginator p) { super(c); this.paginator = p; } public PageList(Paginator p) { this.paginator = p; } /** * 得到分页器,通过Paginator可以得到总页数等值 * @return */ public Paginator getPaginator() { return paginator; } }<file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/servicios/ds/impl/TipoIdentificacionServicioImpl.java package co.com.xoftix.spaservicios.servicios.ds.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import co.com.xoftix.spaservicios.entidades.ds.TipoIdentificacion; import co.com.xoftix.spaservicios.mapper.ds.TipoIdentificacionMapper; import co.com.xoftix.spaservicios.servicios.AbstractServicio; import co.com.xoftix.spaservicios.servicios.ds.ITipoIdentificacionServicio; @Service @Transactional public class TipoIdentificacionServicioImpl extends AbstractServicio<TipoIdentificacion> implements ITipoIdentificacionServicio { @Autowired private TipoIdentificacionMapper tipoIdentificacionMapper; @Override public List<TipoIdentificacion> consultar(TipoIdentificacion entidad) throws Exception { return tipoIdentificacionMapper.consultar(entidad); } } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/servicios/ge/impl/PobladoServicioImpl.java package co.com.xoftix.spaservicios.servicios.ge.impl; import java.util.List; import org.apache.ibatis.session.RowBounds; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import co.com.xoftix.spaservicios.entidades.ge.Poblado; import co.com.xoftix.spaservicios.mapper.ge.PobladoMapper; import co.com.xoftix.spaservicios.servicios.AbstractServicio; import co.com.xoftix.spaservicios.servicios.ge.IPobladoServicio; @Service @Transactional public class PobladoServicioImpl extends AbstractServicio<Poblado> implements IPobladoServicio { @Autowired private PobladoMapper pobladoMapper; @Override public List<Poblado> consultar(Poblado entidad) throws Exception { return pobladoMapper.consultar(entidad); } @Override public List<Poblado> consultar(Poblado entidad, int desde, int hasta) throws Exception { return pobladoMapper.consultar(entidad, new RowBounds(desde, hasta)); } } <file_sep>/SPAMicroServicios/src/main/java/co/com/xoftix/spamicroservicios/restful/PobladoRESTFul.java package co.com.xoftix.spamicroservicios.restful; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import co.com.xoftix.spamicroservicios.util.GeneradorRespuestas; import co.com.xoftix.spaservicios.entidades.ge.Poblado; import co.com.xoftix.spaservicios.servicios.ge.IPobladoServicio; /** * * @author jmoraxoftix * */ @Path("/poblado") @Component public class PobladoRESTFul { @Autowired private IPobladoServicio iPobladoServicio; /** * * @param idProvincia * @return */ @GET @Path("/consultar/{idCorregimiento}") @Produces(MediaType.APPLICATION_JSON) public Response consultar(@PathParam("idCorregimiento") Long idCorregimiento) { try { Poblado poblado = new Poblado(); poblado.setIdCorregimiento(idCorregimiento); List<Poblado> poblados = iPobladoServicio.consultar(poblado); return GeneradorRespuestas.respuestaOK(poblados); } catch (Exception e) { return GeneradorRespuestas.respuestaINTERNAL_SERVER_ERROR(e); } } } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/mapper/ds/OficioMapper.java package co.com.xoftix.spaservicios.mapper.ds; import co.com.xoftix.spaservicios.entidades.ds.Oficio; import co.com.xoftix.spaservicios.mapper.IMapper; public interface OficioMapper extends IMapper<Oficio> { } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/mapper/IMapper.java package co.com.xoftix.spaservicios.mapper; import java.util.List; import org.apache.ibatis.session.RowBounds; /** * * @author jmoraxoftix * * @param <T> */ public interface IMapper<T> { /** * * @param entidad * @return * @throws Exception */ public List<T> consultar(T entidad) throws Exception; /** * * @param entidad * @return * @throws Exception */ public T insertar(T entidad) throws Exception; /** * * @param entidad * @throws Exception */ public void actualizar(T entidad) throws Exception; /** * * @param entidad * @return * @throws Exception */ public T eliminar(T entidad) throws Exception; /** * * @param entidad * @param rowBounds * @return * @throws Exception */ public List<T> consultar(T entidad, RowBounds rowBounds) throws Exception; } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/entidades/ax/Descriptor.java package co.com.xoftix.spaservicios.entidades.ax; import java.io.Serializable; import javax.xml.bind.annotation.XmlRootElement; /** * * @author jmoraxoftix * */ @XmlRootElement public class Descriptor implements Serializable { /** * */ private static final long serialVersionUID = 2381186097664158742L; private Long id; private Long idDescriptor; private String codigo; private String nombre; private Boolean activo; private String icono; private String control; public Long getIdDescriptor() { return idDescriptor; } public void setIdDescriptor(Long idDescriptor) { this.idDescriptor = idDescriptor; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public Boolean getActivo() { return activo; } public void setActivo(Boolean activo) { this.activo = activo; } public String getIcono() { return icono; } public void setIcono(String icono) { this.icono = icono; } public String getControl() { return control; } public void setControl(String control) { this.control = control; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/mapper/ge/DistritoMapper.java package co.com.xoftix.spaservicios.mapper.ge; import co.com.xoftix.spaservicios.entidades.ge.Distrito; import co.com.xoftix.spaservicios.mapper.IMapper; /** * * @author jmoraxoftix */ public interface DistritoMapper extends IMapper<Distrito> { } <file_sep>/SPAMicroServicios/src/main/java/co/com/xoftix/spamicroservicios/restful/OficioRESTFul.java package co.com.xoftix.spamicroservicios.restful; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import co.com.xoftix.spamicroservicios.util.GeneradorRespuestas; import co.com.xoftix.spaservicios.entidades.ds.Oficio; import co.com.xoftix.spaservicios.servicios.ds.IOficioServicio; /** * * @author jmoraxoftix * */ @Path("/oficio") @Component public class OficioRESTFul { @Autowired private IOficioServicio iOficioServicio; @GET @Path("/consultar") @Produces(MediaType.APPLICATION_JSON) public Response consultar() { try { Oficio oficio = new Oficio(); List<Oficio> oficios = iOficioServicio.consultar(oficio); return GeneradorRespuestas.respuestaOK(oficios); } catch (Exception e) { return GeneradorRespuestas.respuestaINTERNAL_SERVER_ERROR(e); } } } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/servicios/ds/impl/GeneroServicioImpl.java package co.com.xoftix.spaservicios.servicios.ds.impl; import java.util.List; import org.apache.ibatis.session.RowBounds; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import co.com.xoftix.spaservicios.entidades.ds.Genero; import co.com.xoftix.spaservicios.mapper.ds.GeneroMapper; import co.com.xoftix.spaservicios.servicios.AbstractServicio; import co.com.xoftix.spaservicios.servicios.ds.IGeneroServicio; @Service @Transactional public class GeneroServicioImpl extends AbstractServicio<Genero> implements IGeneroServicio { @Autowired private GeneroMapper generoMapper; @Override public List<Genero> consultar(Genero entidad) throws Exception { return generoMapper.consultar(entidad); } @Override public List<Genero> consultar(Genero entidad, int desde, int hasta) throws Exception { return generoMapper.consultar(entidad, new RowBounds(desde, hasta)); } } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/servicios/ds/impl/OficioServicioImpl.java package co.com.xoftix.spaservicios.servicios.ds.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import co.com.xoftix.spaservicios.entidades.ds.Oficio; import co.com.xoftix.spaservicios.mapper.ds.OficioMapper; import co.com.xoftix.spaservicios.servicios.AbstractServicio; import co.com.xoftix.spaservicios.servicios.ds.IOficioServicio; @Service @Transactional public class OficioServicioImpl extends AbstractServicio<Oficio> implements IOficioServicio { @Autowired private OficioMapper oficioMapper; @Override public List<Oficio> consultar(Oficio entidad) throws Exception { return oficioMapper.consultar(entidad); } } <file_sep>/SPAMicroServicios/src/main/java/co/com/xoftix/spamicroservicios/restful/CorregimientoRESTFul.java package co.com.xoftix.spamicroservicios.restful; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import co.com.xoftix.spamicroservicios.util.GeneradorRespuestas; import co.com.xoftix.spaservicios.entidades.ge.Corregimiento; import co.com.xoftix.spaservicios.servicios.ge.ICorregimientoServicio; /** * * @author jmoraxoftix * */ @Path("/corregimiento") @Component public class CorregimientoRESTFul { @Autowired private ICorregimientoServicio iCorregimientoServicio; @GET @Path("/consultar/{idDistrito}") @Produces(MediaType.APPLICATION_JSON) public Response consultar(@PathParam("idDistrito") Long idDistrito) { try { Corregimiento corregimiento = new Corregimiento(); corregimiento.setIdDistrito(idDistrito); List<Corregimiento> corregimientos = iCorregimientoServicio .consultar(corregimiento); return GeneradorRespuestas.respuestaOK(corregimientos); } catch (Exception e) { return GeneradorRespuestas.respuestaINTERNAL_SERVER_ERROR(e); } } } <file_sep>/SPAMicroServicios/src/main/java/co/com/xoftix/spamicroservicios/restful/DistritoRESTFul.java package co.com.xoftix.spamicroservicios.restful; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import co.com.xoftix.spamicroservicios.util.GeneradorRespuestas; import co.com.xoftix.spaservicios.entidades.ge.Distrito; import co.com.xoftix.spaservicios.servicios.ge.IDistritoServicio; /** * * @author jmoraxoftix * */ @Path("/distrito") @Component public class DistritoRESTFul { @Autowired private IDistritoServicio iDistritoServicio; @GET @Path("/consultar/{idProvincia}") @Produces(MediaType.APPLICATION_JSON) public Response consultar(@PathParam("idProvincia") Long idProvincia) { try { Distrito distrito = new Distrito(); distrito.setIdProvincia(idProvincia); List<Distrito> distritos = iDistritoServicio.consultar(distrito); return GeneradorRespuestas.respuestaOK(distritos); } catch (Exception e) { return GeneradorRespuestas.respuestaINTERNAL_SERVER_ERROR(e); } } } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/mapper/ds/TipoIdentificacionMapper.java package co.com.xoftix.spaservicios.mapper.ds; import co.com.xoftix.spaservicios.entidades.ds.TipoIdentificacion; import co.com.xoftix.spaservicios.mapper.IMapper; public interface TipoIdentificacionMapper extends IMapper<TipoIdentificacion> { } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/entidades/ds/NivelEducativo.java package co.com.xoftix.spaservicios.entidades.ds; import co.com.xoftix.spaservicios.entidades.ax.Descriptor; public class NivelEducativo extends Descriptor { /** * */ private static final long serialVersionUID = -8744153159600424956L; } <file_sep>/SPAServicios/src/test/java/co/com/xoftix/spaservicios/servicios/ge/IProvinciaServicioTest.java package co.com.xoftix.spaservicios.servicios.ge; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import co.com.xoftix.spaservicios.entidades.ge.Provincia; import co.com.xoftix.spaservicios.servicios.BaseTest; public class IProvinciaServicioTest extends BaseTest { @Autowired private IProvinciaServicio iProvinciaServicio; @Test public void consultar() { try { List<Provincia> provincias = iProvinciaServicio .consultar(new Provincia()); Assert.assertNotNull(provincias); Assert.assertTrue(provincias.size() >= 0); } catch (Exception e) { Assert.fail("Se ha presentado un error en la consulta " + e.getMessage()); } } @Test public void consultarPaginado() { try { List<Provincia> provincias = iProvinciaServicio.consultar( new Provincia(), 6, 5); Assert.assertNotNull(provincias); Assert.assertTrue(provincias.size() >= 0); } catch (Exception e) { Assert.fail("Se ha presentado un error en la consulta " + e.getMessage()); } } } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/servicios/ds/ITipoIdentificacionServicio.java package co.com.xoftix.spaservicios.servicios.ds; import co.com.xoftix.spaservicios.entidades.ds.TipoIdentificacion; import co.com.xoftix.spaservicios.servicios.IServicio; /** * * @author jmoraxoftix */ public interface ITipoIdentificacionServicio extends IServicio<TipoIdentificacion> { } <file_sep>/SPAServicios/src/main/java/co/com/xoftix/spaservicios/servicios/ds/impl/NivelEducativoServicioImpl.java package co.com.xoftix.spaservicios.servicios.ds.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import co.com.xoftix.spaservicios.entidades.ds.NivelEducativo; import co.com.xoftix.spaservicios.mapper.ds.NivelEducativoMapper; import co.com.xoftix.spaservicios.servicios.AbstractServicio; import co.com.xoftix.spaservicios.servicios.ds.INivelEducativoServicio; @Service @Transactional public class NivelEducativoServicioImpl extends AbstractServicio<NivelEducativo> implements INivelEducativoServicio { @Autowired private NivelEducativoMapper nivelEducativoMapper; @Override public List<NivelEducativo> consultar(NivelEducativo entidad) throws Exception { return nivelEducativoMapper.consultar(entidad); } } <file_sep>/SPAServicios/src/test/java/co/com/xoftix/spaservicios/servicios/ds/INivelEducativoServicioTest.java package co.com.xoftix.spaservicios.servicios.ds; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import co.com.xoftix.spaservicios.entidades.ds.NivelEducativo; import co.com.xoftix.spaservicios.servicios.BaseTest; public class INivelEducativoServicioTest extends BaseTest { @Autowired private INivelEducativoServicio iNivelEducativoServicio; @Test public void consultar() { try { List<NivelEducativo> NivelEducativos = iNivelEducativoServicio .consultar(new NivelEducativo()); if (!NivelEducativos.isEmpty()) { NivelEducativo NivelEducativo = NivelEducativos.get(0); NivelEducativo.setId(null); NivelEducativos = iNivelEducativoServicio .consultar(NivelEducativo); Assert.assertNotNull(NivelEducativos); Assert.assertTrue(NivelEducativos.size() >= 1); NivelEducativo.setActivo(null); NivelEducativos = iNivelEducativoServicio .consultar(NivelEducativo); Assert.assertNotNull(NivelEducativos); Assert.assertTrue(NivelEducativos.size() >= 1); NivelEducativo.setCodigo(null); NivelEducativos = iNivelEducativoServicio .consultar(NivelEducativo); Assert.assertNotNull(NivelEducativos); Assert.assertTrue(NivelEducativos.size() >= 1); NivelEducativo.setNombre(null); NivelEducativos = iNivelEducativoServicio .consultar(NivelEducativo); Assert.assertNotNull(NivelEducativos); Assert.assertTrue(NivelEducativos.size() >= 1); NivelEducativo.setControl(null); NivelEducativos = iNivelEducativoServicio .consultar(NivelEducativo); Assert.assertNotNull(NivelEducativos); Assert.assertTrue(NivelEducativos.size() >= 1); NivelEducativo.setIdDescriptor(null); NivelEducativos = iNivelEducativoServicio .consultar(NivelEducativo); Assert.assertNotNull(NivelEducativos); Assert.assertTrue(NivelEducativos.size() >= 1); NivelEducativo.setIcono(null); NivelEducativos = iNivelEducativoServicio .consultar(NivelEducativo); Assert.assertNotNull(NivelEducativos); Assert.assertTrue(NivelEducativos.size() >= 1); } Assert.assertNotNull(NivelEducativos); Assert.assertTrue(NivelEducativos.size() >= 0); } catch (Exception e) { Assert.fail("Se ha presentado un error en la consulta " + e.getMessage()); } } } <file_sep>/SPAServicios/src/test/java/co/com/xoftix/spaservicios/servicios/ds/IOficioServicioTest.java package co.com.xoftix.spaservicios.servicios.ds; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import co.com.xoftix.spaservicios.entidades.ds.Oficio; import co.com.xoftix.spaservicios.servicios.BaseTest; public class IOficioServicioTest extends BaseTest { @Autowired private IOficioServicio iOficioServicio; @Test public void consultar() { try { List<Oficio> Oficios = iOficioServicio.consultar(new Oficio()); if (!Oficios.isEmpty()) { Oficio Oficio = Oficios.get(0); Oficio.setId(null); Oficios = iOficioServicio.consultar(Oficio); Assert.assertNotNull(Oficios); Assert.assertTrue(Oficios.size() >= 1); Oficio.setActivo(null); Oficios = iOficioServicio.consultar(Oficio); Assert.assertNotNull(Oficios); Assert.assertTrue(Oficios.size() >= 1); Oficio.setCodigo(null); Oficios = iOficioServicio.consultar(Oficio); Assert.assertNotNull(Oficios); Assert.assertTrue(Oficios.size() >= 1); Oficio.setNombre(null); Oficios = iOficioServicio.consultar(Oficio); Assert.assertNotNull(Oficios); Assert.assertTrue(Oficios.size() >= 1); Oficio.setControl(null); Oficios = iOficioServicio.consultar(Oficio); Assert.assertNotNull(Oficios); Assert.assertTrue(Oficios.size() >= 1); Oficio.setIdDescriptor(null); Oficios = iOficioServicio.consultar(Oficio); Assert.assertNotNull(Oficios); Assert.assertTrue(Oficios.size() >= 1); Oficio.setIcono(null); Oficios = iOficioServicio.consultar(Oficio); Assert.assertNotNull(Oficios); Assert.assertTrue(Oficios.size() >= 1); } Assert.assertNotNull(Oficios); Assert.assertTrue(Oficios.size() >= 0); } catch (Exception e) { Assert.fail("Se ha presentado un error en la consulta " + e.getMessage()); } } } <file_sep>/SPAServicios/src/test/java/co/com/xoftix/spaservicios/servicios/ds/TipoIdentificacionServicioTest.java package co.com.xoftix.spaservicios.servicios.ds; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import co.com.xoftix.spaservicios.entidades.ds.TipoIdentificacion; import co.com.xoftix.spaservicios.servicios.BaseTest; public class TipoIdentificacionServicioTest extends BaseTest { @Autowired private ITipoIdentificacionServicio iTipoIdentificacionServicio; @Test public void consultar() { try { List<TipoIdentificacion> TipoIdentificacions = iTipoIdentificacionServicio.consultar(new TipoIdentificacion()); if (!TipoIdentificacions.isEmpty()) { TipoIdentificacion TipoIdentificacion = TipoIdentificacions.get(0); TipoIdentificacion.setId(null); TipoIdentificacions = iTipoIdentificacionServicio.consultar(TipoIdentificacion); Assert.assertNotNull(TipoIdentificacions); Assert.assertTrue(TipoIdentificacions.size() >= 1); TipoIdentificacion.setActivo(null); TipoIdentificacions = iTipoIdentificacionServicio.consultar(TipoIdentificacion); Assert.assertNotNull(TipoIdentificacions); Assert.assertTrue(TipoIdentificacions.size() >= 1); TipoIdentificacion.setCodigo(null); TipoIdentificacions = iTipoIdentificacionServicio.consultar(TipoIdentificacion); Assert.assertNotNull(TipoIdentificacions); Assert.assertTrue(TipoIdentificacions.size() >= 1); TipoIdentificacion.setNombre(null); TipoIdentificacions = iTipoIdentificacionServicio.consultar(TipoIdentificacion); Assert.assertNotNull(TipoIdentificacions); Assert.assertTrue(TipoIdentificacions.size() >= 1); TipoIdentificacion.setControl(null); TipoIdentificacions = iTipoIdentificacionServicio.consultar(TipoIdentificacion); Assert.assertNotNull(TipoIdentificacions); Assert.assertTrue(TipoIdentificacions.size() >= 1); TipoIdentificacion.setIdDescriptor(null); TipoIdentificacions = iTipoIdentificacionServicio.consultar(TipoIdentificacion); Assert.assertNotNull(TipoIdentificacions); Assert.assertTrue(TipoIdentificacions.size() >= 1); TipoIdentificacion.setIcono(null); TipoIdentificacions = iTipoIdentificacionServicio.consultar(TipoIdentificacion); Assert.assertNotNull(TipoIdentificacions); Assert.assertTrue(TipoIdentificacions.size() >= 1); } Assert.assertNotNull(TipoIdentificacions); Assert.assertTrue(TipoIdentificacions.size() >= 0); } catch (Exception e) { Assert.fail("Se ha presentado un error en la consulta " + e.getMessage()); } } }
33f8d8c3cfc3928b7994df1a6f2dc1672c21b91d
[ "Markdown", "Java" ]
33
Java
jluismorav/restful-spring-mybatis-hazelcast
ea5391f25b434a588d9e2ac4fd5acc68ac71c316
82dc32c456b3cd0b74b246f63342d8208cee6c91
refs/heads/master
<repo_name>nextlevelsports/mailchimp-importer<file_sep>/src/api/subscribe.js import _ from 'lodash'; import request from 'superagent'; const API_ENDPOINT = 'http://localhost:8000'; const post = (listId, batch) => request .post(`${API_ENDPOINT}/subscribe`) .send({ list_id: listId, subscribers: batch, }); const subscribe = (listId, records) => { let index = 0; let length = 0; let batch = []; while (length < _.size(records)) { batch.push(records[length]); index += 1; if (index === 500) { post(batch); batch = []; index = 0; } length += 1; } return post(listId, batch); }; export default subscribe; <file_sep>/README.md # User Stories 1. As a user, I can see all the lists in Mailchimp, so that I can select the list I want to import to. 2. As a user, I can upload the CSV report from Blue Sombrero, so that I don't have to manually segment the users by program and location. # Use Cases 1. Send a promotional email to the entire Next Level Family. 2. Send a league updates email to everyone who's playing in the current season. 3. Send a marketing email to a specific program or a groups of programs in the current season. 4. Send a league updates email to a specific division. 5. Send a promotional update email to a specific team name. 6. Send a league email to all volunteers. 7. Send a league email to all registrants. 8. Send a league email to all registrants and volunteers. 9. Send a league email to everyone on the waitlist. # Specifications * Retrieve all lists from Mailchimp and display name in a radio button. * All contacts should be imported to the Taj Mahal list and the specific list selected above. * If contact already exists, update the information, otherwise, create a new contact. * Mailchimp group name and League program name should match exactly. Create a group for the program if it doesn't exist yet. * Create list with merge fields ## Lists * NextLevel Family (The Taj Mahal) * Individual season by sports e.g. 2017-Flag, 2017-Hoops ## Groups * Program Names e.g. San Francisco - Sacred Heart ## List `post` /lists Creates a new list List { name: string, contact { company: string, address1: string, city: string, state: string, zip: string, country: string, phone: string, }, permission_reminder: string campaign_defaults { from_name: string, from_email: string, subject: string, language: string, }, email_type_option: boolean, } `post` /lists/{list_id} Batch sub/unsub list members Batch { members { email_address: string, email_type: string, // html status: string, // subscribed merge_fields: { ... }, location: { latitude: number, longitude: number, }, timestamp_signup: string, timestamp_opt: string, }, update_existing: boolean // true } ### Merge Fields `post` /lists/{list_id}/merge-fields Create merge fields in a specific list Merge Fields { name: string, default_value: string, options: { phone_format: string // US }, type: string, // text number address phone email date url imageurl radio dropdown birthday zip } ### Interest (Groups) `post` /lists/{list_id}/interest-categories Create a new interest category in a specific list Interest Category { title: string, type: string, // hidden } `post` /lists/{list_id}/interest-categories/{interest_category_id}/interests Create a new group name for a specific category Interest { name: string } <file_sep>/src/api/getLists.js import _ from 'lodash'; import request from 'superagent'; <file_sep>/src/csv/read.js const read = (file) => { const reader = new FileReader(); return new Promise((resolve, reject) => { reader.onload = (event) => { file.data = event.target.result; return resolve(file); }; reader.onerror = () => reject(this); reader.readAsText(file); }); }; export default read; <file_sep>/src/file/read.js const readFile = (file) => { let reader = new FileReader(); return new Promise((resolve, reject) => { reader.onload = (event) => { file.data = event.target.result; console.log('Reading file'); return resolve(file); }; reader.onerror = () => { return reject(this); }; reader.readAsText(file); }); }; export default readFile; <file_sep>/serverless/config.js const loadConfig = (config) => { Object.keys(config).forEach((key) => { process.env[key] = config[key]; }); }; export default loadConfig; <file_sep>/src/App.js import React, { Component } from 'react'; import _ from 'lodash'; import readFile from './csv/read'; import parseCSV from './csv/parse'; import subscribe from './api/subscribe'; import { createSegment, getSegments } from './api/segments'; class App extends Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); this.handleFileChange = this.handleFileChange.bind(this); } componentDidMount() { } async handleSubmit(e) { e.preventDefault(); const file = this.inputFile.files[0]; const csvData = await readFile(file); const records = await parseCSV(csvData.data); const listId = 'f88e932bf5'; const programs = _(records).map('Program Name').uniq().value(); const segmentsReq = await getSegments(listId); _.each(programs, (program) => { if (!segmentsReq.body.indexOf(program) > -1) { createSegment(listId, program) .then(res => console.log('Segments created', res)); } }); subscribe(listId, records).end(); } render() { return ( <div className="container my-3"> <div className="row"> <div className="col-sm-8 offset-sm-2"> <h2 className="mb-3">Mailchimp List Importer</h2> <p> This tool parses all register users in the csv and import them to the selected Mailchimp list. </p> <p><strong>Instructions</strong></p> <ol> <li>Download the enrollments report in <em>csv</em> format from <a href="http://nextlevelflag.com/">Blue Sombrero</a>.</li> <li>Upload the <em>csv</em> file here.</li> <li>Log into your <a href="http://mailchimp.com">Mailchimp</a> account and create your campaign.</li> </ol> <form> <div className="input-group"> <input className="form-control" type="file" id="file" ref={(c) => { this.inputFile = c; }} onChange={this.handleFileChange} /> <div className="input-group-btn"> <button className="btn btn-primary" onClick={this.handleSubmit} > Upload File </button> </div> </div> </form> </div> </div> </div> ); } } export default App; <file_sep>/src/csv/parse.js import csv from 'csv'; const parse = (data) => { const parser = csv.parse({ columns: true, auto_parse: true }); const output = []; return new Promise((resolve, reject) => { parser.on('readable', () => { let record; while ((record = parser.read())) { output.push(record); } }); parser.on('finish', () => resolve(output)); parser.on('error', err => reject(err)); parser.write(data); parser.end(); }); }; export default parse;
1b2b4782c2692ecc93d3301b2c19d05ea462566f
[ "JavaScript", "Markdown" ]
8
JavaScript
nextlevelsports/mailchimp-importer
be6d2631d20b2955b8ecd153cb3dfd8d03ea7ee0
06ec051cc2824ac453bd393880f0a1f5fb53e35a
refs/heads/master
<file_sep>function modalImg() { let works = document.querySelector('.works'), photoMin = document.querySelectorAll('.photo_min'), popupImgWorks = document.createElement('div'), popupWorksContent = document.createElement('div'); popupImgWorks.classList.add('popup_img'); popupWorksContent.classList.add('popup_img_content'); works.appendChild(popupImgWorks); popupImgWorks.appendChild(popupWorksContent); photoMin.forEach(function(photo, index) { photo.addEventListener("click", function(event) { event.preventDefault(); popupWorksContent.innerHTML = `<img src='img/our_works/big_img/${index + 1}.png'>`; popupImgWorks.style.display = "block"; }); }); popupImgWorks.addEventListener('click', function(e){ e.preventDefault(); if (e.target == popupImgWorks) { popupImgWorks.style.display = 'none'; document.body.style.overflow = ''; } }); } module.exports = modalImg;<file_sep>window.addEventListener('DOMContentLoaded', function(){ 'use strict'; let calcs = require('./parts/calcs.js'), forms = require('./parts/forms.js'), modalImg = require('./parts/modalimg.js'), modals = require('./parts/modals.js'), tabs = require('./parts/tabs.js'), timer = require('./parts/timer.js'); calcs(); forms(); modalImg(); modals(); tabs(); timer(); });<file_sep>function calcs() { } module.exports = calcs;<file_sep># Дипломная работа на курсе Javascript от Академии Верстки (<NAME>) ### Ссылка на страницу проекта для удобства https://janaratolonbaeva.github.io/diplom_ac_v/public/index.html #### Старт 1) 01.11.2018 собрана папка по модульной структуре.
91e8611d92c65772dfe06b9ece33b32fe456a196
[ "JavaScript", "Markdown" ]
4
JavaScript
janaratolonbaeva/diplom_ac_v
709de7847071c7a2151452b63682cdc0f97df6bc
74a12b9cd03e3d0d2c1c26ed76b81cc05c17f291
refs/heads/master
<file_sep>package common.setup; import static common.setup.AllPages.*; public class AllProducts { public static String getElementSelector(String elementName) { if(System.getProperty("product").equals("YouTube")) return getYouTubeElementSelector(elementName); else if(System.getProperty("product").equals("Google")) return getGoogleElementSelector(elementName); else {System.out.println("Product has not been defined in AllProducts"); return "";} } }
f1604d7e6459ebbd11be629cd15e05b0f34778df
[ "Java" ]
1
Java
hiqatech/cucumber-selenium-tests
567e6c02ac2f071d01cef615a3e38d27bf158d65
fd4b5cb06e2aa65ebf60fdb17ae4d91dc67d41f5
refs/heads/main
<file_sep>let score=0; let Name = prompt('what\'s your name?'); alert(Name + " is a very nice name"); function mood(){ let happiness = prompt('are you happy?'); let score = 0 switch (happiness.toUpperCase()) { case 'YES': case 'Y': alert('that\'s great !'); score++; break; case 'NO': case 'N': alert("do what ever it takes to be happy , it\'s a very important thing"); break; } } mood (); function anticipation () { let end = prompt('Do you know when it\'s going to be the end of the world? '); switch (end.toUpperCase()) { case 'YES': case 'Y': alert('then i guess you already prepared yourself!'); score++; break; case 'NO': case 'N': alert("you have to be prepared as soon as possible because it\s very close"); break; } } anticipation(); function astrology () { let hole = prompt('Do yoy know what is the black hole?'); switch (hole.toUpperCase()) { case 'YES': case 'Y': alert('so you has to make youself not to drop into in'); score++; break; case 'NO': case 'N': alert("it\'s a very dense energy hole that have the capacity to consume every thing even the light!"); break; } } astrology(); function economicStatus(){ let rich = prompt('Do you think you are rich?'); switch (rich.toUpperCase()) { case 'YES': case 'Y': alert('so why you are here in the jordan!'); score++; break; case 'NO': case 'N': alert("i hope you be"); break; } } economicStatus(); function socialComunication(){ let lonely = prompt('Do you feel lonely?'); switch (lonely.toUpperCase()) { case 'YES': case 'Y': alert('that\'s better than to be with fake people'); score++; break; case 'NO': case 'N': alert("okay!"); break; } } socialComunication(); function favoritNumber (){ let num = prompt('can you guess what is my favorite number?'); for (let i = 0; i < 3; i++) { if (num > 11) { num = prompt('you are too high , try to make the number smaller'); } else if (num < 11) { num = prompt('you are too low , try to make the number bigger'); } else if (num == 11) { alert('you are right!') score++; break; } if (i == 2) { alert('my favorite number is 11'); } } } favoritNumber(); function favSeries () { let correct = false; let movie = ['friends', 'narcos', 'dexter', 'orphan black']; for (let v = 0; v < 6; v++) { let show = prompt('can you guess one of my best series ever?'); for (let j = 0; j < movie.length; j++) { if (show == movie[j]) { alert('you are right') correct = true; score++; break; }} if(correct){ break; } if(v==5){ alert('my favorite movies are '+movie); } } } favSeries(); alert('your final score is ' + score); <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>guessing game</title> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Oswald:wght@200&display=swap" rel="stylesheet"> <link rel="stylesheet" href="../css/style.css"> </head> <body> <header> <h1> A short brief about myself </h1> </header> <main> <h1> Biography </h1> <p class="pp"> My name is Qusay, I've been in my birth for almost two and a half decades. At that time, I tried hard to be a better person every new day. I can't stand to live a life full of routine and boredom, which I strive to make my life full of new experiences and here I am currently going through the experience of learning software development and honestly it is an experience full of new knowledge and interesting things </p> <h1> Eeducation history </h1> <p class="demo" > <ul> <li>high school degree in scientific specialization from <i>Omar Bin Khattab School</i> With GPA of 90% </li> <li>Bachelor degree in industrial engineering from <i>JUST</i>with Gpa of 3.2 out of 4qx</li> </ul> </p> <h1> Job Experience </h1> <p class="pp"> i lunched my own business in 2016 which is a small place for making accessories and continue for that for 2 years then, for some personal issues i had to stop this business and go forward another things.. I worked in <i>sujab industrial comapny</i> for three months as a quality control Engineer then, after that i worked in <i>Extensya</i> as customer service representative for three months </p> <h1> My Goals </h1> <p class="pp"> I have two goals: to become a millionaire and to travel to all the countries of the world. The second is to complete my postgraduate studies and get a PhD in industrial engineering from the best university in the world. </p> <h1> My top 10 series </h1> <p id="mm"> <ul> <li>Friends</li> <li>breaking bad</li> <li>prison break</li> <li>Dexter</li> <li>narcos</li> <li>Orphan black</li> <li>stranger things</li> <li>Black mirrors</li> <li>La casa de papel</li> <li>Vis a Vis</li> </ul> </p> </main> <script src="../javascript/app.js"></script> </body> </html><file_sep># class2 this repo is mainly for guessing game
54232e282e4e364fe644578e23f5c4c921e8b42c
[ "JavaScript", "HTML", "Markdown" ]
3
JavaScript
qusaiqishta/class2
3e730a1c4b67fda00f605e5d11aa201753342722
e6f91b009ee173e3dfe6b1f5a6ccc8d3ce6b37d0
refs/heads/master
<repo_name>igormartuci/angular-30.08<file_sep>/src/app/app.component.ts import { Component } from '@angular/core'; import { noComponentFactoryError } from '@angular/core/src/linker/component_factory_resolver'; @Component({ selector: 'has-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { peso:number altura:number icon = 'favicon.ico'; exibir(): void { let imc = this.peso / (Math.pow(this.altura, 2)); alert(`IMC: ${imc.toFixed(1)}`); } }
c3a283223abe9cbe05b271adcf4e976800c67b7b
[ "TypeScript" ]
1
TypeScript
igormartuci/angular-30.08
fffd6490903836aab753315273b450ce528e9b25
be46955c6b5914d791b07502bdb8fdb63c75a09f
refs/heads/master
<file_sep>from datetime import datetime from urllib.parse import urljoin from cssselect import GenericTranslator from lxml import etree from .extractors import XPathExtractor, HtmlXPathExtractor, XmlXPathExtractor from .quantity import Quantity __all__ = ['ParserError', 'ParsingError', 'Prefix', 'Group', 'Element', 'String', 'Url', 'DateTime', 'Date'] class ParserError(Exception): '''Parser is badly initialized.''' class ParsingError(Exception): '''Numebr of parsed elements doesn't match the expected quantity.''' class BaseParser(object): def __init__(self, css=None, xpath=None, namespaces=None): if xpath and css: raise ParserError('At most one of "xpath" or "css" attributes can be specified.') if xpath: self.raw_xpath = xpath elif css: self.raw_xpath = GenericTranslator().css_to_xpath(css) else: self.raw_xpath = 'self::*' self.namespaces = namespaces self._compiled_xpath = None # compile xpath lazily def __call__(self, body, url=None): return self.parse(body, url) def parse(self, body, url=None): if isinstance(body, XPathExtractor): extractor = body else: if '<?xml' in body[:128]: extractor = XmlXPathExtractor(body) else: extractor = HtmlXPathExtractor(body) return self._parse(extractor, {'url': url}) def parse_html(self, body, url=None): '''Force `etree.HTMLParser`.''' return self._parse(HtmlXPathExtractor(body), {'url': url}) def parse_xml(self, body, url=None): '''Force `etree.XMLParser`.''' return self._parse(XmlXPathExtractor(body), {'url': url}) def _parse(self, extractor, context): nodes = extractor.select(self.compiled_xpath) return self._process_nodes(nodes, context) def _process_nodes(self, nodes, context): raise NotImplementedError @property def compiled_xpath(self): if self._compiled_xpath is None: self._compiled_xpath = etree.XPath(self.raw_xpath, namespaces=self.namespaces) return self._compiled_xpath def propagate_namespaces(parser): '''Recursively propagate namespaces to children parsers.''' if parser.namespaces and hasattr(parser, 'children'): for child in parser.children: if not child.namespaces: child.namespaces = parser.namespaces propagate_namespaces(child) class ChildrenParserMixin(object): def __init__(self, **kwargs): self.children = kwargs.pop('children', None) if self.children is None: raise ParserError('You must specify "children" for %s parser.' % self.__class__.__name__) super(ChildrenParserMixin, self).__init__(**kwargs) # ensure that all children elements inherited from BaseNamedParser have names for child in self.children: if isinstance(child, BaseNamedParser) and child.name is None: raise ParserError('Children elements inherited from BaseNamedParser should have "name" specified.') # propagate namespaces to children parsers propagate_namespaces(self) class Prefix(ChildrenParserMixin, BaseParser): ''' This parser doesn't actually parse any data on its own. Instead you can use it, when many of your parsers share the same css/xpath selector prefix. ''' def __init__(self, **kwargs): self.callback = kwargs.pop('callback', None) super(Prefix, self).__init__(**kwargs) def _process_nodes(self, nodes, context): parsed_data = {} for child in self.children: parsed_data.update(child._parse(nodes, context)) if self.callback is not None: parsed_data = self.callback(parsed_data) return parsed_data class BaseNamedParser(BaseParser): def __init__(self, name=None, count=None, quant=None, callback=None, **kwargs): # `quant` is deprecated if quant is not None: if count is not None: raise ParserError('At most one of "count" or "quant" attributes can be specified.') count = quant if count is None: count = '*' super(BaseNamedParser, self).__init__(**kwargs) self.name = name self.quantity = Quantity(count) self.callback = callback def _process_nodes(self, nodes, context): # validate number of nodes num_nodes = len(nodes) if not self.quantity.check_quantity(num_nodes): if self.name: name_msg = '(name="%s")' % self.name else: name_msg = '(xpath="%s")' % self.raw_xpath raise ParsingError( 'Parser %s%s matched %s elements ("%s" expected).' % (self.__class__.__name__, name_msg, num_nodes, self.quantity.raw_quantity)) values = self._process_named_nodes(nodes, context) if self.callback is not None: values = [self.callback(x) for x in values] if self.name is None: return self._flatten_values(values) else: return {self.name: self._flatten_values(values)} def _process_named_nodes(self, nodes, context): raise NotImplementedError def _flatten_values(self, values): if self.quantity.is_single: return values[0] if values else None else: return values class Group(ChildrenParserMixin, BaseNamedParser): ''' For each element matched by css/xpath selector returns the dictionary containing the data extracted by the parsers listed in children parameter. All parsers listed in `children` parameter must have `name` specified - this is then used as the key in dictionary. ''' def _process_named_nodes(self, nodes, context): values = [] for node in nodes: child_parsed_data = {} for child in self.children: child_parsed_data.update(child._parse(node, context)) values.append(child_parsed_data) return values class Element(BaseNamedParser): ''' Returns lxml instance (`lxml.etree._Element`) of the matched element(s). If you use xpath expression and match the text content of the element (e.g. `text()` or `@attr`), unicode is returned. ''' def _process_named_nodes(self, nodes, context): return [node._root for node in nodes] class String(BaseNamedParser): ''' Extract string data from the matched element(s). Extracted value is always unicode. By default, `String` extracts the text content of only the matched element, but not its descendants. To extract and concatenate the text out of every descendant element, use `attr` parameter with the special value "_all_text" ''' def __init__(self, attr='_text', **kwargs): super(String, self).__init__(**kwargs) if attr == '_text': self.attr = 'text()' elif attr == '_all_text': self.attr = 'descendant-or-self::*/text()' elif attr == '_name': self.attr = 'name()' else: self.attr = '@' + attr def _process_named_nodes(self, nodes, context): values = [] for node in nodes: value = ''.join(node.select(self.attr).extract()) values.append(value) return self._process_values(values, context) def _process_values(self, values, context): return values class Url(String): ''' Behaves like `String` parser, but with two exceptions: - default value for `attr` parameter is "href" - if you pass `url` parameter to parse() method, the absolute url will be constructed and returned If callback is specified, it is called after the absolute urls are constructed. ''' def __init__(self, **kwargs): kwargs.setdefault('attr', 'href') super(Url, self).__init__(**kwargs) def _process_values(self, values, context): url = context.get('url') if url: return [urljoin(url, v.strip()) for v in values] else: return [v.strip() for v in values] class DateTime(String): ''' Returns the `datetime.datetime` object constructed out of the extracted data: `datetime.strptime(extracted_data, format)` ''' def __init__(self, format, **kwargs): super(DateTime, self).__init__(**kwargs) self.format = format def _process_values(self, values, context): return [datetime.strptime(v, self.format) for v in values] class Date(DateTime): ''' Returns the `datetime.date` object constructed out of the extracted data: `datetime.strptime(extracted_data, format).date()` ''' def _process_values(self, values, context): values = super(Date, self)._process_values(values, context) return [v.date() for v in values] <file_sep>__all__ = ['XPathExtractor', 'XmlXPathExtractor', 'HtmlXPathExtractor'] from .lxml_extractor import XPathExtractor, XmlXPathExtractor, HtmlXPathExtractor <file_sep>from lxml import etree from .extractor_list import XPathExtractorList class XPathExtractor(object): _parser = etree.HTMLParser _tostring_method = 'html' def __init__(self, body=None, namespaces=None, _root=None): self.namespaces = namespaces if _root is None: self._root = self._get_root(body) else: self._root = _root def _get_root(self, body, encoding=None): body = body.strip() or self._empty_doc if isinstance(body, str): body = body.encode('utf-8') encoding = 'utf-8' parser = self._parser(recover=True, encoding=encoding) return etree.fromstring(body, parser=parser) def select(self, xpath): if not hasattr(self._root, 'xpath'): return XPathExtractorList([]) if isinstance(xpath, etree.XPath): result = xpath(self._root) else: result = self._root.xpath(xpath, namespaces=self.namespaces) if not isinstance(result, list): result = [result] return XPathExtractorList(self.__class__(_root=x, namespaces=self.namespaces) for x in result) def extract(self): try: return etree.tostring(self._root, method=self._tostring_method, encoding=str, with_tail=False) except (AttributeError, TypeError): if self._root is True: return '1' elif self._root is False: return '0' else: return str(self._root) def register_namespace(self, prefix, uri): if self.namespaces is None: self.namespaces = {} self.namespaces[prefix] = uri def __nonzero__(self): return bool(self.extract()) def __str__(self): data = repr(self.extract()[:40]) return '<%s data=%s>' % (type(self).__name__, data) __repr__ = __str__ class XmlXPathExtractor(XPathExtractor): _parser = etree.XMLParser _tostring_method = 'xml' _empty_doc = '<?xml version="1.0" encoding="UTF-8"?>' class HtmlXPathExtractor(XPathExtractor): _parser = etree.HTMLParser _tostring_method = 'html' _empty_doc = '<html/>' <file_sep>from .parsers import * __version__ = '0.1.8' <file_sep>from datetime import datetime, date from urllib.parse import urlparse import copy import unittest from lxml import etree from xextract.parsers import ( ParserError, ParsingError, BaseParser, BaseNamedParser, Prefix, Group, Element, String, Url, DateTime, Date) class TestBuild(unittest.TestCase): def test_build(self): # missing children for Group / Prefix parsers self.assertRaisesRegex(ParserError, r'You must specify "children" for Prefix parser', Prefix) self.assertRaisesRegex(ParserError, r'You must specify "children" for Group parser', Group) # missing name of children elements self.assertRaisesRegex(ParserError, r'Children elements inherited from BaseNamedParser', lambda: Prefix(children=[String()])) self.assertRaisesRegex(ParserError, r'Children elements inherited from BaseNamedParser', lambda: Group(children=[String()])) self.assertRaisesRegex(ParserError, r'Children elements inherited from BaseNamedParser', lambda: Prefix(children=[Prefix(children=[String()])])) self.assertRaisesRegex(ParserError, r'Children elements inherited from BaseNamedParser', lambda: Prefix(children=[Group(name='x', children=[String()])])) class TestBaseParser(unittest.TestCase): parser_class = BaseParser parser_kwargs = {} def test_init(self): # xpath / css missing parser = self.parser_class(**self.parser_kwargs) self.assertEqual(parser.raw_xpath, 'self::*') # both xpath / css specified self.assertRaises(ParserError, self.parser_class, css='a', xpath='//a', **self.parser_kwargs) # css specified self.parser_class(css='a', **self.parser_kwargs) # xpath specified self.parser_class(xpath='//a', **self.parser_kwargs) class MockParser(BaseParser): def _process_nodes(self, nodes, context): return nodes class TestParser(TestBaseParser): parser_class = MockParser def test_html_extraction(self): html = ''' <ul> <li>a</li> <li>b</li> </ul> ''' # xpath self.assertEqual(len(MockParser(xpath='//ul').parse(html)), 1) self.assertEqual(len(MockParser(xpath='ul').parse(html)), 0) self.assertEqual(len(MockParser(xpath='/ul').parse(html)), 0) self.assertEqual(len(MockParser(xpath='//li').parse(html)), 2) self.assertEqual(len(MockParser(xpath='li').parse(html)), 0) self.assertEqual(len(MockParser(xpath='/li').parse(html)), 0) self.assertEqual(len(MockParser(xpath='//ul/li').parse(html)), 2) self.assertEqual(len(MockParser(xpath='//ul//li').parse(html)), 2) # css self.assertEqual(len(MockParser(css='ol').parse(html)), 0) self.assertEqual(len(MockParser(css='ul').parse(html)), 1) self.assertEqual(len(MockParser(css='li').parse(html)), 2) def test_xml_extraction(self): xml = ''' <?xml version="1.0" encoding="UTF-8"?> <body xmlns="http://test.com/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <ul> <li>a</li> <xsi:li>b</xsi:li> </ul> </body> ''' namespaces = {'a': 'http://test.com/', 'b': 'http://www.w3.org/2001/XMLSchema-instance'} # xpath self.assertEqual(len(MockParser(xpath='//a:ul', namespaces=namespaces).parse(xml)), 1) self.assertEqual(len(MockParser(xpath='a:ul', namespaces=namespaces).parse(xml)), 1) self.assertEqual(len(MockParser(xpath='/a:ul', namespaces=namespaces).parse(xml)), 0) self.assertEqual(len(MockParser(xpath='//a:li', namespaces=namespaces).parse(xml)), 1) self.assertEqual(len(MockParser(xpath='a:li', namespaces=namespaces).parse(xml)), 0) self.assertEqual(len(MockParser(xpath='/a:li', namespaces=namespaces).parse(xml)), 0) self.assertEqual(len(MockParser(xpath='//b:li', namespaces=namespaces).parse(xml)), 1) self.assertEqual(len(MockParser(xpath='b:li', namespaces=namespaces).parse(xml)), 0) self.assertEqual(len(MockParser(xpath='/b:li', namespaces=namespaces).parse(xml)), 0) class MockNamedParser(BaseNamedParser): def _process_named_nodes(self, nodes, context): return [node.extract() for node in nodes] class TestBaseNamedParser(TestBaseParser): parser_class = MockNamedParser parser_kwargs = {'name': 'val'} return_value_type = str html = ''' <ul> <li>a</li> <li>b</li> </ul> ''' def test_check_quantity(self): self.assertRaises(ParsingError, self.parser_class(css='li', count=0, **self.parser_kwargs).parse, self.html) self.assertRaises(ParsingError, self.parser_class(css='li', count=1, **self.parser_kwargs).parse, self.html) self.assertRaises(ParsingError, self.parser_class(css='ul', count=2, **self.parser_kwargs).parse, self.html) self.assertRaises(ParsingError, self.parser_class(css='ul', count=(2, 3), **self.parser_kwargs).parse, self.html) self.assertRaises(ParsingError, self.parser_class(css='li', count='?', **self.parser_kwargs).parse, self.html) self.assertRaises(ParsingError, self.parser_class(css='ol', count='+', **self.parser_kwargs).parse, self.html) def test_check_quantity_return_type(self): self.assertIsNone(self.parser_class(css='ol', count=0, **self.parser_kwargs).parse(self.html)['val']) self.assertIsInstance(self.parser_class(css='ul', count=1, **self.parser_kwargs).parse(self.html)['val'], self.return_value_type) self.assertIsInstance(self.parser_class(css='li', count=2, **self.parser_kwargs).parse(self.html)['val'], list) self.assertIsInstance(self.parser_class(css='ol', count=(0, 0), **self.parser_kwargs).parse(self.html)['val'], list) self.assertIsInstance(self.parser_class(css='ul', count=(1, 1), **self.parser_kwargs).parse(self.html)['val'], list) self.assertIsInstance(self.parser_class(css='li', count=(1, 2), **self.parser_kwargs).parse(self.html)['val'], list) self.assertIsNone(self.parser_class(css='ol', count='?', **self.parser_kwargs).parse(self.html)['val']) self.assertIsInstance(self.parser_class(css='ul', count='?', **self.parser_kwargs).parse(self.html)['val'], self.return_value_type) self.assertIsInstance(self.parser_class(css='ol', count='*', **self.parser_kwargs).parse(self.html)['val'], list) self.assertIsInstance(self.parser_class(css='ul', count='*', **self.parser_kwargs).parse(self.html)['val'], list) self.assertIsInstance(self.parser_class(css='li', count='*', **self.parser_kwargs).parse(self.html)['val'], list) self.assertIsInstance(self.parser_class(css='ul', count='+', **self.parser_kwargs).parse(self.html)['val'], list) self.assertIsInstance(self.parser_class(css='li', count='+', **self.parser_kwargs).parse(self.html)['val'], list) def test_missing_name(self): no_name_parser_kwargs = copy.copy(self.parser_kwargs) del no_name_parser_kwargs['name'] self.assertIsNone(self.parser_class(css='ol', count=0, **no_name_parser_kwargs).parse(self.html)) self.assertIsInstance(self.parser_class(css='ul', count=1, **no_name_parser_kwargs).parse(self.html), self.return_value_type) self.assertIsInstance(self.parser_class(css='li', count=2, **no_name_parser_kwargs).parse(self.html), list) class TestString(TestBaseNamedParser): parser_class = String def test_basic(self): html = '<span data-val="rocks">Hello <b>world</b>!</span>' # by default extract _text self.assertEqual(String(name='val', css='span', count=1).parse(html)['val'], 'Hello !') self.assertEqual(String(name='val', css='span', count=1, attr='_text').parse(html)['val'], 'Hello !') self.assertEqual(String(name='val', css='span', count=1, attr='_all_text').parse(html)['val'], 'Hello world!') self.assertEqual(String(name='val', css='span', count=1, attr='data-val').parse(html)['val'], 'rocks') self.assertEqual(String(name='val', css='span', count=1, attr='data-invalid').parse(html)['val'], '') def test_callback(self): html = '<span>1</span><span>2</span>' self.assertListEqual(String(css='span').parse(html), ['1', '2']) self.assertListEqual(String(css='span', callback=int).parse(html), [1, 2]) self.assertEqual(String(css='span:first-child', callback=int, count=1).parse(html), 1) self.assertListEqual(String(css='div', callback=int).parse(html), []) class TestUrl(TestBaseNamedParser): parser_class = Url def test_basic(self): html = '<a href="/test?a=b" data-val="/val">Hello <b>world</b>!</a>' # by default extract href self.assertEqual(Url(name='val', css='a', count=1).parse(html)['val'], '/test?a=b') self.assertEqual(Url(name='val', css='a', count=1).parse(html, url='http://example.com/a/b/c')['val'], 'http://example.com/test?a=b') self.assertEqual(Url(name='val', css='a', count=1, attr='data-val').parse(html)['val'], '/val') self.assertEqual(Url(name='val', css='a', count=1, attr='data-val').parse(html, url='http://example.com/a/b/c')['val'], 'http://example.com/val') def test_callback(self): def _parse_scheme(url): return urlparse(url).scheme html = '<a href="/test"></a>' self.assertEqual(Url(css='a', count=1, callback=_parse_scheme).parse(html), '') self.assertEqual(Url(css='a', count=1, callback=_parse_scheme).parse(html, url='http://example.com/a/b/c'), 'http') class TestDateTime(TestBaseNamedParser): parser_class = DateTime parser_kwargs = {'name': 'val', 'format': '%d.%m.%Y %H:%M'} return_value_type = datetime html = '''<ul><li>1.1.2001 22:14</li><li>2.1.2001 12:12</li>20.3.2002 0:0</ul>''' def test_basic(self): html = '<span data-val="1.1.2001">24.11.2015 10:12</span>' val = DateTime(name='val', css='span', count=1, format='%d.%m.%Y %H:%M').parse(html)['val'] self.assertEqual(val, datetime(year=2015, month=11, day=24, hour=10, minute=12)) val = DateTime(name='val', css='span', count=1, format='%d.%m.%Y', attr='data-val').parse(html)['val'] self.assertEqual(val, datetime(year=2001, month=1, day=1)) # invalid format self.assertRaises(ValueError, DateTime(name='val', css='span', count=1, format='%d').parse, html) def test_callback(self): def _get_day(dt): return dt.day html = '<span>24.11.2015</span>' self.assertEqual( DateTime(css='span', count=1, format='%d.%m.%Y', callback=_get_day).parse(html), 24) class TestDate(TestBaseNamedParser): parser_class = Date parser_kwargs = {'name': 'val', 'format': '%d.%m.%Y'} return_value_type = date html = '''<ul><li>1.1.2001</li><li>2.1.2001</li>20.3.2002</ul>''' def test_basic(self): html = '<span data-val="1.1.2001">24.11.2015</span>' val = Date(name='val', css='span', count=1, format='%d.%m.%Y').parse(html)['val'] self.assertEqual(val, date(year=2015, month=11, day=24)) val = Date(name='val', css='span', count=1, format='%d.%m.%Y', attr='data-val').parse(html)['val'] self.assertEqual(val, date(year=2001, month=1, day=1)) # invalid format self.assertRaises(ValueError, Date(name='val', css='span', count=1, format='%d').parse, html) def test_callback(self): def _get_day(dt): return dt.day html = '<span>24.11.2015</span>' self.assertEqual( Date(css='span', count=1, format='%d.%m.%Y', callback=_get_day).parse(html), 24) class TestElement(TestBaseNamedParser): parser_class = Element parser_kwargs = {'name': 'val'} return_value_type = etree._Element def test_basic(self): html = '<span>Hello <b>world</b>!</span>' val = Element(name='val', css='span', count=1).parse(html)['val'] self.assertEqual(val.tag, 'span') val = Element(name='val', css='b', count=1).parse(html)['val'] self.assertEqual(val.tag, 'b') def test_callback(self): html = '<span>Hello <b>world</b>!</span>' val = Element(css='b', count=1, callback=lambda el: el.text).parse(html) self.assertEqual(val, 'world') def test_text_extract(self): html = '<span>Hello<br> world<b> nothing to see </b>!</span>' val = Element(xpath='//span/text()').parse(html) self.assertListEqual(val, ['Hello', ' world', '!']) html = '<span class="nice"></span>' val = Element(xpath='//span/@class', count=1).parse(html) self.assertEqual(val, 'nice') class TestGroup(TestBaseNamedParser): parser_class = Group parser_kwargs = {'name': 'val', 'children': []} return_value_type = dict html = ''' <ul> <li> <span>Mike</span> </li> <li> <span>John</span> <a href="/test">link</a> </li> </ul>''' def test_basic(self): extracted = {'val': [ {'name': 'Mike', 'link': None}, {'name': 'John', 'link': 'http://example.com/test'}]} # css val = Group(name='val', css='li', count=2, children=[ String(name='name', css='span', count=1), Url(name='link', css='a', count='?') ]).parse(self.html, url='http://example.com/') self.assertDictEqual(val, extracted) # xpath val = Group(name='val', css='li', count=2, children=[ String(name='name', xpath='span', count=1), Url(name='link', xpath='a', count='?') ]).parse(self.html, url='http://example.com/') self.assertDictEqual(val, extracted) val = Group(name='val', css='li', count=2, children=[ String(name='name', xpath='descendant::span', count=1), Url(name='link', xpath='descendant::a', count='?') ]).parse(self.html, url='http://example.com/') self.assertDictEqual(val, extracted) def test_callback(self): val = Group(css='li', count=2, callback=lambda d: d['name'], children=[ String(name='name', css='span', count=1), ]).parse(self.html) self.assertListEqual(val, ['Mike', 'John']) class TestPrefix(TestBaseParser): parser_class = Prefix parser_kwargs = {'children': []} html = ''' <ul> <li> <span>Mike</span> </li> <li> <span>John</span> </li> </ul> ''' def test_basic(self): # css val = Prefix(css='li', children=[ String(name='name', css='span', count=2) ]).parse(self.html) self.assertDictEqual(val, {'name': ['Mike', 'John']}) # xpath val = Prefix(xpath='//li', children=[ String(name='name', xpath='span', count=2) ]).parse(self.html) self.assertDictEqual(val, {'name': ['Mike', 'John']}) def test_callback(self): val = Prefix(xpath='//li', callback=lambda d: d['name'], children=[ String(name='name', css='span', count=2), ]).parse(self.html) self.assertListEqual(val, ['Mike', 'John']) <file_sep>import unittest from xextract.quantity import Quantity class TestQuantity(unittest.TestCase): def test_create(self): self.assertEqual(Quantity().raw_quantity, '*') good = [' *', ' + ', '? ', ' 1321 ', '007', ' 8800, 9231 ', '1,2', '9999', '5,5', 9999, '0', '10000', 0, 10000, (1, 2), (0, 0)] for g in good: quantity = Quantity(g) self.assertIsNotNone(quantity._check_quantity_func) bad = ['', None, ' * * ', '+*', ' ', '1 2', '1,2,3', '+2', '-2', '3,2', 1.0, -1, (3, 2), (-1, 5)] for b in bad: self.assertRaises(ValueError, Quantity, b) def test_err(self): q = Quantity('*') err = ['0', [0], None, 'help'] for e in err: self.assertRaises(ValueError, q.check_quantity, e) def test_star(self): q = Quantity('*') self._test_good(q, [0, 1, 2, 5, 10, 1000, 2**30]) self._test_bad(q, [-1, -2]) def test_plus(self): q = Quantity('+') self._test_good(q, [1, 2, 5, 10, 1000, 2**30]) self._test_bad(q, [0, -1, -2]) def test_ques(self): q = Quantity('?') self._test_good(q, [0, 1]) self._test_bad(q, [-2, -1, 2, 3, 10, 100]) def test_1d(self): q = Quantity('47') self._test_good(q, [47]) self._test_bad(q, [0, 1, -1, -47, 46, 48, 100]) q = Quantity(47) self._test_good(q, [47]) self._test_bad(q, [0, 1, -1, -47, 46, 48, 100]) def test_2d(self): q = Quantity('5, 10') self._test_good(q, [5, 6, 7, 8, 9, 10]) self._test_bad(q, [0, 1, 2, 3, 4, 11, 12, 13, -5, -10]) q = Quantity((5, 10)) self._test_good(q, [5, 6, 7, 8, 9, 10]) self._test_bad(q, [0, 1, 2, 3, 4, 11, 12, 13, -5, -10]) def _test_good(self, q, good): for g in good: self.assertTrue(q.check_quantity(g)) def _test_bad(self, q, bad): for b in bad: self.assertFalse(q.check_quantity(b)) <file_sep>import unittest from xextract.extractors.lxml_extractor import XPathExtractor, XmlXPathExtractor, HtmlXPathExtractor class TestXpathExtractor(unittest.TestCase): xs_cls = XPathExtractor hxs_cls = HtmlXPathExtractor xxs_cls = XmlXPathExtractor def test_extractor_simple(self): text = '<p><input name="a" value="1"/><input name="b" value="2"/></p>' xpath = self.hxs_cls(text) xl = xpath.select('//input') self.assertEqual(2, len(xl)) for x in xl: self.assertIsInstance(x, self.hxs_cls) self.assertEqual(xpath.select('//input').extract(), [x.extract() for x in xpath.select('//input')]) self.assertEqual([x.extract() for x in xpath.select('//input[@name="a"]/@name')], ['a']) self.assertEqual([x.extract() for x in xpath.select('number(concat(//input[@name="a"]/@value, //input[@name="b"]/@value))')], ['12.0']) self.assertEqual(xpath.select('concat("xpath", "rules")').extract(), ['xpathrules']) self.assertEqual([x.extract() for x in xpath.select('concat(//input[@name="a"]/@value, //input[@name="b"]/@value)')], ['12']) def test_extractor_unicode_query(self): text = '<p><input name="\xa9" value="1"/></p>' xpath = self.hxs_cls(text) self.assertEqual(xpath.select('//input[@name="\xa9"]/@value').extract(), ['1']) def test_extractor_same_type(self): '''Test XPathExtractor returning the same type in x() method.''' text = '<p>test<p>' self.assertIsInstance(self.xxs_cls(text).select('//p')[0], self.xxs_cls) self.assertIsInstance(self.hxs_cls(text).select('//p')[0], self.hxs_cls) def test_extractor_boolean_result(self): text = '<p><input name="a" value="1"/><input name="b" value="2"/></p>' xs = self.hxs_cls(text) self.assertEqual(xs.select('//input[@name="a"]/@name="a"').extract(), ['1']) self.assertEqual(xs.select('//input[@name="a"]/@name="n"').extract(), ['0']) def test_extractor_xml_html(self): '''Test that XML and HTML XPathExtractor's behave differently.''' # some text which is parsed differently by XML and HTML flavors text = '<div><img src="a.jpg"><p>Hello</div>' self.assertEqual(self.xxs_cls(text).select('//div').extract(), ['<div><img src="a.jpg"><p>Hello</p></img></div>']) self.assertEqual(self.hxs_cls(text).select('//div').extract(), ['<div><img src="a.jpg"><p>Hello</p></div>']) def test_extractor_nested(self): '''Nested extractor tests.''' text = '''<body> <div class='one'> <ul> <li>one</li><li>two</li> </ul> </div> <div class='two'> <ul> <li>four</li><li>five</li><li>six</li> </ul> </div> </body>''' x = self.hxs_cls(text) divtwo = x.select('//div[@class="two"]') self.assertEqual(list(map(str.strip, divtwo.select('//li').extract())), ['<li>one</li>', '<li>two</li>', '<li>four</li>', '<li>five</li>', '<li>six</li>']) self.assertEqual(list(map(str.strip, divtwo.select('./ul/li').extract())), ['<li>four</li>', '<li>five</li>', '<li>six</li>']) self.assertEqual(list(map(str.strip, divtwo.select('.//li').extract())), ['<li>four</li>', '<li>five</li>', '<li>six</li>']) self.assertEqual(divtwo.select('./li').extract(), []) def test_dont_strip(self): hxs = self.hxs_cls('<div>fff: <a href="#">zzz</a></div>') self.assertEqual(hxs.select('//text()').extract(), ['fff: ', 'zzz']) def test_extractor_namespaces_simple(self): text = ''' <test xmlns:somens="http://github.com/"> <somens:a id="foo">take this</a> <a id="bar">found</a> </test> ''' x = self.xxs_cls(text) x.register_namespace('somens', 'http://github.com/') self.assertEqual(x.select('//somens:a/text()').extract(), ['take this']) def test_extractor_namespaces_multiple(self): text = '''<?xml version="1.0" encoding="UTF-8"?> <BrowseNode xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05" xmlns:b="http://somens.com" xmlns:p="http://www.github.com/product" > <b:Operation>hello</b:Operation> <TestTag b:att="value"><Other>value</Other></TestTag> <p:SecondTestTag><material>iron</material><price>90</price><p:name><NAME></p:name></p:SecondTestTag> </BrowseNode> ''' x = self.xxs_cls(text) x.register_namespace('xmlns', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05') x.register_namespace('p', 'http://www.github.com/product') x.register_namespace('b', 'http://somens.com') self.assertEqual(len(x.select('//xmlns:TestTag')), 1) self.assertEqual(x.select('//b:Operation/text()').extract()[0], 'hello') self.assertEqual(x.select('//xmlns:TestTag/@b:att').extract()[0], 'value') self.assertEqual(x.select('//p:SecondTestTag/xmlns:price/text()').extract()[0], '90') self.assertEqual(x.select('//p:SecondTestTag').select('./xmlns:price/text()')[0].extract(), '90') self.assertEqual(x.select('//p:SecondTestTag/xmlns:material/text()').extract()[0], 'iron') def test_extractor_over_text(self): hxs = self.hxs_cls('<root>lala</root>') self.assertEqual(hxs.extract(), '<html><body><root>lala</root></body></html>') xxs = self.xxs_cls('<root>lala</root>') self.assertEqual(xxs.extract(), '<root>lala</root>') xxs = self.xxs_cls('<root>lala</root>') self.assertEqual(xxs.select('.').extract(), ['<root>lala</root>']) def test_extractor_invalid_xpath(self): x = self.hxs_cls('<html></html>') xpath = '//test[@foo="bar]' self.assertRaises(Exception, x.select, xpath) def test_empty_bodies(self): # shouldn't raise errors self.hxs_cls('').select('//text()').extract() self.xxs_cls('').select('//text()').extract() def test_null_bytes(self): # shouldn't raise errors text = '<root>pre\x00post</root>' self.hxs_cls(text).select('//text()').extract() self.xxs_cls(text).select('//text()').extract() def test_select_on_unevaluable_nodes(self): r = self.hxs_cls('<span class="big">some text</span>') # Text node x1 = r.select('//text()') self.assertEqual(x1.extract(), ['some text']) self.assertEqual(x1.select('.//b').extract(), []) # Tag attribute x1 = r.select('//span/@class') self.assertEqual(x1.extract(), ['big']) self.assertEqual(x1.select('.//text()').extract(), []) def test_select_on_text_nodes(self): r = self.hxs_cls('<div><b>Options:</b>opt1</div><div><b>Other</b>opt2</div>') x1 = r.select('//div/descendant::text()[preceding-sibling::b[contains(text(), "Options")]]') self.assertEqual(x1.extract(), ['opt1']) x1 = r.select('//div/descendant::text()/preceding-sibling::b[contains(text(), "Options")]') self.assertEqual(x1.extract(), ['<b>Options:</b>']) <file_sep>class XPathExtractorList(list): def __getslice__(self, i, j): return self.__class__(list.__getslice__(self, i, j)) def select(self, xpath): return self.__class__(node for extractor in self for node in extractor.select(xpath)) def extract(self): return [x.extract() for x in self] <file_sep>******** xextract ******** Extract structured data from HTML and XML documents like a boss. **xextract** is simple enough for writing a one-line parser, yet powerful enough to be used in a big project. **Features** - Parsing of HTML and XML documents - Supports **xpath** and **css** selectors - Simple declarative style of parsers - Built-in self-validation to let you know when the structure of the website has changed - Speed - under the hood the library uses `lxml library <http://lxml.de/>`_ with compiled xpath selectors **Table of Contents** .. contents:: :local: :depth: 2 :backlinks: none ==================== A little taste of it ==================== Let's parse `The Shawshank Redemption <http://www.imdb.com/title/tt0111161/>`_'s IMDB page: .. code-block:: python # fetch the website >>> import requests >>> response = requests.get('http://www.imdb.com/title/tt0111161/') # parse like a boss >>> from xextract import String, Group # extract title with css selector >>> String(css='h1[itemprop="name"]', count=1).parse(response.text) 'The Shawshank Redemption' # extract release year with xpath selector >>> String(xpath='//*[@id="titleYear"]/a', count=1, callback=int).parse(response.text) 1994 # extract structured data >>> Group(css='.cast_list tr:not(:first-child)', children=[ ... String(name='name', css='[itemprop="actor"]', attr='_all_text', count=1), ... String(name='character', css='.character', attr='_all_text', count=1) ... ]).parse(response.text) [ {'name': '<NAME>', 'character': '<NAME>'}, {'name': '<NAME>', 'character': "<NAME> 'Red' Redding"}, ... ] ============ Installation ============ To install **xextract**, simply run: .. code-block:: bash $ pip install xextract Requirements: lxml, cssselect Supported Python versions are 3.5 - 3.11. Windows users can download lxml binary `here <http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml>`_. ======= Parsers ======= ------ String ------ **Parameters**: `name`_ (optional), `css / xpath`_ (optional, default ``"self::*"``), `count`_ (optional, default ``"*"``), `attr`_ (optional, default ``"_text"``), `callback`_ (optional), `namespaces`_ (optional) Extract string data from the matched element(s). Extracted value is always unicode. By default, ``String`` extracts the text content of only the matched element, but not its descendants. To extract and concatenate the text out of every descendant element, use ``attr`` parameter with the special value ``"_all_text"``: Use ``attr`` parameter to extract the data from an HTML/XML attribute. Use ``callback`` parameter to post-process extracted values. Example: .. code-block:: python >>> from xextract import String >>> String(css='span', count=1).parse('<span>Hello <b>world</b>!</span>') 'Hello !' >>> String(css='span', count=1, attr='class').parse('<span class="text-success"></span>') 'text-success' # use special `attr` value `_all_text` to extract and concantenate text out of all descendants >>> String(css='span', count=1, attr='_all_text').parse('<span>Hello <b>world</b>!</span>') 'Hello world!' # use special `attr` value `_name` to extract tag name of the matched element >>> String(css='span', count=1, attr='_name').parse('<span>hello</span>') 'span' >>> String(css='span', callback=int).parse('<span>1</span><span>2</span>') [1, 2] --- Url --- **Parameters**: `name`_ (optional), `css / xpath`_ (optional, default ``"self::*"``), `count`_ (optional, default ``"*"``), `attr`_ (optional, default ``"href"``), `callback`_ (optional), `namespaces`_ (optional) Behaves like ``String`` parser, but with two exceptions: * default value for ``attr`` parameter is ``"href"`` * if you pass ``url`` parameter to ``parse()`` method, the absolute url will be constructed and returned If ``callback`` is specified, it is called *after* the absolute urls are constructed. Example: .. code-block:: python >>> from xextract import Url, Prefix >>> content = '<div id="main"> <a href="/test">Link</a> </div>' >>> Url(css='a', count=1).parse(content) '/test' >>> Url(css='a', count=1).parse(content, url='http://github.com/Mimino666') 'http://github.com/test' # absolute url address. Told ya! >>> Prefix(css='#main', children=[ ... Url(css='a', count=1) ... ]).parse(content, url='http://github.com/Mimino666') # you can pass url also to ancestor's parse(). It will propagate down. 'http://github.com/test' -------- DateTime -------- **Parameters**: `name`_ (optional), `css / xpath`_ (optional, default ``"self::*"``), ``format`` (**required**), `count`_ (optional, default ``"*"``), `attr`_ (optional, default ``"_text"``), `callback`_ (optional) `namespaces`_ (optional) Returns the ``datetime.datetime`` object constructed out of the extracted data: ``datetime.strptime(extracted_data, format)``. ``format`` syntax is described in the `Python documentation <https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior>`_. If ``callback`` is specified, it is called *after* the datetime objects are constructed. Example: .. code-block:: python >>> from xextract import DateTime >>> DateTime(css='span', count=1, format='%d.%m.%Y %H:%M').parse('<span>24.12.2015 5:30</span>') datetime.datetime(2015, 12, 24, 50, 30) ---- Date ---- **Parameters**: `name`_ (optional), `css / xpath`_ (optional, default ``"self::*"``), ``format`` (**required**), `count`_ (optional, default ``"*"``), `attr`_ (optional, default ``"_text"``), `callback`_ (optional) `namespaces`_ (optional) Returns the ``datetime.date`` object constructed out of the extracted data: ``datetime.strptime(extracted_data, format).date()``. ``format`` syntax is described in the `Python documentation <https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior>`_. If ``callback`` is specified, it is called *after* the datetime objects are constructed. Example: .. code-block:: python >>> from xextract import Date >>> Date(css='span', count=1, format='%d.%m.%Y').parse('<span>24.12.2015</span>') datetime.date(2015, 12, 24) ------- Element ------- **Parameters**: `name`_ (optional), `css / xpath`_ (optional, default ``"self::*"``), `count`_ (optional, default ``"*"``), `callback`_ (optional), `namespaces`_ (optional) Returns lxml instance (``lxml.etree._Element``) of the matched element(s). If you use xpath expression and match the text content of the element (e.g. ``text()`` or ``@attr``), unicode is returned. If ``callback`` is specified, it is called with ``lxml.etree._Element`` instance. Example: .. code-block:: python >>> from xextract import Element >>> Element(css='span', count=1).parse('<span>Hello</span>') <Element span at 0x2ac2990> >>> Element(css='span', count=1, callback=lambda el: el.text).parse('<span>Hello</span>') 'Hello' # same as above >>> Element(xpath='//span/text()', count=1).parse('<span>Hello</span>') 'Hello' ----- Group ----- **Parameters**: `name`_ (optional), `css / xpath`_ (optional, default ``"self::*"``), `children`_ (**required**), `count`_ (optional, default ``"*"``), `callback`_ (optional), `namespaces`_ (optional) For each element matched by css/xpath selector returns the dictionary containing the data extracted by the parsers listed in ``children`` parameter. All parsers listed in ``children`` parameter **must** have ``name`` specified - this is then used as the key in dictionary. Typical use case for this parser is when you want to parse structured data, e.g. list of user profiles, where each profile contains fields like name, address, etc. Use ``Group`` parser to group the fields of each user profile together. If ``callback`` is specified, it is called with the dictionary of parsed children values. Example: .. code-block:: python >>> from xextract import Group >>> content = '<ul><li id="id1">michal</li> <li id="id2">peter</li></ul>' >>> Group(css='li', count=2, children=[ ... String(name='id', xpath='self::*', count=1, attr='id'), ... String(name='name', xpath='self::*', count=1) ... ]).parse(content) [{'name': 'michal', 'id': 'id1'}, {'name': 'peter', 'id': 'id2'}] ------ Prefix ------ **Parameters**: `css / xpath`_ (optional, default ``"self::*"``), `children`_ (**required**), `namespaces`_ (optional) This parser doesn't actually parse any data on its own. Instead you can use it, when many of your parsers share the same css/xpath selector prefix. ``Prefix`` parser always returns a single dictionary containing the data extracted by the parsers listed in ``children`` parameter. All parsers listed in ``children`` parameter **must** have ``name`` specified - this is then used as the key in dictionary. Example: .. code-block:: python # instead of... >>> String(css='#main .name').parse(...) >>> String(css='#main .date').parse(...) # ...you can use >>> from xextract import Prefix >>> Prefix(css='#main', children=[ ... String(name="name", css='.name'), ... String(name="date", css='.date') ... ]).parse(...) ================= Parser parameters ================= ---- name ---- **Parsers**: `String`_, `Url`_, `DateTime`_, `Date`_, `Element`_, `Group`_ **Default value**: ``None`` If specified, then the extracted data will be returned in a dictionary, with the ``name`` as the key and the data as the value. All parsers listed in ``children`` parameter of ``Group`` or ``Prefix`` parser **must** have ``name`` specified. If multiple children parsers have the same ``name``, the behavior is undefined. Example: .. code-block:: python # when `name` is not specified, raw value is returned >>> String(css='span', count=1).parse('<span>Hello!</span>') 'Hello!' # when `name` is specified, dictionary is returned with `name` as the key >>> String(name='message', css='span', count=1).parse('<span>Hello!</span>') {'message': 'Hello!'} ----------- css / xpath ----------- **Parsers**: `String`_, `Url`_, `DateTime`_, `Date`_, `Element`_, `Group`_, `Prefix`_ **Default value (xpath)**: ``"self::*"`` Use either ``css`` or ``xpath`` parameter (but not both) to select the elements from which to extract the data. Under the hood css selectors are translated into equivalent xpath selectors. For the children of ``Prefix`` or ``Group`` parsers, the elements are selected relative to the elements matched by the parent parser. Example: .. code-block:: python Prefix(xpath='//*[@id="profile"]', children=[ # equivalent to: //*[@id="profile"]/descendant-or-self::*[@class="name"] String(name='name', css='.name', count=1), # equivalent to: //*[@id="profile"]/*[@class="title"] String(name='title', xpath='*[@class="title"]', count=1), # equivalent to: //*[@class="subtitle"] String(name='subtitle', xpath='//*[@class="subtitle"]', count=1) ]) ----- count ----- **Parsers**: `String`_, `Url`_, `DateTime`_, `Date`_, `Element`_, `Group`_ **Default value**: ``"*"`` ``count`` specifies the expected number of elements to be matched with css/xpath selector. It serves two purposes: 1. Number of matched elements is checked against the ``count`` parameter. If the number of elements doesn't match the expected countity, ``xextract.parsers.ParsingError`` exception is raised. This way you will be notified, when the website has changed its structure. 2. It tells the parser whether to return a single extracted value or a list of values. See the table below. Syntax for ``count`` mimics the regular expressions. You can either pass the value as a string, single integer or tuple of two integers. Depending on the value of ``count``, the parser returns either a single extracted value or a list of values. +-------------------+-----------------------------------------------+-----------------------------+ | Value of ``count``| Meaning | Extracted data | +===================+===============================================+=============================+ | ``"*"`` (default) | Zero or more elements. | List of values | +-------------------+-----------------------------------------------+-----------------------------+ | ``"+"`` | One or more elements. | List of values | +-------------------+-----------------------------------------------+-----------------------------+ | ``"?"`` | Zero or one element. | Single value or ``None`` | +-------------------+-----------------------------------------------+-----------------------------+ | ``num`` | Exactly ``num`` elements. | ``num`` == 0: ``None`` | | | | | | | You can pass either string or integer. | ``num`` == 1: Single value | | | | | | | | ``num`` > 1: List of values | +-------------------+-----------------------------------------------+-----------------------------+ | ``(num1, num2)`` | Number of elements has to be between | List of values | | | ``num1`` and ``num2``, inclusive. | | | | | | | | You can pass either a string or 2-tuple. | | +-------------------+-----------------------------------------------+-----------------------------+ Example: .. code-block:: python >>> String(css='.full-name', count=1).parse(content) # return single value '<NAME>' >>> String(css='.full-name', count='1').parse(content) # same as above '<NAME>' >>> String(css='.full-name', count=(1,2)).parse(content) # return list of values ['<NAME>'] >>> String(css='.full-name', count='1,2').parse(content) # same as above ['<NAME>'] >>> String(css='.middle-name', count='?').parse(content) # return single value or None None >>> String(css='.job-titles', count='+').parse(content) # return list of values ['President', 'US Senator', 'State Senator', 'Senior Lecturer in Law'] >>> String(css='.friends', count='*').parse(content) # return possibly empty list of values [] >>> String(css='.friends', count='+').parse(content) # raise exception, when no elements are matched xextract.parsers.ParsingError: Parser String matched 0 elements ("+" expected). ---- attr ---- **Parsers**: `String`_, `Url`_, `DateTime`_, `Date`_ **Default value**: ``"href"`` for ``Url`` parser. ``"_text"`` otherwise. Use ``attr`` parameter to specify what data to extract from the matched element. +-------------------+-----------------------------------------------------+ | Value of ``attr`` | Meaning | +===================+=====================================================+ | ``"_text"`` | Extract the text content of the matched element. | +-------------------+-----------------------------------------------------+ | ``"_all_text"`` | Extract and concatenate the text content of | | | the matched element and all its descendants. | +-------------------+-----------------------------------------------------+ | ``"_name"`` | Extract tag name of the matched element. | +-------------------+-----------------------------------------------------+ | ``att_name`` | Extract the value out of ``att_name`` attribute of | | | the matched element. | | | | | | If such attribute doesn't exist, empty string is | | | returned. | +-------------------+-----------------------------------------------------+ Example: .. code-block:: python >>> from xextract import String, Url >>> content = '<span class="name">Barack <strong>Obama</strong> III.</span> <a href="/test">Link</a>' >>> String(css='.name', count=1).parse(content) # default attr is "_text" 'Barack III.' >>> String(css='.name', count=1, attr='_text').parse(content) # same as above 'Barack III.' >>> String(css='.name', count=1, attr='_all_text').parse(content) # all text 'Barack Obama III.' >>> String(css='.name', count=1, attr='_name').parse(content) # tag name 'span' >>> Url(css='a', count='1').parse(content) # Url extracts href by default '/test' >>> String(css='a', count='1', attr='id').parse(content) # non-existent attributes return empty string '' -------- callback -------- **Parsers**: `String`_, `Url`_, `DateTime`_, `Date`_, `Element`_, `Group`_ Provides an easy way to post-process extracted values. It should be a function that takes a single argument, the extracted value, and returns the postprocessed value. Example: .. code-block:: python >>> String(css='span', callback=int).parse('<span>1</span><span>2</span>') [1, 2] >>> Element(css='span', count=1, callback=lambda el: el.text).parse('<span>Hello</span>') 'Hello' -------- children -------- **Parsers**: `Group`_, `Prefix`_ Specifies the children parsers for the ``Group`` and ``Prefix`` parsers. All parsers listed in ``children`` parameter **must** have ``name`` specified Css/xpath selectors in the children parsers are relative to the selectors specified in the parent parser. Example: .. code-block:: python Prefix(xpath='//*[@id="profile"]', children=[ # equivalent to: //*[@id="profile"]/descendant-or-self::*[@class="name"] String(name='name', css='.name', count=1), # equivalent to: //*[@id="profile"]/*[@class="title"] String(name='title', xpath='*[@class="title"]', count=1), # equivalent to: //*[@class="subtitle"] String(name='subtitle', xpath='//*[@class="subtitle"]', count=1) ]) ---------- namespaces ---------- **Parsers**: `String`_, `Url`_, `DateTime`_, `Date`_, `Element`_, `Group`_, `Prefix`_ When parsing XML documents containing namespace prefixes, pass the dictionary mapping namespace prefixes to namespace URIs. Use then full name for elements in xpath selector in the form ``"prefix:element"`` As for the moment, you **cannot use default namespace** for parsing (see `lxml docs <http://lxml.de/FAQ.html#how-can-i-specify-a-default-namespace-for-xpath-expressions>`_ for more information). Just use an arbitrary prefix. Example: .. code-block:: python >>> content = '''<?xml version='1.0' encoding='UTF-8'?> ... <movie xmlns="http://imdb.com/ns/"> ... <title>The Shawshank Redemption</title> ... <year>1994</year> ... </movie>''' >>> nsmap = {'imdb': 'http://imdb.com/ns/'} # use arbitrary prefix for default namespace >>> Prefix(xpath='//imdb:movie', namespaces=nsmap, children=[ # pass namespaces to the outermost parser ... String(name='title', xpath='imdb:title', count=1), ... String(name='year', xpath='imdb:year', count=1) ... ]).parse(content) {'title': 'The Shawshank Redemption', 'year': '1994'} ==================== HTML vs. XML parsing ==================== To extract data from HTML or XML document, simply call ``parse()`` method of the parser: .. code-block:: python >>> from xextract import * >>> parser = Prefix(..., children=[...]) >>> extracted_data = parser.parse(content) ``content`` can be either string or unicode, containing the content of the document. Under the hood **xextact** uses either ``lxml.etree.XMLParser`` or ``lxml.etree.HTMLParser`` to parse the document. To select the parser, **xextract** looks for ``"<?xml"`` string in the first 128 bytes of the document. If it is found, then ``XMLParser`` is used. To force either of the parsers, you can call ``parse_html()`` or ``parse_xml()`` method: .. code-block:: python >>> parser.parse_html(content) # force lxml.etree.HTMLParser >>> parser.parse_xml(content) # force lxml.etree.XMLParser <file_sep>from setuptools import setup with open('README.rst', 'r') as f: readme = f.read() setup( name='xextract', version='0.1.8', description='Extract structured data from HTML and XML documents like a boss.', long_description=readme, long_description_content_type='text/x-rst', author='Michal "Mimino" Danilak', author_email='<EMAIL>', url='https://github.com/Mimino666/python-xextract', keywords='HTML parse parsing extraction extract crawl', packages=['xextract', 'xextract.extractors'], package_data={'': ['LICENSE']}, include_package_data=True, install_requires=['lxml', 'cssselect'], test_suite='tests', license='MIT', zip_safe=False, classifiers=( 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ), ) <file_sep>import re class Quantity(object): ''' Quantity is used to verify that the number of items satisfies the expected quantity, which you specify with a regexp-like syntax. Syntax: * - zero or more items + - one or more items ? - zero or one item count - specified number of items (0 <= count) lower, upper - number of items in interval [lower, upper] (0 <= lower <= upper). ''' def __init__(self, quantity='*'): self.raw_quantity = quantity self.lower = self.upper = 0 # lower and upper bounds on quantity self._check_quantity_func = self._parse_quantity(quantity) def check_quantity(self, n): '''Return True, if `n` matches the specified quantity.''' if not isinstance(n, int): raise ValueError( 'Invalid argument for `check_quantity()`. ' 'Integer expected, %s received: %s' % (type(n), repr(n))) return self._check_quantity_func(n) def _check_star(self, n): return n >= 0 def _check_plus(self, n): return n >= 1 def _check_question_mark(self, n): return n == 0 or n == 1 def _check_1d(self, n): return n == self.upper def _check_2d(self, n): return self.lower <= n <= self.upper _quantity_parsers = ( # regex, check_funcname (re.compile(r'^\s*\*\s*$'), '_check_star'), (re.compile(r'^\s*\+\s*$'), '_check_plus'), (re.compile(r'^\s*\?\s*$'), '_check_question_mark'), (re.compile(r'^\s*(?P<upper>\d+)\s*$'), '_check_1d'), (re.compile(r'^\s*(?P<lower>\d+)\s*,\s*(?P<upper>\d+)\s*$'), '_check_2d')) def _parse_quantity(self, quantity): ''' If `quantity` represents a valid quantity expression, return the method that checks for the specified quantity. Otherwise raise ValueError. ''' # quantity is specified as a single integer if isinstance(quantity, int): self.upper = quantity if 0 <= self.upper: return self._check_1d else: raise ValueError('Invalid quantity: %s' % repr(quantity)) # quantity is specified as a pair of integers if isinstance(quantity, (list, tuple)) and len(quantity) == 2: self.lower, self.upper = quantity if (isinstance(self.lower, int) and isinstance(self.upper, int) and 0 <= self.lower <= self.upper): return self._check_2d else: raise ValueError('Invalid quantity: %s' % repr(quantity)) # quantity is specified as a string if isinstance(quantity, str): for parser, check_funcname in self._quantity_parsers: match = parser.search(quantity) if match: # set lower and upper values gd = match.groupdict() self.lower = int(gd.get('lower', 0)) self.upper = int(gd.get('upper', 0)) # check lower/upper bounds if self.lower <= self.upper: return getattr(self, check_funcname) else: raise ValueError('Invalid quantity: %s' % repr(quantity)) # quantity is of a bad type raise ValueError('Invalid quantity: %s' % repr(quantity)) @property def is_single(self): '''True, if the quantity represents a single element.''' return ( self._check_quantity_func == self._check_question_mark or (self._check_quantity_func == self._check_1d and self.upper <= 1))
8f3ba8b4776b10972be881af96b38d849d8095bd
[ "Python", "reStructuredText" ]
11
Python
Mimino666/python-xextract
08b9c326b6433ee931bb7703e2acf27ffc317029
b90f51bbd7862f4ffb93a17f9810c435a0158c61
refs/heads/main
<repo_name>Charlito33/Tyvalia-RP-Launcher<file_sep>/Tyvalia RP Launcher/src/fr/tyvaliarp/launcher/LauncherMain.java package fr.tyvaliarp.launcher; import fr.trxyy.alternative.alternative_api.*; import fr.trxyy.alternative.alternative_api.maintenance.GameMaintenance; import fr.trxyy.alternative.alternative_api.maintenance.Maintenance; import fr.trxyy.alternative.alternative_api_ui.LauncherBackground; import fr.trxyy.alternative.alternative_api_ui.LauncherPane; import fr.trxyy.alternative.alternative_api_ui.base.AlternativeBase; import fr.trxyy.alternative.alternative_api_ui.base.LauncherBase; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.stage.StageStyle; /* Launcher by Charlito33 made with Love <3 PLEASE DON'T DELETE CREDITS */ public class LauncherMain extends AlternativeBase { private GameFolder gameFolder = new GameFolder("tyvaliaRP"); private LauncherPreferences launcherPreferences = new LauncherPreferences("Tyvalia RP Launcher", 950, 600, true); private GameEngine gameEngine = new GameEngine(gameFolder, launcherPreferences, GameVersion.V_1_12_2, GameStyle.FORGE_1_8_TO_1_12_2); private GameLinks gameLinks = new GameLinks("http://tyvalia-rp.000webhostapp.com/launcher/", "1.12.2.json"); private GameConnect gameConnect = new GameConnect("tyvalia-rp.mine.gg", "10004"); private GameMaintenance gameMaintenance = new GameMaintenance(Maintenance.USE, gameEngine); private GameMemory gameMemory = GameMemory.RAM_4G; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { Scene scene = new Scene(createContent()); this.gameEngine.reg(primaryStage); this.gameEngine.reg(this.gameLinks); this.gameEngine.reg(this.gameConnect); this.gameEngine.reg(this.gameMaintenance); this.gameEngine.reg(this.gameMemory); LauncherBase launcherBase = new LauncherBase(primaryStage, scene, StageStyle.TRANSPARENT, gameEngine); launcherBase.setIconImage(primaryStage, getResourceLocation().loadImage(gameEngine, "favicon.png")); } private Parent createContent() { LauncherPane contentPane = new LauncherPane(gameEngine); Rectangle rectangle = new Rectangle(gameEngine.getLauncherPreferences().getWidth(), gameEngine.getLauncherPreferences().getHeight()); rectangle.setArcWidth(15.0); rectangle.setArcHeight(15.0); contentPane.setClip(rectangle); new LauncherBackground(gameEngine, getResourceLocation().getMedia(gameEngine, "background.mp4"), contentPane); new LauncherPanel(contentPane, gameEngine); return contentPane; } } <file_sep>/README.md # Tyvalia RP Launcher Launcher officiel de Tyvalia RP **Versions :** - 0.1.0 : - Création du Launcher - 0.2.0 *(Version jamais compilée)* : - Modifications de l'interface - 0.3.0d : - Ajout du "d" en fin de version pour les versions de dev - Ajout de la musique - Ajout du bouton du site web - 0.3.1d : - Patch de la mise à jour qui ne se lance pas - Patch de la musique qui continue pendant la MAJ et pendant le jeu - 0.4.0d : - Ajout de l'IP du serveur - Ajout de la connexion crack - 0.5.0d : - Changement du nom de version dans le titre (Qui n'avais pas été changé en v0.4.0d) - Changement du player de la musique - Ajout d'un slider pour changer le volume de la musique - Le bouton de musique est caché quand on se connecte - Ajout d'un check du pseudo pour éviter les pseudos avec des caractères spéciaux - 0.6.0d : - Ajout du Changement de la RAM - Autres modifications - 1.0.0 : - Passage en version release - Ajout d'une checkbox pour un compte premium ou non<file_sep>/JARS/Infos.md # Informations - La version 0.1.0 est aussi connue sous le nom "Dev Release 0", qui n'est pas sur le GitHub - La version 0.2.0 n'existe pas - A partir de la version 0.3.0d, il y a un "d" à la fin de la version pour indiquer une version de dev <file_sep>/Tyvalia RP Launcher/src/fr/tyvaliarp/launcher/LauncherAlertPanel.java package fr.tyvaliarp.launcher; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LauncherAlertPanel extends JPanel { int frameWidth, frameHeight; String title, text; JButton closeButton; LauncherAlertPanel INSTANCE; public LauncherAlertPanel(JFrame frame, String title, String text) { this.INSTANCE = this; this.frameWidth = frame.getWidth(); this.frameHeight = frame.getHeight(); this.title = title; this.text = text; setBackground(new Color(0, 0, 0, 0)); setForeground(new Color(255, 255, 255, 255)); setLayout(null); closeButton = new JButton("Fermer"); closeButton.setForeground(new Color(255, 255, 255, 255)); closeButton.setBounds(frameWidth - 10 - 100, frameHeight - 10 - 25, 100, 25); closeButton.setContentAreaFilled(false); closeButton.setBorderPainted(false); closeButton.setFocusPainted(false); closeButton.setOpaque(false); closeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SwingUtilities.getWindowAncestor(INSTANCE).dispose(); } }); add(closeButton); } @Override public void paint(Graphics g) { super.paint(g); g.setColor(Color.BLACK); g.fillRect(frameWidth - 10 - 100, frameHeight - 10 - 25, 100, 25); g.setColor(Color.WHITE); g.setFont(new Font("TimesRoman", Font.PLAIN, 12)); g.drawString("Fermer", frameWidth - 80, frameHeight - 18); g.setColor(Color.BLACK); g.fillRect(0, 0, frameWidth, 38); g.setColor(Color.WHITE); g.setFont(new Font("TimesRoman", Font.PLAIN, 28)); g.drawString(title, 5, 28); g.setColor(new Color(255, 255, 255, 191)); g.setFont(new Font("TimesRoman", Font.PLAIN, 14)); g.drawString(text, 5, 60); } } <file_sep>/Tyvalia RP Launcher/src/fr/tyvaliarp/launcher/LauncherPanel.java package fr.tyvaliarp.launcher; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.text.DecimalFormat; import fr.trxyy.alternative.alternative_api.GameEngine; import fr.trxyy.alternative.alternative_api.GameMemory; import fr.trxyy.alternative.alternative_api.account.AccountType; import fr.trxyy.alternative.alternative_api.auth.GameAuth; import fr.trxyy.alternative.alternative_api.updater.GameUpdater; import fr.trxyy.alternative.alternative_api.utils.FontLoader; import fr.trxyy.alternative.alternative_api.utils.Mover; import fr.trxyy.alternative.alternative_api_ui.base.IScreen; import fr.trxyy.alternative.alternative_api_ui.components.LauncherButton; import fr.trxyy.alternative.alternative_api_ui.components.LauncherImage; import fr.trxyy.alternative.alternative_api_ui.components.LauncherLabel; import fr.trxyy.alternative.alternative_api_ui.components.LauncherPasswordField; import fr.trxyy.alternative.alternative_api_ui.components.LauncherRectangle; import fr.trxyy.alternative.alternative_api_ui.components.LauncherTextField; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.geometry.Pos; import javafx.scene.control.CheckBox; import javafx.scene.control.Slider; import javafx.scene.layout.Pane; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.stage.Stage; import javax.sound.sampled.*; public class LauncherPanel extends IScreen { private LauncherRectangle topRectangle; private LauncherLabel titleLabel; private LauncherImage titleImage; private LauncherTextField usernameField; private LauncherPasswordField passwordField; private LauncherButton loginButton; private LauncherButton settingsButton; private LauncherButton websiteButton; private LauncherButton musicButton; private Slider musicSlider; private Slider ramSlider; private LauncherLabel ramLabel; private LauncherButton closeButton; private LauncherButton reduceButton; private Timeline timeline; private DecimalFormat decimalFormat = new DecimalFormat(".#"); private Thread updateThread; private GameUpdater gameUpdater = new GameUpdater(); private LauncherRectangle updateRectangle; private LauncherLabel updateLabel; private LauncherLabel currentFileLabel; private LauncherLabel percentageLabel; private LauncherLabel currentStep; private Media music; private MediaPlayer musicPlayer; private CheckBox premiumCheckbox; public LauncherPanel(Pane root, GameEngine engine) { music = new Media(LauncherPanel.class.getResource("/music.wav").toString()); musicPlayer = new MediaPlayer(music); musicPlayer.setVolume(0.5); musicPlayer.play(); this.topRectangle = new LauncherRectangle(root, 0, 0, engine.getWidth(), 31); this.topRectangle.setFill(Color.rgb(0, 0, 0, 0.70)); this.drawLogo(engine, getResourceLocation().loadImage(engine, "logo.png"), engine.getWidth() / 2 - 165, 100, 330, 100, root, Mover.DONT_MOVE); this.titleLabel = new LauncherLabel(root); this.titleLabel.setText("Tyvalia RP Launcher - 1.0.0"); this.titleLabel.setFont(FontLoader.loadFont("Roboto-Light.tff", "Robota Light", 18f)); this.titleLabel.setStyle("-fx-background-color: transparent; -fx-text-fill: white;"); this.titleLabel.setPosition(engine.getWidth() / 2 - 120, -4); this.titleLabel.setOpacity(0.7); this.titleLabel.setSize(500, 40); this.titleImage = new LauncherImage(root); this.titleImage.setImage(getResourceLocation().loadImage(engine, "favicon.png")); this.titleImage.setSize(25, 25); this.titleImage.setPosition(engine.getWidth() / 3, 3); this.usernameField = new LauncherTextField(root); this.usernameField.setPosition(engine.getWidth() / 2 - 135, engine.getHeight() / 2 - 57); this.usernameField.setSize(270, 50); this.usernameField.setFont(FontLoader.loadFont("Roboto-Light.tff", "<NAME>", 14f)); this.usernameField.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4); -fx-text-fill: white;"); this.usernameField.setVoidText("Pseudo / Email"); this.passwordField = new LauncherPasswordField(root); this.passwordField.setPosition(engine.getWidth() / 2 - 135, engine.getHeight() / 2); this.passwordField.setSize(270, 50); this.passwordField.setFont(FontLoader.loadFont("Roboto-Light.tff", "<NAME>", 14f)); this.passwordField.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4); -fx-text-fill: white;"); this.passwordField.setVoidText("Mot de passe"); this.loginButton = new LauncherButton(root); this.loginButton.setText("Se Connecter"); this.loginButton.setFont(FontLoader.loadFont("Roboto-Light.tff", "<NAME>", 22f)); this.loginButton.setPosition(engine.getWidth() / 2 - 135, engine.getHeight() / 2 + 60); this.loginButton.setSize(270, 45); this.loginButton.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4); -fx-text-fill: white;"); this.loginButton.setAction(event -> { if (this.usernameField.getText().length() < 3 || this.usernameField.getText().length() > 16) { new LauncherAlert("Connexion échouée", "La case du pseudo / email doit entre 3 et 16 charactères."); } else if (!NicknameUtils.check(this.usernameField.getText()) && this.passwordField.getText().isEmpty()) { new LauncherAlert("Connexion échouée", "Le pseudo contient des caractères spéciaux."); } else if (this.usernameField.getText().length() >= 3 && this.passwordField.getText().isEmpty()) { GameAuth auth = new GameAuth(this.usernameField.getText(), this.passwordField.getText(), AccountType.OFFLINE); if (auth.isLogged()) { musicPlayer.stop(); musicButton.setVisible(false); musicSlider.setVisible(false); this.update(engine, auth); } //new LauncherAlert("Connexion échouée", "Les Cracks ne sont pas acceptés !"); } else if (this.usernameField.getText().length() >= 3 && !this.passwordField.getText().isEmpty()) { GameAuth auth = new GameAuth(this.usernameField.getText(), this.passwordField.getText(), AccountType.MOJANG); if (auth.isLogged()) { musicPlayer.stop(); musicButton.setVisible(false); musicSlider.setVisible(false); this.update(engine, auth); } else { new LauncherAlert("Connexion échouée", "Identifiants incorrects"); } } else { new LauncherAlert("Connexion échouée", "La connexion à échouée, contactez un Administateur"); } }); /* this.settingsButton = new LauncherButton(root); this.settingsButton.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4); -fx-text-fill: white;"); LauncherImage settingsImg = new LauncherImage(root, getResourceLocation().loadImage(engine, "settings.png")); settingsImg.setSize(40, 40); this.settingsButton.setGraphic(settingsImg); this.settingsButton.setPosition(10, engine.getHeight() - 55); this.settingsButton.setSize(60, 45); this.settingsButton.setAction(event -> { new LauncherAlert("Action Impossible", "Cette fonction n'est pas encore implémentée"); }); */ this.websiteButton = new LauncherButton(root); this.websiteButton.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4); -fx-text-fill: white;"); LauncherImage websiteImg = new LauncherImage(root, getResourceLocation().loadImage(engine, "website.png")); websiteImg.setSize(40, 40); this.websiteButton.setGraphic(websiteImg); this.websiteButton.setPosition(10, engine.getHeight() - 55); this.websiteButton.setSize(60, 45); this.websiteButton.setAction(event -> { try { java.awt.Desktop.getDesktop().browse(new URI("https://tyvalia-rp.fr.nf/?from=launcher")); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } }); this.musicButton = new LauncherButton(root); this.musicButton.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4); -fx-text-fill: white;"); LauncherImage musicImg = new LauncherImage(root, getResourceLocation().loadImage(engine, "music-playing.png")); musicImg.setSize(40, 40); this.musicButton.setGraphic(musicImg); this.musicButton.setPosition(engine.getWidth() - 70, engine.getHeight() - 55); this.musicButton.setSize(60, 45); this.musicButton.setAction(event -> { if (musicPlayer.getStatus().equals(MediaPlayer.Status.PLAYING)) { musicPlayer.stop(); LauncherImage tempImg = new LauncherImage(root, getResourceLocation().loadImage(engine, "music-muted.png")); tempImg.setSize(40, 40); musicButton.setGraphic(tempImg); } else { musicPlayer.play(); LauncherImage tempImg = new LauncherImage(root, getResourceLocation().loadImage(engine, "music-playing.png")); tempImg.setSize(40, 40); musicButton.setGraphic(tempImg); } }); this.musicSlider = new Slider(); this.musicSlider.setMin(0); this.musicSlider.setMax(100); this.musicSlider.setValue(50); /* this.musicSlider.setShowTickLabels(true); this.musicSlider.setShowTickMarks(true); */ this.musicSlider.setBlockIncrement(10); this.musicSlider.setVisible(true); this.musicSlider.setLayoutX(engine.getWidth() - 220); this.musicSlider.setLayoutY(engine.getHeight() - 40); this.musicSlider.valueProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { musicPlayer.setVolume(newValue.doubleValue() / 100); } }); root.getChildren().add(musicSlider); this.ramSlider = new Slider(); this.ramSlider.setMin(2); this.ramSlider.setMax(10); this.ramSlider.setValue(4); this.ramSlider.setBlockIncrement(1); this.ramSlider.setVisible(true); this.ramSlider.setLayoutX(80); this.ramSlider.setLayoutY(engine.getHeight() - 40); this.ramSlider.valueProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { engine.reg(GameMemory.valueOf("RAM_" + newValue.intValue() + "G")); ramLabel.setText("RAM : " + newValue.intValue() + "GB"); } }); root.getChildren().add(ramSlider); this.premiumCheckbox = new CheckBox("Connexion Premium"); this.premiumCheckbox.setTextFill(Color.WHITE); this.premiumCheckbox.setLayoutX(400); this.premiumCheckbox.setLayoutY(420); this.premiumCheckbox.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue == Boolean.TRUE) { passwordField.setVisible(true); } else { passwordField.setText(""); passwordField.setVisible(false); } } }); this.premiumCheckbox.setSelected(true); this.premiumCheckbox.setVisible(true); root.getChildren().add(premiumCheckbox); this.ramLabel = new LauncherLabel(root); this.ramLabel.setText("RAM : 4GB"); this.ramLabel.setFont(FontLoader.loadFont("Roboto-Light.tff", "Robota Light", 18f)); this.ramLabel.setStyle("-fx-background-color: transparent; -fx-text-fill: white;"); this.ramLabel.setPosition(230, engine.getHeight() - 54); this.ramLabel.setOpacity(0.7); this.ramLabel.setSize(500, 40); this.closeButton = new LauncherButton(root); this.closeButton.setPosition(engine.getWidth() - 35, 2); this.closeButton.setInvisible(); this.closeButton.setSize(15, 15); this.closeButton.setBackground(null); LauncherImage closeImg = new LauncherImage(root, getResourceLocation().loadImage(engine, "close.png")); closeImg.setSize(15, 15); this.closeButton.setGraphic(closeImg); this.closeButton.setOnAction(event -> { System.exit(0); }); this.reduceButton = new LauncherButton(root); this.reduceButton.setPosition(engine.getWidth() - 55, 2); this.reduceButton.setInvisible(); this.reduceButton.setSize(15, 15); this.reduceButton.setBackground(null); LauncherImage reduceImg = new LauncherImage(root, getResourceLocation().loadImage(engine, "minimize.png")); reduceImg.setSize(15, 15); this.reduceButton.setGraphic(reduceImg); this.reduceButton.setOnAction(event -> { Stage stage = (Stage) ((LauncherButton) event.getSource()).getScene().getWindow(); stage.setIconified(true); }); this.updateRectangle = new LauncherRectangle(root, engine.getWidth() / 2 - 175, engine.getHeight() / 2 - 60, 350, 180); this.updateRectangle.setArcWidth(10.0); this.updateRectangle.setArcHeight(10.0); this.updateRectangle.setFill(Color.rgb(0, 0, 0, 0.60)); this.updateRectangle.setVisible(false); this.updateLabel = new LauncherLabel(root); this.updateLabel.setText("Mise à jour..."); this.updateLabel.setAlignment(Pos.CENTER); this.updateLabel.setFont(FontLoader.loadFont("Roboto-Light.tff", "Roboto Light",22f)); this.updateLabel.setStyle("-fx-background-color: transparent; -fx-text-fill: white;"); this.updateLabel.setPosition(engine.getWidth() / 2 - 95, engine.getHeight() / 2 - 55); this.updateLabel.setSize(190, 40); this.updateLabel.setVisible(false); this.currentStep = new LauncherLabel(root); this.currentStep.setText("Préparation de la mise à jour..."); this.currentStep.setFont(Font.font("Verdana", FontPosture.ITALIC, 18f)); this.currentStep.setStyle("-fx-background-color: transparent; -fx-text-fill: white;"); this.currentStep.setAlignment(Pos.CENTER); this.currentStep.setPosition(engine.getWidth() / 2 - 160, engine.getHeight() / 2 + 83); this.currentStep.setOpacity(0.4); this.currentStep.setSize(320, 40); this.currentStep.setVisible(false); this.currentFileLabel = new LauncherLabel(root); this.currentFileLabel.setText(""); this.currentFileLabel.setAlignment(Pos.CENTER); this.currentFileLabel.setFont(FontLoader.loadFont("Roboto-Light.tff", "Roboto Light",18f)); this.currentFileLabel.setStyle("-fx-background-color: transparent; -fx-text-fill: white;"); this.currentFileLabel.setPosition(engine.getWidth() / 2 - 160, engine.getHeight() / 2 + 25); this.currentFileLabel.setSize(320, 40); this.currentFileLabel.setVisible(false); this.percentageLabel = new LauncherLabel(root); this.percentageLabel.setText("0%"); this.percentageLabel.setAlignment(Pos.CENTER); this.percentageLabel.setFont(FontLoader.loadFont("Roboto-Light.tff", "Roboto Light",30f)); this.percentageLabel.setStyle("-fx-background-color: transparent; -fx-text-fill: white;"); this.percentageLabel.setPosition(engine.getWidth() / 2 - 50, engine.getHeight() / 2 - 5); this.percentageLabel.setOpacity(0.8); this.percentageLabel.setSize(100, 40); this.percentageLabel.setVisible(false); } public void update(GameEngine engine, GameAuth auth) { this.usernameField.setDisable(true); this.usernameField.setVisible(false); this.passwordField.setDisable(true); this.passwordField.setVisible(false); this.loginButton.setDisable(true); this.loginButton.setVisible(false); //this.settingsButton.setDisable(true); //this.settingsButton.setVisible(false); this.updateRectangle.setVisible(true); this.updateLabel.setVisible(true); this.currentStep.setVisible(true); this.currentFileLabel.setVisible(true); this.percentageLabel.setVisible(true); gameUpdater.reg(engine); gameUpdater.reg(auth.getSession()); engine.reg(this.gameUpdater); this.updateThread = new Thread() { public void run() { engine.getGameUpdater().run(); } }; this.updateThread.start(); this.timeline = new Timeline(new KeyFrame[] { new KeyFrame(javafx.util.Duration.seconds(0.0D), e -> updateDownload(engine), new javafx.animation.KeyValue[0]), new KeyFrame (javafx.util.Duration.seconds(0.1D), new javafx.animation.KeyValue[0]) }); this.timeline.setCycleCount(Animation.INDEFINITE); this.timeline.play(); } private void updateDownload(GameEngine engine) { if (engine.getGameUpdater().downloadedFiles > 0) { this.percentageLabel.setText(decimalFormat.format(engine.getGameUpdater().downloadedFiles * 100.0d / engine.getGameUpdater().filesToDownload) + "%"); } this.currentFileLabel.setText(engine.getGameUpdater().getCurrentFile()); this.currentStep.setText(engine.getGameUpdater().getCurrentInfo()); } }
3da049139d23653a5f247e59d9251706cc3f4070
[ "Markdown", "Java" ]
5
Java
Charlito33/Tyvalia-RP-Launcher
d8e290fb3a7a851a79df2153ce38d7c70c9ea69b
1a225fd429b529251159e8451c30db12fac2720a
refs/heads/master
<file_sep>print("hello") print("<NAME>") print("Hello Trevor!") print("I broke it!") x = 20 if(x == 20): print("X was 20!") x = 4000 print("X is now 4000!") if(x == 0): print("9+10=21!") def wordcount(sentence): word = sentence.split() print(len(word)) wordcount("this is a sentence")
d42631e9e24b77dacaf676a0be1d0cedf93b45ed
[ "Python" ]
1
Python
Sploder12/gitting
609f39bdf1828cacde08fc00912cc164902e23bc
9a29c4bf1588660d1d2c9505648b589ee8963726
refs/heads/master
<file_sep>import GetDataUtil from './get-data.js' import displayChart from './chart.js' // 展示 now 数据 const nowTemp = document.querySelector('.now-temp') const nowWeather = document.querySelector('.now-weather') const humidityInfo = document.querySelector('.humidity-info') const windDir = document.querySelector('.wind-dir') const windSc = document.querySelector('.wind-sc') const airAqi = document.querySelector('.aqi') const airStatus = document.querySelector('.status') const nowDesc = document.querySelector('.now-desc') const now = document.querySelector('.now') const locationTit = document.querySelector('.location-tit') async function displayNow(data) { locationTit.textContent = data.location nowTemp.textContent = data.tmp nowWeather.textContent = data.cond_txt humidityInfo.textContent = data.hum windDir.textContent = data.wind_dir windSc.textContent = data.wind_sc nowDesc.textContent = data.desc now.style.backgroundImage = `url(${data.bg})` airAqi.textContent = data.aqi airStatus.textContent = data.qlty } // 展示今明两天数据 const todayTempMax = document.querySelector('.today-temp>.max') const todayTempMin = document.querySelector('.today-temp>.min') const tomorrowTempMax = document.querySelector('.tomorrow-temp>.max') const tomorrowTempMin = document.querySelector('.tomorrow-temp>.min') const todayWeather = document.querySelector('.today-weather') const tomorrowWeather = document.querySelector('.tomorrow-weather') const todayWeatherIcon = document.querySelector('#todayWeatherIcon') const tomorrowWeatherIcon = document.querySelector('#tomorrowWeatherIcon') function displayTwoRecent(data) { todayTempMax.textContent = data[0].tmp_max todayTempMin.textContent = data[0].tmp_min tomorrowTempMax.textContent = data[1].tmp_max tomorrowTempMin.textContent = data[1].tmp_min todayWeather.textContent = data[0].cond_txt_d !== data[0].cond_txt_n ? `${data[0].cond_txt_d}转${data[0].cond_txt_n}` : `${data[0].cond_txt_n}` tomorrowWeather.textContent = data[1].cond_txt_d !== data[1].cond_txt_n ? `${data[1].cond_txt_d}转${data[1].cond_txt_n}` : `${data[1].cond_txt_n}` todayWeatherIcon.className = `iconfont ${data.todaySet.iconClass}` tomorrowWeatherIcon.className = `iconfont ${data.tomorrowSet.iconClass}` } // 展示结果 const cancel = document.querySelector('.cancel') async function displayResult(result) { try { const nowData = await GetDataUtil.now(result) displayNow(nowData) const twoRecentData = await GetDataUtil.twoRecent(result) displayTwoRecent(twoRecentData) const weekData = await GetDataUtil.weekData(result) displayWeek(weekData) const hourlyData = await GetDataUtil.hourlyData(result) displayHourly(hourlyData) cancel.click() } catch { alert('获取数据失败 😢...') } } // 对搜索历史进行储存 function handleStorage(value) { const history = JSON.parse(window.localStorage.history || '[]') !history.includes(value) && value !== '' && history.push(value) window.localStorage.history = JSON.stringify(history) } // 展示搜索结果 const results = document.querySelector('.results') async function displaySearchResult() { handleStorage(this.value) displayHistory() try { const data = await GetDataUtil.search(`/find?location=${this.value}`) const html = data.basic.map(info => ` <li class="result" data-location="${info.location}">${info.location}</li> `).join('') results.innerHTML = html } catch { results.innerHTML = '没有数据 😢...' } results.style.display = 'block' } // 展示 7 天天气 const chartTop = document.querySelector('.chart-top') const chartBottom = document.querySelector('.chart-bottom') function displayWeek(json) { let topHtml = '' let bottomHtml = '' const maxArr = [] const minArr = [] json.data.forEach(info => { const set = GetDataUtil.set(info.wea) topHtml += ` <div class="top-item"> <div class="day">${info.day.slice(3, 5)}</div> <div class="date">${info.date}</span></div> <span class="iconfont ${set.iconClass}"></span> </div>` bottomHtml += ` <div class="bottom-item"> <div class="weather">${info.wea}</div> <div class="wind">${info.win[0]}${info.win_speed}</div> </div>` maxArr.push(info.tem1.slice(0, 2)) minArr.push(info.tem2.slice(0, 2)) }) chartTop.innerHTML = topHtml chartBottom.innerHTML = bottomHtml displayChart(maxArr, minArr) } // 展示 hourly 数据 const hourlyWrap = document.querySelector('.hourly-wrap') function displayHourly(json) { const html = json.data[0].hours.map(hour => { const set = GetDataUtil.set(hour.wea) return ` <div class="hour"> <div class="time">${hour.day.slice(3)}</div> <span class="iconfont ${set.iconClass}"></span> <div class="temp">${hour.tem}</div> </div> `}).join('') hourlyWrap.innerHTML = html } // 展示搜索历史 const historyInfos = document.querySelector('.history>.infos') function displayHistory() { const history = JSON.parse(window.localStorage.history || '[]') const html = history.map(his => ` <div class="info" data-location="${his}">${his}</div> `).join('') historyInfos.innerHTML = html } // 第一次打开时的展示 async function firstDisplay() { GetDataUtil.hotCity() displayHistory() const location = '重庆' let cqNowData = await GetDataUtil.now(location) let cqTwoRecentData = await GetDataUtil.twoRecent(location) let cqWeekData = await GetDataUtil.weekData(location) let cqHourlyData = await GetDataUtil.hourlyData(location) displayNow(cqNowData) displayTwoRecent(cqTwoRecentData) displayWeek(cqWeekData) displayHourly(cqHourlyData) } export default { firstDisplay, searchResult: displaySearchResult, result: displayResult, } <file_sep>import jiaonang from '../img/jiaonang.png' import cloth from '../img/cloth.png' import wind from '../img/wind.png' import car from '../img/car.png' export default class lifestyle extends HTMLElement { constructor() { super() const shadow = this.attachShadow({ mode: 'open' }) const wrapper = document.createElement('div') wrapper.classList.add('wrap') wrapper.innerHTML = ` <span class="icon"></span> <p>${this.getAttribute('tit')}</p> <div class="popup-wrap"> <div class="popup"> <div class="popup-tit">${this.getAttribute('tit')}指数</div> <div class="popup-txt"></div> <button type="button" class="i-know">我知道了</button> </div> </div> ` let icon switch (this.getAttribute('tit')) { case '紫外线指数': icon = jiaonang break case '穿衣指数': icon = cloth break case '洗车指数': icon = car break case '空气污染扩散指数': icon = wind } const style = document.createElement('style') style.textContent = ` .wrap { width: 48vw; height: 48vw; border: 1vw solid #f2f2f2; display: inline-flex; background: #fff; flex-direction: column; align-items: center; } .icon { background: url(${icon}) no-repeat; background-size: 100%; background-position: center; width: 90px; height: 90px; margin-top: 8vw; } .popup-wrap { display: none; width: 100vw; position:fixed; top: 0px; left: 0px; background: rgba(0, 0, 0, 0.7); height: ${document.body.clientHeight}px; justify-content: center; align-items: center; } .popup { width: 66vw; background: #fff; border-radius: 10px; } .popup-tit { text-align: center; background: #3bbcff; border-radius: 10px 10px 0 0; line-height: 58px; color: #fff; font-size: 22px; width: 66vw; height: 58px; background: ${this.getAttribute('color')}; } .popup-txt { width: 50vw; padding: 8vw; color: #000; font-size: 16px; } .i-know { display: block; width: 50vw; height: 40px; margin: 0 auto 20px; background: #3bbcff; color: #fff; border-radius: 10px; border: none; outline: none; }` shadow.appendChild(wrapper) shadow.appendChild(style) this.bindEvent() } async changeData(city) { const json = await fetch(`https://www.tianqiapi.com/api/?version=v1&city=${city}`).then(res => res.json()) const [obj] = json.data[0].index.filter(lifestyle => lifestyle.title === this.getAttribute('tit')) this.shadowRoot.querySelector('.popup-txt').innerHTML = obj.desc } bindEvent() { this.shadowRoot.querySelector('.i-know').addEventListener('click', e => { e.stopPropagation() document.querySelector('html').style.overflow = '' this.shadowRoot.querySelector('.popup-wrap').style.display = 'none' }) this.addEventListener('click', e => { document.querySelector('html').style.overflow = 'hidden' this.shadowRoot.querySelector('.popup-wrap').style.display = 'flex' }) } static get observedAttributes() { return ['city'] } attributeChangedCallback(attr, oldVal, newVal) { this.changeData(newVal) } } <file_sep># ahab-weather [ahabhgk.github.io/ahab-weather](https://ahabhgk.github.io/ahab-weather) **基本信息** * 城市 - 地区 * 空气质量 * 温度 - 天气 - 风力 / 湿度 * 今明两天的天气 * 24 小时天气 * 一周的天气 * 生活指数 **实现功能** * H5 页面切图 - 还原度 - 美观 - 交互功能 - 用户体验 * 调用 API 并展示上面基本信息中的内容 * 搜索 - 选择城市 ( 定位城市功能可以不实现 ) * 使用 iconfont ( 天气图标 ) * 使用 Chart.js 库画出一周的天气温度曲线 * 将写好的页面部署到自己 github.io 上 <file_sep>import clear from'../img/clear.jpg' import cloud from '../img/cloud.jpg' import overcast from '../img/overcast.jpg' import rain from '../img/rain.jpg' import snow from '../img/snow.jpg' import thunder from '../img/thunder.jpg' // 用于获取数据的 async function getData(parameters) { const data = await fetch(`https://free-api.heweather.net/s6${parameters}&key=b52a498653264e23a6a795fb4ede5c97`) const json = await data.json() return json.HeWeather6[0] } // 用于搜索的 async function getSearch(parameters) { const data = await fetch(`https://search.heweather.net${parameters}&key=b52a498653264e23a6a795fb4ede5c97`) const json = await data.json() return json.HeWeather6[0] } // 获取热门城市 async function getHotCity() { const data = await getSearch('/top?group=world&number=15') const html = data.basic.map(info => ` <div class="info" data-location="${info.location}">${info.location}</div> `).join('') document.querySelector('.hot-city>.infos').innerHTML = html } // 天气图标、背景和描述处理 function getSetByDesc(description) { const set = {} if (description.includes('晴')) { set.bg = clear set.iconClass = 'icon-clear' set.desc = '今天天气不错呦~' } else if (description.includes('阴')) { set.bg = overcast set.iconClass = 'icon-overcast' set.desc = '天暗下来,你就是阳光~' } else if (description.includes('雨')) { set.bg = rain set.iconClass = 'icon-rain' set.desc = '下雨记得带伞哦~' } else if (description.includes('多云')) { set.bg = cloud set.iconClass = 'icon-cloud' set.desc = '现在温度比较凉爽~' } else if (description.includes('雪')) { set.bg = snow set.iconClass = 'icon-snow' set.desc = '来堆雪人吧~' } else if (description.includes('雷')) { set.bg = thunder set.iconClass = 'icon-thunder' set.desc = '小心装逼遭雷劈哦~' } return set } // 获取 now 的数据 async function getNow(location) { const data = await getData(`/weather/now?location=${location}`) const airData = await getData(`/air/now?location=${location}`) const set = getSetByDesc(data.now.cond_txt) return { location, ...data.now, ...airData.air_now_city, ...set } } // 获取今明两天数据 async function getTwoRecent(location) { const data = await getData(`/weather/forecast?location=${location}`) const todaySet = getSetByDesc(data.daily_forecast[0].cond_txt_d) const tomorrowSet = getSetByDesc(data.daily_forecast[1].cond_txt_d) return { ...data.daily_forecast, todaySet, tomorrowSet } } // 获取 7 天天气和 hourly async function getWeekAndHourlyData(location) { const json = await fetch(`https://www.tianqiapi.com/api/?version=v1&city=${location}`).then(res => res.json()) return json } export default { search: getSearch, now: getNow, twoRecent: getTwoRecent, hotCity: getHotCity, weekData: getWeekAndHourlyData, hourlyData: getWeekAndHourlyData, set: getSetByDesc, } <file_sep>const path = require('path') const merge = require('webpack-merge') const HtmlWebpackPlugin = require('html-webpack-plugin') const devConfig = require('./webpack.dev.js') const prodConfig = require('./webpack.prod.js') const commonConfig = { entry: './src/js/index.js', output: { path: path.resolve('dist'), }, module: { rules: [ { test: /\.(eot|ttf|svg|woff|otf|woff2)$/, use: { loader: 'file-loader', options: { outputPath: './style/font/', }, }, }, { test: /\.(png|jpe?g|gif)$/, use: [ { loader: 'url-loader', options: { limit: 8192, outputPath: './img/', }, }, ], }, { test: /\.html$/, use: [ { loader: 'html-withimg-loader' }, ], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', }), ], } module.exports = (env) => { if (env && env.production) { return merge(commonConfig, prodConfig) } return merge(commonConfig, devConfig) } <file_sep>const { CleanWebpackPlugin } = require('clean-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin') module.exports = { mode: 'production', output: { filename: './js/[name].[contenthash:8].js', }, devtool: 'cheap-module-source-map', plugins: [ new MiniCssExtractPlugin({ filename: './style/[name].[hash:8].css', }), new CleanWebpackPlugin(), ], module: { rules: [ { test: /\.s?css$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { publicPath: '../', }, }, 'css-loader', 'sass-loader', ], }, ], }, optimization: { minimizer: [new OptimizeCSSAssetsPlugin({})], }, }
a8ad8e945731a119dd9b9fe95fb17eb98a93bb66
[ "JavaScript", "Markdown" ]
6
JavaScript
ahabhgk/ahab-weather
515d82a20005de9d45761efb76941749198fa5c5
17ae4efba55bda538717fa318e947d64e00dea65
refs/heads/master
<file_sep>var position = 0; var container = document.getElementById("slide-block__container"); var block = document.getElementsByClassName('slide-block__item'); var dots = document.getElementsByClassName('dot__item'); var getStyle = getComputedStyle(block[0]); var getStyleSize = parseInt(getStyle.width); var maxSizeAllBlock = parseInt(block.length - 1) * getStyleSize; var mas = []; var acum = 0; for (var i = 0; i < block.length ; i++) { mas[i] = (getStyleSize * acum); acum++; } function showSlide(s){ if (s == 1) { if (position == maxSizeAllBlock) { position = 0; container.style.right = position + "px"; } else { position += getStyleSize; container.style.right = position + "px"; } changeDots(position / getStyleSize); } if (s == -1) { if (position == 0) { position = maxSizeAllBlock; container.style.right = position + "px"; } else { position += -getStyleSize; container.style.right = position + "px"; } changeDots(position / getStyleSize ); } } function changeDots(n) { for (var i = 0; i < dots.length; i++) { dots[i].className = dots[i].className.replace(' activ',' no-active'); } dots[n].className = dots[n].className.replace('no-active','activ'); } function changeSlideClick(n){ container.style.right = mas[n] + "px"; position = mas[n]; changeDots(n); } <file_sep># Andreywolf.github.io
de42034747cc89e4730a4c061a5b592556f35e7b
[ "JavaScript", "Markdown" ]
2
JavaScript
Andreywolf/Andreywolf.github.io
bfaf8f4d08601f6699ebd888fb570e48d8b1f3e9
8cf37c3a1c6a41bcf09648ae3abb9ea5ce0dced1
refs/heads/master
<repo_name>Thearyim/weekday-calculator<file_sep>/src/calculator.js export function Date2(date, month, year){ this.date = date, this.month = month, this.year = year; Date2.prototype.getDateCode = function(){ return this.date; }; Date2.prototype.getMonthCode = function(){ if(this.month.toLowerCase() === "january" || this.month.toLowerCase() === "october"){ return 0; } else if(this.month.toLowerCase() === "may"){ return 1; } else if(this.month.toLowerCase() === "august"){ return 2; } else if(this.month.toLowerCase() === "february" || this.month.toLowerCase() === "march" || this.month.toLowerCase() === "november"){ return 3; } else if(this.month.toLowerCase() === "june"){ return 4; } else if(this.month.toLowerCase() === "september" || this.month.toLowerCase() === "december"){ return 5; } else if(this.month.toLowerCase() === "april" || this.month.toLowerCase() === "july"){ return 6; } }; Date2.prototype.leapYearCode = function(){ if(this.month.toLowerCase() === "january" || this.month.toLowerCase() === "february"){ if(this.year % 4 === 0 && this.year % 100 != 0 && this.year % 400 === 0){ return -1; } return 0; } else { return 0; } }; Date2.prototype.getCenturyCode = function(){ var firstTwoDigit = parseInt(this.year.toString().substr(0,2)); if(firstTwoDigit === 17 || firstTwoDigit === 21){ return 4; } else if(firstTwoDigit === 18 || firstTwoDigit === 22){ return 2; } else if(firstTwoDigit === 19 || firstTwoDigit === 23){ return 0; } else if(firstTwoDigit === 20){ return 6; } }; Date2.prototype.getYearCode = function(){ var yearString = this.year.toString(); var lastTwoDigit = 0; if(yearString[yearString-2] === "0"){ lastTwoDigit = parseInt(yearString[yearString-1]); } else { lastTwoDigit = parseInt(this.year.toString().substr(2,2)); } var yearCode = (lastTwoDigit + Math.floor((lastTwoDigit / 4))) % 7; return yearCode; }; Date2.prototype.calculateDay = function(){ var totalFromFormula = this.getDateCode() + this.getMonthCode() + this.leapYearCode() + this.getCenturyCode() + this.getYearCode(); var number = totalFromFormula % 7; if(number === 0){ return "Sunday"; } else if(number === 1){ return "Monday"; } else if (number === 2){ return "Tuesday"; } else if(number === 3){ return "Wednesday"; } else if (number === 4){ return "Thursday"; } else if(number === 5){ return "Friday"; } else if (number === 6){ return "Saturday"; } }; } <file_sep>/src/main.js import './styles.css'; import { Date2 } from './calculator.js'; $(document).ready(function() { $("#calculator").submit(function(event){ event.preventDefault(); var date3 = parseInt($("#date").val()); var month3 = $("#month").val(); var year3 = parseInt($("#year").val()); alert(date3); alert(month3); alert(year3); var testDate = new Date2(date3,month3,year3); $("#solution").text(testDate.calculateDay()); }); });
041f70b26daef786d339ffe15b8fa9846dcb614c
[ "JavaScript" ]
2
JavaScript
Thearyim/weekday-calculator
c543da9af29605fb56385dbaa39ee265bdca6030
6e0fa6b5b6ab9cc4f1d2c41cd8dcd64f283e2f71
refs/heads/master
<repo_name>vbarbarosh/w240_gimp_thumbnailer<file_sep>/src/thumbnailer #!/bin/bash # http://www.gnu.org/software/bash/manual/bash.html#The-Set-Builtin set -o errexit function error() { echo "${scriptname}: error:" "${@}" > /dev/stderr exit 1 } script="$(readlink --canonicalize "${0}")" scriptdir="$(dirname "${script}")" scriptname="$(basename "${script}")" rm --force *.jpg gimp --new-instance --batch - <<-EOF ; scale image by *scalefactor* (define (vb-image-scale image scalefactor) (gimp-image-scale image (round (* (car (gimp-image-width image)) scalefactor)) (round (* (car (gimp-image-height image)) scalefactor))) ) ; scale image down (i.e. never scale it up) "horizontally" to specified ; *newwidth* (define (vb-image-scale-down-width image newwidth) (if (> (car (gimp-image-width image)) newwidth) (vb-image-scale image (/ newwidth (car (gimp-image-width image)))) ) ) ; cut top part of an image (define (vb-image-crop-top image newheight) (let* ( (width (car (gimp-image-width image))) (height (car (gimp-image-height image))) ) (if (> height newheight) (gimp-image-crop image width newheight 0 0)) ) ) ; cut bottom part of an image (define (vb-image-crop-bottom image newheight) (let* ( (width (car (gimp-image-width image))) (height (car (gimp-image-height image))) ) (if (> height newheight) (gimp-image-crop image width newheight 0 (- height newheight))) ) ) (define (process-file infile outfile outfilesm) (let* ( (image (car (gimp-file-load RUN-NONINTERACTIVE infile "blahblahblah"))) (layer (car (gimp-image-flatten image))) ) (vb-image-scale-down-width image 800) (gimp-file-save RUN-NONINTERACTIVE image layer outfile "blahblahblah") (vb-image-scale-down-width image 233) (gimp-file-save RUN-NONINTERACTIVE image layer outfilesm "blahblahblah") (gimp-image-delete image) ) ) $(for filename in *.xcf; do echo "(process-file \ \"${filename}\" \ \"${filename%.xcf}.jpg\" \ \"${filename%.xcf}-sm.jpg\")" done) (gimp-quit 0) EOF
cf4f0f7bc177c2d112c99572880403de58fa5241
[ "Shell" ]
1
Shell
vbarbarosh/w240_gimp_thumbnailer
665ae75ed1ae5a33d20c7a54016d3f301edec40f
afce127e7af779c295bfd935a57070b7d2000e8f
refs/heads/master
<file_sep># # 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. # # Authors: <NAME> <<EMAIL>> # import numpy as np import tensorflow as tf import tensorflow_fold.public.blocks as td import unittest import sequence_transcoder import bi_lstm class TestBiLstm(unittest.TestCase): def test_outputs(self): st = sequence_transcoder.build_sequence_transcoder('src/test_data/vocab.txt', 3) bilstm = bi_lstm.build_bi_lstm(num_units=5, forget_bias=1.0, layer_norm=1, norm_gain=1.0, norm_shift=0.0, dropout_keep_prob=1.0, dropout_prob_seed=None) block = (st >> bilstm) # One output for the fw pass, one for the bw output = block.eval(["hello", "world", "unknown_word"]) self.assertEqual(len(output), 2) # Two outputs for each pass ([h1,h2,h3] and [c3,h3]) self.assertEqual(len(output[0]), 2) self.assertEqual(len(output[1]), 2) # # Forward pass # fw_hs = output[0][0] fw_last_h = output[0][1][1] # Three as the words self.assertEqual(len(fw_hs), 3) self.assertTrue(np.array_equal(fw_hs[2], fw_last_h)) # Five as the num_units self.assertTrue(len(fw_last_h), 5) # # Backward pass # bw_hs = output[1][0] bw_last_h = output[1][1][1] # Three as the words self.assertEqual(len(bw_hs), 3) self.assertTrue(np.array_equal(bw_hs[2], bw_last_h)) # Five as the num_units self.assertTrue(len(bw_last_h), 5) # Make sure fw and bw are not equal, it can happen but # it should be pretty rare. self.assertFalse(np.array_equal(fw_hs, bw_hs)) # Not a real unittest, just a way to test that td.Slice(step=-1) # reversts a sequences def test_reversed(self): reverse_sequence=td.Slice(step=-1) st = sequence_transcoder.build_sequence_transcoder('src/test_data/vocab.txt', 3) block = (st >> reverse_sequence) s1 = st.eval(["hello", "world", "ciao", "unknown_word"]) s2 = block.eval(["hello", "world","ciao", "unknown_word"]) self.assertTrue(np.array_equal(s1[::-1], s2)) if __name__ == '__main__': sess = tf.InteractiveSession() unittest.main() <file_sep># context2vec Implemenation of context2vec [1] using tensorflow fold. [1] https://github.com/orenmel/context2vec <file_sep># # 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. # # Authors: <NAME> <<EMAIL>> # import tensorflow as tf import tensorflow_fold.public.blocks as td def __build_lstm_cell(num_units, forget_bias, layer_norm, norm_gain, norm_shift, dropout_keep_prob, dropout_prob_seed, name_or_scope): lstm_cell = td.ScopedLayer( tf.contrib.rnn.DropoutWrapper( tf.contrib.rnn.LayerNormBasicLSTMCell(num_units=num_units, forget_bias=forget_bias, layer_norm=layer_norm, norm_gain=norm_gain, norm_shift=norm_shift, dropout_keep_prob=dropout_keep_prob, dropout_prob_seed=dropout_prob_seed), input_keep_prob=dropout_keep_prob, output_keep_prob=dropout_keep_prob), name_or_scope=name_or_scope) return lstm_cell def build_bi_lstm(num_units, forget_bias, layer_norm, norm_gain, norm_shift, dropout_keep_prob, dropout_prob_seed): fw_lstm_cell=__build_lstm_cell( num_units = num_units, forget_bias = forget_bias, layer_norm = layer_norm, norm_gain = norm_gain, norm_shift = norm_shift, dropout_keep_prob = dropout_keep_prob, dropout_prob_seed = dropout_prob_seed, name_or_scope = "fw_lstm_cell") fw_pass=td.RNN(fw_lstm_cell) reverse_sequence=td.Slice(step=-1) bw_lstm_cell = __build_lstm_cell( num_units=num_units, forget_bias=forget_bias, layer_norm=layer_norm, norm_gain=norm_gain, norm_shift=norm_shift, dropout_keep_prob=dropout_keep_prob, dropout_prob_seed=dropout_prob_seed, name_or_scope="bw_lstm_cell") bw_pass = (reverse_sequence >> td.RNN(bw_lstm_cell)) return td.AllOf(fw_pass, bw_pass) <file_sep># # 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. # # Authors: <NAME> <<EMAIL>> # import numpy as np import tensorflow as tf import tensorflow_fold.public.blocks as td import unittest import sequence_transcoder class TestSequenceTranscoder(unittest.TestCase): def test_sequence_length(self): st = sequence_transcoder.build_sequence_transcoder('src/test_data/vocab.txt', 3) self.assertEqual(len(st.eval(["hello", "world"])), 2) self.assertEqual(len(st.eval(["hello", "world", "ciao", "mondo"])), 4) self.assertEqual(len(st.eval(["hello", "world", "unknown_word"])), 3) def test_word_embedding_size(self): st = sequence_transcoder.build_sequence_transcoder('src/test_data/vocab.txt', 3) sequence = st.eval(["hello", "world"]) self.assertEqual([len(w) for w in sequence], [3,3]) st = sequence_transcoder.build_sequence_transcoder('src/test_data/vocab.txt', 5) sequence = st.eval(["hello", "world"]) self.assertEqual([len(w) for w in sequence], [5,5]) def test_same_word_embedding(self): st = sequence_transcoder.build_sequence_transcoder('src/test_data/vocab.txt', 3) sequence1 = st.eval(["hello", "world", "hello"]) sequence2 = st.eval(["hello", "world", "hello"]) self.assertTrue(np.array_equal(sequence1[0], sequence1[2])) self.assertTrue(np.array_equal(sequence1, sequence2)) def test_unknown_word(self): st = sequence_transcoder.build_sequence_transcoder('src/test_data/vocab.txt', 3) sequence1 = st.eval(["unknown_word1", "world", "unknown_word2"]) sequence2 = st.eval(["unknown_word3", "world", "unknown_word4"]) self.assertTrue(np.array_equal(sequence1[0], sequence1[2])) self.assertTrue(np.array_equal(sequence1, sequence2)) if __name__ == '__main__': sess = tf.InteractiveSession() unittest.main() <file_sep># # 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. # # Authors: <NAME> <<EMAIL>> # import codecs import os import tensorflow as tf import tensorflow_fold.public.blocks as td def load_vocab(filepath): assert os.path.exists(filepath), "%s does not exists." % filepath with codecs.open(filepath, encoding='utf-8') as f: lines = f.read().splitlines() assert len( lines) > 0, "Invald vocabulary file: %s has invalid lenght." % filepath vocab = dict() for i, word in enumerate(lines[1:]): vocab[word] = i return vocab def word2index(vocab, word): if word in vocab: return vocab[word] else: return len(vocab) def build_sequence_transcoder(vocab_filepath, word_embedding_size): vocab_size = 5 # From words to list of integers vocab = load_vocab(vocab_filepath) words2integers = td.InputTransform( lambda s: [word2index(vocab, w) for w in s]) # From interger to word embedding word2embedding = td.Scalar('int32') >> td.Function( td.Embedding(vocab_size, word_embedding_size)) # From word to array of embeddings sequence_transcoder = words2integers >> td.Map(word2embedding) return sequence_transcoder
eee928a3a1eb5b038cb0537cb916cbd6aac91f18
[ "Markdown", "Python" ]
5
Python
CalculatedContent/context2vec-1
ac11d9bc2b306d064593a376e6efdaf9628186b9
f4ea31828c68155ff01f539a2dff8c00b471e502
refs/heads/master
<file_sep># GifTastic.github.io<file_sep>// Initial array of gif var topics = ["psychoactive", "colorful", "eye-opening", "astonishing", "unforeseen", "beautiful", "drug", "painkiller", "amazing", "wonderful", "exceptional", "superb", "diverting", "alluring", "attractive", "stirred", "gorgeous", "cat's-whiskers", "punk", "steampunk", "expressionist", "medieval", "minimalism"]; var maxGifs = 10; var maxRating = ""; function renderButtons(){ for(var i = 0; i < topics.length; i++) { var newButton = $("<button>"); newButton.addClass("btn"); newButton.addClass("art-button"); newButton.text(topics[i]); $("#button-container").append(newButton); } $("#add-art").on("click", function(event) { // Preventing the buttons default behavior when clicked (which is submitting a form) event.preventDefault();$("#add-art").on("click", function(event) { // Preventing the buttons default behavior when clicked (which is submitting a form) event.preventDefault(); var newTopic = $("#add-art").val().trim(); // Adding the movie from the textbox to our array topics.push(newTopic);showshowshow // Calling renderButtons which handles the processing of our movie array renderButtons(); }); }); $(".art-button").unbind("click"); $(".art-button").on("click", function(){ $(".gif-image").unbind("click"); $("#gif-container").empty(); $("#gif-container").removeClass(""); popGifContainer($(this).text()); console.log($(this).text()); }); } function addButton(show){ if(topics.indexOf(show) === -1) { topics.push(show); $("#button-container").empty(); renderButtons(); } } function popGifContainer(show){ var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + show + "&api_key=<KEY>&limit=10"; $.ajax({ url: queryURL, method: "GET" }).then(function(response){ response.data.forEach(function(element){ newDiv = $("<div>"); newDiv.addClass("individual-gif-container"); newDiv.append("<p>Rating:" + element.rating.toUpperCase() + "</p>"); var newImage = $("<img src = '" + element.images.fixed_height_still.url + "'>"); newImage.addClass("gif-image"); newImage.attr("state", "still"); newImage.attr("still-data", element.images.fixed_height_still.url); newImage.attr("animated-data", element.images.fixed_height.url); newDiv.append(newImage); $("#gif-container").append(newDiv); }); $("#gif-container").addClass(""); $(".gif-image").unbind("click"); $(".gif-image").on("click", function(){ if($(this).attr("state") === "still") { $(this).attr("state", "animated"); $(this).attr("src", $(this).attr("animated-data")); } else { $(this).attr("state", "still"); $(this).attr("src", $(this).attr("still-data")); } }); }); } $(document).ready(function(){ renderButtons(); $("#add-art").on("click", function(){ event.preventDefault(); addButton($("#art-show").val().trim()); $("#art-show").val(""); }); });
3a9539ef7d01f10d470c07d295da9d5e70da0d75
[ "Markdown", "JavaScript" ]
2
Markdown
weezie33/GifTastic.github.io
b09040639c40fcbec89e34aa7f394432c20a6785
9f577116031e442d50e4b4d2dd5e9d07a38df544
refs/heads/master
<file_sep>// // MemoryModifier.cpp // // // Created by MJ (Ruit) on 1/1/19. // // #include "MemoryModifier.hpp" MemoryModifier::MemoryModifier(){ _binaryName = NULL; _address = NULL; _size = 0; _originalValue = NULL; _modValue = NULL; } MemoryModifier::MemoryModifier(void *address, const void *modifier, size_t size){ MemoryModifier(); if(address && modifier && size > 0){ _address = address; _size = size; _originalValue = new uint8_t[size]; _modValue = new uint8_t[size]; // backups MemKitty::readMemory(_address, _originalValue, size); MemKitty::readMemory((void *)modifier, _modValue, size); } } MemoryModifier::MemoryModifier(const char *binName, void *address, const void *modifier, size_t size){ MemoryModifier(); if(address && modifier && size > 0){ _binaryName = binName; _address = getAbsoluteAddress(address); _size = size; _originalValue = new uint8_t[size]; _modValue = new uint8_t[size]; // backups MemKitty::readMemory(_address, _originalValue, size); MemKitty::readMemory((void *)modifier, _modValue, size); } } MemoryModifier::~MemoryModifier(){ // clean up if(_originalValue){ delete[] _originalValue; _originalValue = NULL; } if(_modValue){ delete[] _modValue; _modValue = NULL; } } bool MemoryModifier::isValid() const{ return (_address && _size > 0 && _originalValue && _modValue); } size_t MemoryModifier::get_size() const{ return _size; } void *MemoryModifier::get_Address() const{ return _address; } void *MemoryModifier::getAbsoluteAddress(void *addr) const{ if(_binaryName == NULL){ return MemKitty::hasASLR() ? (void *)(MemKitty::getBaseInfo().address + ((uintptr_t)addr)) : addr; } return (void *)(MemKitty::getMemoryMachInfo(_binaryName).address + ((uintptr_t)addr)); } bool MemoryModifier::Restore(){ if(!isValid()) return false; return MemKitty::writeMemory(_address, _originalValue, _size); } bool MemoryModifier::Modify(){ if(!isValid()) return false; return MemKitty::writeMemory(_address, _modValue, _size); } bool MemoryModifier::setNewModifier(const void *modifier, size_t size){ if(!modifier || size < 1) return false; _size = size; if(_modValue){ delete[] _modValue; _modValue = NULL; } _modValue = new uint8_t[size]; return MemKitty::writeMemory(_modValue, modifier, size); } std::string MemoryModifier::ToHexString(){ if(!isValid()) return std::string("0xInvalid"); return MemKitty::read2HexStr(_address, _size); } <file_sep>// // MemoryModifier.hpp // // // Created by MJ (Ruit) on 1/1/19. // // #ifndef MemoryModifier_hpp #define MemoryModifier_hpp #include "KittyMemory.hpp" class MemoryModifier { private: const char *_binaryName; void * _address; size_t _size; uint8_t *_originalValue; uint8_t *_modValue; public: MemoryModifier(); // expects absolute address MemoryModifier(void *address, const void *modifier, size_t size); // expects binary name and relative address, if binary name is NULL then it'll consider the base executable MemoryModifier(const char *binName, void *address, const void *modifier, size_t size); ~MemoryModifier(); // validate modifier bool isValid() const; // get mod size size_t get_size() const; // returns pointer to the target address void *get_Address() const; // final address pointer void *getAbsoluteAddress(void *addr) const; // restore to original value bool Restore(); // apply modifications to target address bool Modify(); // reset mod value/size bool setNewModifier(const void *modifier, size_t size); // returns current target address bytes as hex string std::string ToHexString(); }; #endif /* MemoryModifier_hpp */ <file_sep>// // KittyMemory.cpp // // // Created by MJ (Ruit) on 1/1/19. // // #include "KittyMemory.hpp" bool MemKitty::hasASLR() { // PIE applies ASLR to the binary return (_dyld_get_image_header(0)->flags & MH_PIE); } bool MemKitty::x_protect(void *addr, size_t length, int protection) { void *pageStart = (void *)_START_PAGE_OF_(addr); uintptr_t pageSize = _SIZE_PAGE_OF_(addr, length); return ( mprotect(pageStart, pageSize, protection) != -1 ); } kern_return_t MemKitty::getPageInfo(uintptr_t addr, vm_region_submap_short_info_64 *outInfo) { vm_address_t region = (vm_address_t) addr; vm_size_t region_len = 0; mach_msg_type_number_t info_count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64; natural_t max_depth = 99999; kern_return_t kr = vm_region_recurse_64(mach_task_self(), &region, &region_len, &max_depth, (vm_region_recurse_info_t) outInfo, &info_count); if(kr == KERN_SUCCESS) outInfo->protection &= (PROT_READ | PROT_WRITE | PROT_EXEC); return kr; } void *MemKitty::MemCopy(void* dst, const void* src, size_t size){ uint8_t *destination = (uint8_t*) dst; uint8_t *source = (uint8_t*) src; int step = sizeof(uint8_t); for(int i = 0; i < size; i++){ *((uint8_t*)destination) = *((uint8_t*)source); destination += step; source += step; } return dst; } /* refs to: https://github.com/comex/substitute/blob/master/lib/darwin/execmem. https://github.com/everettjf/AppleTrace/blob/master/hookzz/src/zzdeps/darwin/memory-utils-darwin.c */ void *MemKitty::writeWrapper(void *dst, const void *src, size_t len) { uintptr_t startPage = _START_PAGE_OF_(dst); uintptr_t offsetPage = _OFFSET_PAGE_OF_(dst); uintptr_t pageSize = _SIZE_PAGE_OF_(dst, len); vm_region_submap_short_info_64 info; if(getPageInfo(startPage, &info) != KERN_SUCCESS) return NULL; // check if write permission is already there if(info.protection & PROT_WRITE) return MemCopy(dst, src, len); // map new page for our changes void *newMap = mmap(NULL, pageSize, PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0); if (newMap == NULL) return NULL; mach_port_t selfTask = mach_task_self(); kern_return_t kr; // copy dst page into our new mapped page kr = vm_copy(selfTask, startPage, pageSize, (vm_address_t)newMap); if (kr != KERN_SUCCESS) return NULL; // write changes into our page MemCopy((void *)((uintptr_t)newMap + offsetPage), src, len); // change protection to match dst protection if(mprotect(newMap, pageSize, info.protection) == -1) return NULL; // re-map our page and overwrite dst mach_vm_address_t dstTarget = (mach_vm_address_t)startPage; vm_prot_t c, m; kr = mach_vm_remap(selfTask, &dstTarget, pageSize, 0, VM_FLAGS_OVERWRITE, selfTask, (mach_vm_address_t)newMap, /*copy*/ TRUE, &c, &m, info.inheritance); if (kr != KERN_SUCCESS) return NULL; // clean up munmap(newMap, pageSize); return dst; } // write in memory at given address (copies src into dst) void *MemKitty::writeMemory(void *dst, const void *src, size_t len) { if (!src || !dst || len < 1) return NULL; void *address = (void *)_FIXED_ADDR_(dst); return writeWrapper(address, src, len); } // reads from memory at given address (copies dst bytes into the buffer) void *MemKitty::readMemory(void *dst, void *buffer, size_t len) { if (!dst || len < 1) return NULL; void *address = (void *)_FIXED_ADDR_(dst); vm_region_submap_short_info_64 info; if(getPageInfo(_START_PAGE_OF_(address), &info) != KERN_SUCCESS) return NULL; // check read permission if(info.protection & PROT_READ) return MemCopy(buffer, address, len); if(x_protect(address, len, info.protection | PROT_READ)){ void *ret = MemCopy(buffer, address, len); x_protect(address, len, info.protection); return ret; } return NULL; } // reads bytes into hex string at the given address std::string MemKitty::read2HexStr(void *addr, size_t len) { char tmp[len]; memset(tmp, 0, len); size_t bufferLen = len*2 + 1; char buffer[bufferLen]; memset(buffer, 0, bufferLen); std::string ret = "0x"; if(readMemory(addr, tmp, len) == NULL) return ret; for(int i = 0; i < len; i++){ sprintf(&buffer[i*2], "%02X", (unsigned char)tmp[i]); } ret += buffer; return ret; } MemKitty::mach_info MemKitty::getBaseInfo(){ mach_info _info = { 0, _dyld_get_image_header(0), _dyld_get_image_name(0), (uintptr_t)_dyld_get_image_vmaddr_slide(0) }; return _info; } MemKitty::mach_info MemKitty::getMemoryMachInfo(const char *fileName){ mach_info _info = {}; int imageCount = _dyld_image_count(); for(int i = 0; i < imageCount; i++) { const char *name = _dyld_get_image_name(i); const mach_header *header = _dyld_get_image_header(i); if(!strstr(name, fileName)) continue; mach_info new_info = { i, header, name, (uintptr_t)_dyld_get_image_vmaddr_slide(i) }; _info = new_info; } return _info; } <file_sep># KittyMemory-IOS runtime memory editor library, made specifically for IOS <file_sep>// // KittyMemory.cpp // // // Created by MJ (Ruit) on 1/1/19. // // #include "KittyMemory.hpp" bool MemKitty::hasASLR() { // PIE applies ASLR to the binary return (_dyld_get_image_header(0)->flags & MH_PIE); } kern_return_t MemKitty::getPageInfo(uintptr_t addr, vm_region_submap_short_info_64 *outInfo) { vm_address_t region = (vm_address_t) addr; vm_size_t region_len = 0; mach_msg_type_number_t info_count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64; natural_t max_depth = 99999; kern_return_t kr = vm_region_recurse_64(mach_task_self(), &region, &region_len, &max_depth, (vm_region_recurse_info_t) outInfo, &info_count); if(kr == KERN_SUCCESS) outInfo->protection &= (PROT_READ | PROT_WRITE | PROT_EXEC); return kr; } void *MemKitty::MemCopy(void* dst, const void* src, size_t size){ uint8_t *destination = (uint8_t*) dst; uint8_t *source = (uint8_t*) src; int step = sizeof(uint8_t); for(int i = 0; i < size; i++){ *((uint8_t*)destination) = *((uint8_t*)source); destination += step; source += step; } return dst; } // write in memory at given address (copies src into dst) void *MemKitty::writeMemory(void *dst, const void *src, size_t len) { if (!src || !dst || len < 1) return NULL; void *address = (void *)_FIXED_ADDR_(dst); uintptr_t startPage = _START_PAGE_OF_(address); vm_region_submap_short_info_64 info; if(getPageInfo(startPage, &info) != KERN_SUCCESS) return NULL; // check write rights if(info.protection & PROT_WRITE) return MemCopy(dst, src, len); return NULL; } // reads from memory at given address (copies dst into the buffer) void *MemKitty::readMemory(void *dst, void *buffer, size_t len) { if (!dst || len < 1) return NULL; void *address = (void *)_FIXED_ADDR_(dst); uintptr_t startPage = _START_PAGE_OF_(address); vm_region_submap_short_info_64 info; if(getPageInfo(_START_PAGE_OF_(address), &info) != KERN_SUCCESS) return NULL; // check read rights if(info.protection & PROT_READ) return MemCopy(buffer, address, len); return NULL; } // reads bytes into hex string at the given address std::string MemKitty::read2HexStr(void *addr, size_t len) { char tmp[len]; memset(tmp, 0, len); size_t bufferLen = len*2 + 1; char buffer[bufferLen]; memset(buffer, 0, bufferLen); std::string ret = "0x"; if(readMemory(addr, tmp, len) == NULL) return ret; for(int i = 0; i < len; i++){ sprintf(&buffer[i*2], "%02X", (unsigned char)tmp[i]); } ret += buffer; return ret; } MemKitty::mach_info MemKitty::getBaseInfo(){ mach_info _info = { 0, _dyld_get_image_header(0), _dyld_get_image_name(0), (uintptr_t)_dyld_get_image_vmaddr_slide(0) }; return _info; } MemKitty::mach_info MemKitty::getMemoryMachInfo(const char *fileName){ mach_info _info = {}; int imageCount = _dyld_image_count(); for(int i = 0; i < imageCount; i++) { const char *name = _dyld_get_image_name(i); const mach_header *header = _dyld_get_image_header(i); if(!strstr(name, fileName)) continue; mach_info new_info = { i, header, name, (uintptr_t)_dyld_get_image_vmaddr_slide(i) }; _info = new_info; } return _info; } <file_sep>// // KittyMemory.hpp // // // Created by MJ (Ruit) on 1/1/19. // // #ifndef KittyMemory_hpp #define KittyMemory_hpp #include <stdio.h> #include <string> #include <unistd.h> #include <sys/mman.h> #include <mach-o/dyld.h> #include <mach/mach.h> #include "darwin/mach_vm.h" #define _FIXED_ADDR_(x) ((uintptr_t)x & ~(uintptr_t)1) #define _SYS_PAGE_SIZE_ (sysconf(_SC_PAGE_SIZE)) #define _START_PAGE_OF_(x) ((uintptr_t)x & ~(uintptr_t)(_SYS_PAGE_SIZE_ - 1)) #define _END_PAGE_OF_(x, len) (_START_PAGE_OF_((uintptr_t)x + len - 1)) #define _OFFSET_PAGE_OF_(x) ((uintptr_t)x - _START_PAGE_OF_(x)); #define _SIZE_PAGE_OF_(x, len)(_END_PAGE_OF_(x, len) - _START_PAGE_OF_(x) + _SYS_PAGE_SIZE_) namespace MemKitty { typedef struct { int index; const mach_header *header; const char *name; uintptr_t address; } mach_info; bool hasASLR(); kern_return_t getPageInfo(uintptr_t addr, vm_region_submap_short_info_64 *outInfo); void *MemCopy(void *dst, const void *src, size_t len); void *writeMemory(void *dst, const void *src, size_t len); void *readMemory(void *src, void *buffer, size_t len); std::string read2HexStr(void *addr, size_t len); mach_info getBaseInfo(); mach_info getMemoryMachInfo(const char *fileName); }; #endif /* KittyMemory_hpp */
fd1de99f256a7aae14d4abe56ac386f566371d5e
[ "Markdown", "C++" ]
6
C++
Ezi06/KittyMemory-IOS
09aa476f8f50fc36dc7a650be10b79f9482263e4
8bdc17dcfb623075e3786db57e8e234289fca8a8
refs/heads/master
<file_sep>import { Dropdown } from 'react-native-material-dropdown'; export default class extends Dropdown { constructor(props) { super(props); } /* Patch the bug referenced in the following github issue: - https://github.com/n4kz/react-native-material-dropdown/issues/27 Issue is still open and are yet to be resolved on react-native-material-dropdown package */ componentWillReceiveProps({ value }) { this.setState({ value }); } }
c2b7e898fed6cafacddd55321088ebcc23159a7d
[ "JavaScript" ]
1
JavaScript
Casecommons/react-native-formio
77f255d3a676f2f4acab82c4601d246d0bfa42c6
493aae1d812b7f670b4782a32509b8fdb6ca40ab
refs/heads/main
<repo_name>pablocazorla/stockfishverb<file_sep>/src/views/about/index.js import React from "react"; import View from "components/view"; import stf_logo from "assets/img/stf_logo.svg"; const About = ({ visible, onCancel }) => { return ( <View visible={visible} onClose={onCancel}> <div className="view_presentation"> <div className="presentation-logo"> <img src={stf_logo} alt="" /> </div> <div className="presentation-title">Stockfish Verbose</div> <div className="presentation-text"> v1.0 <br /> by Davicazu </div> </div> </View> ); }; export default About; <file_sep>/src/views/end/index.js import React from "react"; import View from "components/view"; import classnames from "classnames"; const EndView = ({ visible, endType, newGame }) => { return ( <View visible={visible} footer={[ { text: "New game", action: () => { newGame(); }, }, ]} > <div className={classnames("end-title", { mate: endType === "mate", draw: endType === "draw", })} > {endType === "mate" ? "Check Mate!" : "Draw"} </div> </View> ); }; export default EndView; <file_sep>/src/views/presentation/index.js import React from "react"; import View from "components/view"; import stf_logo from "assets/img/stf_logo.svg"; const Presentation = ({ visible, actionNewGame }) => { return ( <View visible={visible} footer={[ { text: "New Game", action: actionNewGame, }, ]} > <div className="view_presentation"> <div className="presentation-logo"> <img src={stf_logo} alt="" /> </div> <div className="presentation-title">Stockfish Verbose</div> <div className="presentation-text"> v1.0 <br /> by Davicazu </div> </div> </View> ); }; export default Presentation; <file_sep>/src/views/newgame/index.js import React, { useState } from "react"; import classnames from "classnames"; import View from "components/view"; import Piece from "components/piece"; const NewGame = ({ visible, actionStartNewGame, onCancel }) => { const [humanColor, setHumanColor] = useState("white"); const [depth, setDepth] = useState("15"); return ( <View visible={visible} onClose={onCancel} footer={[ { text: "Start Game", action: () => { if (actionStartNewGame) actionStartNewGame({ humanColor, depth }); }, }, ]} > <div className="view__new-game"> <div className="view-title">New Game</div> <div className="color-selector"> <div className="title-sec">Play with:</div> <div className="color-selector-row"> <div className={classnames("c-selector white", { selected: humanColor === "white", })} onClick={() => { setHumanColor("white"); }} > <Piece color="white" /> <div className="title">White</div> </div> <div className={classnames("c-selector black", { selected: humanColor === "black", })} onClick={() => { setHumanColor("black"); }} > <Piece color="black" /> <div className="title">Black</div> </div> </div> </div> <div className="depth-selector"> <div className="title-sec">Difficulty:</div> <div className="depth-selector-num"> <div className="depth-selector-num_row"> <div className="depth-selector-num_col wide"> <input type="range" value={depth} min="5" max="25" onChange={(e) => { setDepth(e.target.value); }} /> </div> <div className="depth-selector-num_col"> <div className="num_result">{depth}</div> </div> </div> </div> </div> </div> </View> ); }; export default NewGame; <file_sep>/src/components/icon/index.js import React from "react"; const Icon = ({ id = "times", className }) => { return <i className={`icon fa fa-${id} ${className}`} />; }; export default Icon; <file_sep>/src/components/piece/index.js import React from "react"; import img_white_pawn from "assets/img/chesspieces/wP.png"; import img_black_pawn from "assets/img/chesspieces/bP.png"; import img_white_knight from "assets/img/chesspieces/wN.png"; import img_black_knight from "assets/img/chesspieces/bN.png"; import img_white_bishop from "assets/img/chesspieces/wB.png"; import img_black_bishop from "assets/img/chesspieces/bB.png"; import img_white_rook from "assets/img/chesspieces/wR.png"; import img_black_rook from "assets/img/chesspieces/bR.png"; import img_white_queen from "assets/img/chesspieces/wQ.png"; import img_black_queen from "assets/img/chesspieces/bQ.png"; import img_white_king from "assets/img/chesspieces/wK.png"; import img_black_king from "assets/img/chesspieces/bK.png"; const imgs = { P: { white: img_white_pawn, black: img_black_pawn, }, N: { white: img_white_knight, black: img_black_knight, }, B: { white: img_white_bishop, black: img_black_bishop, }, R: { white: img_white_rook, black: img_black_rook, }, Q: { white: img_white_queen, black: img_black_queen, }, K: { white: img_white_king, black: img_black_king, }, }; const Piece = ({ piece = "K", className, color = "white" }) => { return <img src={imgs[piece][color]} alt="Piece" className={className} />; }; export default Piece; <file_sep>/src/index.js import React from "react"; import ReactDOM from "react-dom"; import { Provider } from "react-redux"; import { createStore, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import reducers from "rdx/reducers"; import "assets/css/font-awesome.min.css"; import "assets/scss/index.scss"; import Game from "views/Game"; let store = createStore(reducers, applyMiddleware(thunk)); ReactDOM.render( <Provider store={store}> <Game /> </Provider>, document.getElementById("root") ); <file_sep>/src/views/human/index.js import React, { useState, useEffect } from "react"; import View from "components/view"; import Icon from "components/icon"; import Piece from "components/piece"; const pieceList = ["P", "N", "B", "R", "Q", "K"]; const Human = ({ visible, possibleMoves, humanColor, onSelectMovement }) => { const [selectedPiece, setSelectedPiece] = useState(null); const [movements, setMovements] = useState({ P: [], N: [], B: [], R: [], Q: [], K: [], }); useEffect(() => { setSelectedPiece(null); }, [visible]); useEffect(() => { const movs = {}; movs.P = possibleMoves.filter((m) => { const firstLetter = m.substring(0, 1); return firstLetter === firstLetter.toLowerCase(); }); ["N", "B", "R", "Q", "K"].forEach((p) => { movs[p] = possibleMoves.filter((m) => { return m.indexOf(p) === 0; }); }); if (possibleMoves.indexOf("O-O") >= 0) { movs.K.push("O-O"); } if (possibleMoves.indexOf("O-O-O") >= 0) { movs.K.push("O-O-O"); } setMovements(movs); }, [possibleMoves]); return ( <View visible={visible} // footer={[ // { // text: "Start Game", // action: () => { // if (actionStartNewGame) actionStartNewGame({ humanColor, depth }); // }, // }, // ]} > {!selectedPiece ? ( <div className="view__human"> <div className="view-title">Select Piece</div> <div className="human-piece-selector"> {pieceList.map((p) => { if (movements[p].length === 0) { return null; } return ( <div className="human-piece-item" onClick={() => { setSelectedPiece(p); }} key={p} > <Piece piece={p} color={humanColor} /> </div> ); })} </div> </div> ) : ( <div className="view__human"> <div className="movement-piece"> <Piece piece={selectedPiece} color={humanColor} /> <div className="movement-piece-another" onClick={() => { setSelectedPiece(null); }} > <Icon id="chevron-left" /> Select another piece </div> </div> <div className="view-title">Select Movement</div> <div className="movement-selector"> {movements[selectedPiece].map((mov) => { return ( <div className="movement-selector-item" key={mov} onClick={() => { if (onSelectMovement) onSelectMovement(mov); }} > {mov} </div> ); })} </div> </div> )} </View> ); }; export default Human; <file_sep>/src/components/view/index.js import React from "react"; import classnames from "classnames"; import Icon from "components/icon"; const View = ({ children, footer, visible, base, onClose }) => { return ( <div className={classnames("view", { visible, base })}> {onClose ? ( <div className="view-close-btn" title="Close" onClick={onClose}> <Icon /> </div> ) : null} <div className="view-content">{children}</div> {footer ? ( <div className="view-footer"> {footer.map((button, k) => { const { text, action, color, size, title } = button; return ( <div className={classnames("view-footer_col", size || "")} key={k} title={title} > <div className={classnames("btn", color || "primary")} onClick={() => { if (action) action(); }} > {text} </div> </div> ); })} </div> ) : null} </div> ); }; export default View; <file_sep>/src/components/header/index.js import React from "react"; import classnames from "classnames"; import Icon from "components/icon"; const Header = ({ visible, menu = [] }) => { return ( <div className={classnames("header", { visible })}> <div className="header-row"> <div className="title">Stockfish Verbose</div> <div className="menu"> {menu.map((m, k) => { const { text, icon, action, transparent } = m; return ( <div className={classnames("menu-btn", { transparent })} key={k} onClick={action} > {icon ? <Icon id={icon} /> : null} {text} </div> ); })} </div> </div> </div> ); }; export default Header; <file_sep>/src/components/board/index.js import React, { useState, useEffect, useCallback } from "react"; import Square from "./square"; import Icon from "components/icon"; //const FenEjemplo = "r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R"; const fenToGrid = (fenOrig) => { const list = []; const fenArray = (() => { const index = fenOrig.indexOf(" "); const part1 = fenOrig.substr(0, index); const part2 = fenOrig.substr(index + 1); return [part1, part2]; })(); const fen = fenArray[0]; let index = 0; // for (let i = 0; i < fen.length; i++) { const letter = fen.substr(i, 1); if (letter !== "/") { const num = parseInt(letter, 10); if (isNaN(num)) { list.push({ piece: letter, index: index++, }); } else { for (let j = 0; j < num; j++) { list.push({ piece: null, index: index++, }); } } } } // const restFen = fenArray[1]; let fen_move = "white"; let fen_castling_white = true; let fen_castling_black = true; // if (restFen.indexOf("b") === 0) { fen_move = "black"; } if (restFen.indexOf("KQ") < 0) { fen_castling_white = false; } if (restFen.indexOf("kq") < 0) { fen_castling_black = false; } return { list, fen_move, fen_castling_white, fen_castling_black, }; }; const Board = ({ humanColor = "white", fen = "8/8/8/8/8/8/8/8 w KQkq - 0 1", onCancel, setBoard, visible, }) => { const [grid, setGrid] = useState([]); const [showButtons, setShowButtons] = useState(false); const [fen_move, set_fen_move] = useState("white"); const [fen_castling_white, set_fen_castling_white] = useState(true); const [fen_castling_black, set_fen_castling_black] = useState(true); const createGridFromFEN = useCallback( (fenPosition) => { const fenConverted = fenToGrid(fenPosition); const gr = fenConverted.list; set_fen_move(fenConverted.fen_move); set_fen_castling_white(fenConverted.fen_castling_white); set_fen_castling_black(fenConverted.fen_castling_black); if (humanColor === "black") { setGrid(gr.reverse()); } else { setGrid(gr); } }, [ setGrid, humanColor, set_fen_move, set_fen_castling_white, set_fen_castling_black, ] ); const updateGrid = useCallback( (piece, index) => { const gridCopy = grid.filter(() => true); gridCopy.forEach((s) => { if (s.index === index) { s.piece = piece; } }); setShowButtons(true); setGrid(gridCopy); }, [setGrid, grid, setShowButtons] ); const getFenFromGrid = useCallback(() => { const gridCopy = humanColor === "black" ? grid.filter(() => true).reverse() : grid.filter(() => true); let txt = ""; let emptySquares = 0; gridCopy.forEach((sq, i) => { if (i !== 0 && i % 8 === 0) { if (emptySquares > 0) { txt += emptySquares; emptySquares = 0; } txt += "/"; } if (sq.piece) { if (emptySquares > 0) { txt += emptySquares; emptySquares = 0; } txt += sq.piece; } else { emptySquares++; } }); if (emptySquares > 0) { txt += emptySquares; } txt += fen_move === "white" ? " w " : " b "; txt += fen_castling_white ? "KQ" : ""; txt += fen_castling_black ? "kq" : ""; txt += !fen_castling_white && !fen_castling_black ? "-" : ""; txt += " - 0 1"; return txt; }, [grid, humanColor, fen_move, fen_castling_white, fen_castling_black]); useEffect(() => { if (visible && fen) { createGridFromFEN(fen); setShowButtons(false); } }, [fen, createGridFromFEN, visible]); return ( <div className="board-container"> <div className="board-top-options"> <div className="board-top-option" onClick={() => { setShowButtons(true); set_fen_move(fen_move === "white" ? "black" : "white"); }} >{`Move ${fen_move}`}</div> <div className="board-top-option" onClick={() => { setShowButtons(true); set_fen_castling_white(!fen_castling_white); }} > <Icon id={fen_castling_white ? "check-square-o" : "square-o"} />{" "} Castling white </div> <div className="board-top-option" onClick={() => { setShowButtons(true); set_fen_castling_black(!fen_castling_black); }} > <Icon id={fen_castling_black ? "check-square-o" : "square-o"} />{" "} Castling black </div> </div> <div className="board-grid"> {grid.map((q, k) => { const { piece, index } = q; const squareColor = (k % 16 > 7 ? 1 : -1) * (k % 2 ? 1 : -1); const toRight = k % 8 > 3 ? true : false; return ( <Square key={k} white={squareColor > 0} piece={piece} toRight={toRight} index={index} setSquare={updateGrid} /> ); })} </div> <div className="board-buttons"> <div className="board-button" onClick={() => { setShowButtons(true); createGridFromFEN( "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" ); }} > Start Position </div> <div className="board-button" onClick={() => { setShowButtons(true); createGridFromFEN("8/8/8/8/8/8/8/8 w - - 0 1"); }} > Clear all </div> </div> <div className="board-footer"> {showButtons ? ( <div className="board-footer-row"> <div className="btn cancel rounded" onClick={() => { if (onCancel) onCancel(); }} > Cancel </div> <div className="btn primary rounded" onClick={() => { if (setBoard) { const fenResult = getFenFromGrid(); setBoard(fenResult, fen_move); } }} > Set board </div> </div> ) : null} </div> </div> ); }; export default Board;
9735c208a9c7971f93049c2c072585cb9ba7fa30
[ "JavaScript" ]
11
JavaScript
pablocazorla/stockfishverb
719c384539260009b03a73b8b669c7c35429e9a7
8722dafb4d95078cc42522de256627dcb19cff19
refs/heads/master
<file_sep>#ifndef RESERVETICKETSMENU_H #define RESERVETICKETSMENU_H #include <QWidget> #include <backend.h> #include <QStandardItemModel> namespace Ui { class reserveTicketsMenu; } class reserveTicketsMenu : public QWidget { Q_OBJECT public: explicit reserveTicketsMenu(BackEnd* bckEnd, QWidget* parent = nullptr); ~reserveTicketsMenu(); private: Ui::reserveTicketsMenu* ui; BackEnd* bckEnd; QStandardItemModel* unActiveTicketsModel; QStandardItemModel* reservedTicketsModel; QStandardItemModel* boughtTicketsModel; QModelIndex reservedTicketIndex; void showBoughtTickets(QVariantList boughtTicketsList); void showReservedTickets(QVariantList reservedTicketsList); void showUnActiveTickets(QVariantList unActiveTicketsList); private slots: void showUserTickets(QVariantList unActiveTickets, QVariantList boughtTickets, QVariantList reservedTickets); void reservedTicketTableClicked(const QModelIndex& index); void on_tabWidget_currentChanged(int index); void on_buyButton_clicked(); void on_returnButton_clicked(); void reservedTicketBought(); void returnTicket(); signals: void _dataToSend(QByteArray); }; #endif // RESERVETICKETSMENU_H <file_sep>#ifndef MYSERVER_H #define MYSERVER_H // secondary libraries #include <QDebug> #include <QList> #include <QObject> // server stuff #include <QTcpServer> #include <QTcpSocket> // JSON #include <QJsonDocument> #include <QJsonObject> #include <QJsonParseError> // SQL #include <QSqlDatabase> #include <QSqlError> #include <QSqlQuery> class myServer : public QTcpServer { Q_OBJECT public: myServer(); ~myServer(); void startServer(); private: QString errStrMsg; QByteArray recievedData; QList<QTcpSocket*>* connectedClients; QJsonDocument* jsnDoc; QJsonParseError* errJsn = new QJsonParseError(); QJsonObject* obj; QSqlDatabase* db; QSqlQuery* qry; void sendData(QTcpSocket* socket, QString& data); void decAndExec(QJsonDocument* doc, QTcpSocket* socket); void logProc(QTcpSocket* socket); void regProc(QTcpSocket* socket); void getCities(QTcpSocket* socket); void getTrainsList(QTcpSocket* socket); void getAvailableSeats(QTcpSocket* socket); void buyTicket(QTcpSocket* socket); void getUserTickets(QTcpSocket* socket); void buyReservedTicket(QTcpSocket* socket); void returnTicket(QTcpSocket* socket); QString createJsonStringFromQuery(QStringList& jsonFields, QSqlQuery* qry); private slots: void incomingConnection(qintptr socketDescriptor); void sockReady(); void sockDisc(); }; #endif // MYSERVER_H <file_sep>#ifndef WAGONBUTTON_H #define WAGONBUTTON_H #include <QPushButton> #include <QObject> #include <QString> class customButton : public QPushButton { Q_OBJECT public: int number; customButton(QWidget* parent); signals: void cB_clicked(int wagonName); protected slots: void slotForClick(); }; #endif // WAGONBUTTON_H <file_sep>#include "loadingscreen.h" #include "ui_loadingscreen.h" LoadingScreen::LoadingScreen(QWidget* parent) : QDialog(parent), ui(new Ui::LoadingScreen) { // this->setWindowFlags(Qt::Window | Qt::FramelessWindowHint); this->setWindowFlags(Qt::CustomizeWindowHint); ui->setupUi(this); movie = new QMovie(":/recources/img/loadingGif.gif"); ui->mLabel->setMovie(movie); ui->mLabel->show(); movie->start(); } LoadingScreen::~LoadingScreen() { delete ui; } <file_sep>#ifndef BUYTICKETS_H #define BUYTICKETS_H #include <QWidget> #include <QDebug> #include <backend.h> #include <QCompleter> #include <customButton.h> #include <QStandardItemModel> #include <math.h> namespace Ui { class BuyTickets; } class BuyTickets : public QWidget { Q_OBJECT public: explicit BuyTickets(BackEnd* bckEnd, QWidget* parent = nullptr); ~BuyTickets(); private slots: void on_SearchButton_clicked(); void on_ReverseDepDest_clicked(); void aComplete(QStringList cList); void showTrainsList(QVariantList trainsList); void on_TrainsTable_pressed(const QModelIndex& index); void on_goToTrainSelect_clicked(); void showAvailableSeats(QString wagonCount, QStringList takenSeats); void changeWagon(int wagonNumber); void showTicketPurchaseMenu(int seatNumber); void on_buyTicketButton_clicked(); void on_reserveTicketButton_clicked(); void ticketPurchaseDone(); void ticketAlreadyTaken(); private: Ui::BuyTickets* ui; QStandardItemModel* trainModel; BackEnd* bckEnd; QCompleter* depCompleter; QCompleter* destCompleter; QVector<customButton*>* seatsList; QVector<customButton*>* wagonsList; QString depTxt; QString destTxt; QString dateTxt; QString timeTxt; QString trainId; QStringList* cityList; QStringList* takenSeatslist; QModelIndex trainTableIndex; int currentWagon; int currentSeat; void setShadowEff(); void setCompleterStyle(QAbstractItemView* popup); void deleteSeatsAndWagons(); void showSeatsForWagon(int wagonNumber); int countFreeSpaces(QString wagonNumber); void buyOrReserveTicket(QString buyOrReserve); signals: void _dataToSend(QByteArray dataToSend); }; #endif // BUYTICKETS_H <file_sep>#pragma once #ifndef BACKEND_H #define BACKEND_H #include <QMessageBox> #include <QObject> #include <QWhatsThis> #include <QTcpSocket> #include <QJsonObject> #include <QJsonParseError> #include <QJsonDocument> #include <QJsonArray> #include <QPushButton> #include <QFile> class BackEnd : public QObject { Q_OBJECT public: explicit BackEnd(QObject* parent = nullptr); ~BackEnd(); void setCurUsername(QString userName); QString getCurUserame(); void showErrorMsg(QWidget* widget, QString errMsg); private: QTcpSocket* socket; QByteArray recievedData; QJsonDocument* jsnDoc; QJsonParseError* errJsn; QJsonObject* obj; QString curUsername; void decAndExec(); void logProc(); void regProc(); void cListProc(); void trainsListProc(); void getAvailableSeats(); void buyTicket(); void getUserTickets(); void buyReservedTicket(); void returnTicket(); private slots: void createSocket(); void sendData(QByteArray dataToSend); void sockReady(); void tryToReccon(); void sockDisc(); signals: void _reconnFailed(); void _reconnSuccess(); void _logSuccess(); void _regSuccess(); void _errSignalMW(QString info); void _cList(QStringList cList); void _trainsList(QVariantList trainsList); void _availableSeats(QString wagonsCounr, QStringList trainsList); void _ticketPurchaseSuccess(); void _userTickets(QVariantList unActiveTickets, QVariantList boughtTickets, QVariantList reservedTickets); void _ticketAlreadyTaken(); void _reservedTicketBought(); void _returnTicket(); }; #endif <file_sep>#include "myserver.h" myServer::myServer() { connectedClients = new QList<QTcpSocket*>(); this->errStrMsg = "{\"operation\":\"fatalErr\", \"resp\":\"bad\", \"err\":\"Something went wrong when transfering data. Please restart the app\"}"; }; myServer::~myServer() { } void myServer::startServer() { QHostAddress _adress("192.168.0.103"); if (this->listen(_adress, 27000)) { qDebug() << "Server listening to: " << _adress; QString serverName = "GF65\\SQLEXPRESS"; QString dbName = "TrainsDb"; db = new QSqlDatabase(); *db = QSqlDatabase::addDatabase("QODBC"); QString dsn = QString("Driver={SQL Server};Server=%1;Database=%2;Trusted_Connection=Yes;").arg(serverName).arg(dbName); db->setDatabaseName(dsn); if (db->open()) { qDebug() << "Database opened"; qry = new QSqlQuery(*db); } else { qDebug() << "Database not opened. ERROR: " << db->lastError().text(); } } else { qDebug() << "Server NOT listening to:" << _adress; } } void myServer::sendData(QTcpSocket* socket, QString& data) { socket->write((data + "DATAEND").toUtf8()); socket->waitForBytesWritten(3000); } void myServer::sockDisc() { QTcpSocket* socket; socket = new QTcpSocket(); socket = qobject_cast<QTcpSocket*>(sender()); socket->deleteLater(); qDebug() << "Client " << socket->socketDescriptor() << "disconected"; } void myServer::incomingConnection(qintptr socketDescriptor) { QTcpSocket* socket; socket = new QTcpSocket(); // set uniqe descriptor to client to be able to identify it later socket->setSocketDescriptor(socketDescriptor); // add client to list of connected clients connectedClients->append(socket); connect(socket, SIGNAL(readyRead()), this, SLOT(sockReady())); connect(socket, SIGNAL(disconnected()), this, SLOT(sockDisc())); qDebug() << "Client connected " << socketDescriptor; } void myServer::sockReady() { QTcpSocket* socket; socket = new QTcpSocket(); socket = qobject_cast<QTcpSocket*>(sender()); if (socket->waitForConnected(1500)) { recievedData = socket->readAll(); jsnDoc = new QJsonDocument(); *jsnDoc = QJsonDocument::fromJson(recievedData, errJsn); if (errJsn->errorString().toInt() == QJsonParseError::NoError) { decAndExec(jsnDoc, socket); return; } else { sendData(socket, errStrMsg); return; } } else { sendData(socket, errStrMsg); qDebug() << "Can not read data from client: Connestion failed"; return; } } void myServer::decAndExec(QJsonDocument* doc, QTcpSocket* socket) { obj = new QJsonObject; *obj = doc->object(); if (obj->value("operation") == "login") { logProc(socket); } else if (obj->value("operation") == "register") { regProc(socket); } else if (obj->value("operation") == "getCities") { getCities(socket); } else if (obj->value("operation") == "getTrainsList") { getTrainsList(socket); } else if (obj->value("operation") == "getAvailableSeats") { getAvailableSeats(socket); } else if (obj->value("operation") == "buyTicket") { buyTicket(socket); } else if (obj->value("operation") == "getUserTickets") { getUserTickets(socket); } else if (obj->value("operation") == "buyReservedTicket") { buyReservedTicket(socket); } else if (obj->value("operation") == "returnTicket") { returnTicket(socket); } else { sendData(socket, errStrMsg); } } void myServer::logProc(QTcpSocket* socket) { qry->prepare("select * from uInfo where uLog like :log COLLATE SQL_Latin1_General_Cp1_CS_AS"); qry->bindValue(":log", obj->value("log").toString()); if (qry->exec()) { if (qry->next()) { if (qry->value(1).toString() == obj->value("pass").toString()) { QString dataToSend = "{\"operation\":\"login\", \"resp\":\"ok\"}"; sendData(socket, dataToSend); } else { QString dataToSend = "{\"operation\":\"login\", \"resp\":\"bad\", \"err\":\"Invalid password\"}"; sendData(socket, dataToSend); } } else { QString dataToSend = "{\"operation\":\"login\", \"resp\":\"bad\", \"err\":\"Login doesn't exist\"}"; sendData(socket, dataToSend); } } else { sendData(socket, errStrMsg); } } void myServer::regProc(QTcpSocket* socket) { qry->prepare("select * from uInfo where uLog like :log COLLATE SQL_Latin1_General_Cp1_CS_AS"); qry->bindValue(":log", obj->value("log").toString()); if (qry->exec()) { if (qry->next()) { QString dataToSend = "{\"operation\":\"register\", \"resp\":\"bad\", \"err\":\"User already exist\"}"; sendData(socket, dataToSend); } else { qry->prepare("insert into uInfo (uLog, uPass) values (:log, :pass)"); qry->bindValue(":log", obj->value("log").toString()); qry->bindValue(":pass", obj->value("pass").toString()); if (qry->exec()) { QString dataToSend = "{\"operation\":\"register\", \"resp\":\"ok\"}"; sendData(socket, dataToSend); } else { sendData(socket, errStrMsg); } } } else { sendData(socket, errStrMsg); } } void myServer::getCities(QTcpSocket* socket) { if (qry->exec("select * from citiesList")) { QString cList = "{\"operation\":\"getCities\", \"resp\":\"ok\", \"data\":["; unsigned dataCounter = 0; while (qry->next()) { ++dataCounter; cList.push_back("\"" + qry->value(0).toString() + "\","); } if (dataCounter) cList.remove(cList.length() - 1, 1); cList.push_back("]}"); sendData(socket, cList); } else { sendData(socket, errStrMsg); } } void myServer::getTrainsList(QTcpSocket* socket) { qry->prepare("select * from getNeededTrainsList(:dep, :dest, :date, :time)"); qry->bindValue(":dep", obj->value("dep").toString()); qry->bindValue(":dest", obj->value("dest").toString()); qry->bindValue(":date", obj->value("arrDate").toString()); qry->bindValue(":time", obj->value("arrTime").toString()); if (qry->exec()) { QString trainsList = "{\"operation\":\"getTrainsList\", \"resp\":\"ok\", \"data\":"; QStringList jsonFields = { "trainId", "depArriveDate", "depArriveTime", "dapDepDate", "dapDepTime", "destArriveDate", "destArriveTime", "freeSeats" }; trainsList += createJsonStringFromQuery(jsonFields, qry); trainsList += "}"; sendData(socket, trainsList); } else { sendData(socket, errStrMsg); } } void myServer::getAvailableSeats(QTcpSocket* socket) { qry->prepare("select MAX(wagonNumber) from wagonsList where trainid = :trainId"); qry->bindValue(":trainId", obj->value("trainId").toString()); if (qry->exec()) { qry->next(); QString notAvailiableSeats = "{\"operation\":\"getAvailableSeats\", \"resp\":\"ok\", \"wagons\":\"" + qry->value(0).toString() + "\", \"data\":["; qry->prepare("select * from getAvailablePlaces(:trainDate, :trainId, :dep, :dest)"); qry->bindValue(":trainDate", obj->value("trainDate").toString()); qry->bindValue(":trainId", obj->value("trainId").toString()); qry->bindValue(":dep", obj->value("dep").toString()); qry->bindValue(":dest", obj->value("dest").toString()); if (qry->exec()) { unsigned dataCounter = 0; while (qry->next()) { for (unsigned short iter = 0; iter < 2; ++iter) { ++dataCounter; notAvailiableSeats.push_back("\"" + qry->value(iter).toString() + "\","); } } if (dataCounter) { notAvailiableSeats.remove(notAvailiableSeats.length() - 1, 1); } notAvailiableSeats.push_back("]}"); sendData(socket, notAvailiableSeats); } else { // handle bad query execution sendData(socket, errStrMsg); } } else { // handle bad query execution sendData(socket, errStrMsg); } } void myServer::buyTicket(QTcpSocket* socket) { // check if ticket is still available qry->prepare("select * from getAvailablePlaces(:trainDate, :trainId, :dep, :dest)"); qry->bindValue(":trainDate", obj->value("trainDate").toString()); qry->bindValue(":trainId", obj->value("trainId").toString()); qry->bindValue(":dep", obj->value("dep").toString()); qry->bindValue(":dest", obj->value("dest").toString()); QString wagonNumber = obj->value("wagonNumber").toString(); QString placeNumber = obj->value("placeNumber").toString(); if (qry->exec()) { while (qry->next()) { QString tmp1 = qry->value(0).toString(); QString tmp2 = qry->value(1).toString(); if (qry->value(0).toString() == wagonNumber && qry->value(1).toString() == placeNumber) { QString txtToSend = "{\"operation\":\"buyTicket\", \"resp\":\"alreadyTaken\"}"; sendData(socket, txtToSend); return; } } } else { sendData(socket, errStrMsg); } // buy ticket if it is available qry->prepare("insert into takenSeats values(:trainDate, :trainId, :wagonNumber, :placeNumber, dbo.getStationNumber(:trainId, :dep) , " "dbo.getStationNumber(:trainId, :dest), :buyOrReserve, :ownerInfo, :fName, :lName, CONVERT(DATE,GETDATE()), " "CONVERT(TIME,GETDATE()))"); qry->bindValue(":trainDate", obj->value("trainDate").toString()); qry->bindValue(":trainId", obj->value("trainId").toString()); qry->bindValue(":wagonNumber", obj->value("wagonNumber").toString()); qry->bindValue(":placeNumber", obj->value("placeNumber").toString()); qry->bindValue(":dep", obj->value("dep").toString()); qry->bindValue(":dest", obj->value("dest").toString()); qry->bindValue(":buyOrReserve", obj->value("buyOrReserve").toString()); qry->bindValue(":ownerInfo", obj->value("ownerInfo").toString()); qry->bindValue(":fName", obj->value("fName").toString()); qry->bindValue(":lName", obj->value("lName").toString()); if (qry->exec()) { QString txtToSend = "{\"operation\":\"buyTicket\", \"resp\":\"ok\"}"; sendData(socket, txtToSend); } else { // handle bad query execution sendData(socket, errStrMsg); } } void myServer::getUserTickets(QTcpSocket* socket) { qry->prepare("select * from getUnActiveTickets(:userName)"); qry->bindValue(":userName", obj->value("userName").toString()); if (qry->exec()) { QString userTickets = "{\"operation\":\"getUserTickets\", \"resp\":\"ok\", \"unActiveTickets\":"; QStringList jsonFields = { "trainId", "trainDate", "dep", "dest", "wagonNumber", "placeNumber", "ownerFname", "ownerLname", "purchaseDate", "purchaseTime", "buyOrRes" }; userTickets += createJsonStringFromQuery(jsonFields, qry); userTickets += ", \"boughtTickets\":"; qry->prepare("select * from getBoughtTickets(:userName)"); qry->bindValue(":userName", obj->value("userName").toString()); if (qry->exec()) { userTickets += createJsonStringFromQuery(jsonFields, qry); userTickets += ", \"reservedTickets\":"; qry->prepare("select * from getReservedTickets(:userName)"); qry->bindValue(":userName", obj->value("userName").toString()); if (qry->exec()) { userTickets += createJsonStringFromQuery(jsonFields, qry); userTickets.push_back("}"); sendData(socket, userTickets); } else { // handle bad query execution sendData(socket, errStrMsg); } } else { // handle bad query execution sendData(socket, errStrMsg); } } else { // handle bad query execution sendData(socket, errStrMsg); } } void myServer::buyReservedTicket(QTcpSocket* socket) { qry->prepare("UPDATE takenSeats" " SET buyOrReserve = 0, ownerFirstName =:fName, ownerLastName = :lName, purchaseDate = convert(date,GETDATE()), purchaseTime = " "convert(time,GETDATE())" " WHERE trainDate =:trainDate and trainId = :trainId and wagonNumber = :wagonNumber and placeNumber = :placeNumber and " "takenFromStation = dbo.getStationNumber(:trainId, :dep) and takenToStation = dbo.getStationNumber(:trainId,:dest )"); qry->bindValue(":trainDate", obj->value("trainDate").toString()); qry->bindValue(":trainId", obj->value("trainId").toString()); qry->bindValue(":wagonNumber", obj->value("wagonNumber").toString()); qry->bindValue(":placeNumber", obj->value("placeNumber").toString()); qry->bindValue(":dep", obj->value("dep").toString()); qry->bindValue(":dest", obj->value("dest").toString()); qry->bindValue(":fName", obj->value("fName").toString()); qry->bindValue(":lName", obj->value("lName").toString()); if (qry->exec()) { QString dataToSend = "{\"operation\":\"buyReservedTicket\", \"resp\":\"ok\"}"; sendData(socket, dataToSend); } else { // handle bad query execution sendData(socket, errStrMsg); } } void myServer::returnTicket(QTcpSocket* socket) { qry->prepare("delete from takenSeats where trainDate =:trainDate and trainId = :trainId and wagonNumber = :wagonNumber and placeNumber = " ":placeNumber and " "takenFromStation = dbo.getStationNumber(:trainId, :dep) and takenToStation = dbo.getStationNumber(:trainId,:dest )"); qry->bindValue(":trainDate", obj->value("trainDate").toString()); qry->bindValue(":trainId", obj->value("trainId").toString()); qry->bindValue(":wagonNumber", obj->value("wagonNumber").toString()); qry->bindValue(":placeNumber", obj->value("placeNumber").toString()); qry->bindValue(":dep", obj->value("dep").toString()); qry->bindValue(":dest", obj->value("dest").toString()); if (qry->exec()) { QString dataToSend = "{\"operation\":\"returnTicket\", \"resp\":\"ok\"}"; sendData(socket, dataToSend); } else { // handle bad query execution sendData(socket, errStrMsg); } } QString myServer::createJsonStringFromQuery(QStringList& jsonFields, QSqlQuery* qry) { QString resStr = "["; unsigned dataCounter = 0; while (qry->next()) { resStr.push_back("{"); for (unsigned short iter = 0; iter < jsonFields.length(); ++iter) { ++dataCounter; resStr.push_back("\"" + jsonFields[iter] + "\":\"" + qry->value(iter).toString() + "\","); } resStr.remove(resStr.length() - 1, 1); resStr.push_back("},"); } if (dataCounter) { resStr.remove(resStr.length() - 1, 1); } resStr.push_back("]"); return resStr; } <file_sep>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QGraphicsDropShadowEffect> // set shadows in Log and Reg menus void MainWindow::setShadowEff() { QGraphicsDropShadowEffect* LogEffect = new QGraphicsDropShadowEffect; LogEffect->setBlurRadius(20); LogEffect->setXOffset(0); LogEffect->setYOffset(0); LogEffect->setColor(Qt::black); ui->LoginLineEdit->setGraphicsEffect(LogEffect); QGraphicsDropShadowEffect* PassEffect = new QGraphicsDropShadowEffect; PassEffect->setBlurRadius(20); PassEffect->setXOffset(0); PassEffect->setYOffset(0); PassEffect->setColor(Qt::black); ui->PassLineEdit->setGraphicsEffect(PassEffect); QGraphicsDropShadowEffect* LogButtonEffect = new QGraphicsDropShadowEffect; LogButtonEffect->setBlurRadius(20); LogButtonEffect->setXOffset(0); LogButtonEffect->setYOffset(0); LogButtonEffect->setColor(Qt::black); ui->LogButton->setGraphicsEffect(LogButtonEffect); QGraphicsDropShadowEffect* REgButtonEffect = new QGraphicsDropShadowEffect; REgButtonEffect->setBlurRadius(20); REgButtonEffect->setXOffset(0); REgButtonEffect->setYOffset(0); REgButtonEffect->setColor(Qt::black); ui->RegButton->setGraphicsEffect(REgButtonEffect); QGraphicsDropShadowEffect* ExitEffect = new QGraphicsDropShadowEffect; ExitEffect->setBlurRadius(20); ExitEffect->setXOffset(0); ExitEffect->setYOffset(0); ExitEffect->setColor(Qt::black); ui->ExitButton->setGraphicsEffect(ExitEffect); QGraphicsDropShadowEffect* RegLofEffect = new QGraphicsDropShadowEffect; RegLofEffect->setBlurRadius(20); RegLofEffect->setXOffset(0); RegLofEffect->setYOffset(0); RegLofEffect->setColor(Qt::black); ui->RegLogLineEdit->setGraphicsEffect(RegLofEffect); QGraphicsDropShadowEffect* RegPassEffect = new QGraphicsDropShadowEffect; RegPassEffect->setBlurRadius(20); RegPassEffect->setXOffset(0); RegPassEffect->setYOffset(0); RegPassEffect->setColor(Qt::black); ui->RegPassLineEdit->setGraphicsEffect(RegPassEffect); QGraphicsDropShadowEffect* RegPConfEffect = new QGraphicsDropShadowEffect; RegPConfEffect->setBlurRadius(20); RegPConfEffect->setXOffset(0); RegPConfEffect->setYOffset(0); RegPConfEffect->setColor(Qt::black); ui->RegConfLineEdit->setGraphicsEffect(RegPConfEffect); QGraphicsDropShadowEffect* RegRegfEffect = new QGraphicsDropShadowEffect; RegRegfEffect->setBlurRadius(20); RegRegfEffect->setXOffset(0); RegRegfEffect->setYOffset(0); RegRegfEffect->setColor(Qt::black); ui->RegRegButton->setGraphicsEffect(RegRegfEffect); QGraphicsDropShadowEffect* RegBackfEffect = new QGraphicsDropShadowEffect; RegBackfEffect->setBlurRadius(20); RegBackfEffect->setXOffset(0); RegBackfEffect->setYOffset(0); RegBackfEffect->setColor(Qt::black); ui->RegGoBackButton->setGraphicsEffect(RegBackfEffect); retryLoadingYesBtn->setStyleSheet("QPushButton" "{" "background-color: rgba(242, 150, 47, 220);" "border:none;" "border-radius:10px;" "color:#1b2327;" "font-family: \"Calibri Bold\";" "font-size: 17px;" "}" "QPushButton:hover:!pressed{" "background-color: #455A64;" "color:#EEEEEE;" "}" "QPushButton:hover:pressed{" " background-color: #37474F;" "color:#DDDDDD;" "}"); retryLoadingNoBtn->setStyleSheet("QPushButton" "{" "background-color: rgba(242, 150, 47, 220);" "border:none;" "border-radius:10px;" "color:#1b2327;" "font-family: \"Calibri Bold\";" "font-size: 17px;" "}" "QPushButton:hover:!pressed{" "background-color: #455A64;" "color:#EEEEEE;" "}" "QPushButton:hover:pressed{" " background-color: #37474F;" "color:#DDDDDD;" "}"); retConnLabel->setStyleSheet("QLabel{" "background:none ;" "color:#EEEEEE;" "font: \"Calibri\";" "font-size: 14px;" "}"); } void MainWindow::resizeLoadindScreen() { short wW = this->width(); short wH = this->height(); short hM = 10; short totalH = retConnLabel->height() + retryLoadingYesBtn->height() + 2 * hM; short totalW = retryLoadingYesBtn->width() + retryLoadingNoBtn->width() + 20; loadingBckGround->resize(wW, wH); loadingBckGround->move(0, 0); loadingGif->move(wW / 2 - loadingGif->width() / 2 + 25, wH / 2 - loadingGif->height() / 2); retConnLabel->move(wW / 2 - retConnLabel->width() / 2, wH / 2 - totalH / 2); retryLoadingYesBtn->move(wW / 2 - totalW / 2, wH / 2 - totalH / 2 + retConnLabel->height() + hM); retryLoadingNoBtn->move(wW / 2 - totalW / 2 + retryLoadingYesBtn->width() + 20, wH / 2 - totalH / 2 + retConnLabel->height() + hM); } // resizing Log menuacording ro window size void MainWindow::resizeLogMenu() { const short hMarg = 6; const short betweenMarg = 50; const short wW = this->size().width(); const short wH = this->size().height(); const short LeH = 22 + wH / 50; const short LeW = 250 + wW / 15; const short bH = 17 + wH / 75; const short bW = 52 + wW / 25; const short CbH = ui->RemMeCheckBox->size().height(); const short CbW = ui->RemMeCheckBox->size().width(); short totalHeight = 4 * hMarg + betweenMarg + 2 * LeH + 3 * bH + CbH; ui->LoginLineEdit->resize(LeW, LeH); ui->PassLineEdit->resize(LeW, LeH); ui->LoginLineEdit->move(wW / 2 - LeW / 2, wH / 2 - totalHeight / 2); ui->PassLineEdit->move(wW / 2 - LeW / 2, wH / 2 - totalHeight / 2 + LeH + hMarg); ui->RemMeCheckBox->move(wW / 2 - LeW / 2, wH / 2 - totalHeight / 2 + LeH + hMarg + LeH + hMarg); ui->LogButton->resize(bW, bH); ui->RegButton->resize(bW, bH); ui->ExitButton->resize(bW, bH); ui->LogButton->move(wW / 2 - bW / 2, wH / 2 - totalHeight / 2 + LeH + hMarg + LeH + betweenMarg); ui->RegButton->move(wW / 2 - bW / 2, wH / 2 - totalHeight / 2 + LeH + hMarg + LeH + betweenMarg + bH + hMarg); ui->ExitButton->move(wW / 2 - bW / 2, wH / 2 - totalHeight / 2 + LeH + hMarg + LeH + betweenMarg + bH + hMarg + bH + hMarg); QString bordRadButton = "QPushButton { border-radius: " + QString::number(bH / 2) + "px; }"; QString bordRadLe = "QLineEdit { border-radius: " + QString::number(LeH / 4) + "px; }"; ui->LogButton->setStyleSheet(bordRadButton); ui->RegButton->setStyleSheet(bordRadButton); ui->ExitButton->setStyleSheet(bordRadButton); ui->LoginLineEdit->setStyleSheet(bordRadLe); ui->PassLineEdit->setStyleSheet(bordRadLe); } // resizing Reg menuacording ro window size void MainWindow::resizeRegMenu() { const short hMarg = 6; const short betweenMarg = 30; const short wW = this->size().width(); const short wH = this->size().height(); const short LeH = 22 + wH / 50; const short LeW = 250 + wW / 15; const short bH = 17 + wH / 75; const short bW = 52 + wW / 25; short totalHeight = 2 * hMarg + betweenMarg + 3 * LeH + bH; ui->RegLogLineEdit->resize(LeW, LeH); ui->RegPassLineEdit->resize(LeW, LeH); ui->RegConfLineEdit->resize(LeW, LeH); ui->RegLogLineEdit->move(wW / 2 - LeW / 2, wH / 2 - totalHeight / 2); ui->RegPassLineEdit->move(wW / 2 - LeW / 2, wH / 2 - totalHeight / 2 + LeH + hMarg); ui->RegConfLineEdit->move(wW / 2 - LeW / 2, wH / 2 - totalHeight / 2 + LeH + hMarg + LeH + hMarg); ui->RegRegButton->resize(bW, bH); ui->RegRegButton->move(wW / 2 - bW / 2, wH / 2 - totalHeight / 2 + LeH + hMarg + LeH + hMarg + LeH + betweenMarg); QString bordRadButton = "QPushButton { border-radius: " + QString::number(bH / 2) + "px; }"; QString bordRadLe = "QLineEdit { border-radius: " + QString::number(LeH / 4) + "px; }"; ui->RegLogLineEdit->setStyleSheet(bordRadLe); ui->RegPassLineEdit->setStyleSheet(bordRadLe); ui->RegConfLineEdit->setStyleSheet(bordRadLe); ui->RegRegButton->setStyleSheet(bordRadButton); } <file_sep>#ifndef MAINWINDOW_H #define MAINWINDOW_H // secondary libreries #include <QEvent> #include <QToolTip> #include <QMainWindow> #include <QFile> #include <QDir> #include <purchasesmenu.h> // for communication with server #include <backend.h> // for multi threading #include <QThread> // for showing gifs #include <QMovie> // for loading screen #include <QLabel> // for format of strings checking #include <QRegularExpression> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget* parent = nullptr); ~MainWindow(); private slots: void on_RegRegButton_clicked(); void on_ExitButton_clicked(); void on_RegButton_clicked(); void on_RegGoBackButton_clicked(); void on_LogButton_clicked(); void retryLoadingYesBtn_clicked(); void on_LoginLineEdit_textChanged(const QString& arg1); void on_PassLineEdit_textEdited(const QString& arg1); void resizeEvent(QResizeEvent*); // redefinition of QResize event void loadScrnShow(); // show loading screen void loadScrnHide(); // hide loading screen void logSuccess(); void regSuccess(); // go to lof menu if registration is successful void errSlot(QString Info); void logOutSlot(); private: Ui::MainWindow* ui; QThread* secThread; BackEnd* bckEnd; QLabel* loadingGif; QLabel* retConnLabel; QLabel* loadingBckGround; QMovie* movie; QPushButton* retryLoadingYesBtn; QPushButton* retryLoadingNoBtn; PurchasesMenu* OvScreen; // main menu screen void resizeLogMenu(); // resizing elements in Log menu when window size changes void resizeRegMenu(); // resizing elements in Reg menu when window size changes void setShadowEff(); // set shadows in Log and Reg menus void resizeLoadindScreen(); // resizing loading screen signals: void _dataToSend(QByteArray dataToSend); // emit this signal when you need send data to server void _tryToReconn(); // tells back end to try to reconnect to server }; #endif // MAINWINDOW_H <file_sep>#include "mainwindow.h" #include <UiHelperMainWindow.cpp> #include "ui_mainwindow.h" // constructor MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // create blue background for loading screen loadingBckGround = new QLabel(this); loadingBckGround->setStyleSheet("QLabel{background-color:rgb(38,50,56);}"); // create view for gif loadingGif = new QLabel(this); loadingGif->resize(200, 124); movie = new QMovie(":/recources/img/loadingGif.gif"); movie->setScaledSize(QSize(loadingGif->width(), loadingGif->height())); loadingGif->setMovie(movie); movie->setSpeed(110); // create buttons for loading screen retryLoadingYesBtn = new QPushButton(this); retryLoadingNoBtn = new QPushButton(this); retryLoadingYesBtn->setText("Retry"); retryLoadingNoBtn->setText("Quit app"); // create lable to show text on loading screen retConnLabel = new QLabel(this); retConnLabel->setText("Could not connect to server. Do you want to rty again?"); retConnLabel->resize(345, 17); // setting Log menu as starting screen (0 is index of login menu in stackedwidget) ui->stackedWidget->setCurrentIndex(0); // calling func to make shadows in login and reg menus setShadowEff(); // creating new backend bckEnd = new BackEnd(); // crerate new thread this makes possible showing animations while connecting secThread = new QThread(this); // quit second thred when app closes connect(this, SIGNAL(destroyed()), secThread, SLOT(quit())); // create socket and connect to server when new threa started connect(secThread, SIGNAL(started()), bckEnd, SLOT(createSocket())); // to be able to send data to bckEnd object connect(this, SIGNAL(_dataToSend(QByteArray)), bckEnd, SLOT(sendData(QByteArray))); // when back end can not connect to server show loading screen connect(bckEnd, SIGNAL(_reconnFailed()), this, SLOT(loadScrnShow())); // close loading screen when connection restored connect(bckEnd, SIGNAL(_reconnSuccess()), this, SLOT(loadScrnHide())); // when loginization is successful connect(bckEnd, SIGNAL(_logSuccess()), this, SLOT(logSuccess())); // when registration is successful connect(bckEnd, SIGNAL(_regSuccess()), this, SLOT(regSuccess())); // when error in log or reg process connect(bckEnd, SIGNAL(_errSignalMW(QString)), this, SLOT(errSlot(QString))); // when user dont want to try connecting again connect(retryLoadingNoBtn, SIGNAL(clicked()), this, SLOT(on_ExitButton_clicked())); // when user dont want to try connecting again connect(retryLoadingYesBtn, SIGNAL(clicked()), bckEnd, SLOT(tryToReccon())); // show gif while trying to conect connect(retryLoadingYesBtn, SIGNAL(clicked()), this, SLOT(retryLoadingYesBtn_clicked())); // start new thread bckEnd->moveToThread(secThread); secThread->start(); resizeLoadindScreen(); // check if any user pressed remember me QFile rMeFile(".remMe"); if (rMeFile.open(QIODevice::ReadOnly)) { { ui->LoginLineEdit->setText(rMeFile.readLine().replace("\n", "")); ui->PassLineEdit->setText(rMeFile.readLine().replace("\n", "")); rMeFile.close(); if (ui->LoginLineEdit->text() != "") { ui->RemMeCheckBox->setChecked(1); ui->LogButton->animateClick(0); } } } } // destructor MainWindow::~MainWindow() { secThread->quit(); secThread->wait(); delete bckEnd; delete ui; } void MainWindow::on_LoginLineEdit_textChanged(const QString& arg1) { ui->LoginLineEdit->setStyleSheet("border-color: #455A64;"); } void MainWindow::on_PassLineEdit_textEdited(const QString& arg1) { ui->PassLineEdit->setStyleSheet("border-color: #455A64;"); } void MainWindow::on_RegButton_clicked() { resizeRegMenu(); ui->stackedWidget->setCurrentIndex(1); } void MainWindow::on_LogButton_clicked() { QString logTxt = ui->LoginLineEdit->text(); QString passTxt = ui->PassLineEdit->text(); QRegularExpression logPattern("[a-zA-Z0-9@.]{5,}"); QRegularExpression passPattern("[a-zA-Z0-9]{6,}"); if (logPattern.match(logTxt).capturedLength() >= 5 && logPattern.match(logTxt).capturedLength() == logTxt.length()) { if (passPattern.match(passTxt).capturedLength() >= 6 && passPattern.match(passTxt).capturedLength() == passTxt.length()) { QString txtToSend = QString("{\"operation\":\"login\", \"log\":\"%1\", \"pass\":\"%2\"}").arg(logTxt).arg(passTxt); emit _dataToSend(txtToSend.toUtf8()); } else { bckEnd->showErrorMsg(ui->PassLineEdit, "Password can only contain latin letters and numbers and must be longer than 6 characters"); } } // if log format is incorrect else { // check pass format if (passPattern.match(passTxt).capturedLength() < 6 || passPattern.match(passTxt).capturedLength() != passTxt.length()) // if password format is incorrect { bckEnd->showErrorMsg(ui->LoginLineEdit, "<p>Login can only contain latin letters, numbers and characters . and @ and must be longer than 5 " "characters</p>" "<p>Password can only contain latin letters and numbers and must be longer than 6 characters</p>"); } else { bckEnd->showErrorMsg(ui->LoginLineEdit, "Login can only contain latin letters, numbers and characters . and @ and must be longer than 5 " "characters"); } } } void MainWindow::retryLoadingYesBtn_clicked() { retryLoadingYesBtn->hide(); retryLoadingNoBtn->hide(); retConnLabel->hide(); movie->start(); loadingGif->show(); } void MainWindow::on_ExitButton_clicked() { QMessageBox msgBox(this); msgBox.setObjectName("msgBox"); msgBox.setStyleSheet("#msgBox{ background-color:#1e282d;}" "QLabel{background:none;color:#e4e4e4;font-family: \"Calibri\";font-size: 14px;border:none;}" "QPushButton{width:60px;background-color: rgba(242, 150, 47, 220);border:none;border-radius:10px;color:#1b2327;font-family: " "\"Calibri " "Bold\";font-size: 17px;}" "QPushButton:hover:!pressed{background-color: #455A64;color:#EEEEEE;}" "QPushButton:hover:pressed{background-color: #37474F;color:#DDDDDD;}"); msgBox.setWindowTitle("Exit confirmation"); msgBox.setInformativeText("<p>Do you want to exit the app?<p>"); msgBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes); msgBox.setDefaultButton(QMessageBox::No); int userAnswer = msgBox.exec(); if (userAnswer == QMessageBox::Yes) { this->close(); } } void MainWindow::on_RegGoBackButton_clicked() { resizeLogMenu(); ui->stackedWidget->setCurrentIndex(0); } void MainWindow::on_RegRegButton_clicked() { QString logTxt = ui->RegLogLineEdit->text(); QString passTxt = ui->RegPassLineEdit->text(); QString confTxt = ui->RegConfLineEdit->text(); QRegularExpression logFormat("[a-zA-Z0-9@.]{5,}"); QRegularExpression passFormat("[A-Za-z0-9]{6,}"); if (logFormat.match(logTxt).capturedLength() >= 5 && logFormat.match(logTxt).capturedLength() == logTxt.length()) // if login fits log format { if (passFormat.match(passTxt).capturedLength() >= 6 && passFormat.match(passTxt).capturedLength() == passTxt.length()) // if pass match pass format { if (passTxt == confTxt) // if pass==conf { // read data from line edits and convert it to JSON format QString txtToSend = QString("{\"operation\":\"register\", \"log\":\"%1\", \"pass\":\"%2\"}").arg(logTxt).arg(passTxt); // send log and pass to server emit _dataToSend(txtToSend.toUtf8()); } else { bckEnd->showErrorMsg(ui->RegConfLineEdit, "Password and confirm field must match"); } } else { bckEnd->showErrorMsg(ui->RegPassLineEdit, "Password can only contain latin letters and numbers and must be longer than 6 characters"); } } // if login doesnt match needed format else { if (passFormat.match(passTxt).capturedLength() < 6 || passFormat.match(passTxt).capturedLength() != passTxt.length()) // if pass doesnt match needed format { bckEnd->showErrorMsg(ui->RegPassLineEdit, "<p>Login can only contain latin letters, numbers and characters . and @ and must be longer than 5 " "characters</p>" "<p>Password can only contain latin letters and numbers and must be longer than 6 characters</p>"); } else { bckEnd->showErrorMsg(ui->RegLogLineEdit, "Login can only contain latin letters, numbers and characters . and @ and must be longer than 5 " "characters"); } } } // for handeling MainWindow resize event void MainWindow::resizeEvent(QResizeEvent* event) { if (loadingBckGround->isVisible()) { resizeLoadindScreen(); } if (ui->stackedWidget->currentIndex() == 0) { resizeLogMenu(); } else if (ui->stackedWidget->currentIndex() == 1) { resizeRegMenu(); } QWidget::resizeEvent(event); } void MainWindow::loadScrnShow() { retryLoadingYesBtn->show(); retryLoadingNoBtn->show(); retConnLabel->show(); movie->stop(); loadingGif->hide(); if (!loadingBckGround->isVisible()) { resizeLoadindScreen(); loadingGif->show(); loadingBckGround->show(); } } void MainWindow::loadScrnHide() { retryLoadingYesBtn->hide(); retryLoadingNoBtn->hide(); retConnLabel->hide(); movie->stop(); loadingBckGround->hide(); loadingGif->hide(); } void MainWindow::logSuccess() { QDir dir(QCoreApplication::applicationDirPath() + ".remMe"); QFile rMeFile(".remMe"); bckEnd->setCurUsername(ui->LoginLineEdit->text()); // if remember me is checked // write log and pass to remME file if (rMeFile.open(QIODevice::WriteOnly)) { if (ui->RemMeCheckBox->isChecked()) { { QString fileInputTex = ui->LoginLineEdit->text() + "\n" + ui->PassLineEdit->text(); rMeFile.write(fileInputTex.toUtf8()); rMeFile.waitForBytesWritten(100); rMeFile.close(); } } else { rMeFile.close(); } } // adding main menu ui to stacked widget OvScreen = new PurchasesMenu(bckEnd); ui->stackedWidget->addWidget(OvScreen); connect(OvScreen, SIGNAL(_closeApp()), this, SLOT(on_ExitButton_clicked())); connect(OvScreen, SIGNAL(_logOut()), this, SLOT(logOutSlot())); // go to main menu ui->stackedWidget->setCurrentWidget(OvScreen); // send lrequest to get cities list emit _dataToSend("{\"operation\":\"getCities\"}"); } void MainWindow::regSuccess() { ui->stackedWidget->setCurrentIndex(0); bckEnd->showErrorMsg(ui->LoginLineEdit, "Registration is successful, now you can login."); } void MainWindow::errSlot(QString Info) { if (Info == "Login doesn't exist") { bckEnd->showErrorMsg(ui->LoginLineEdit, "Login doesn't exist"); ui->LoginLineEdit->setStyleSheet("border-color:#990329;"); } else if (Info == "Invalid password") { bckEnd->showErrorMsg(ui->PassLineEdit, "Invalid password"); ui->PassLineEdit->setStyleSheet("border-color:#990329;"); } else if (Info == "User already exist") { bckEnd->showErrorMsg(ui->RegLogLineEdit, "User already exist"); } else { QMessageBox::critical(this, "Fatal error", Info); } } void MainWindow::logOutSlot() { QMessageBox msgBox(this); msgBox.setObjectName("msgBox"); msgBox.setStyleSheet("#msgBox{ background-color:#1e282d;}" "QLabel{background:none;color:#e4e4e4;font-family: \"Calibri\";font-size: 14px;border:none;}" "QPushButton{width:60px;background-color: rgba(242, 150, 47, 220);border:none;border-radius:10px;color:#1b2327;font-family: " "\"Calibri " "Bold\";font-size: 17px;}" "QPushButton:hover:!pressed{background-color: #455A64;color:#EEEEEE;}" "QPushButton:hover:pressed{background-color: #37474F;color:#DDDDDD;}"); msgBox.setWindowTitle("Exit confirmation"); msgBox.setInformativeText("<p>Do you want to exit the app?<p>"); msgBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes); msgBox.setDefaultButton(QMessageBox::No); int userAnswer = msgBox.exec(); if (userAnswer == QMessageBox::No) { return; } else { ui->stackedWidget->removeWidget(OvScreen); disconnect(OvScreen, SIGNAL(_closeApp()), this, SLOT(on_ExitButton_clicked())); disconnect(OvScreen, SIGNAL(_logOut()), this, SLOT(logOutSlot())); QFile rMeFile(".remMe"); rMeFile.open(QIODevice::WriteOnly); rMeFile.close(); ui->LoginLineEdit->clear(); ui->PassLineEdit->clear(); resizeLogMenu(); ui->stackedWidget->setCurrentIndex(0); delete OvScreen; } } <file_sep>#include "buytickets.h" #include "ui_buytickets.h" #include <QGraphicsDropShadowEffect> void BuyTickets::setShadowEff() { QGraphicsDropShadowEffect* DepartEffect = new QGraphicsDropShadowEffect; DepartEffect->setBlurRadius(20); DepartEffect->setXOffset(0); DepartEffect->setYOffset(0); DepartEffect->setColor(Qt::black); ui->DepartureLineEdit->setGraphicsEffect(DepartEffect); QGraphicsDropShadowEffect* DestEffect = new QGraphicsDropShadowEffect; DestEffect->setBlurRadius(20); DestEffect->setXOffset(0); DestEffect->setYOffset(0); DestEffect->setColor(Qt::black); ui->DestinationLineEdit->setGraphicsEffect(DestEffect); QGraphicsDropShadowEffect* FromLabelEffect = new QGraphicsDropShadowEffect; FromLabelEffect->setBlurRadius(20); FromLabelEffect->setXOffset(0); FromLabelEffect->setYOffset(0); FromLabelEffect->setColor(Qt::black); ui->FromLabel->setGraphicsEffect(FromLabelEffect); QGraphicsDropShadowEffect* ToLabelEffect = new QGraphicsDropShadowEffect; ToLabelEffect->setBlurRadius(20); ToLabelEffect->setXOffset(0); ToLabelEffect->setYOffset(0); ToLabelEffect->setColor(Qt::black); ui->ToLabel->setGraphicsEffect(ToLabelEffect); QGraphicsDropShadowEffect* DepTimeLabEffect = new QGraphicsDropShadowEffect; DepTimeLabEffect->setBlurRadius(20); DepTimeLabEffect->setXOffset(0); DepTimeLabEffect->setYOffset(0); DepTimeLabEffect->setColor(Qt::black); ui->DepTimeLab->setGraphicsEffect(DepTimeLabEffect); QGraphicsDropShadowEffect* HourLabelEffect = new QGraphicsDropShadowEffect; HourLabelEffect->setBlurRadius(20); HourLabelEffect->setXOffset(0); HourLabelEffect->setYOffset(0); HourLabelEffect->setColor(Qt::black); ui->HourLabel->setGraphicsEffect(HourLabelEffect); QGraphicsDropShadowEffect* DateEditEffect = new QGraphicsDropShadowEffect; DateEditEffect->setBlurRadius(20); DateEditEffect->setXOffset(0); DateEditEffect->setYOffset(0); DateEditEffect->setColor(Qt::black); ui->DateEdit->setGraphicsEffect(DateEditEffect); QGraphicsDropShadowEffect* TimeEditEffect = new QGraphicsDropShadowEffect; TimeEditEffect->setBlurRadius(20); TimeEditEffect->setXOffset(0); TimeEditEffect->setYOffset(0); TimeEditEffect->setColor(Qt::black); ui->TimeEdit->setGraphicsEffect(TimeEditEffect); QGraphicsDropShadowEffect* SearchButtonEffect = new QGraphicsDropShadowEffect; SearchButtonEffect->setBlurRadius(20); SearchButtonEffect->setXOffset(0); SearchButtonEffect->setYOffset(0); SearchButtonEffect->setColor(Qt::black); ui->SearchButton->setGraphicsEffect(SearchButtonEffect); } void BuyTickets::setCompleterStyle(QAbstractItemView *popup) { popup->setStyleSheet(" QListView {background-color:#37474F ; " " " " border-style: solid; " " border-width: 2px; " " border-color: #455A64; " " color:#ECEFF1; " " font-family: \" Calibri \"; " " font-size: 13px; }" " QScrollBar:vertical { \ border: 2px solid #90A4AE; \ background: #263238; \ width: 15px; \ margin: 22px 0 22px 0; \ } \ QScrollBar::handle:vertical { \ background: white; \ min-height: 20px; \ } \ QScrollBar::add-line:vertical { \ border: 2px solid grey; \ background: #32CC99; \ height: 20px; \ subcontrol-position: bottom; \ subcontrol-origin: margin; \ } \ \ QScrollBar::sub-line:vertical { \ border: 2px solid grey; \ background: #32CC99; \ height: 20px; \ subcontrol-position: top; \ subcontrol-origin: margin; \ } \ QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { \ border: 2px solid grey; \ width: 3px; \ height: 3px; \ background: white; \ } \ \ QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { \ background: none;\ }"); } <file_sep>#include "purchasesmenu.h" #include "ui_purchasesmenu.h" #include "mainwindow.h" #include "ui_mainwindow.h" #include <UiHelperPurchasesMenu.cpp> #include <QPixmap> #include <QEvent> // constructor PurchasesMenu::PurchasesMenu(BackEnd* bckEnd, QWidget* parent) : QWidget(parent), ui(new Ui::PurchasesMenu) { ui->setupUi(this); // create pointer wich points to mainwindow bckEnd this->bckEnd = bckEnd; // adding BuyTickets screen to stacked widget BuyScreen = new BuyTickets(bckEnd); ui->stackedWidget->addWidget(BuyScreen); reserveScreen = new reserveTicketsMenu(bckEnd); ui->stackedWidget->addWidget(reserveScreen); // seting ButTickets as start screen ui->stackedWidget->setCurrentWidget(BuyScreen); // to be able to send data to bckEnd object connect(this, SIGNAL(_dataToSend(QByteArray)), bckEnd, SLOT(sendData(QByteArray))); // set icons on start of ui setIcons(); ui->BuyButton->setCheckable(0); QPixmap BuyIcon(":/recources/img/TrainIconFocus.png"); ui->BuyButton->setIcon(BuyIcon); setShadowEff(); } // destructor PurchasesMenu::~PurchasesMenu() { delete ui; } // to handle on button click events bool PurchasesMenu::eventFilter(QObject* watched, QEvent* event) { QPushButton* button = qobject_cast<QPushButton*>(watched); if (!button) { return false; } if (event->type() == QEvent::HoverEnter) { setEnterIcon(watched); return true; } else if (event->type() == QEvent::HoverLeave) { setLeaveIcon(watched); return true; } return false; } void PurchasesMenu::showTicketsForCurrentUser() { QString txtToSend = QString("{\"operation\":\"getUserTickets\", \"userName\":\"%1\"}").arg(bckEnd->getCurUserame()); emit _dataToSend(txtToSend.toUtf8()); } void PurchasesMenu::on_BuyButton_clicked() { ui->BuyButton->setCheckable(0); QPixmap BuyIcon(":/recources/img/TrainIconFocus.png"); ui->BuyButton->setIcon(BuyIcon); ui->ReserveButton->setCheckable(1); QPixmap ReservedIcon(":/recources/img/BookedTicketsIcon.png"); ui->ReserveButton->setIcon(ReservedIcon); ui->LogOutButton->setCheckable(1); QPixmap LogOutIcon(":/recources/img/ExitIcon.png"); ui->LogOutButton->setIcon(LogOutIcon); ui->stackedWidget->setCurrentWidget(BuyScreen); } void PurchasesMenu::on_ReserveButton_clicked() { showTicketsForCurrentUser(); ui->BuyButton->setCheckable(1); QPixmap BuyIcon(":/recources/img/TrainIcon.png"); ui->BuyButton->setIcon(BuyIcon); ui->ReserveButton->setCheckable(0); QPixmap ReservedIcon(":/recources/img/BookedTicketsIconFocus.png"); ui->ReserveButton->setIcon(ReservedIcon); ui->LogOutButton->setCheckable(1); QPixmap LogOutIcon(":/recources/img/ExitIcon.png"); ui->LogOutButton->setIcon(LogOutIcon); ui->stackedWidget->setCurrentWidget(reserveScreen); } void PurchasesMenu::on_LogOutButton_clicked() { ui->stackedWidget->setCurrentIndex(0); ui->BuyButton->setCheckable(1); QPixmap BuyIcon(":/recources/img/TrainIcon.png"); ui->BuyButton->setIcon(BuyIcon); ui->ReserveButton->setCheckable(1); QPixmap ReservedIcon(":/recources/img/BookedTicketsIcon.png"); ui->ReserveButton->setIcon(ReservedIcon); ui->LogOutButton->setCheckable(0); QPixmap LogOutIcon(":/recources/img/ExitIconFocus.png"); ui->LogOutButton->setIcon(LogOutIcon); } void PurchasesMenu::on_exitButton_clicked() { emit _closeApp(); } void PurchasesMenu::on_logOutButton_clicked() { emit _logOut(); } <file_sep>#include "mainwindow.h" #include <QApplication> //unsigned long long totalMem = 0; //void* operator new(size_t size) //{ // totalMem += size; // qDebug() << totalMem; // void* p = malloc(size); // return p; //} //void operator delete(void* p, size_t size) //{ // totalMem -= size; // qDebug() <<"delete: "<< totalMem; // free(p); //} int main(int argc, char* argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } <file_sep>#include "buytickets.h" #include "ui_buytickets.h" #include <UiHelperBuyTickets.cpp> #define selectBuy "0" #define selectReserve "1" BuyTickets::BuyTickets(BackEnd* bckEnd, QWidget* parent) : QWidget(parent), ui(new Ui::BuyTickets) { ui->setupUi(this); this->bckEnd = bckEnd; connect(bckEnd, SIGNAL(_cList(QStringList)), this, SLOT(aComplete(QStringList))); connect(bckEnd, SIGNAL(_trainsList(QVariantList)), this, SLOT(showTrainsList(QVariantList))); connect(bckEnd, SIGNAL(_availableSeats(QString, QStringList)), this, SLOT(showAvailableSeats(QString, QStringList))); connect(bckEnd, SIGNAL(_ticketPurchaseSuccess()), this, SLOT(ticketPurchaseDone())); connect(this, SIGNAL(_dataToSend(QByteArray)), bckEnd, SLOT(sendData(QByteArray))); connect(bckEnd, SIGNAL(_ticketAlreadyTaken()), this, SLOT(ticketAlreadyTaken())); ui->DateEdit->setMinimumDateTime(QDateTime::currentDateTime()); trainModel = nullptr; depCompleter = nullptr; destCompleter = nullptr; seatsList = nullptr; wagonsList = nullptr; cityList = nullptr; takenSeatslist = nullptr; setShadowEff(); ui->TrainsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->TrainsTable->setSelectionBehavior(QAbstractItemView::SelectRows); ui->TrainsTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->stackedWidget->setCurrentIndex(0); ui->TrainsTable->hide(); this->currentWagon = 1; } BuyTickets::~BuyTickets() { delete ui; delete trainModel; delete depCompleter; delete destCompleter; delete cityList; delete takenSeatslist; } void BuyTickets::on_SearchButton_clicked() { ui->SearchButton->setCheckable(0); depTxt = ui->DepartureLineEdit->text(); destTxt = ui->DestinationLineEdit->text(); if (!cityList->contains(depTxt, Qt::CaseInsensitive)) { bckEnd->showErrorMsg(ui->DepartureLineEdit, ("There is no \"" + depTxt + "\" city in the system")); } else if (!cityList->contains(destTxt, Qt::CaseInsensitive)) { bckEnd->showErrorMsg(ui->DestinationLineEdit, ("There is no \"" + destTxt + "\" city in the system")); } else { this->dateTxt = QString::number(ui->DateEdit->date().year()) + "-" + QString::number(ui->DateEdit->date().month()) + "-" + QString::number(ui->DateEdit->date().day()); this->timeTxt = ui->TimeEdit->time().toString(); if (ui->DateEdit->date() == QDate::currentDate() && ui->TimeEdit->time() < QTime::currentTime()) { bckEnd->showErrorMsg(ui->TimeEdit, "This time already passed"); } else { QString txtToSend = QString("{\"operation\":\"getTrainsList\", \"dep\":\"%1\", \"dest\":\"%2\", \"arrDate\":\"%3\", \"arrTime\":\"%4\"}") .arg(this->depTxt) .arg(this->destTxt) .arg(this->dateTxt) .arg(this->timeTxt); emit _dataToSend(txtToSend.toUtf8()); } } } void BuyTickets::on_ReverseDepDest_clicked() { QString depTmp = ui->DepartureLineEdit->text(); ui->DepartureLineEdit->setText(ui->DestinationLineEdit->text()); ui->DestinationLineEdit->setText(depTmp); } void BuyTickets::aComplete(QStringList cList) { delete depCompleter; delete destCompleter; delete cityList; cityList = new QStringList(cList); depCompleter = new QCompleter(cList, this); destCompleter = new QCompleter(cList, this); depCompleter->setCaseSensitivity(Qt::CaseInsensitive); destCompleter->setCaseSensitivity(Qt::CaseInsensitive); ui->DepartureLineEdit->setCompleter(depCompleter); ui->DestinationLineEdit->setCompleter(destCompleter); QAbstractItemView* popupDep = depCompleter->popup(); setCompleterStyle(popupDep); QAbstractItemView* popupDest = destCompleter->popup(); setCompleterStyle(popupDest); } void BuyTickets::showTrainsList(QVariantList trainsList) { ui->SearchButton->setCheckable(1); if (trainsList.length() == 0) { ui->TrainsTable->hide(); bckEnd->showErrorMsg(ui->SearchButton, "Sorry but we can't find any trains from " + this->depTxt + " to " + this->destTxt); return; } delete trainModel; unsigned short columnCount = 4; trainModel = new QStandardItemModel(trainsList.length(), columnCount, this); int row = 0; for (auto& _train : trainsList) { QJsonObject train = _train.toJsonObject(); QModelIndex modelIndex; modelIndex = trainModel->index(row, 0); trainModel->setData(modelIndex, train.value("trainId").toString(), Qt::DisplayRole); modelIndex = trainModel->index(row, 1); QString depDateInfo = train.value("depArriveTime").toString() + " " + train.value("depArriveDate").toString() + " - " + train.value("dapDepTime").toString() + " " + train.value("dapDepDate").toString(); trainModel->setData(modelIndex, depDateInfo, Qt::DisplayRole); modelIndex = trainModel->index(row, 2); QString destArriveTime = train.value("destArriveTime").toString() + " " + train.value("destArriveDate").toString(); trainModel->setData(modelIndex, destArriveTime, Qt::DisplayRole); modelIndex = trainModel->index(row, 3); trainModel->setData(modelIndex, train.value("freeSeats").toString(), Qt::DisplayRole); ++row; } trainModel->setHeaderData(0, Qt::Horizontal, "Train number"); trainModel->setHeaderData(1, Qt::Horizontal, "Departure info"); trainModel->setHeaderData(2, Qt::Horizontal, "Destination arrival time"); trainModel->setHeaderData(3, Qt::Horizontal, "Tickets available"); ui->TrainsTable->setModel(trainModel); ui->TrainsTable->show(); } void BuyTickets::on_TrainsTable_pressed(const QModelIndex& index) { this->currentWagon = 1; QModelIndex tNameIndex = trainModel->index(index.row(), 0); this->trainId = trainModel->data(tNameIndex).toString(); QString txtToSend = QString("{\"operation\":\"getAvailableSeats\", \"trainDate\":\"%1\", \"trainId\":\"%2\", \"dep\":\"%3\", \"dest\":\"%4\"}") .arg(dateTxt) .arg(trainId) .arg(depTxt) .arg(destTxt); emit _dataToSend(txtToSend.toUtf8()); } void BuyTickets::on_goToTrainSelect_clicked() { QString txtToSend = QString("{\"operation\":\"getTrainsList\", \"dep\":\"%1\", \"dest\":\"%2\", \"arrDate\":\"%3\", \"arrTime\":\"%4\"}") .arg(this->depTxt) .arg(this->destTxt) .arg(this->dateTxt) .arg(this->timeTxt); emit _dataToSend(txtToSend.toUtf8()); ui->stackedWidget->setCurrentIndex(0); deleteSeatsAndWagons(); } void BuyTickets::showAvailableSeats(QString wagonCount, QStringList takenSeats) { delete takenSeatslist; takenSeatslist = new QStringList(takenSeats); seatsList = new QVector<customButton*>; wagonsList = new QVector<customButton*>; for (int row = 0; row < ceil(((double)wagonCount.toInt() / 3)); ++row) { for (int col = 1; col <= 3 && (row * 3 + col) <= wagonCount.toInt(); ++col) { customButton* wagon = new customButton(ui->stackedWidget->currentWidget()); int freeSpaces = countFreeSpaces(QString::number(row * 3 + col)); wagon->setMinimumSize(50, 50); wagon->setText(" w:" + QString::number(row * 3 + col) + " free:" + QString::number(freeSpaces)); wagon->number = row * 3 + col; wagon->show(); wagon->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); connect(wagon, SIGNAL(cB_clicked(int)), this, SLOT(changeWagon(int))); QIcon selectedSeatIcon; selectedSeatIcon.addPixmap(QPixmap(":/recources/img/wagonIcon.png"), QIcon::Normal); selectedSeatIcon.addPixmap(QPixmap(":/recources/img/wagonIcon.png"), QIcon::Disabled); wagon->setIcon(selectedSeatIcon); wagon->setIconSize(QSize(150, 30)); ui->wagonLayout->addWidget(wagon, row, col); wagonsList->push_back(wagon); } } ui->wagonLayout->setVerticalSpacing(20); ui->wagonLayout->setHorizontalSpacing(20); for (int i = 0; i < 56; ++i) { customButton* seat = new customButton(ui->stackedWidget->currentWidget()); seat->setMinimumSize(30, 30); seat->setText(QString::number(i + 1)); seat->number = i; seat->show(); seat->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); connect(seat, SIGNAL(cB_clicked(int)), this, SLOT(showTicketPurchaseMenu(int))); ui->seatsLayout->addWidget(seat, i % 4, i / 4); seatsList->push_back(seat); } ui->seatsLayout->setVerticalSpacing(20); ui->seatsLayout->setHorizontalSpacing(20); changeWagon(this->currentWagon); ui->stackedWidget->setCurrentIndex(1); } void BuyTickets::changeWagon(int wagonNumber) { this->currentWagon = wagonNumber; ui->ownerFnameLineEdit->hide(); ui->ownerLnameLineEdit->hide(); ui->buyTicketButton->setVisible((0)); ui->reserveTicketButton->hide(); ui->seatNumberLabel->hide(); for (auto& wagon : *wagonsList) { wagon->setStyleSheet("QPushButton:hover:!pressed{background-color: #b2b2b2;color:black;} QPushButton{background-color: #d9d9d9; color: black} "); wagon->setEnabled(1); } (*wagonsList)[wagonNumber - 1]->setStyleSheet("QPushButton{background-color:#79a1b6;}"); (*wagonsList)[wagonNumber - 1]->setEnabled(0); showSeatsForWagon(wagonNumber); } void BuyTickets::showTicketPurchaseMenu(int seatNumber) { this->currentSeat = seatNumber; ui->ownerFnameLineEdit->show(); ui->ownerLnameLineEdit->show(); ui->buyTicketButton->show(); ui->reserveTicketButton->show(); ui->seatNumberLabel->show(); ui->seatNumberLabel->setText("Seat number: " + QString::number(seatNumber + 1) + "\nprice 250 uah"); // to clear previos selected seat showSeatsForWagon(currentWagon); QIcon selectedSeatIcon; selectedSeatIcon.addPixmap(QPixmap(":/recources/img/selectedSeat.png"), QIcon::Normal); selectedSeatIcon.addPixmap(QPixmap(":/recources/img/selectedSeat.png"), QIcon::Disabled); seatsList->at(seatNumber)->setIcon(selectedSeatIcon); seatsList->at(seatNumber)->setIconSize(QSize(25, 25)); seatsList->at(seatNumber)->setStyleSheet("background-color: #F7F9F9; color: #1b2327;"); } void BuyTickets::deleteSeatsAndWagons() { for (auto wagon : *wagonsList) { ui->seatsLayout->removeWidget(wagon); delete wagon; } for (auto seat : *seatsList) { ui->seatsLayout->removeWidget(seat); delete seat; } delete seatsList; delete wagonsList; } void BuyTickets::showSeatsForWagon(int wagonNumber) { for (auto& freeSeat : *seatsList) { QIcon freeSeatIcon; freeSeatIcon.addPixmap(QPixmap(":/recources/img/freeSeat.png"), QIcon::Normal); freeSeatIcon.addPixmap(QPixmap(":/recources/img/freeSeat.png"), QIcon::Disabled); freeSeat->setIcon(freeSeatIcon); freeSeat->setIconSize(QSize(25, 25)); freeSeat->setEnabled(1); freeSeat->setStyleSheet("background-color: green;"); } for (int i = 0; i < takenSeatslist->length() / 2; ++i) { if ((*takenSeatslist)[i * 2].toInt() == wagonNumber) { QIcon takenSeatIcon; customButton* takenSeat = (*seatsList)[(*takenSeatslist)[i * 2 + 1].toInt() - 1]; takenSeatIcon.addPixmap(QPixmap(":/recources/img/takenSeat.png"), QIcon::Normal); takenSeatIcon.addPixmap(QPixmap(":/recources/img/takenSeat.png"), QIcon::Disabled); takenSeat->setIcon(takenSeatIcon); takenSeat->setIconSize(QSize(25, 25)); takenSeat->setEnabled(0); takenSeat->setStyleSheet("background-color: red;"); } } } int BuyTickets::countFreeSpaces(QString wagonNumber) { int freeSpaces = 56; for (int i = 0; i < takenSeatslist->length(); i += 2) { if ((*takenSeatslist)[i] == wagonNumber) { --freeSpaces; } } return freeSpaces; } void BuyTickets::buyOrReserveTicket(QString buyOrReserve) { QString fName = ui->ownerFnameLineEdit->text(); QString lName = ui->ownerLnameLineEdit->text(); QRegularExpression rgx("[\\p{Cyrillic}[a-zA-z]{1,50}"); if (fName.length() == 0) { bckEnd->showErrorMsg(ui->ownerFnameLineEdit, "First name can't be empty"); return; } if (lName.length() == 0) { bckEnd->showErrorMsg(ui->ownerLnameLineEdit, "Last name can't be empty"); return; } if (rgx.match(fName).capturedLength() != fName.length()) { bckEnd->showErrorMsg(ui->ownerFnameLineEdit, "first name can only contain latin and cyrylic characters"); return; } if (rgx.match(lName).capturedLength() != lName.length()) { bckEnd->showErrorMsg(ui->ownerLnameLineEdit, "last name can only contain latin and cyrylic characters"); return; } QString txtToSend = QString("{\"operation\":\"buyTicket\", \"trainDate\":\"%1\", \"trainId\":\"%2\", \"wagonNumber\":\"%3\", " "\"placeNumber\":\"%4\", \"dep\":\"%5\", \"dest\":\"%6\", \"buyOrReserve\":\"%7\", \"ownerInfo\":\"%8\", " "\"fName\":\"%9\", " "\"lName\":\"%10\"}") .arg(this->dateTxt) .arg(this->trainId) .arg(this->currentWagon) .arg(this->currentSeat + 1) .arg(this->depTxt) .arg(this->destTxt) .arg(buyOrReserve) .arg(bckEnd->getCurUserame()) .arg(fName) .arg(lName); emit _dataToSend(txtToSend.toUtf8()); } void BuyTickets::on_buyTicketButton_clicked() { buyOrReserveTicket(selectBuy); } void BuyTickets::on_reserveTicketButton_clicked() { buyOrReserveTicket(selectReserve); } void BuyTickets::ticketPurchaseDone() { deleteSeatsAndWagons(); QString txtToSend = QString("{\"operation\":\"getAvailableSeats\", \"trainDate\":\"%1\", \"trainId\":\"%2\", \"dep\":\"%3\", \"dest\":\"%4\"}") .arg(dateTxt) .arg(trainId) .arg(depTxt) .arg(destTxt); emit _dataToSend(txtToSend.toUtf8()); bckEnd->showErrorMsg(ui->ownerFnameLineEdit, "Operation done succesfully"); } void BuyTickets::ticketAlreadyTaken() { deleteSeatsAndWagons(); QString txtToSend = QString("{\"operation\":\"getAvailableSeats\", \"trainDate\":\"%1\", \"trainId\":\"%2\", \"dep\":\"%3\", \"dest\":\"%4\"}") .arg(dateTxt) .arg(trainId) .arg(depTxt) .arg(destTxt); emit _dataToSend(txtToSend.toUtf8()); bckEnd->showErrorMsg(ui->ownerFnameLineEdit, "<p>Sorry this seat is already taken.<p>" "<p>Here is updatet information.<p>"); } <file_sep>#include "customButton.h" customButton::customButton(QWidget* parent) : QPushButton(parent) { connect(this, SIGNAL(clicked()), this, SLOT(slotForClick())); } void customButton::slotForClick() { emit this->cB_clicked(number); } <file_sep>#ifndef PURCHASESMENU_H #define PURCHASESMENU_H #include <QWidget> #include <buytickets.h> #include <reserveticketsmenu.h> #include <backend.h> namespace Ui { class PurchasesMenu; } class PurchasesMenu : public QWidget { Q_OBJECT public: explicit PurchasesMenu(BackEnd* bckEnd, QWidget* parent = nullptr); ~PurchasesMenu(); bool eventFilter(QObject* watched, QEvent* event); // for handling on button click event private: Ui::PurchasesMenu* ui; BuyTickets* BuyScreen; reserveTicketsMenu* reserveScreen; BackEnd* bckEnd; void setShadowEff(); void setIcons(); // set icons on start of ui void setEnterIcon(QObject* watched); // set new icon when mouse enter button void setLeaveIcon(QObject* watched); // set new icon when mouse leave button void showTicketsForCurrentUser(); private slots: void on_BuyButton_clicked(); void on_ReserveButton_clicked(); void on_LogOutButton_clicked(); void on_exitButton_clicked(); void on_logOutButton_clicked(); signals: void _dataToSend(QByteArray dataToSend); void _closeApp(); void _logOut(); }; #endif // PURCHASESMENU_H <file_sep>#ifndef LOADINGSCREEN_H #define LOADINGSCREEN_H // secondary libraries #include <QDialog> #include <QLabel> // for showing gifs #include <QMovie> namespace Ui { class LoadingScreen; } class LoadingScreen : public QDialog { Q_OBJECT public: explicit LoadingScreen(QWidget* parent = nullptr); ~LoadingScreen(); QMovie* movie; private: Ui::LoadingScreen* ui; }; #endif // LOADINGSCREEN_H <file_sep>#include "reserveticketsmenu.h" #include "ui_reserveticketsmenu.h" reserveTicketsMenu::reserveTicketsMenu(BackEnd* bckEnd, QWidget* parent) : QWidget(parent), ui(new Ui::reserveTicketsMenu) { ui->setupUi(this); this->bckEnd = bckEnd; connect(bckEnd, SIGNAL(_userTickets(QVariantList, QVariantList, QVariantList)), this, SLOT(showUserTickets(QVariantList, QVariantList, QVariantList))); connect(this, SIGNAL(_dataToSend(QByteArray)), bckEnd, SLOT(sendData(QByteArray))); connect(bckEnd, SIGNAL(_reservedTicketBought()), this, SLOT(reservedTicketBought())); connect(bckEnd, SIGNAL(_returnTicket()), this, SLOT(returnTicket())); ui->unActiveTicketsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->unActiveTicketsTable->setSelectionBehavior(QAbstractItemView::SelectRows); ui->unActiveTicketsTable->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); this->boughtTicketsModel = nullptr; this->reservedTicketsModel = nullptr; this->unActiveTicketsModel = nullptr; ui->boughtTicketsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->boughtTicketsTable->setSelectionBehavior(QAbstractItemView::SelectRows); ui->boughtTicketsTable->setSelectionMode(QAbstractItemView::SingleSelection); ui->boughtTicketsTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->reservedTicketsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->reservedTicketsTable->setSelectionBehavior(QAbstractItemView::SelectRows); ui->reservedTicketsTable->setSelectionMode(QAbstractItemView::SingleSelection); ui->reservedTicketsTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->unActiveTicketsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->unActiveTicketsTable->setSelectionBehavior(QAbstractItemView::SelectRows); ui->unActiveTicketsTable->setSelectionMode(QAbstractItemView::SingleSelection); ui->unActiveTicketsTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->tabWidget->setCurrentIndex(0); ui->buyButton->hide(); ui->returnButton->hide(); ui->ownerFname->hide(); ui->ownerLname->hide(); } reserveTicketsMenu::~reserveTicketsMenu() { delete ui; } void reserveTicketsMenu::showBoughtTickets(QVariantList boughtTicketsList) { delete boughtTicketsModel; if (boughtTicketsList.length() == 0) { boughtTicketsModel = new QStandardItemModel(1, 1, this); QModelIndex modelIndex; modelIndex = boughtTicketsModel->index(0, 0); boughtTicketsModel->setData(modelIndex, "You dont have any bought tickets that are active", Qt::DisplayRole); ui->boughtTicketsTable->setModel(boughtTicketsModel); boughtTicketsModel->setHeaderData(0, Qt::Horizontal, "Information"); ui->boughtTicketsTable->setSelectionMode(QAbstractItemView::NoSelection); return; } ui->boughtTicketsTable->setSelectionMode(QAbstractItemView::SingleSelection); QModelIndex modelIndex; QStringList jsonFields = { "trainId", "trainDate", "dep", "dest", "wagonNumber", "placeNumber", "ownerFname", "ownerLname", "purchaseDate", "purchaseTime" }; boughtTicketsModel = new QStandardItemModel(boughtTicketsList.length(), jsonFields.length(), this); int row = 0; int col = 0; for (auto& _ticket : boughtTicketsList) { col = 0; QJsonObject ticket = _ticket.toJsonObject(); for (QString& field : jsonFields) { modelIndex = boughtTicketsModel->index(row, col); boughtTicketsModel->setData(modelIndex, ticket.value(field).toString(), Qt::DisplayRole); ++col; } ui->boughtTicketsTable->setModel(boughtTicketsModel); ++row; } QStringList headerNames = { "Train id", "Departure date", "Departure", "Destination", "Wagon number", "Place number", "Owner name", "Owner last name", "Purchase date", "Purchase time" }; for (int i = 0; i < headerNames.length(); ++i) { boughtTicketsModel->setHeaderData(i, Qt::Horizontal, headerNames[i]); } } void reserveTicketsMenu::showReservedTickets(QVariantList reservedTicketsList) { delete reservedTicketsModel; if (reservedTicketsList.length() == 0) { reservedTicketsModel = new QStandardItemModel(1, 1, this); QModelIndex modelIndex; modelIndex = reservedTicketsModel->index(0, 0); reservedTicketsModel->setData(modelIndex, "You dont have any reserved tickets that are active", Qt::DisplayRole); ui->reservedTicketsTable->setModel(reservedTicketsModel); reservedTicketsModel->setHeaderData(0, Qt::Horizontal, "Information"); disconnect(ui->reservedTicketsTable, SIGNAL(clicked(QModelIndex)), this, SLOT(reservedTicketTableClicked(QModelIndex))); ui->reservedTicketsTable->setSelectionMode(QAbstractItemView::NoSelection); return; } connect(ui->reservedTicketsTable, SIGNAL(clicked(QModelIndex)), this, SLOT(reservedTicketTableClicked(QModelIndex))); ui->reservedTicketsTable->setSelectionMode(QAbstractItemView::SingleSelection); QStringList jsonFields = { "trainId", "trainDate", "dep", "dest", "wagonNumber", "placeNumber", "ownerFname", "ownerLname", "purchaseDate", "purchaseTime" }; reservedTicketsModel = new QStandardItemModel(reservedTicketsList.length(), jsonFields.length(), this); QModelIndex modelIndex; int row = 0; int col = 0; for (auto& _ticket : reservedTicketsList) { col = 0; QJsonObject ticket = _ticket.toJsonObject(); for (QString& field : jsonFields) { modelIndex = reservedTicketsModel->index(row, col); reservedTicketsModel->setData(modelIndex, ticket.value(field).toString(), Qt::DisplayRole); ++col; } ui->reservedTicketsTable->setModel(reservedTicketsModel); ++row; } QStringList headerNames = { "Train id", "Departure date", "Departure", "Destination", "Wagon number", "Place number", "Owner name", "Owner last name", "Reservation date", "Reservation time" }; for (int i = 0; i < headerNames.length(); ++i) { reservedTicketsModel->setHeaderData(i, Qt::Horizontal, headerNames[i]); } } void reserveTicketsMenu::showUnActiveTickets(QVariantList unActiveTicketsList) { delete unActiveTicketsModel; if (unActiveTicketsList.length() == 0) { unActiveTicketsModel = new QStandardItemModel(1, 1, this); QModelIndex modelIndex; modelIndex = unActiveTicketsModel->index(0, 0); unActiveTicketsModel->setData(modelIndex, "You dont have any unactive tickets", Qt::DisplayRole); ui->unActiveTicketsTable->setModel(unActiveTicketsModel); unActiveTicketsModel->setHeaderData(0, Qt::Horizontal, "Information"); ui->unActiveTicketsTable->setSelectionMode(QAbstractItemView::NoSelection); return; } ui->unActiveTicketsTable->setSelectionMode(QAbstractItemView::SingleSelection); QStringList jsonFields = { "trainId", "trainDate", "dep", "dest", "wagonNumber", "placeNumber", "ownerFname", "ownerLname", "purchaseDate", "purchaseTime", "buyOrRes" }; unActiveTicketsModel = new QStandardItemModel(unActiveTicketsList.length(), jsonFields.length(), this); QModelIndex modelIndex; int row = 0; int col = 0; for (auto& _ticket : unActiveTicketsList) { col = 0; QJsonObject ticket = _ticket.toJsonObject(); for (QString& field : jsonFields) { if (field == "buyOrRes") { if (ticket.value(field).toString() == "0") { modelIndex = unActiveTicketsModel->index(row, col); unActiveTicketsModel->setData(modelIndex, "Bought", Qt::DisplayRole); } else { modelIndex = unActiveTicketsModel->index(row, col); unActiveTicketsModel->setData(modelIndex, "Reserved", Qt::DisplayRole); } } else { modelIndex = unActiveTicketsModel->index(row, col); unActiveTicketsModel->setData(modelIndex, ticket.value(field).toString(), Qt::DisplayRole); } ++col; } ui->unActiveTicketsTable->setModel(unActiveTicketsModel); ++row; } QStringList headerNames = { "Train id", "Departure date", "Departure", "Destination", "Wagon number", "Place number", "Owner name", "Owner last name", "Reservation date", "Reservation time", "Status" }; for (int i = 0; i < headerNames.length(); ++i) { unActiveTicketsModel->setHeaderData(i, Qt::Horizontal, headerNames[i]); } } void reserveTicketsMenu::showUserTickets(QVariantList unActiveTickets, QVariantList boughtTickets, QVariantList reservedTickets) { showBoughtTickets(boughtTickets); showReservedTickets(reservedTickets); showUnActiveTickets(unActiveTickets); } void reserveTicketsMenu::reservedTicketTableClicked(const QModelIndex& index) { reservedTicketIndex = index; ui->buyButton->show(); ui->returnButton->show(); ui->ownerFname->show(); ui->ownerLname->show(); reservedTicketIndex = reservedTicketsModel->index(reservedTicketIndex.row(), 6); ui->ownerFname->setText(reservedTicketsModel->data(reservedTicketIndex).toString()); reservedTicketIndex = reservedTicketsModel->index(reservedTicketIndex.row(), 7); ui->ownerLname->setText(reservedTicketsModel->data(reservedTicketIndex).toString()); } void reserveTicketsMenu::on_tabWidget_currentChanged(int index) { ui->boughtTicketsTable->clearSelection(); ui->buyButton->hide(); ui->returnButton->hide(); ui->ownerFname->hide(); ui->ownerLname->hide(); } void reserveTicketsMenu::on_buyButton_clicked() { ui->reservedTicketsTable->selectRow(reservedTicketIndex.row()); QString fName = ui->ownerFname->text(); QString lName = ui->ownerLname->text(); QRegularExpression rgx("[\\p{Cyrillic}[a-zA-z]{1,50}"); if (fName.length() == 0) { bckEnd->showErrorMsg(ui->ownerFname, "First name can't be empty"); return; } if (lName.length() == 0) { bckEnd->showErrorMsg(ui->ownerLname, "Last name can't be empty"); return; } if (rgx.match(fName).capturedLength() != fName.length()) { bckEnd->showErrorMsg(ui->ownerFname, "first name can only contain latin and cyrylic characters"); return; } if (rgx.match(lName).capturedLength() != lName.length()) { bckEnd->showErrorMsg(ui->ownerFname, "last name can only contain latin and cyrylic characters"); return; } int row = reservedTicketIndex.row(); QString ticketInfo = "{\"operation\":\"buyReservedTicket\", \"trainId\":\"%1\", \"trainDate\":\"%2\", \"dep\":\"%3\", \"dest\":\"%4\", " "\"wagonNumber\":\"%5\", " "\"placeNumber\":\"%6\", \"fName\":\"%7\", \"lName\":\"%8\"}"; for (int column = 0; column < 8; ++column) { reservedTicketIndex = reservedTicketsModel->index(row, column); QString modelData = reservedTicketsModel->data(reservedTicketIndex).toString(); ticketInfo.replace("%" + QString::number(column + 1), modelData); } emit _dataToSend(ticketInfo.toUtf8()); } void reserveTicketsMenu::on_returnButton_clicked() { ui->reservedTicketsTable->selectRow(reservedTicketIndex.row()); int row = reservedTicketIndex.row(); QString ticketInfo = "{\"operation\":\"returnTicket\", \"trainId\":\"%1\", \"trainDate\":\"%2\", \"dep\":\"%3\", \"dest\":\"%4\", " "\"wagonNumber\":\"%5\", " "\"placeNumber\":\"%6\"}"; for (int column = 0; column < 6; ++column) { reservedTicketIndex = reservedTicketsModel->index(row, column); QString modelData = reservedTicketsModel->data(reservedTicketIndex).toString(); ticketInfo.replace("%" + QString::number(column + 1), modelData); } emit _dataToSend(ticketInfo.toUtf8()); } void reserveTicketsMenu::reservedTicketBought() { QString txtToSend = QString("{\"operation\":\"getUserTickets\", \"userName\":\"%1\"}").arg(bckEnd->getCurUserame()); emit _dataToSend(txtToSend.toUtf8()); bckEnd->showErrorMsg(ui->ownerLname, "Reserved ticket bought successfully"); ui->buyButton->hide(); ui->returnButton->hide(); ui->ownerFname->hide(); ui->ownerLname->hide(); } void reserveTicketsMenu::returnTicket() { QString txtToSend = QString("{\"operation\":\"getUserTickets\", \"userName\":\"%1\"}").arg(bckEnd->getCurUserame()); emit _dataToSend(txtToSend.toUtf8()); bckEnd->showErrorMsg(ui->ownerLname, "Ticket returned successfully"); ui->buyButton->hide(); ui->returnButton->hide(); ui->ownerFname->hide(); ui->ownerLname->hide(); } <file_sep>#include "purchasesmenu.h" #include "ui_purchasesmenu.h" #include <QPixmap> #include <QGraphicsDropShadowEffect> void PurchasesMenu::setShadowEff() { QGraphicsDropShadowEffect* logOut = new QGraphicsDropShadowEffect; logOut->setBlurRadius(20); logOut->setXOffset(0); logOut->setYOffset(0); logOut->setColor(Qt::black); ui->logOutButton->setGraphicsEffect(logOut); QGraphicsDropShadowEffect* exitEffect = new QGraphicsDropShadowEffect; exitEffect->setBlurRadius(20); exitEffect->setXOffset(0); exitEffect->setYOffset(0); exitEffect->setColor(Qt::black); ui->exitButton->setGraphicsEffect(exitEffect); } // set icons on start of ui void PurchasesMenu::setIcons() { QPixmap BuyIcon(":/recources/img/TrainIcon.png"); ui->BuyButton->setIcon(BuyIcon); ui->BuyButton->setIconSize(QSize(65, 55)); QPixmap ReservedIcon(":/recources/img/BookedTicketsIcon.png"); ui->ReserveButton->setIcon(ReservedIcon); ui->ReserveButton->setIconSize(QSize(65, 55)); QPixmap LogOutIcon(":/recources/img/ExitIcon.png"); ui->LogOutButton->setIcon(LogOutIcon); ui->LogOutButton->setIconSize(QSize(65, 55)); ui->BuyButton->installEventFilter(this); ui->ReserveButton->installEventFilter(this); ui->LogOutButton->installEventFilter(this); } // set icon on mouse enter button event void PurchasesMenu::setEnterIcon(QObject* watched) { QPushButton* button = qobject_cast<QPushButton*>(watched); if (button->objectName() == "BuyButton") { if (!ui->BuyButton->isCheckable()) { return; } QPixmap BuyIcon(":/recources/img/TrainIconHover.png"); ui->BuyButton->setIcon(BuyIcon); } else if (button->objectName() == "ReserveButton") { if (!ui->ReserveButton->isCheckable()) { return; } QPixmap ReservedIcon(":/recources/img/BookedTicketsIconHover.png"); ui->ReserveButton->setIcon(ReservedIcon); } else if (button->objectName() == "LogOutButton") { if (!ui->LogOutButton->isCheckable()) { return; } QPixmap LogOutIcon(":/recources/img/ExitIconHover.png"); ui->LogOutButton->setIcon(LogOutIcon); } return; } // set icon on mouse leave button event void PurchasesMenu::setLeaveIcon(QObject* watched) { QPushButton* button = qobject_cast<QPushButton*>(watched); if (button->objectName() == "BuyButton") { if (!ui->BuyButton->isCheckable()) { return; } QPixmap BuyIcon(":/recources/img/TrainIcon.png"); ui->BuyButton->setIcon(BuyIcon); } else if (button->objectName() == "ReserveButton") { if (!ui->ReserveButton->isCheckable()) { return; } QPixmap ReservedIcon(":/recources/img/BookedTicketsIcon.png"); ui->ReserveButton->setIcon(ReservedIcon); } else if (button->objectName() == "LogOutButton") { if (!ui->LogOutButton->isCheckable()) { return; } QPixmap LogOutIcon(":/recources/img/ExitIcon.png"); ui->LogOutButton->setIcon(LogOutIcon); } return; } <file_sep>#include "backend.h" BackEnd::BackEnd(QObject* parent) : QObject(parent) { errJsn = new QJsonParseError(); obj = new QJsonObject(); jsnDoc = new QJsonDocument(); socket = nullptr; } BackEnd::~BackEnd() { delete socket; delete obj; delete errJsn; delete jsnDoc; } void BackEnd::setCurUsername(QString userName) { this->curUsername = userName; } QString BackEnd::getCurUserame() { return this->curUsername; } void BackEnd::showErrorMsg(QWidget* widget, QString errMsg) { QWhatsThis::showText(widget->mapToGlobal(QPoint(widget->width() / 2, widget->height())), "<html><font style =\"font: 12px;\">" + errMsg + "</font></html>"); } void BackEnd::createSocket() { delete socket; socket = new QTcpSocket(); connect(socket, SIGNAL(readyRead()), this, SLOT(sockReady())); connect(socket, SIGNAL(disconnected()), this, SLOT(sockDisc())); tryToReccon(); } void BackEnd::tryToReccon() { socket->connectToHost("172.16.58.3", 27000); socket->waitForConnected(7000); if (socket->state() != QTcpSocket::ConnectedState) { emit _reconnFailed(); } else { emit _reconnSuccess(); } } void BackEnd::sendData(QByteArray dataToSend) { if (socket->state() == QTcpSocket::ConnectedState) { socket->write(dataToSend); socket->waitForBytesWritten(5000); } else { tryToReccon(); } } // when recieved data from server void BackEnd::sockReady() { if (socket->waitForConnected(1500)) { recievedData += socket->readAll(); } else { // to do: show can not convert err msg box qDebug() << "Can not read data from server: Connestion failed"; return; } QByteArray terminantWord = "DATAEND"; int recDatLength = recievedData.length(); for (int i = 1; i <= terminantWord.length(); ++i) { if (recievedData[recDatLength - i] != terminantWord[terminantWord.length() - i] || (recDatLength - i < 0)) { return; } } recievedData.resize(recievedData.length() - terminantWord.length()); *jsnDoc = QJsonDocument::fromJson(recievedData, errJsn); recievedData.clear(); *obj = jsnDoc->object(); if (errJsn->error == QJsonParseError::NoError) { decAndExec(); return; } else { emit _errSignalMW("Cannot convert data from server"); return; } } void BackEnd::decAndExec() { if (obj->value("operation").toString() == "login") { logProc(); } else if (obj->value("operation").toString() == "register") { regProc(); } else if (obj->value("operation").toString() == "getCities") { cListProc(); } else if (obj->value("operation").toString() == "getTrainsList") { trainsListProc(); } else if (obj->value("operation").toString() == "getAvailableSeats") { getAvailableSeats(); } else if (obj->value("operation").toString() == "buyTicket") { buyTicket(); } else if (obj->value("operation").toString() == "getUserTickets") { getUserTickets(); } else if (obj->value("operation").toString() == "buyReservedTicket") { buyReservedTicket(); } else if (obj->value("operation").toString() == "returnTicket") { returnTicket(); } else { // to do: show bad respond msg emit _errSignalMW(obj->value("err").toString()); } } void BackEnd::sockDisc() { emit _reconnFailed(); } void BackEnd::logProc() { if (obj->value("resp").toString() == "ok") { emit _logSuccess(); } else { emit _errSignalMW(obj->value("err").toString()); } } void BackEnd::regProc() { if (obj->value("resp").toString() == "ok") { emit _regSuccess(); } else { emit _errSignalMW(obj->value("err").toString()); } } void BackEnd::cListProc() { if (obj->value("resp").toString() == "ok") { emit _cList(obj->value("data").toVariant().toStringList()); } else { emit _errSignalMW(obj->value("err").toString()); } } void BackEnd::trainsListProc() { if (obj->value("resp").toString() == "ok") { emit _trainsList(obj->value("data").toVariant().toJsonArray().toVariantList()); } else { emit _errSignalMW(obj->value("err").toString()); } } void BackEnd::getAvailableSeats() { if (obj->value("resp").toString() == "ok") { emit _availableSeats(obj->value("wagons").toString(), obj->value("data").toVariant().toStringList()); } else { emit _errSignalMW(obj->value("err").toString()); } } void BackEnd::buyTicket() { if (obj->value("resp").toString() == "ok") { emit _ticketPurchaseSuccess(); } else if (obj->value("resp").toString() == "alreadyTaken") { emit _ticketAlreadyTaken(); } else { emit _errSignalMW(obj->value("err").toString()); } } void BackEnd::getUserTickets() { if (obj->value("resp").toString() == "ok") { emit _userTickets(obj->value("unActiveTickets").toVariant().toJsonArray().toVariantList(), obj->value("boughtTickets").toVariant().toJsonArray().toVariantList(), obj->value("reservedTickets").toVariant().toJsonArray().toVariantList()); } else { emit _errSignalMW(obj->value("err").toString()); } } void BackEnd::buyReservedTicket() { emit _reservedTicketBought(); } void BackEnd::returnTicket() { emit _returnTicket(); }
e7e855dc6f68c3bfe4a98fddc09897d77ceb9c39
[ "C++" ]
20
C++
hunkob/clientServetTcpIp
f80e65ea9fcc940121b94b9351326cb617b8a31b
4ceed472ca6a90e8e8cbf023999836b59bebd4c6
refs/heads/master
<repo_name>fazo96/lambda-vue-cypress<file_sep>/frontend/frontend.js const apiUrl = 'https://n0z4ae7ktl.execute-api.eu-central-1.amazonaws.com/default/' const app = window.vueApp = new Vue({ el: '#app', data: { width: 0, file: null, result: null, resultSrc: null, imageSrc: null, imageInfo: null }, methods: { resize () { console.log(`resize, width ${this.width}`) const req = new XMLHttpRequest() const url = `${apiUrl}?width=${this.width}&height=` req.responseType = 'blob' req.open('POST', url, true) req.setRequestHeader("Content-type", "image/png") req.onreadystatechange = () => { console.log('state changed', req) } req.onload = e => { console.log('done', e) console.log(req.responseType, typeof req.response) this.result = req.response console.log('result updated to', this.result) const reader = new FileReader() reader.onload = e => { this.resultSrc = e.target.result console.log('resultSrc updated to', this.resultSrc) } reader.readAsDataURL(this.result) } req.send(this.file) }, reset () { this.width = this.imageInfo.width this.result = null this.resultSrc = null }, download () { if (this.result) saveBlob(this.result, 'result.png') }, updateImageInfo (e) { this.imageInfo = { height: e.target.height, width: e.target.width } this.width = this.imageInfo.width }, fileChanged(event) { console.log('file changed', event) this.result = null this.resultSrc = null if (event.target.files && event.target.files.length > 0) { this.setFile(event.target.files[0]) } else { this.setFile(null) } }, setFile(file) { if (file) { this.file = file console.log('file updated to', this.file) const reader = new FileReader() reader.onload = e => { this.imageSrc = e.target.result console.log('imageSrc updated to', this.imageSrc) } reader.readAsDataURL(this.file) } else { console.log('file removed') this.file = null } } } }) function saveBlob (blob, fileName) { var a = document.getElementById('downloader') if (!a) { a = document.createElement("a"); a.setAttribute('id', 'downloader') document.body.appendChild(a); a.style = "display: none"; } var url = window.URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); }<file_sep>/cypress/integration/resize.js describe('Image Resize', () => { it('load homepage', () => { cy.visit('/') }) it('resize a picture', () => { cy.visit('/') .uploadFile('#input-image', 'avatar.jpeg') .get('#image').invoke('width').should('equal', 302) .get('#width') // Check that the default Width is loaded correctly .should('have.value', '302') // Type in desired width .clear() .type('100') .get('#process-image').click() .get('#result').invoke('width').should('equal', 100) }) })<file_sep>/ci.sh #!/usr/bin/env bash # Run server in background npm start & # Run tests npm test<file_sep>/README.md # Lambda Vue Cypress Demo - npm install - npm start - visit http://localhost:8080 ### Automated tests [![Build Status](https://travis-ci.org/fazo96/lambda-vue-cypress.svg?branch=master)](https://travis-ci.org/fazo96/lambda-vue-cypress) - make sure the app is running using `npm start` - run `npm test`
f98f8e6cc3fc4b62dae9f338022830d9ea915ca5
[ "JavaScript", "Markdown", "Shell" ]
4
JavaScript
fazo96/lambda-vue-cypress
8a23e3596c591ffc7a9bd170024bffe4d119e8db
b85f9a507a821e365630f4714a0fe1195ce9ef82
refs/heads/master
<repo_name>Code-Institute-Submissions/django-ecomm-2019<file_sep>/contacts/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-06-29 15:06 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Contact', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('full_name', models.CharField(max_length=50)), ('email', models.EmailField(max_length=254)), ('phone_number', models.IntegerField()), ('details', models.TextField(max_length=400)), ('submission_date', models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True)), ], ), ] <file_sep>/products/test_models.py from django.test import TestCase from .models import Product, Category class TestProductModel(TestCase): def test_product_model(self): category = Category(name="Jeans") category.save() product = Product(name="test item",description="This is a test of the description", price=40.00, category=category) product.save() self.assertEqual(product.name,"test item") self.assertEqual(product.description,"This is a test of the description") self.assertEqual(product.price, 40.00) self.assertEqual(product.category,category) def test_product_name_is_string(self): product = Product(name="Generic name") self.assertEqual("Generic name", str(product)) def test_category_name_is_string(self): category = Category(name="Jeans") self.assertEqual("Jeans", str(category))<file_sep>/cart/views.py from django.shortcuts import render, redirect, reverse from contacts.forms import ContactSubmissionForm from django.contrib import auth, messages # Create your views here. # Create your views here. def view_cart(request): """ This renders the cart contents page """ if request.method =="POST": form = ContactSubmissionForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("index") else: form = ContactSubmissionForm() return render(request, "cart.html", {'form':form}) def add_to_cart(request, id): """Adds a specified quantity to the cart""" quantity = int(request.POST.get('quantity')) cart = request.session.get('cart', {}) if id in cart: cart[id] = int(cart[id]) + quantity else: cart[id] = cart.get(id, quantity) request.session['cart'] = cart return redirect(reverse('view_cart')) def adjust_cart(request, id): """ Adjust the quantity of an item in the cart """ quantity = int(request.POST.get('quantity')) cart = request.session.get('cart', {}) if quantity > 0 : cart[id] = quantity else: cart.pop(id) request.session['cart'] = cart return redirect(reverse('view_cart'))<file_sep>/accounts/test_views.py from django.test import TestCase from .forms import UserRegistrationForm, UserLoginForm from django.contrib.auth.models import User class TestAccountsViews(TestCase): def test_get_login_page(self): login_page = self.client.get("/accounts/login", follow=True) self.assertEqual(login_page.status_code, 200) self.assertTemplateUsed(login_page, "login.html") def test_get_registration_page(self): registration_page = self.client.get("/accounts/register/") self.assertEqual(registration_page.status_code, 200) self.assertTemplateUsed(registration_page, "registration.html") def test_get_user_profile_page(self): user = User.objects.create_user(username="admin", password="<PASSWORD>") self.client.login(username="admin", password="<PASSWORD>") profile_page = self.client.get("/accounts/profile", follow=True) self.assertEqual(profile_page.status_code, 200) self.assertTemplateUsed(profile_page, "profile.html") <file_sep>/products/models.py from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=254, default="", blank=False) def __str__(self): return self.name #Below is the basic model for our product item we will list on the site. class Product(models.Model): name = models.CharField(max_length=254, default="") description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to="img") category = models.ForeignKey(Category, on_delete=models.CASCADE) new_in = models.BooleanField(default=True) def __str__(self): return self.name<file_sep>/checkout/admin.py from django.contrib import admin from .models import Order, OrderLineItem # Register your models here. class OrderLineAdminInLine(admin.TabularInline): model = OrderLineItem class OrderAdmin(admin.ModelAdmin): inlines = (OrderLineAdminInLine, ) list_display = ('full_name', 'contact_number', 'date') search_fields = ('full_name', 'contact_number', 'date') #This allows admin to use a search feature when looking for specific contact submissions admin.site.register(Order, OrderAdmin) <file_sep>/products/tests.py from django.test import TestCase from .models import Product # Create your tests here. class ProductTests(TestCase): """ We define our tests below that will be run against our product models """ def test_str(self): test_name = Product(name="A product") self.assertEqual(str(test_name),"A product")<file_sep>/contacts/urls.py from django.conf.urls import url, include from .views import contact_submission, faq_page, about_page urlpatterns = [ url(r'^contact_submission/$', contact_submission, name="contact_submission"), url(r'^faq_page/$', faq_page, name="faq_page"), url(r'^about_page/$', about_page, name="about_page"), ]<file_sep>/requirements.txt Django==1.11 Pillow==3.4.2 boto3==1.9.142 botocore==1.12.142 certifi==2019.3.9 chardet==3.0.4 coverage==4.5.3 dj-database-url==0.5.0 django-forms-bootstrap==3.1.0 django-storages==1.7.1 docutils==0.14 gunicorn==19.9.0 idna==2.8 jmespath==0.9.4 psycopg2==2.8.2 python-dateutil==2.8.0 pytz==2019.1 requests==2.21.0 s3transfer==0.2.0 stripe==2.27.0 urllib3==1.24.2 whitenoise==4.1.2 <file_sep>/checkout/views.py from django.shortcuts import render, get_object_or_404, reverse, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import OrderForm, MakePaymentForm from .models import OrderLineItem from django.conf import settings from django.utils import timezone from products.models import Product import stripe # Create your views here. stripe.api_key = settings.STRIPE_SECRET @login_required() def checkout(request): delivery_charge = 15 if request.method=="POST": order_form = OrderForm(request.POST) #contains their personal details payment_form = MakePaymentForm(request.POST) #contains payment information if order_form.is_valid() and payment_form.is_valid(): order = order_form.save(commit=False) order.date = timezone.now() order.save() cart = request.session.get('cart', {}) total = 0 sub_total = 0 for id, quantity in cart.items(): product = get_object_or_404(Product, pk=id) total += quantity * product.price sub_total += quantity * product.price order_line_item = OrderLineItem( order = order, product = product, quantity = quantity ) order_line_item.save() #The below code add's a delivery charge of 15 EUR to all orders below or equal to 50 if total <= 50: total = total + delivery_charge else: total = total try: customer = stripe.Charge.create( amount=int(total*100), currency = "EUR", description = request.user.email, card = payment_form.cleaned_data["stripe_id"], ) except stripe.error.CardError: messages.error(request,"Your card was declined.") if customer.paid: messages.error(request, "You have successfully paid") request.session['cart']= {} return redirect('index') else: messages.error(request, "This payment was not successfull") else: print(payment_form.errors) messages.error(request,"We were unable to take a payment from this card.") else: payment_form = MakePaymentForm() order_form = OrderForm() return render(request, "checkout.html", {'order_form':order_form, 'payment_form':payment_form, 'publishable':settings.STRIPE_PUBLISHABLE}) <file_sep>/products/test_views.py from django.test import TestCase from django.shortcuts import get_object_or_404 from .models import Product, Category class TestProductViews(TestCase): def test_all_products_page(self): all_products = self.client.get("/products/all/") self.assertEqual(all_products.status_code, 200) def test_get_page_for_product_that_does_not_exist(self): page = self.client.get("/products/999") self.assertEqual(page.status_code, 404) def test_product_details_page(self): category = Category(name="Jeans") category.save() product = Product(name="test item",description="This is a test of the description", price=40.00, category=category) product.save() product_details = self.client.get("/products/{0}".format(product.id)) self.assertEqual(product_details.status_code, 200) self.assertTemplateUsed(product_details, "product_details.html") <file_sep>/products/admin.py from django.contrib import admin from .models import Product, Category # Register your models here. #This will alow us to add new products through the admin panel class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'category', 'new_in') search_fields = ('name', 'price', 'category', 'new_in')#This allows admin to use a search feature when looking for specific products admin.site.register(Product, ProductAdmin) admin.site.register(Category) <file_sep>/products/urls.py from django.conf.urls import url, include from .views import all_products, product_details, view_category,new_in urlpatterns = [ url(r'^all/$', all_products, name="all_products"), url(r'^(?P<product_id>\d+)$', product_details, name="product_details"), url(r'^(?P<category>[a-zA-Z]+)/$', view_category, name="category"), url(r'^new_in/$', new_in, name="new_in"), ]<file_sep>/accounts/test_forms.py from django.test import TestCase from .forms import UserRegistrationForm, UserLoginForm from django.contrib.auth.models import User # Create your tests here. class TestAccountsForms(TestCase): def test_user_registration_form(self): form = UserRegistrationForm({ "username": "admin", "email":"<EMAIL>", "password1":"<PASSWORD>", "password2":"<PASSWORD>" }) self.assertTrue(form.is_valid()) def test_username_is_unique_for_registration(self): User.objects.create_user( username="admin", email="<EMAIL>") form = UserRegistrationForm({ "username": "admin", "email":"<EMAIL>", "password1":"<PASSWORD>", "password2":"<PASSWORD>" }) self.assertFalse(form.is_valid()) def test_user_login_form(self): form = UserLoginForm({ "username": "admin", "password":"<PASSWORD>" }) self.assertTrue(form.is_valid()) def test_password_is_required_for_login(self): form = UserLoginForm({ "username": "admin", "password":"" }) self.assertFalse(form.is_valid()) self.assertEqual(form.errors["password"], ["This field is required."]) def test_username_is_required_for_login(self): form = UserLoginForm({ "username": "", "password":"<PASSWORD>" }) self.assertFalse(form.is_valid()) self.assertEqual(form.errors["username"], ["This field is required."]) def test_registration_passwords_must_match(self): form = UserRegistrationForm({ "username": "admin", "email":"<EMAIL>", "password1":"<PASSWORD>", "password2":"<PASSWORD>" }) self.assertFalse(form.is_valid()) self.assertEqual(form.errors["password2"], ["Passwords must match"]) def test_registration_email_must_be_unique(self): User.objects.create_user( username="admin", email="<EMAIL>") form = UserRegistrationForm({ "username": "tester", "email": "<EMAIL>", "password1": "<PASSWORD>", "password2": "<PASSWORD>" }) self.assertFalse(form.is_valid()) self.assertEqual(form.errors["email"], ["Email address must be unique"])<file_sep>/README.md # Obaju E-Commerce Store [![Build Status](https://travis-ci.org/ldettorre/django-ecomm-2019.svg?branch=master)](https://travis-ci.org/ldettorre/django-ecomm-2019) ## Fullstack Frameworks with Django Project - Code Institute ###### This project is intended for educational purposes only. Obaju is an fictional e-commerce site built as part of my course work with Code Institute. This site in particular is our Fullstack Frameworks project which gives us the opportunity to utilize everything we have learned on the course from the foundation of HTML, the implementation of a frameworks and databases, and everything in between. To help with styling, I decided to use a template. I chose [Obaju - ecommerce template](https://bootstraptemple.com/p/obaju-e-commerce-template) as it was very comprehensive and fit my needs. To view the live version of this site, click [here!](https://e-comm-2019.herokuapp.com/) ## UX and UI My original intention behind this e-commerce project was to create it in such a fashion where any indiviual needing an e-commerce site could take it as a template and add their own imagery, style and settings as needed. It was also my intention to have this as a base application to build upon over time and have as a product to sell for small businesses. Before beginning the project I imagined the User Interface being light and simple and the User Experience being quite vanilla. The trade off I was aiming for was that by following my initial idea, the site would be easily useable on all smart devices and style of computer as well as extremely reliable by not having a ton of unnecessary flashy features that may not work across different browsers. Ultimately there would be less maintenance across the entire app by having a limited set of technologies being used in conjuction with each other. As the site developed and I passed the 'walking skeleton' stage, I realised that even a template should have some styling or a theme. So to help with giving the project more life I took inspiration from the layout of my favourite clothing sites [Superdry](https://www.superdry.ie/) and [Diesel](https://www.diesel.ie/) and married that with the template from [Obaju - ecommerce template](https://bootstraptemple.com/p/obaju-e-commerce-template). The result ended up being a basic but functional layout that isn't filled with distracting features but has plenty of space to grow into. From the UX perspective it is still missing some information you'd find standard on other e-commerce sites could do with more information presented in the current layout, this is to benefit the user ### Technologies Used For This Project * HTML * CSS * Bootstrap Version 3.3.7 * Javascript and Jquery * Font-Awesome * Google Fonts * Python 3.4.3 * Django 1.11 Framework * Heroku - Deployment * SQLite Database * Stripe * For processing payments. * Balsamiq * For creating wireframes. These can be found in the Wireframes folder. ## Features ### Existing Features ###### Site Specific: * The site is responsive through it's use of Bootstrap. * The site automatically adds a delivery charge of €15 on orders above €50 * The site has the core feature implemented already for sending emails. Currently this is done for the password reset feature. * The site requires that users be logged in before making purchases. ###### As the Site Admin: * You can create products with a name, description, price, image, category and 'new in' field. * You can mark products as "new in" which renders them to the customer collectively regardless of category. * You can view contact forms submitted by the customer which contains their name, phone number, email, and the time/date of their submission. * You can search for contact form submission by name, phone number and email. * You can view current registered user information as well as the date they signed up. * You can search for current registered users by username and email. * You can create categories with ease which will be automatically rendered to the app navbar. * You can view order information of users and search for orders by name, contact number and date. * You can take payments through Stripe. ###### As a customer: * You can browse products by category. * You can submit a contact form asking for further information without needing to be registered. * You can create a profile account. * You have access to a standard 'Forgot My Password' feature. * You can create a shopping cart of items without needing to be registered. * I can see a breakdown of my order on quantity, unit price and any extra delivery charges if applicable. ### Features Left to Implement In the Accounts app, with users being able to easily create an account, log in and log out, I could work on saving a users previous purchase history and contact form submission for their own reference. In the Products app would also like to further develop the category and product models to implement more fields such as gender, size options and added images for an improved UX. In future, I would like to implement a Blog app which would add more value to the user when visiting the site for a browse. The Blog app could benefit from the Accounts app by identifying users and granting them certain permissions with posts such as commenting on all but only editing their own comments to name a few. With regards to the existing emailing functionality, this would be a good base to add in an email confirmation/invoice feature to notify users of further details. In the Checkout app I would like to develop the delivery logic more allowing the user to choose a range of different delivery options and whatever is chosen would be representing on their order model. ## Deployment and Hosting Deployment of this site was done by creating a free Heroku account and creating a new app. Once this was done, I navigated the Heroku app tabs at the top of the page and performed the following: * Deploy > Deployment method > GitHub. * App connected to GitHub > Connected to my chosen project app. * Resources > Addon > Selecting Heroku Postgres FREE TIER. * Settings > Config Vars > Reveal Config Vars > Set up appropriate environment variables based on the prod.py file in the settings folder of the app. The static files are hosted on AWS S3 using a bucket with custom user and permissions. ### Running Locally To get this project running locally, you will need to clone the repository and install the requirements.txt file. Following that, you must ensure all secret keys within the ecommerce.settings.base are set up either in an env.py file or using the .bashrc. For the likes of the Email feature and Stripe payments, you will need to obtain your own keys and place them in the app. Also be sure to have your allowed hosts updated with the address returned in the error message upon first running the app. ## Testing To test this project I did a mixture of manual testing and incorporated Travis C.I. When it came to manually testing, I checked that: * All the links on the site redirected as expected. * The contact form correctly submitted it's information to the admin dashboard. * Users who 'purchased' products had their information submitted to the admin dashboard. * Users could successfully register new accounts and once created they could easily log in and out with ease. * The Admin could create new categories with ease and create new products. These products were filtered and rendered to their template as expected. * The password reset feature correctly emailed the address I registered with and I was able to successfully reset my password. Although this did bring me to the django template it still functioned as expected. For synthetic testing, I used Chrome Dev Tools for responsiveness. I found that the deployed site was responsive across it's entirety. It is worth mentioning that the cart view and order summary do have a horizontal scroll but only on the items and not on the page. This is acceptable given the information being displayed is important but also it doesn't break the site or impact it negatively. For testing with Travis, I created 19 tests across the Accounts and Products app. These tests passed giving me some 90~% coverage for Products App and 76% coverage for Accounts App. You can check out the current build [here](https://travis-ci.org/ldettorre/django-ecomm-2019). The reason for the high build log is due to dealing with a bug in the manage.py file that turned out to be nothing more than a space between the ! and # in line one. ## Remaining Issues At the moment the site has alot of unnecessary CSS and scripts due to it being taken from a template which will need to be cleaned up. Also the confirmation message is only functioning upon successfully paying for your items and not for the contact form submission. Where datetime is used with regards to the models, it is an hour ahead of Irish Time. This is not major at the moment but something to look at for future revisions. For an unknown reason when I set DEBUG to False it still returns error messages. I currently have the config vars set up as expected so this will require more attention as it is a security issue. ### Credits ## Acknowledgements I want to thank [<NAME>](https://github.com/mparkcode) for introducing me to context processors and helping me with creating categories for the Products app. I also want to thank [<NAME>](https://github.com/hschafer2017) for helping me debug my database migration issues and Travis errors. ## Content The second carousel on the landing page are images of a YouTuber named [<NAME>](https://www.youtube.com/user/xMadeInBrazil). I do not own these images. The template used is from [Bootstrap Temple](https://bootstraptemple.com/p/obaju-e-commerce-template) All product images and information was taken from [Superdry](https://www.superdry.ie/). <file_sep>/contacts/admin.py from django.contrib import admin from .models import Contact class ContactAdmin(admin.ModelAdmin): list_display = ('full_name', 'phone_number', 'email', 'details', 'submission_date') search_fields = ('full_name', 'phone_number', 'email') #This allows admin to use a search feature when looking for specific contact submissions admin.site.register(Contact, ContactAdmin) # Register your models here.<file_sep>/products/views.py from django.shortcuts import render, get_object_or_404 from .models import Product, Category # Create your views here. def all_products(request): products = Product.objects.all() # returns all the products in the db. return render(request, "products.html", {"products":products}) def product_details(request, product_id): product = get_object_or_404(Product, id=product_id) return render(request, "product_details.html", {"product": product}) def view_category(request, category): category = get_object_or_404(Category, name=category) products = Product.objects.filter(category = category) #returns products filtered by chosen category. return render(request, "products.html", {"products":products}) def new_in(request): products = Product.objects.filter(new_in=True) # returns all the products in the db that are marked as new items return render(request, "products.html", {"products":products}) <file_sep>/cart/contexts.py from django.shortcuts import get_object_or_404 from products.models import Product #This app focuses on keeping the items in a session and then it removes them upon logging out def cart_contents(request): """ Makes cart contents viewable on every page """ cart = request.session.get('cart', {}) cart_items = [] delivery_charge = 15 total = 0 sub_total = 0 product_count = 0 for id, quantity in cart.items(): product = get_object_or_404(Product, pk=id) total += quantity * product.price sub_total += quantity * product.price product_count += quantity cart_items.append({"id":id, "quantity":quantity,"product":product}) # The below code adds a 'delivery charge' if the total is below the minimum required if total <= 50: total = total + delivery_charge else: total = total return { "cart_items":cart_items, "total":total,"product_count":product_count,"sub_total":sub_total } <file_sep>/contacts/models.py from django.db import models from django.utils import timezone # Create your models here. class Contact(models.Model): full_name = models.CharField(max_length=50) email = models.EmailField(max_length=254) phone_number = models.CharField(max_length=50) details = models.TextField(max_length=400) submission_date = models.DateTimeField(blank=True, null=True, default=timezone.now) def __str__(self): return self.full_name <file_sep>/contacts/views.py from django.shortcuts import render, redirect from .forms import ContactSubmissionForm from .models import Contact # Create your views here. def contact_submission(request): if request.method =="POST": form = ContactSubmissionForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("index") else: form = ContactSubmissionForm() return render(request, 'contactpage.html', {'form':form}) def faq_page(request): """ This will render the frequently asked questions page """ return render(request, "faq.html") def about_page(request): """ This will render the frequently asked questions page """ return render(request, "about.html")<file_sep>/contacts/forms.py from django import forms from .models import Contact class ContactSubmissionForm(forms.ModelForm): class Meta: model = Contact fields =('full_name','email','phone_number','details')
f9687fae424a7b6833a3651010ad2bae826c60d4
[ "Markdown", "Python", "Text" ]
21
Python
Code-Institute-Submissions/django-ecomm-2019
b95d570081dc38a0032b7d49e771f06bab6c71dc
fac1136d207e1bb451f5286270730d04032e9368
refs/heads/master
<file_sep># nelnet-table Gets all loans on nelnet, computes monthly interest for each loan, total interest per month, and shows data in ascii table. --- I wanted a quick and easy way to see which student loans I should be concentrating on. My go to for website scraping is Python's requests and beautifulsoup4 libraries but I decided to go with nightwatch.js for this one. Nelnet uses AngularJS 1.4.9 with csrf tokens so given the messy nature of AngularJS DOM structures I opted for a higher level browser automation library. This script gets all my student loans and displays the principle, interest, accured interest, outstanding balance, and my own calculated monthly interest field. I use this monthly interest to know which student loan I should be concentrating on to minimize my interest payments. --- # how to use ``` git clone https://github.com/ljmerza/nelnet-table.git npm install ``` Rename example.creds.json to creds.json and enter your username and password to log into nelnet then run: ``` node_modules/nightwatch/bin/nightwatch ``` <file_sep>const creds = require('../creds'); const AsciiTable = require('ascii-table') var table = new AsciiTable('Nelnet Loans') table .setHeading('Due Date','Fees','Status','Interest Rate','Accrued Interest','Last Payment Received','Outstanding Balance','Principle Balance','Interest Per Month','Total', 'Total Interest Per Month') module.exports = { 'Nelnet': function (browser) { const wait = 2000; let data = []; browser // go to nelnet .url('https://www.nelnet.com/welcome') // enter usernane .waitForElementVisible('#username') .pause(wait) .setValue('#username', creds.username) .click('#submit-username') // enter password .waitForElementVisible('#Password') .setValue('#Password', <PASSWORD>) .click('#submit-password') .pause(wait) // go to loan details .url('https://www.nelnet.com/Loan/Details') .waitForElementVisible('#maincontent') .pause(3000) // open group details .click('.account-row:nth-child(1) a') .waitForElementVisible('#maincontent') .pause(wait) .click('.account-row:nth-child(2) a') .waitForElementVisible('#maincontent') .pause(5000) // get all data .elements('css selector', '.account-detail div tr td', function (elements) { elements.value.forEach( function(element, i) { browser.elementIdText(element.ELEMENT, function(result){ if(result.value) data.push(result.value); }); }); }) // format data .perform( () => { let total = 0, total_int = 0; // reformat data const chunk_size = 8; const loans = data.map( (e,i) => { return i%chunk_size===0 ? data.slice(i,i+chunk_size) : null; }) .filter(function(e){ return e; }); // reformat to console table format const tables = loans.forEach( (loan, index) => { const monthly_interest = parseInt(loan[3].replace(/%/, '')) / 100 / 12; const outstanding_format = parseInt(loan[6].replace(/\$|,/g, '')); const interest_per_month = outstanding_format * monthly_interest; total += outstanding_format; total_int += interest_per_month table.addRow( loan[0],loan[1],loan[2], loan[3],loan[4],loan[5], loan[6],loan[7], '$'+ interest_per_month.toFixed(2), '$'+total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","), '$'+total_int.toFixed(2) ); }); console.log(table.toString()) }) .end(); } };
4eac05edf78d88379e38c86f98b93003050c1d0d
[ "Markdown", "JavaScript" ]
2
Markdown
ljmerza/nelnet-table
010ddfeec275f469ca2f30b26c4844b3a459a85d
d70b56bd5816135de2826a3b1943b76f3efb9697
refs/heads/master
<repo_name>x0rb3l/nmap_quick_script<file_sep>/nmap_quick_script.py ################################################################# ## Title: Nmap Quick Script ## ## Author: <NAME> ## ## Position: Penetration Tester ## ## Company: ePlus Technology ## ## Date Created: 7/3/2019 ## ## Website: https://github.com/robel1889/nmap_quick_script.git ## ################################################################# import os import sys print("Nmap Quick Script Tool! \nA python script to automate frequent nmap scans at work. \nWritten By: <NAME> \nhttps://github.com/robel1889/nmap_quick_script.git") def usage(): print("\nPlease enter a list of valid IP addresses.\n") print ("Usage: python3 ", sys.argv[0], " <ip list file>\n") if (len(sys.argv) < 2 or len(sys.argv) > 2): usage() sys.exit() else: # Create nmap directory if it doesn't exist. if not os.path.exists('nmap/'): print("\n[+] Creating nmap directory...\n") os.makedirs('nmap') else: print("\n[+] Nmap directory already exists...\n") # Run all three nmap scans and store results in all file formats. print("\n[+] Enumerating hosts-up!...\n") os.system('nmap -sP -Pn -oA nmap/hosts_up -iL %s > /dev/null' % (sys.argv[1])) print("\n[+] Running quick port scan!...\n") os.system('nmap -T4 --max-retries=1 -Pn -oA nmap/port_scan -iL %s > /dev/null' % (sys.argv[1])) print("\n[+] Running script scan!...This may take a minute...\n") os.system('nmap -sV -sC -T4 --max-retries=1 -Pn -oA nmap/script_scan -iL %s > /dev/null' % (sys.argv[1])) print("\n[+] Scanning complete!...please check nmap directory for results.") <file_sep>/README.md # nmap_quick_script A short nmap script written in Python3 that I use to automate daily nmap scans for work. I usually have to run three different nmap scans against a client's scope of IP addresses and output those results to various file formats. With this script, I can perform all three scans in one command. Usage: python3 nmap_quick_script.py ip_list_file ![POC for the script](https://github.com/robel1889/nmap_quick_script/blob/master/nmap_quick_script.png)
b2f40f2c13e7ed02b8c661dabc829aa62698f276
[ "Markdown", "Python" ]
2
Python
x0rb3l/nmap_quick_script
368be4b69ec7381899c14bf6d30692cb004a711c
c96ff7345b1213b0529e7a3b9eb70df9a61978c4
refs/heads/master
<file_sep>#ifndef BATTERYSTATUS_H #define BATTERYSTATUS_H void batteryStatusSC(void *statusStruct); #endif <file_sep>#include <Arduino.h> #include "DataStructs.h" // send a String to PS and receive a data packet from the PS void communicationSC(char *str, void *dataStruct) { // send process Serial1.write(str,13); Serial1.flush(); // Wait print to complete // receive process if (str[0] == 'M') { char measureIn[12]; while ((Serial1.available() < 10)) { } Serial1.readBytes(measureIn, 10); // Store values in the measureIn to measureStruct MeasureData* mData = (MeasureData*) dataStruct; // Add statements checking if a variable is being tracked currently if ((*(mData->tempSelection)) == TRUE){ for (int i = 7; i > 0; i--){ (*(mData->temperatureRawBuf))[2*i] = (*(mData->temperatureRawBuf))[2*(i-1)]; // temp (*(mData->temperatureRawBuf))[2*i+1] = (*(mData->temperatureRawBuf))[2*(i-1)+1]; } (*(mData->temperatureRawBuf))[0] = measureIn[0]; (*(mData->temperatureRawBuf))[1] = measureIn[1]; } if ((*(mData->bpSelection)) == TRUE){ for (int i = 7; i > 0; i--){ (*(mData->bloodPressRawBuf))[3*i] = (*(mData->bloodPressRawBuf))[3*(i-1)]; // temp (*(mData->bloodPressRawBuf))[3*i+1] = (*(mData->bloodPressRawBuf))[3*(i-1)+1]; (*(mData->bloodPressRawBuf))[3*i+2] = (*(mData->bloodPressRawBuf))[3*(i-1)+2]; (*(mData->bloodPressRawBuf))[24+2*i] = (*(mData->bloodPressRawBuf))[24+2*(i-1)]; (*(mData->bloodPressRawBuf))[24+2*i+1] = (*(mData->bloodPressRawBuf))[24+2*(i-1)+1]; } (*(mData->bloodPressRawBuf))[0] = measureIn[2]; (*(mData->bloodPressRawBuf))[1] = measureIn[3]; (*(mData->bloodPressRawBuf))[2] = measureIn[4]; (*(mData->bloodPressRawBuf))[24] = measureIn[5]; (*(mData->bloodPressRawBuf))[25] = measureIn[6]; } if ((*(mData->pulseSelection)) == TRUE){ for (int i = 7; i > 0; i--){ (*(mData->bloodPressRawBuf))[3*i] = (*(mData->bloodPressRawBuf))[3*(i-1)]; // temp (*(mData->bloodPressRawBuf))[3*i+1] = (*(mData->bloodPressRawBuf))[3*(i-1)+1]; (*(mData->bloodPressRawBuf))[3*i+2] = (*(mData->bloodPressRawBuf))[3*(i-1)+2]; } (*(mData->pulseRateRawBuf))[0] = measureIn[7]; (*(mData->pulseRateRawBuf))[1] = measureIn[8]; (*(mData->pulseRateRawBuf))[2] = measureIn[9]; } } else if (str[0] =='C') { char computeIn[15]; while ((Serial1.available() < 13)) { } Serial1.readBytes(computeIn, 13); // TODO: store values in the computeIn to computeStruct // need to wait until top level code is set ComputeData* cData = (ComputeData*) dataStruct; if ((*(cData->tempSelection)) == TRUE){ for (int i = 7; i > 0; i--){ (*(cData->tempCorrectedBuf))[4*i] = (*(cData->tempCorrectedBuf))[4*(i-1)]; // temp (*(cData->tempCorrectedBuf))[4*i+1] = (*(cData->tempCorrectedBuf))[4*(i-1)+1]; (*(cData->tempCorrectedBuf))[4*i+2] = (*(cData->tempCorrectedBuf))[4*(i-1)+2]; (*(cData->tempCorrectedBuf))[4*i+3] = (*(cData->tempCorrectedBuf))[4*(i-1)+3]; } (*(cData->tempCorrectedBuf))[0] = computeIn[0]; // temp (*(cData->tempCorrectedBuf))[1] = computeIn[1]; (*(cData->tempCorrectedBuf))[2] = computeIn[2]; (*(cData->tempCorrectedBuf))[3] = computeIn[3]; } if ((*(cData->bpSelection)) == TRUE){ for (int i = 7; i > 0; i--){ (*(cData->bloodPressCorrectedBuf))[3*i] = (*(cData->bloodPressCorrectedBuf))[3*(i-1)]; // Sys (*(cData->bloodPressCorrectedBuf))[3*i+1] = (*(cData->bloodPressCorrectedBuf))[3*(i-1)+1]; (*(cData->bloodPressCorrectedBuf))[3*i+2] = (*(cData->bloodPressCorrectedBuf))[3*(i-1)+2]; (*(cData->bloodPressCorrectedBuf))[24+3*i] = (*(cData->bloodPressCorrectedBuf))[24+3*(i-1)]; // Dias (*(cData->bloodPressCorrectedBuf))[24+3*i+1] = (*(cData->bloodPressCorrectedBuf))[24+3*(i-1)+1]; (*(cData->bloodPressCorrectedBuf))[24+3*i+2] = (*(cData->bloodPressCorrectedBuf))[24+3*(i-1)+2]; } (*(cData->bloodPressCorrectedBuf))[0] = computeIn[4]; // sys (*(cData->bloodPressCorrectedBuf))[1] = computeIn[5]; (*(cData->bloodPressCorrectedBuf))[2] = computeIn[6]; (*(cData->bloodPressCorrectedBuf))[24] = computeIn[7]; //dias (*(cData->bloodPressCorrectedBuf))[25] = computeIn[8]; (*(cData->bloodPressCorrectedBuf))[26] = computeIn[9]; } if ((*(cData->pulseSelection)) == TRUE){ for (int i = 7; i > 0; i--){ (*(cData->pulseRateCorrectedBuf))[3*i] = (*(cData->pulseRateCorrectedBuf))[3*(i-1)]; // pulse (*(cData->pulseRateCorrectedBuf))[3*i+1] = (*(cData->pulseRateCorrectedBuf))[3*(i-1)+1]; (*(cData->pulseRateCorrectedBuf))[3*i+2] = (*(cData->pulseRateCorrectedBuf))[3*(i-1)+2]; } (*(cData->pulseRateCorrectedBuf))[0] = computeIn[10]; // pulse (*(cData->pulseRateCorrectedBuf))[1] = computeIn[11]; (*(cData->pulseRateCorrectedBuf))[2] = computeIn[12]; } } else if (str[0] == 'S') { char statusIn[5]; while (Serial1.available() < 3) { } Serial1.readBytes(statusIn, 3); StatusData* sData = (StatusData*) dataStruct; (*(sData->batteryState))[0] = statusIn[0]; (*(sData->batteryState))[1] = statusIn[1]; (*(sData->batteryState))[2] = statusIn[2]; } } <file_sep>#include "DataStructsPS.h" void batteryStatusPS(void *statusStruct) { // TODO: modify lab2 code StatusDataPS *sData = (StatusDataPS*) statusStruct; *(sData->batteryState) -= 1; }<file_sep>#ifndef MEASURESC_H #define MEASURESC_H #include "Bool.h" void measurerSC(void *measureStruct); #endif <file_sep>#include <stdio.h> #include "DataStructs.h" #include "tasks.h" #include <Elegoo_GFX.h> // Core graphics library #include <Elegoo_TFTLCD.h> // Hardware-specific library // The control pins for the LCD can be assigned to any digital or // analog pins...but we'll use the analog pins as this allows us to // double up the pins with the touch screen (see the TFT paint example). #define LCD_CS A3 // Chip Select goes to Analog 3 #define LCD_CD A2 // Command/Data goes to Analog 2 #define LCD_WR A1 // LCD Write goes to Analog 1 #define LCD_RD A0 // LCD Read goes to Analog 0 #define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin // When using the BREAKOUT BOARD only, use these 8 data lines to the LCD: // For the Arduino Uno, Duemilanove, Diecimila, etc.: // D0 connects to digital pin 8 (Notice these are // D1 connects to digital pin 9 NOT in order!) // D2 connects to digital pin 2 // D3 connects to digital pin 3 // D4 connects to digital pin 4 // D5 connects to digital pin 5 // D6 connects to digital pin 6 // D7 connects to digital pin 7 // For the Arduino Mega, use digital pins 22 through 29 // (on the 2-row header at the end of the board). // Assign human-readable names to some common 16-bit color values: #define BLACK 0x0000 #define BLUE 0x001F #define RED 0xF800 #define GREEN 0x07E0 #define CYAN 0x07FF #define MAGENTA 0xF81F #define YELLOW 0xFFE0 #define WHITE 0xFFFF Elegoo_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET); // If using the shield, all control and data lines are fixed, and // a simpler declaration can optionally be used: // Elegoo_TFTLCD tft; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //unsigned int measureInterval = 5; unsigned int globalCounter = 0; // Problems: 'Bool's are expected to be 'enum Bool *' // numOfMeasureCalls void measureData(void *measureStruct) { MeasureData *mData = (MeasureData*) measureStruct; if ((globalCounter % (*(mData->measureInterval))) != 0){ return; } measureTemp(mData->temperatureRaw, mData->tempIncrease, mData->numOfMeasureCalls); //Serial.println(*(mData->temperatureRaw)); measureSysPres(mData->systolicPressRaw,mData->sysMeasureComplete, mData->diaMeasureComplete, mData->numOfMeasureCalls); measureDiaPres(mData->diastolicPressRaw,mData->sysMeasureComplete, mData->diaMeasureComplete, mData->numOfMeasureCalls); measurePulseRate(mData->pulseRateRaw, mData->bpIncrease, mData->numOfMeasureCalls); *(mData->numOfMeasureCalls) += 1; } void computeData(void *computeStruct) { ComputeData *cData = (ComputeData*) computeStruct; if ((globalCounter % *(cData->computeInterval)) != 0){ return; } double temp = 5 + 0.75 * (*(cData->temperatureRaw)); unsigned int systolicPres = (unsigned int) 9 + 2 * (*(cData->systolicPressRaw)); unsigned int diastolicPres = (unsigned int) floor(6 + 1.5 * (*(cData->diastolicPressRaw))); unsigned int pr = (unsigned int) 8 + 3 * (*(cData->pulseRateRaw)); *(cData->tempNumeric) = temp; *(cData->sysNumeric) = systolicPres; *(cData->diasNumeric) = diastolicPres; *(cData->pulseNumeric) = pr; /* sprintf(**(cData->tempCorrected), "%f", temp); Serial.println(F("Updated tempCorrected in computefun")); delay(200); sprintf(**(cData->sysPressCorrected), "%d", systolicPres); sprintf(**(cData->diasCorrected), "%d", diastolicPres); sprintf(**(cData->prCorrected), "%d", pr); Serial.println(F("Done with computefun")); delay(200); */ } void displayData(void *displayStruct) { DisplayData *dData = (DisplayData*) displayStruct; if ((globalCounter % *(dData->displayInterval)) != 0){ return; }; tft.fillScreen(BLACK); tft.setTextSize(2); tft.setCursor(0, 0); // print low and high presure tft.setTextColor(*(dData->bpHigh) ? RED : GREEN); //tft.print(*(dData->sysNumeric)); tft.print(*(dData->sysNumeric)); tft.setTextColor(WHITE); tft.print("/"); tft.setTextColor(*(dData->bpLow) ? RED : GREEN); //tft.print(*(dData->diasNumeric)); tft.print(*(dData->diasNumeric)); tft.setTextColor(WHITE); //tft.write(80); tft.println(" mm Hg"); // print temp tft.setTextColor(*(dData->tempOff) ? RED : GREEN); //tft.print(*(dData->tempNumeric)); tft.print((float)*(dData->tempNumeric), 1); tft.setTextColor(WHITE); tft.print("C "); // print pulserate tft.setTextColor(*(dData->pulseOff) ? RED : GREEN); //tft.print(*(dData->pulseNumeric)); tft.print(*(dData->pulseNumeric)); tft.setTextColor(WHITE); tft.println(" BPM "); // print battery tft.setTextColor(*(dData->batteryLow) ? RED : GREEN); tft.print(*(dData->batteryState)); tft.setTextColor(WHITE); tft.print(" Charges"); } void annuciate(void *warningAlarmStruct) { WarningAlarmData *wData = (WarningAlarmData*) warningAlarmStruct; if ((globalCounter % *(wData->warningInterval)) != 0){ return; } // Battery *(wData->batteryLow) = (((*(wData->batteryState)) < 40) ? TRUE : FALSE); // syst *(wData->bpHigh) = (((*(wData->sysNumeric)) > 120) ? TRUE : FALSE); // dias *(wData->bpLow) = (((*(wData->diasNumeric)) < 80) ? TRUE : FALSE); // pulserate *(wData->pulseOff) = ((((*(wData->pulseNumeric)) < 60) || ((*(wData->pulseNumeric)) > 100)) ? TRUE : FALSE); // Temperature *(wData->tempOff) = ((*(wData->tempNumeric) > 37.8) || (*(wData->tempNumeric) < 36.1)) ? TRUE : FALSE; } void batteryStatus(void *statusStruct) { StatusData *sData = (StatusData*) statusStruct; if ((globalCounter % *(sData->statusInterval)) != 0){ return; } *(sData->batteryState) -= 1; } void schedule(TCB **tasks) { Serial.print(F("GlobalCounter = ")); Serial.println(globalCounter); (*(tasks[0]->taskPtr))(tasks[0]->taskDataPtr); (*(tasks[1]->taskPtr))(tasks[1]->taskDataPtr); (*(tasks[2]->taskPtr))(tasks[2]->taskDataPtr); (*(tasks[3]->taskPtr))(tasks[3]->taskDataPtr); (*(tasks[4]->taskPtr))(tasks[4]->taskDataPtr); delay(100); //delay_ms(10000); globalCounter++; } ////////////////// // MEASURE TEMP // ////////////////// void measureTemp(unsigned int *temperature, Bool *tempIncrease, unsigned int *numOfMeasureCalls) { if (*tempIncrease && *temperature > 50){ *tempIncrease = FALSE; } if (!(*tempIncrease) && *temperature < 15){ *tempIncrease = TRUE; } if (*tempIncrease) { if (*numOfMeasureCalls % 2 == 0) { *temperature += 2; } else { *temperature -= 1; } } else { if (*numOfMeasureCalls % 2 == 0) { *temperature -= 2; } else { *temperature += 1; } } } void measureSysPres(unsigned int *sysPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *numOfMeasureCalls) { if (*diaMeasureComplete && *sysMeasureComplete){ *sysMeasureComplete = FALSE; *sysPres = 80; } if (!*sysMeasureComplete) { if (*numOfMeasureCalls % 2 == 0) { *sysPres += 3; } else { *sysPres -= 1; } if (*sysPres > 100) { *sysMeasureComplete = TRUE; } } } void measureDiaPres(unsigned int *diaPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *numOfMeasureCalls) { if (*sysMeasureComplete && *diaMeasureComplete){ *diaMeasureComplete = FALSE; *diaPres = 80; } if (!*diaMeasureComplete) { if (*numOfMeasureCalls % 2 == 0) { *diaPres -= 2; } else { *diaPres += 1; } if (*diaPres < 40) { *diaMeasureComplete = TRUE; } } } void measurePulseRate(unsigned int *pulseRate, Bool *bpIncrease, unsigned int *numOfMeasureCalls){ if (*bpIncrease && (*pulseRate > 40)){ *bpIncrease = FALSE; } if (!(*bpIncrease) && (*pulseRate < 15)){ *bpIncrease = TRUE; } if (*bpIncrease) { if (*numOfMeasureCalls % 2 == 0) { *pulseRate -= 1; } else { *pulseRate += 3; } } else { if (*numOfMeasureCalls % 2 == 0) { *pulseRate += 1; } else { *pulseRate -= 3; } } } /////////////////// // DELAY // /////////////////// void delay_ms(unsigned long time) { volatile int i, j; for (i = 0; i <= 3000; i++) { // 32767 for (j = time; j > 0; j--) { // empty } } } /////////////////// // SETUP DISPLAY // /////////////////// void setupDisplay(void) { Serial.begin(9600); Serial.println(F("TFT LCD test")); #ifdef USE_Elegoo_SHIELD_PINOUT Serial.println(F("Using Elegoo 2.4\" TFT Arduino Shield Pinout")); #else Serial.println(F("Using Elegoo 2.4\" TFT Breakout Board Pinout")); #endif Serial.print("TFT size is "); Serial.print(tft.width()); Serial.print("x"); Serial.println(tft.height()); tft.reset(); uint16_t identifier = tft.readID(); if(identifier == 0x9325) { Serial.println(F("Found ILI9325 LCD driver")); } else if(identifier == 0x9328) { Serial.println(F("Found ILI9328 LCD driver")); } else if(identifier == 0x4535) { Serial.println(F("Found LGDP4535 LCD driver")); }else if(identifier == 0x7575) { Serial.println(F("Found HX8347G LCD driver")); } else if(identifier == 0x9341) { Serial.println(F("Found ILI9341 LCD driver")); } else if(identifier == 0x8357) { Serial.println(F("Found HX8357D LCD driver")); } else if(identifier==0x0101) { identifier=0x9341; Serial.println(F("Found 0x9341 LCD driver")); } else if(identifier==0x1111) { identifier=0x9328; Serial.println(F("Found 0x9328 LCD driver")); } else { Serial.print(F("Unknown LCD driver chip: ")); Serial.println(identifier, HEX); Serial.println(F("If using the Elegoo 2.8\" TFT Arduino shield, the line:")); Serial.println(F(" #define USE_Elegoo_SHIELD_PINOUT")); Serial.println(F("should appear in the library header (Elegoo_TFT.h).")); Serial.println(F("If using the breakout board, it should NOT be #defined!")); Serial.println(F("Also if using the breakout, double-check that all wiring")); Serial.println(F("matches the tutorial.")); identifier=0x9328; } tft.begin(identifier); } <file_sep>#ifndef TFTKEYPAD_H #define TFTKEYPAD_H #include "Datastructs.h" void displayLoop(void *tftStruct); void setupDisplay(void *tftStruct); void drawDefaultMode(void *tftStruct); void drawMenu(void *tftStruct); void drawAnnunciate(void *tftStruct); #endif <file_sep>#include "DataStructsPS.h" #include "Bool.h" #include <math.h> #include "measurePS.h" #include <Arduino.h> void measurePS(void *measureStruct) { MeasureDataPS *mData = (MeasureDataPS*) measureStruct; // measure temperature if (*(mData->tempSelection)){ measureTemp(mData->temperatureRaw, mData->tempIncrease, mData->numOfMeasureCalls); } // measure blood pressures if (*(mData->bpSelection)){ measureSysPres(mData->systolicPressRaw, mData->sysMeasureComplete, mData->diaMeasureComplete, mData->numOfMeasureCalls); measureDiaPres(mData->diastolicPressRaw, mData->sysMeasureComplete, mData->diaMeasureComplete, mData->numOfMeasureCalls); } // measure pulse rate if (*(mData->pulseSelection)){ measurePulseRate(mData->pulseRateRaw); } // increment simulation counter *(mData->numOfMeasureCalls) += 1; } void measureTemp(unsigned int *temperature, Bool *tempIncrease, unsigned int *numOfMeasureCalls) { if (*tempIncrease && *temperature > 50){ *tempIncrease = FALSE; } if (!(*tempIncrease) && *temperature < 15){ *tempIncrease = TRUE; } if (*tempIncrease) { if (*numOfMeasureCalls % 2 == 0) { *temperature += 2; } else { *temperature -= 1; } } else { if (*numOfMeasureCalls % 2 == 0) { *temperature -= 2; } else { *temperature += 1; } } } void measureSysPres(unsigned int *sysPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *numOfMeasureCalls) { if (*diaMeasureComplete && *sysMeasureComplete){ *sysMeasureComplete = FALSE; *sysPres = 80; } if (!*sysMeasureComplete) { if (*numOfMeasureCalls % 2 == 0) { *sysPres += 3; } else { *sysPres -= 1; } if (*sysPres > 100) { *sysMeasureComplete = TRUE; } } } void measureDiaPres(unsigned int *diaPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *numOfMeasureCalls) { if (*sysMeasureComplete && *diaMeasureComplete){ *diaMeasureComplete = FALSE; *diaPres = 80; } if (!*diaMeasureComplete) { if (*numOfMeasureCalls % 2 == 0) { *diaPres -= 2; } else { *diaPres += 1; } if (*diaPres < 40) { *diaMeasureComplete = TRUE; } } } void measurePulseRate(unsigned int *pulseRate){ unsigned long halfPeriod = pulseIn(PIN_IN, LOW, 2000000UL); double halfPeriodInS = (1.0 * halfPeriod) / 1000000; int pulse = (int) 1 / (2 * halfPeriodInS); *pulseRate = pulse; } <file_sep>void peripheralCom();<file_sep>#include "DataStructs.h" #include "schedulerSC.h" // Don't forget to add functions to header file unsigned int globalTime; void scheduler(struct TCB* head, struct TCB* tail, unsigned long globalTime) { TCB* curr = head; while (curr != tail){ /* if (*(curr->nick) == 'M'){ deleteNode(ComputeTCB, head, tail); insertNode(ComputeTCB, MeasureTCB, head, tail); } */ (*(curr->taskPtr))(curr->taskDataPtr); curr = curr->next; } // While loop ends before tail is executed // So we call it one last time to run through everything (*(curr->taskPtr))(curr->taskDataPtr); // Delay one second //globalTime++; } void deleteNode(struct TCB* node, struct TCB* head, struct TCB* tail) { TCB* curr; TCB* prevNode; TCB* nextNode; if (node == head){ // Node is head // 1. Set head->next to head curr = head; head = head->next; // 2. Set internal pointers to NULL curr->next = NULL; } else if (node == tail){ // Node is tail // 1. Set tail->prev to tail curr = tail; tail = tail->prev; // 2. Set internal pointer to NULL curr->prev = NULL; } else { // Node is somewhere in between // 1. Find node curr = head->next; while(node != curr){ curr = curr->next; } // 2. Node found, update neighbor pointers, set internal pointers to NULL prevNode = curr->prev; nextNode = curr->next; prevNode->next = nextNode; nextNode->prev = prevNode; curr->next = NULL; curr->prev = NULL; } return; } // Do insert(TCBToInsert, TCBtoadd it to after) // So calling insert(compute, measure) adds compute after measure void insertNode(struct TCB* node, struct TCB* precNode, struct TCB* head, struct TCB* tail) { // Since C lacks default parameters, // The user has to input NULL as 2nd arg if not specified if (NULL == precNode){ precNode = tail; } if(NULL == head){ // If the head pointer is pointing to nothing head = node; // set the head and tail pointers to point to this node tail = node; } else if (tail == precNode) { // otherwise, head is not NULL, add the node to the end of the list tail->next = node; node->prev = tail; // note that the tail pointer is still pointing // to the prior last node at this point tail = node; // update the tail pointer } else { TCB* curr = precNode->next; precNode->next = node; curr->prev = node; node->next=curr; node->prev = precNode; } return; } <file_sep>#include "DataStructs.h" #include <arduinoFFT.h> #include <math.h> #include <Arduino.h> #include "EKGCapture.h" void EKGProcess(void *EKGStruct) { ComputeData *eData = (ComputeData*) EKGStruct; arduinoFFT fft = arduinoFFT(); fft.Windowing(*(eData->vReal), SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD); fft.Compute(*(eData->vReal), *(eData->vImag), SAMPLES, FFT_FORWARD); fft.ComplexToMagnitude(*(eData->vReal), *(eData->vImag), SAMPLES); double peak = fft.MajorPeak(*(eData->vReal), SAMPLES, FS); //for (int i = 16; i > 0; i--) { // (*(eData->freqBuf))[i] = (*(eData->freqBuf))[i - 1]; //} (*(eData->freqBuf))[0] = peak; //Serial.print("peak ======= "); //Serial.println(peak); } <file_sep>#include "DataStructsPS.h" #include "Bool.h" #include <math.h> #include "measurePS.h" #include <Arduino.h> void measurePS(void *measureStruct) { MeasureDataPS *mData = (MeasureDataPS*) measureStruct; // measure temperature if (*(mData->tempSelection)){ measureTemp(mData->temperatureRaw); } // measure blood pressures if (*(mData->bpSelection)){ measureBloodPres(mData->systolicPressRaw, mData->diastolicPressRaw, mData->sysMeasureComplete, mData->diaMeasureComplete, mData->bloodPressure, mData->patient); (*(mData->bpSelection)) = FALSE; } // measure pulse rate if (*(mData->pulseSelection)){ measurePulseRate(mData->pulseRateRaw); } if (*(mData->respSelection)) { measureRespiration(mData->respirationRaw); } // increment simulation counter *(mData->numOfMeasureCalls) += 1; } void measureTemp(unsigned int *temperature) { int val = analogRead(TEMP_IN); int temp = map(val, 0, 1023, 15, 50); *temperature = temp; /* if (*tempIncrease && *temperature > 50){ *tempIncrease = FALSE; } if (!(*tempIncrease) && *temperature < 15){ *tempIncrease = TRUE; } if (*tempIncrease) { if (*numOfMeasureCalls % 2 == 0) { *temperature += 2; } else { *temperature -= 1; } } else { if (*numOfMeasureCalls % 2 == 0) { *temperature -= 2; } else { *temperature += 1; } } */ } void measureBloodPres(unsigned int *sysPres, unsigned int *diaPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *bloodPressure, int *patient) { /* Bool IncRead; Bool DecRead; while (!(*(sysMeasureComplete)) || !(*(diaMeasureComplete))) { do { IncRead = digitalRead(BP_INC); DecRead = digitalRead(BP_DEC); } while (IncRead == DecRead); if (IncRead) { *(bloodPressure) *= 1.1; } else if (DecRead) { *(bloodPressure) *= 0.9; } if (!(*(sysMeasureComplete))) { if (*(bloodPressure) >= 110 && *(bloodPressure) <= 150) { *sysPres = *bloodPressure; *sysMeasureComplete = TRUE; digitalWrite(LED_BUILTIN, HIGH); delay(100); digitalWrite(LED_BUILTIN, LOW); delay(100); } } else if (!(*(diaMeasureComplete))) { if (*(bloodPressure) <= 80 && *(bloodPressure) >=50 ) { *diaPres = *bloodPressure; *diaMeasureComplete = TRUE; digitalWrite(LED_BUILTIN, HIGH); delay(100); digitalWrite(LED_BUILTIN, LOW); delay(100); } } delay(300); } *sysMeasureComplete = FALSE; *diaMeasureComplete = FALSE; */ if (*patient == -1) { randomSeed(analogRead(A1)); *patient = random(0, 3); } if (!(*(sysMeasureComplete))) { if (*patient == 0) { if (*(bloodPressure) >= 110 && *(bloodPressure) <= 130) { *sysPres = *bloodPressure; *sysMeasureComplete = TRUE; digitalWrite(LED_BUILTIN, HIGH); delay(100); digitalWrite(LED_BUILTIN, LOW); } } else if (*patient == 1) { if (*(bloodPressure) >= 120 && *(bloodPressure) <= 140) { *sysPres = *bloodPressure; *sysMeasureComplete = TRUE; digitalWrite(LED_BUILTIN, HIGH); delay(100); digitalWrite(LED_BUILTIN, LOW); } } else if (*patient == 2) { if (*(bloodPressure) >= 130 && *(bloodPressure) <= 150) { *sysPres = *bloodPressure; *sysMeasureComplete = TRUE; digitalWrite(LED_BUILTIN, HIGH); delay(100); digitalWrite(LED_BUILTIN, LOW); } } } else if (!(*(diaMeasureComplete))) { if (*patient == 0) { if (*(bloodPressure) <= 60 && *(bloodPressure) >= 50 ) { *diaPres = *bloodPressure; *diaMeasureComplete = TRUE; digitalWrite(LED_BUILTIN, HIGH); delay(100); digitalWrite(LED_BUILTIN, LOW); } } else if (*patient == 1) { if (*(bloodPressure) <= 70 && *(bloodPressure) >= 60) { *diaPres = *bloodPressure; *diaMeasureComplete = TRUE; digitalWrite(LED_BUILTIN, HIGH); delay(100); digitalWrite(LED_BUILTIN, LOW); } } else if (*patient == 2) { if (*(bloodPressure) <= 80 && *(bloodPressure) >= 70) { *diaPres = *bloodPressure; *diaMeasureComplete = TRUE; digitalWrite(LED_BUILTIN, HIGH); delay(100); digitalWrite(LED_BUILTIN, LOW); } } } if (*sysMeasureComplete && *diaMeasureComplete) { *sysMeasureComplete = FALSE; *diaMeasureComplete = FALSE; *patient = -1; } } void measureSysPres(unsigned int *sysPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *numOfMeasureCalls) { if (*diaMeasureComplete && *sysMeasureComplete){ *sysMeasureComplete = FALSE; *sysPres = 80; } if (!*sysMeasureComplete) { if (*numOfMeasureCalls % 2 == 0) { *sysPres += 3; } else { *sysPres -= 1; } if (*sysPres > 100) { *sysMeasureComplete = TRUE; } } } void measureDiaPres(unsigned int *diaPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *numOfMeasureCalls) { if (*sysMeasureComplete && *diaMeasureComplete){ *diaMeasureComplete = FALSE; *diaPres = 80; } if (!*diaMeasureComplete) { if (*numOfMeasureCalls % 2 == 0) { *diaPres -= 2; } else { *diaPres += 1; } if (*diaPres < 40) { *diaMeasureComplete = TRUE; } } } void measurePulseRate(unsigned int *pulseRate){ unsigned long halfPeriod = pulseIn(PULSE_IN, LOW, 2000000UL); double halfPeriodInS = (1.0 * halfPeriod) / 1000000; int pulse = (int) 1 / (2 * halfPeriodInS); *pulseRate = pulse; } void measureRespiration(unsigned int *respirationRaw) { unsigned long halfPeriod = pulseIn(PULSE_IN, LOW, 2000000UL); double halfPeriodInS = (1.0 * halfPeriod) / 1000000; int freq = (int) 1 / (2 * halfPeriodInS); // map freq (range [10, 200]) to resp (range [1, 14]) int resp = (int)(((freq - 10.0)/(200 - 10.0)) * (14.33 - 1.0) + 1.0); *respirationRaw = resp; } <file_sep>#ifndef COMSC #define COMSC void communicationSC(char *str, void *dataStruct); #endif<file_sep>#ifndef COMPUTESC_H #define COMPUTESC_H void computeSC(void *computeStruct); #endif <file_sep>#include "DataStructs.h" #include "communicationSC.h" #include "EKGProcess.h" #include <Arduino.h> // SC part of the compute. Send data packet to call compute. void computeSC(void *computeStruct) { ComputeData *cData = (ComputeData*) computeStruct; //Serial.println("inside compute"); delay(50); char str[13]; str[0] = 'C'; str[1] = ((*(cData->bpSelection)) ? 'B' : 'b'); str[2] = ((*(cData->tempSelection)) ? 'T' : 't'); str[3] = ((*(cData->pulseSelection)) ? 'P' : 'p'); str[4] = ((*(cData->respSelection)) ? 'R' : 'r'); str[5] = 'C'; str[6] = 'o'; str[7] = 'm'; str[8] = 'p'; str[9] = 'u'; str[10] = 't'; str[11] = 'e'; str[12] = '>'; //Serial.println(str); delay(50); // transfer and receive communicationSC(str, computeStruct); //Serial.println("Finished compute"); EKGProcess(computeStruct); } <file_sep>#include "Bool.h" #include <stdio.h> #include "DataStructs.h" #include "tasks.h" TCB* taskQueue[5]; TCB MeasureTCB; TCB ComputeTCB; TCB DisplayTCB; TCB WarningAlarmTCB; TCB StatusTCB; unsigned int globalTime = 0; Bool sysMeasureComplete = FALSE; Bool diaMeasureComplete = FALSE; Bool tempIncrease = TRUE; Bool bpIncrease = TRUE; unsigned int numOfMeasureCalls = 0; unsigned int measureInterval = 5; unsigned int computeInterval = 5; unsigned int displayInterval = 5; unsigned int warningInterval = 1; unsigned int statusInterval = 5; unsigned int temperatureRaw = 75; unsigned int systolicPressRaw = 80; unsigned int diastolicPressRaw = 80; unsigned int pulseRateRaw = 50; double tempNumeric = 0; unsigned int sysNumeric = 0; unsigned int diasNumeric = 0; unsigned int pulseNumeric = 0; unsigned char *tempCorrected = NULL; unsigned char *sysPressCorrected = NULL; unsigned char *diasCorrected = NULL; unsigned char *prCorrected = NULL; unsigned short batteryState = 200; unsigned char bpOutOfRange = 0; unsigned char tempOutOfRange = 0; unsigned char pulseOutOfRange = 0; Bool bpHigh = FALSE; Bool bpLow = FALSE; Bool tempOff = FALSE; Bool pulseOff = FALSE; Bool batteryLow = FALSE; MeasureData mData; ComputeData cData; DisplayData dData; WarningAlarmData wData; StatusData stData; void setup(void) { setupDisplay(); // Add variables to measure struct mData.globalTime = &globalTime; mData.measureInterval = &measureInterval; mData.diastolicPressRaw = &diastolicPressRaw; mData.systolicPressRaw = &systolicPressRaw; mData.pulseRateRaw = &pulseRateRaw; mData.temperatureRaw = &temperatureRaw; mData.sysMeasureComplete = &sysMeasureComplete; mData.diaMeasureComplete = &diaMeasureComplete; mData.tempIncrease = &tempIncrease; mData.bpIncrease = &bpIncrease; mData.numOfMeasureCalls = &numOfMeasureCalls; // Add variables to compute struct cData.globalTime = &globalTime; cData.diastolicPressRaw = &diastolicPressRaw; cData.computeInterval = &computeInterval; cData.systolicPressRaw = &systolicPressRaw; cData.pulseRateRaw = &pulseRateRaw; cData.temperatureRaw = &temperatureRaw; cData.diasCorrected = &diasCorrected; cData.sysPressCorrected = &sysPressCorrected; cData.prCorrected = &prCorrected; cData.tempCorrected = &tempCorrected; cData.tempNumeric = &tempNumeric; cData.sysNumeric = &sysNumeric; cData.diasNumeric = &diasNumeric; cData.pulseNumeric = &pulseNumeric; // Add variables to display struct dData.globalTime = &globalTime; dData.displayInterval = &displayInterval; dData.diasCorrected = &diasCorrected; dData.sysPressCorrected = &sysPressCorrected; dData.prCorrected = &prCorrected; dData.tempCorrected = &tempCorrected; dData.bpHigh = &bpHigh; dData.bpLow = &bpLow; dData.tempOff = &tempOff; dData.pulseOff = &pulseOff; dData.bpOutOfRange = &bpOutOfRange; dData.pulseOutOfRange = &pulseOutOfRange; dData.tempOutOfRange = &tempOutOfRange; dData.batteryLow = &batteryLow; dData.tempNumeric = &tempNumeric; dData.sysNumeric = &sysNumeric; dData.diasNumeric = &diasNumeric; dData.pulseNumeric = &pulseNumeric; dData.batteryState = &batteryState; dData.displayInterval = &measureInterval; dData.diastolicPressRaw = &diastolicPressRaw; dData.systolicPressRaw = &systolicPressRaw; dData.pulseRateRaw = &pulseRateRaw; dData.temperatureRaw = &temperatureRaw; // Add values to warning/alarm struct wData.globalTime = &globalTime; wData.warningInterval = &warningInterval; wData.diastolicPressRaw = &diastolicPressRaw; wData.systolicPressRaw = &systolicPressRaw; wData.pulseRateRaw = &pulseRateRaw; wData.temperatureRaw = &temperatureRaw; wData.bpOutOfRange = &bpOutOfRange; wData.pulseOutOfRange = &pulseOutOfRange; wData.tempOutOfRange = &tempOutOfRange; wData.batteryState = &batteryState; wData.bpHigh = &bpHigh; wData.bpLow = &bpLow; wData.tempOff = &tempOff; wData.pulseOff = &pulseOff; wData.batteryLow = &batteryLow; wData.tempNumeric = &tempNumeric; wData.sysNumeric = &sysNumeric; wData.diasNumeric = &diasNumeric; wData.pulseNumeric = &pulseNumeric; // Add data to status struct stData.globalTime = &globalTime; stData.statusInterval = &statusInterval; stData.batteryState = &batteryState; // Initialize the TCBs MeasureTCB.taskPtr = &measureData; MeasureTCB.taskDataPtr = (void*)&mData; ComputeTCB.taskPtr = &computeData; ComputeTCB.taskDataPtr = (void*)&cData; DisplayTCB.taskPtr = &displayData; DisplayTCB.taskDataPtr = (void*)&dData; WarningAlarmTCB.taskPtr = &annuciate; WarningAlarmTCB.taskDataPtr = (void*)&wData; StatusTCB.taskPtr = &batteryStatus; StatusTCB.taskDataPtr = (void*)&stData; // Initialize the taskQueue taskQueue[0] = &MeasureTCB; taskQueue[1] = &ComputeTCB; taskQueue[2] = &DisplayTCB; taskQueue[3] = &WarningAlarmTCB; taskQueue[4] = &StatusTCB; } void loop(void) { schedule(taskQueue); } <file_sep>#ifdef __cplusplus extern "C" { #endif #include "Bool.h" #include "measurePS.h" #include "DataStructsPS.h" #include "computePS.h" #include "batteryStatusPS.h" #ifdef __cplusplus } #endif /* Shared global variables for storing data */ // Measure Data unsigned int temperatureRaw = 75; unsigned int systolicPressRaw = 80; unsigned int diastolicPressRaw = 80; unsigned int pulseRateRaw = 50; Bool sysMeasureComplete = FALSE; Bool diaMeasureComplete = FALSE; Bool tempIncrease = FALSE; Bool bpIncrease = FALSE; Bool tempSelection = TRUE; Bool bpSelection = TRUE; Bool pulseSelection = TRUE; unsigned int numOfMeasureCalls = 0; // ComputeData float tempCorrected = 0; unsigned int systolicPressCorrected = 0; unsigned int diastolicPressCorrected = 0; unsigned int pulseRateCorrected = 0; // WarningAlarm Bool bpOutOfRange = FALSE; Bool tempOutOfRange = FALSE; Bool pulseOutOfRange = FALSE; Bool bpHigh = FALSE; Bool bpLow = FALSE; Bool bpOff = FALSE; Bool tempOff = FALSE; Bool pulseOff = FALSE; Bool batteryLow = FALSE; unsigned int bpAlarmCount; //Battery Status unsigned short batteryState = 200; /* end of shared global variables */ MeasureDataPS mData; ComputeDataPS cData; WarningAlarmDataPS wData; StatusDataPS sData; void setup() { Serial.begin(9600); pinMode(PIN_IN, INPUT); // MeasureData fields mData.temperatureRaw = &temperatureRaw; mData.systolicPressRaw = &systolicPressRaw; mData.diastolicPressRaw = &diastolicPressRaw; mData.pulseRateRaw = &pulseRateRaw; mData.sysMeasureComplete = &sysMeasureComplete; mData.diaMeasureComplete = &diaMeasureComplete; mData.tempIncrease = &tempIncrease; mData.bpIncrease = &bpIncrease; mData.tempSelection = &tempSelection; mData.bpSelection = &bpSelection; mData.pulseSelection = &pulseSelection; mData.numOfMeasureCalls = &numOfMeasureCalls; // ComputeData fields. cData.temperatureRaw = &temperatureRaw; cData.systolicPressRaw = &systolicPressRaw; cData.diastolicPressRaw = &diastolicPressRaw; cData.pulseRateRaw = &pulseRateRaw; cData.tempCorrected = &tempCorrected; cData.systolicPressCorrected = &systolicPressCorrected; cData.diastolicPressCorrected = &diastolicPressCorrected; cData.pulseRateCorrected = &pulseRateCorrected; cData.tempSelection = &tempSelection; cData.bpSelection = &bpSelection; cData.pulseSelection = &pulseSelection; // WarningAlarmData fields wData.temperatureRaw = &temperatureRaw; wData.systolicPressRaw = &systolicPressRaw; wData.diastolicPressRaw = &diastolicPressRaw; wData.pulseRateRaw = &pulseRateRaw; wData.batteryState = &batteryState; wData.batteryState = &batteryState; wData.bpOutOfRange = &bpOutOfRange; wData.tempOutOfRange = &tempOutOfRange; wData.pulseOutOfRange = &pulseOutOfRange; wData.bpHigh = &bpHigh; wData.tempOff = &tempOff; wData.pulseOff = &pulseOff; wData.batteryLow = &batteryLow; wData.bpAlarmCount = &bpAlarmCount; wData.tempSelection = &tempSelection; wData.bpSelection = &bpSelection; wData.pulseSelection = &pulseSelection; // StatusData fields sData.batteryState = &batteryState; } void loop() { char inBytes[13]; if (Serial.available() > 12) { //Format[mbtp<Measure>] Serial.readBytes(inBytes, 13); // Measure case if (inBytes[0] == 'M') { // Set measure selection fields // Blood pressure if (inBytes[1] == 'B') { *(mData.bpSelection) = TRUE; } else if (inBytes[1] == 'b') { *(mData.bpSelection) = FALSE; } // Temperature if (inBytes[2] == 'T') { *(mData.tempSelection) = TRUE; } else if (inBytes[2] == 't') { *(mData.tempSelection) = FALSE; } // Pulse Rate if (inBytes[3] == 'P') { *(mData.pulseSelection) == TRUE; } else if (inBytes[3] == 'p') { *(mData.pulseSelection) == FALSE; } // end of measure selection processing // call measure function void* mDataPtr = (void*)&mData; measurePS(mDataPtr); // Send raw data back Serial.print(*(mData.temperatureRaw)); Serial.flush(); if (*(mData.systolicPressRaw) < 100) { Serial.print(0); Serial.flush(); } Serial.print(*(mData.systolicPressRaw)); Serial.flush(); Serial.print(*(mData.diastolicPressRaw)); Serial.flush(); if (*(mData.pulseRateRaw) < 10) { Serial.print(0); Serial.flush(); Serial.print(0); Serial.flush(); } else if (*(mData.pulseRateRaw) < 100) { Serial.print(0); Serial.flush(); } Serial.print(*(mData.pulseRateRaw)); Serial.flush(); } else if (inBytes[0] == 'C') { // call compute void* cDataPtr = (void*)&cData; computePS(cDataPtr); // print corrected data Serial.print(*(cData.tempCorrected), 1); // 4 chars Serial.flush(); if (*(cData.systolicPressCorrected) < 100) { Serial.print(0); Serial.flush(); } Serial.print(*(cData.systolicPressCorrected)); // 3 chars Serial.flush(); if (*(cData.diastolicPressCorrected) < 100) { Serial.print(0); Serial.flush(); } Serial.print(*(cData.diastolicPressCorrected)); if (*(cData.pulseRateCorrected) < 10) { Serial.print(0); Serial.flush(); Serial.print(0); Serial.flush(); } else if (*(cData.pulseRateCorrected) < 100) { Serial.print(0); Serial.flush(); } Serial.print(*(cData.pulseRateCorrected)); Serial.flush(); } else if (inBytes[0] == 'S') { void* sDataPtr = (void*) &sData; batteryStatusPS(sDataPtr); if (*(sData.batteryState) < 10) { Serial.print(0); Serial.flush(); Serial.print(0); Serial.flush(); } else if (*(sData.batteryState) < 100) { Serial.print(0); Serial.flush(); } Serial.print(*(sData.batteryState)); Serial.flush(); } } /* // Test code for each function void* mDataPtr = (void*)&mData; measurePS(mDataPtr); Serial.println(*(mData.temperatureRaw)); Serial.println(*(mData.systolicPressRaw)); Serial.println(*(mData.diastolicPressRaw)); Serial.println(*(mData.pulseRateRaw)); Serial.println("Finished measure"); //Serial.println(); void* cDataPtr = (void*)&cData; computePS(cDataPtr); Serial.println(*(cData.tempCorrected)); Serial.println(*(cData.systolicPressCorrected)); Serial.println(*(cData.diastolicPressCorrected)); Serial.println(*(cData.pulseRateCorrected)); Serial.println("Finished compute"); void* sDataPtr = (void*)&sData; batteryStatusPS(sDataPtr); Serial.println(*(sData.batteryState)); Serial.println(); delay(1000);*/ } <file_sep> int globalCounter; // send a String to PS and receive a data packet from the PS void communicationSC(char *data, void *dataStruct) { // send process if (globalCounter % 5 == 0) { // Every 5 second // Call measure/compute/batteryStatus if (data[0] == 'M' || data[0] == 'C' || data[0] == 'B') { Serial.write(data); // send } } // always call warningAlarm if (data[0] == 'W') { Serial.write(data); // send } // receive process // TODO: implement } void communicationPS() { // TODO: implement if (Serial.available() > 0) { char received[30]; int i = 0; while (Serial.available() > 0) { received[i] = Serial.read(); i++; } // if (received[1] == 'M') { measure(); Serial.write(''); } } } <file_sep>#define EKG_PIN A15 #define FS 10000 #define SAMPLES 256 void EKGCapture(void *EKGStruct); <file_sep> char strM[13] = {'M', 'B', 'T', 'p', '<', 'M', 'e', 'a', 's', 'u', 'r', 'e', '>'}; char strC[13] = {'C', 'B', 'T', 'p', '<', 'C', 'o', 'm', 'p', 'u', 't', 'e', '>'}; char inbyte; char measureIn[12]; char computeIn[15]; char statusIn[5]; void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial1.begin(9600); } void loop() { measureSC(); //delay(1000); computeSC(); //delay(1000); statusSC(); Serial.println(); delay(1000); } void communication(char* str) { Serial1.print(str); Serial1.flush(); if (str[0] == 'M') { while ((Serial.available() < 10)) { } Serial.readBytes(measureIn, 10); Serial.print(measureIn); // print input chars one by one /* while (Serial.available() > 0) { inbyte = Serial.read(); Serial.print(inbyte); Serial.print(" "); } */ Serial.println(); } else if (str[0] =='C') { while ((Serial.available() < 13)) { } Serial.readBytes(computeIn, 13); Serial.print(computeIn); /* while (Serial.available() > 0) { inbyte = Serial.read(); Serial.print(inbyte); Serial.print(" "); } */ Serial.println(); } else if (str[0] == 'S') { while (Serial.available() < 3) { } Serial.readBytes(statusIn, 3); Serial.print(statusIn); /* while (Serial.available() > 0) { inbyte = Serial.read(); Serial.print(inbyte); Serial.print(" "); } */ Serial.println(); } } void measureSC() { char str[13]; str[0] = 'M'; str[1] = 'B'; str[2] = 'T'; str[3] = 'P'; str[4] = '<'; str[5] = 'M'; str[6] = 'e'; str[7] = 'a'; str[8] = 's'; str[9] = 'u'; str[10] = 'r'; str[11] = 'e'; str[12] = '>'; communication(str); } void computeSC() { char str[13]; str[0] = 'C'; str[1] = 'B'; str[2] = 'T'; str[3] = 'P'; str[4] = '<'; str[5] = 'C'; str[6] = 'o'; str[7] = 'm'; str[8] = 'p'; str[9] = 'u'; str[10] = 't'; str[11] = 'e'; str[12] = '>'; communication(str); } void statusSC() { char str[13]; str[0] = 'S'; str[1] = 'A'; str[2] = 'A'; str[3] = 'A'; str[4] = '<'; str[5] = 'B'; str[6] = 'a'; str[7] = 't'; str[8] = 'S'; str[9] = 't'; str[10] = 'a'; str[11] = 't'; str[12] = '>'; communication(str); } <file_sep>#ifndef BOOL_H #define BOOL_H /* Code by Prof. Peckol, University of Washintgton, 2018*/ enum _myBool {FALSE = 0, TRUE = 1}; typedef enum _myBool Bool; #endif <file_sep>void warningAlarmPS(void *warningAlarmStruct); <file_sep>#include "DataStructs.h" #include "warningSC.h" #include "Bool.h" void annunciate(void *warningAlarmStruct) { WarningAlarmData *wData = (WarningAlarmData*) warningAlarmStruct; if ((*(wData->globalTime) % *(wData->warningInterval)) != 0){ return; } int batterystate = 100*((*(wData->batteryState))[0] - '0')+ 10*((*(wData->batteryState))[1] - '0') + ((*(wData->batteryState))[2]) - '0'; int sys = 100*((*(wData->bloodPressCorrectedBuf))[0] - '0')+ 10*((*(wData->bloodPressCorrectedBuf))[1] - '0') + ((*(wData->bloodPressCorrectedBuf))[2]) - '0'; int dias = 100*((*(wData->bloodPressCorrectedBuf))[24] - '0')+ 10*((*(wData->bloodPressCorrectedBuf))[25] - '0') + ((*(wData->bloodPressCorrectedBuf))[26]) - '0'; int pulse = 100*((*(wData->pulseRateCorrectedBuf))[0] - '0') + 10*((*(wData->pulseRateCorrectedBuf))[1] - '0') + ((*(wData->pulseRateCorrectedBuf))[2])- '0'; float temp = 100*((*(wData->tempCorrectedBuf))[0] - '0') + 10*((*(wData->tempCorrectedBuf))[1] - '0') + (*(wData->tempCorrectedBuf)[2]) - '0' + ((*(wData->tempCorrectedBuf)[3])- '0')/10; // Battery *(wData->batteryLow) = ((batterystate < 40) ? TRUE : FALSE); // syst *(wData->bpHigh) = ((sys > 120) ? TRUE : FALSE); if (*(wData->alarmAcknowledge)){ (*(wData->alarmTimer))++; if (*(wData->alarmTimer) > 5){ (*(wData->sysAlarm)) = TRUE; (*(wData->alarmAcknowledge)) = FALSE; } } // sys *(wData->sysAlarm) = ((sys > 140) ? TRUE : FALSE); // dias *(wData->bpLow) = ((dias < 80) ? TRUE : FALSE); // pulserate *(wData->pulseOff) = ((pulse < 60) || ((pulse > 100)) ? TRUE : FALSE); // Temperature *(wData->tempOff) = ((temp > 37.8) || ((temp < 36.1)) ? TRUE : FALSE); } <file_sep>#ifndef MEASURE #define MEASURE #include "Bool.h" #define PULSE_IN 7 #define TEMP_IN A0 #define BP_INC 2 #define BP_DEC 3 void measurePS(void *measureStruct); void measureTemp(unsigned int *temperature); void measureBloodPres(unsigned int *sysPres, unsigned int *diaPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *bloodPressure, int *patient); void measureSysPres(unsigned int *sysPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *numOfMeasureCalls); void measureDiaPres(unsigned int *diaPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *numOfMeasureCalls); void measurePulseRate(unsigned int *pulseRate); void measureRespiration(unsigned int *respirationRaw); #endif <file_sep>#ifndef PERIPHERALCOM_H #define PERIHPERALCOM_H void communicationSC(char *data, void *dataStruct); #endif PERIPHERALCOM_H <file_sep>#include "DataStructs.h" #include "communicationSC.h" void batteryStatusSC(void *statusStruct) { // create string to be sent to the PS StatusData *sData = (StatusData*) statusStruct; if ((*(sData->globalTime)) % (*(sData->statusInterval)) != 0){ return; } char str[13]; str[0] = 'S'; str[1] = 'A'; str[2] = 'A'; str[3] = 'A'; str[4] = '<'; str[5] = 'B'; str[6] = 'a'; str[7] = 't'; str[8] = 'S'; str[9] = 't'; str[10] = 'a'; str[11] = 't'; str[12] = '>'; // transfer and receive communicationSC(str, statusStruct); } <file_sep>#include "DataStructsPS.h" void warningAlarm(void *warningAlarmStruct) { WarningAlarmDataPS *wData = (WarningAlarmDataPS*) warningAlarmStruct; // Set battery low signal *(wData->batteryLow) = (((*(wData->batteryState)) < 40) ? TRUE : FALSE); if (*(wData->bpSelection)){ // syst *(wData->bpHigh) = ((((*(wData->sysNumeric)) > 130) || (*(wData->sysNumeric) < 120)) ? TRUE : FALSE); *(wData->bpAlarmHigh) = (((*(wData->sysNumeric)) > 130*1.20) ? TRUE : FALSE); // Update how many times in a row blood pressure has been at an alarm level if (*(wData->bpAlarmHigh)){ (*(wData->bpAlarmCount))++; } else { (*(wData->bpAlarmCount)) = 0; } // dias *(wData->bpLow) = (((*(wData->diasNumeric)) > 80) || ((*(wData->diasNumeric)) < 70) ? TRUE : FALSE); } if (*(wData->pulseSelection)){ // pulserate *(wData->pulseOff) = ((((*(wData->pulseNumeric)) < 60) || ((*(wData->pulseNumeric)) > 100)) ? TRUE : FALSE); } if (*(wData->tempSelection)){ // Temperature, CHECK IF this is alarm or warning! *(wData->tempOff) = ((*(wData->tempNumeric) > 37.8) || (*(wData->tempNumeric) < 36.1)) ? TRUE : FALSE; } } void warningASC(void *computeStruct) { // create string to be sent to the PS char start = 2; char stop = 3; char str[25]; str[0] = 'C'; str[1] = 'B'; // To be changed after implemented TFTKeypad str[2] = 'T'; // To be changed after implemented TFTKeypad str[3] = 'P'; // To be changed after implemented TFTKeypad strcat(str, &start); strcat(str, "Starting compute"); strcat(str, &stop); // transfer and receive com(char *data, void *dataStruct); } <file_sep>#ifndef MEASURESC_H #define MEASURESC_H void measurerSC(void *measureStruct); #endif <file_sep>#ifdef __cplusplus extern "C" { #endif #include "Bool.h" //#include "measurePS.h" #include "DataStructsPS.h" #include "computePS.h" #include "batteryStatusPS.h" #ifdef __cplusplus } #endif #include "measurePS.h" /* Shared global variables for storing data */ // Measure Data unsigned int temperatureRaw = 75; unsigned int systolicPressRaw = 80; unsigned int diastolicPressRaw = 80; unsigned int pulseRateRaw = 0; unsigned int respirationRaw = 0; Bool sysMeasureComplete = FALSE; Bool diaMeasureComplete = FALSE; Bool bpIncrease = FALSE; Bool tempSelection = TRUE; Bool bpSelection = FALSE; Bool pulseSelection = TRUE; Bool respSelection = TRUE; unsigned int numOfMeasureCalls = 0; unsigned int bloodPressure = 80; // ComputeData float tempCorrected = 0; unsigned int systolicPressCorrected = 0; unsigned int diastolicPressCorrected = 0; unsigned int pulseRateCorrected = 0; unsigned int respirationCorrected = 0; //Battery Status unsigned short batteryState = 200; /* end of shared global variables */ MeasureDataPS mData; ComputeDataPS cData; StatusDataPS sData; void setup() { Serial.begin(9600); pinMode(PULSE_IN, INPUT); pinMode(BP_INC, INPUT); pinMode(BP_DEC, INPUT); pinMode(LED_BUILTIN, OUTPUT); // MeasureData fields mData.temperatureRaw = &temperatureRaw; mData.systolicPressRaw = &systolicPressRaw; mData.diastolicPressRaw = &diastolicPressRaw; mData.pulseRateRaw = &pulseRateRaw; mData.respirationRaw = &respirationRaw; mData.sysMeasureComplete = &sysMeasureComplete; mData.diaMeasureComplete = &diaMeasureComplete; mData.bpIncrease = &bpIncrease; mData.tempSelection = &tempSelection; mData.bpSelection = &bpSelection; mData.pulseSelection = &pulseSelection; mData.respSelection = &respSelection; mData.numOfMeasureCalls = &numOfMeasureCalls; mData.bloodPressure = &bloodPressure; // ComputeData fields. cData.temperatureRaw = &temperatureRaw; cData.systolicPressRaw = &systolicPressRaw; cData.diastolicPressRaw = &diastolicPressRaw; cData.pulseRateRaw = &pulseRateRaw; cData.respirationRaw = &respirationRaw; cData.tempCorrected = &tempCorrected; cData.systolicPressCorrected = &systolicPressCorrected; cData.diastolicPressCorrected = &diastolicPressCorrected; cData.pulseRateCorrected = &pulseRateCorrected; cData.respirationCorrected = &respirationCorrected; cData.tempSelection = &tempSelection; cData.bpSelection = &bpSelection; cData.pulseSelection = &pulseSelection; cData.respSelection = &respSelection; // StatusData fields sData.batteryState = &batteryState; } void loop() { char inBytes[13]; if (Serial.available() > 12) { //Format[mbtp<Measure>] Serial.readBytes(inBytes, 13); // Measure case if (inBytes[0] == 'M') { // Set measure selection fields // Blood pressure if (inBytes[1] == 'B') { *(mData.bpSelection) = TRUE; } else if (inBytes[1] == 'b') { *(mData.bpSelection) = FALSE; } // Temperature if (inBytes[2] == 'T') { *(mData.tempSelection) = TRUE; } else if (inBytes[2] == 't') { *(mData.tempSelection) = FALSE; } // Pulse Rate if (inBytes[3] == 'P') { *(mData.pulseSelection) = TRUE; } else if (inBytes[3] == 'p') { *(mData.pulseSelection) = FALSE; } // Respiration if (inBytes[4] == 'R') { *(mData.respSelection) = TRUE; } else if (inBytes[4] == 'r') { *(mData.respSelection) = FALSE; } // end of measure selection processing // call measure function void* mDataPtr = (void*)&mData; measurePS(mDataPtr); // Send raw data back Serial.print(*(mData.temperatureRaw)); Serial.flush(); if (*(mData.systolicPressRaw) < 100) { Serial.print(0); Serial.flush(); } Serial.print(*(mData.systolicPressRaw)); Serial.flush(); Serial.print(*(mData.diastolicPressRaw)); Serial.flush(); if (*(mData.pulseRateRaw) < 10) { Serial.print(0); Serial.flush(); Serial.print(0); Serial.flush(); } else if (*(mData.pulseRateRaw) < 100) { Serial.print(0); Serial.flush(); } Serial.print(*(mData.pulseRateRaw)); Serial.flush(); if (*(mData.respirationRaw) < 10) { Serial.print(0); Serial.flush(); } Serial.print(*(mData.respirationRaw)); Serial.flush(); } else if (inBytes[0] == 'C') { // call compute void* cDataPtr = (void*)&cData; computePS(cDataPtr); // print corrected data Serial.print(*(cData.tempCorrected), 1); // 4 chars Serial.flush(); if (*(cData.systolicPressCorrected) < 100) { Serial.print(0); Serial.flush(); } Serial.print(*(cData.systolicPressCorrected)); // 3 chars Serial.flush(); if (*(cData.diastolicPressCorrected) < 100) { Serial.print(0); Serial.flush(); } Serial.print(*(cData.diastolicPressCorrected)); if (*(cData.pulseRateCorrected) < 10) { Serial.print(0); Serial.flush(); Serial.print(0); Serial.flush(); } else if (*(cData.pulseRateCorrected) < 100) { Serial.print(0); Serial.flush(); } Serial.print(*(cData.pulseRateCorrected)); Serial.flush(); Serial.print(*(cData.respirationCorrected)); Serial.flush(); } // Battery status case else if (inBytes[0] == 'S') { void* sDataPtr = (void*) &sData; batteryStatusPS(sDataPtr); if (*(sData.batteryState) < 10) { Serial.print(0); Serial.flush(); Serial.print(0); Serial.flush(); } else if (*(sData.batteryState) < 100) { Serial.print(0); Serial.flush(); } Serial.print(*(sData.batteryState)); Serial.flush(); } } /* // Test code for each function void* mDataPtr = (void*)&mData; measurePS(mDataPtr); Serial.println(*(mData.temperatureRaw)); Serial.println(*(mData.systolicPressRaw)); Serial.println(*(mData.diastolicPressRaw)); Serial.println(*(mData.pulseRateRaw)); Serial.println(*(mData.respirationRaw)); Serial.println("Finished measure"); //Serial.println(); void* cDataPtr = (void*)&cData; computePS(cDataPtr); Serial.println(*(cData.tempCorrected)); Serial.println(*(cData.systolicPressCorrected)); Serial.println(*(cData.diastolicPressCorrected)); Serial.println(*(cData.pulseRateCorrected)); Serial.println(*(cData.respirationCorrected)); Serial.println("Finished compute"); void* sDataPtr = (void*)&sData; batteryStatusPS(sDataPtr); Serial.println(*(sData.batteryState)); Serial.println(); delay(5000);*/ } <file_sep>void computePS(void *computeStruct);<file_sep>#ifndef MEASURE #define MEASURE #include "Bool.h" #define PULSE_IN 7 #define SYS_IN 2 #define DIA_IN 4 void measurePS(void *measureStruct); void measureTemp(unsigned int *temperature, Bool *tempIncrease, unsigned int *numOfMeasureCalls); void measureSysPres(unsigned int *sysPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *numOfMeasureCalls); void measureDiaPres(unsigned int *diaPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *numOfMeasureCalls); void measurePulseRate(unsigned int *pulseRate); #endif <file_sep>#ifdef __cplusplus extern "C" { #endif #include "Bool.h" #include "DataStructs.h" //#include "schedulerSC.h" #ifdef __cplusplus } #endif #include "warningSC.h" #include "computeSC.h" #include "TFTKeypad.h" #include "batteryStatusSC.h" #include "measureSC.h" TCB* head; TCB* tail; TCB MeasureTCB; TCB ComputeTCB; TCB tftTCB; TCB WarningAlarmTCB; TCB StatusTCB; unsigned int globalTime = 0; // Change this to millis Bool sysMeasureComplete = FALSE; Bool diaMeasureComplete = FALSE; Bool tempIncrease = FALSE; Bool bpIncrease = FALSE; unsigned int numOfMeasureCalls = 0; const unsigned int measureInterval = 5; const unsigned int computeInterval = 5; const unsigned int displayInterval = 5; const unsigned int warningInterval = 1; const unsigned int statusInterval = 5; char bloodPressCorrectedBuf[48] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char tempCorrectedBuf[32] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char pulseRateCorrectedBuf[24] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char respirationRateCorrectedBuf[16]={'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; // Maybe change the size of this here and everywhere else char bloodPressRawBuf[40] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char temperatureRawBuf[16] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char pulseRateRawBuf[24] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char respirationRateRawBuf[16] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char batteryState[3] = {'0','0','0'}; Bool pulseWarning = FALSE; Bool pulseAlarm = FALSE; Bool tempWarning = FALSE; Bool tempAlarm = FALSE; Bool sysWarning = FALSE; Bool diasWarning = FALSE; Bool sysAlarm = FALSE; Bool respAlarm = FALSE; Bool batteryLow = FALSE; /* Bool bpHigh = FALSE; Bool bpLow = FALSE; Bool tempOff = FALSE; Bool pulseOff = FALSE; Bool batteryLow = FALSE; Bool sysAlarm = FALSE; Bool respOff = FALSE; */ Bool tempSelection = TRUE; Bool bpSelection = FALSE; Bool pulseSelection = TRUE; Bool respSelection = TRUE; Bool sysAlarmAcknowledge = TRUE; Bool tempAlarmAcknowledge = TRUE; Bool pulseAlarmAcknowledge = TRUE; Bool respAlarmAcknowledge = TRUE; unsigned int sysAlarmTimer = 0; unsigned int tempAlarmTimer = 0; unsigned int pulseAlarmTimer = 0; unsigned int respAlarmTimer = 0; Bool sysFlash = FALSE; Bool diasFlash = FALSE; Bool tempFlash = FALSE; Bool pulseFlash = FALSE; unsigned long lastSysFlash = 0; unsigned long lastDiasFlash = 0; unsigned long lastTempFlash = 0; unsigned long lastPulseFlash = 0; unsigned long timeNow = 0; Bool justPressed = FALSE; MeasureData mData; ComputeData cData; TFTData dData; WarningAlarmData wData; StatusData stData; void setup(void) { Serial1.begin(9600); Serial.begin(9600); // Add variables to measure struct mData.globalTime = &globalTime; mData.measureInterval = &measureInterval; // Raw data mData.bloodPressRawBuf = &bloodPressRawBuf; mData.pulseRateRawBuf = &pulseRateRawBuf; mData.temperatureRawBuf = &temperatureRawBuf; mData.respirationRateRawBuf = &respirationRateRawBuf; // measure selections mData.tempSelection = &tempSelection; mData.bpSelection = &bpSelection; mData.pulseSelection = &pulseSelection; mData.respSelection = &respSelection; // Add variables to compute struct cData.globalTime = &globalTime; cData.computeInterval = &computeInterval; cData.tempSelection = &tempSelection; cData.bpSelection = &bpSelection; cData.pulseSelection = &pulseSelection; cData.respSelection = &respSelection; cData.tempCorrectedBuf = &tempCorrectedBuf; cData.bloodPressCorrectedBuf = &bloodPressCorrectedBuf; cData.pulseRateCorrectedBuf = &pulseRateCorrectedBuf; cData.respirationRateCorrectedBuf = &respirationRateCorrectedBuf; // Add variables to display struct dData.globalTime = &globalTime; dData.displayInterval = &displayInterval; dData.bloodPressCorrectedBuf = &bloodPressCorrectedBuf; dData.pulseRateCorrectedBuf = &pulseRateCorrectedBuf; dData.tempCorrectedBuf = &tempCorrectedBuf; dData.respirationRateCorrectedBuf = &respirationRateCorrectedBuf; dData.pulseWarning = &pulseWarning; dData.pulseAlarm = &pulseAlarm; dData.tempWarning = &tempWarning; dData.tempAlarm = &tempAlarm; dData.sysWarning = &sysWarning; dData.diasWarning = &diasWarning; dData.sysAlarm = &sysAlarm; dData.respAlarm = &respAlarm; dData.batteryLow = &batteryLow; dData.sysAlarmAcknowledge = &sysAlarmAcknowledge; dData.sysAlarmTimer = &sysAlarmTimer; dData.tempAlarmAcknowledge = &tempAlarmAcknowledge; dData.tempAlarmTimer = &tempAlarmTimer; dData.pulseAlarmAcknowledge = &pulseAlarmAcknowledge; dData.pulseAlarmTimer = &pulseAlarmTimer; dData.respAlarmAcknowledge = &respAlarmAcknowledge; dData.respAlarmTimer = &respAlarmTimer; dData.batteryState = &batteryState; dData.displayInterval = &displayInterval; dData.tempSelection = &tempSelection; dData.bpSelection = &bpSelection; dData.pulseSelection = &pulseSelection; dData.respSelection = &respSelection; dData.sysAlarm = &sysAlarm; dData.timeNow = &timeNow; dData.justPressed = &justPressed; dData.lastSysFlash = &lastSysFlash; dData.sysFlash = &sysFlash; dData.lastDiasFlash = &lastDiasFlash; dData.diasFlash = &diasFlash; dData.lastTempFlash = &lastTempFlash; dData.tempFlash = &tempFlash; dData.lastPulseFlash = &lastPulseFlash; dData.pulseFlash = &pulseFlash; // Add values to warning/alarm struct wData.globalTime = &globalTime; wData.warningInterval = &warningInterval; // Raw Data wData.bloodPressRawBuf = &bloodPressRawBuf; wData.pulseRateRawBuf = &pulseRateRawBuf; wData.temperatureRawBuf = &temperatureRawBuf; mData.respirationRateRawBuf = &respirationRateRawBuf; wData.bloodPressCorrectedBuf = &bloodPressCorrectedBuf; wData.pulseRateCorrectedBuf = &pulseRateCorrectedBuf; wData.tempCorrectedBuf = &tempCorrectedBuf; wData.respirationRateCorrectedBuf = &respirationRateCorrectedBuf; wData.batteryState = &batteryState; wData.pulseWarning = &pulseWarning; wData.pulseAlarm = &pulseAlarm; wData.tempWarning = &tempWarning; wData.tempAlarm = &tempAlarm; wData.sysWarning = &sysWarning; wData.diasWarning = &diasWarning; wData.sysAlarm = &sysAlarm; wData.respAlarm = &respAlarm; wData.batteryLow = &batteryLow; wData.sysAlarmAcknowledge = &sysAlarmAcknowledge; wData.sysAlarmTimer = &sysAlarmTimer; wData.tempAlarmAcknowledge = &tempAlarmAcknowledge; wData.tempAlarmTimer = &tempAlarmTimer; wData.pulseAlarmAcknowledge = &pulseAlarmAcknowledge; wData.pulseAlarmTimer = &pulseAlarmTimer; wData.respAlarmAcknowledge = &respAlarmAcknowledge; wData.respAlarmTimer = &respAlarmTimer; // Add data to status struct stData.globalTime = &globalTime; stData.statusInterval = &statusInterval; stData.batteryState = &batteryState; // Initialize the TCBs MeasureTCB.taskPtr = &measurerSC; MeasureTCB.taskDataPtr = (void*)&mData; MeasureTCB.prev = NULL; MeasureTCB.next = &StatusTCB; ComputeTCB.taskPtr = &computeSC; ComputeTCB.taskDataPtr = (void*)&cData; ComputeTCB.prev = NULL; // Compute is by default not part of the queue ComputeTCB.next = NULL; StatusTCB.taskPtr = &batteryStatusSC; StatusTCB.taskDataPtr = (void*)&stData; StatusTCB.prev = &MeasureTCB; StatusTCB.next = &WarningAlarmTCB; WarningAlarmTCB.taskPtr = &annunciate; WarningAlarmTCB.taskDataPtr = (void*)&wData; WarningAlarmTCB.prev = &StatusTCB; WarningAlarmTCB.next = &tftTCB; tftTCB.taskPtr = &displayLoop; tftTCB.taskDataPtr = (void*)&dData; tftTCB.prev = &WarningAlarmTCB; tftTCB.next = NULL; // Initialize the taskQueue head = &MeasureTCB; tail = &tftTCB; setupDisplay(&tftTCB); Serial.println("End of setup"); delay(100); } void loop(void) { //Serial.println("Start of loop: are we here?"); timeNow = millis(); TCB* curr = head; TCB* oldcurr; while (curr != tail){ //Serial.println("Task begun");delay(50); Serial.println("Inside task loop"); (*(curr->taskPtr))(curr->taskDataPtr); if ((curr == &MeasureTCB) && (globalTime % measureInterval == 0)){ Serial.println("adding compute"); insertNode(&ComputeTCB, &MeasureTCB, head, tail); Serial.println("compute added"); } oldcurr = curr; curr = curr->next; if ((oldcurr == &ComputeTCB) && (globalTime % measureInterval == 0)){ deleteNode(&ComputeTCB,head,tail); } } // While loop ends before tail is executed // So we call it one last time to run through everything (*(curr->taskPtr))(curr->taskDataPtr); Serial.println("Done with loop"); delay(50); // Delay one second globalTime++; } void deleteNode(struct TCB* node, struct TCB* head, struct TCB* tail) { TCB* curr; TCB* prevNode; TCB* nextNode; if (node == head){ // Node is head // 1. Set head->next to head curr = head; head = head->next; // 2. Set internal pointers to NULL curr->next = NULL; } else if (node == tail){ // Node is tail // 1. Set tail->prev to tail curr = tail; tail = tail->prev; // 2. Set internal pointer to NULL curr->prev = NULL; } else { // Node is somewhere in between // 1. Find node curr = head->next; while(node != curr){ curr = curr->next; } // 2. Node found, update neighbor pointers, set internal pointers to NULL prevNode = curr->prev; nextNode = curr->next; prevNode->next = nextNode; nextNode->prev = prevNode; curr->next = NULL; curr->prev = NULL; } return; } // Do insert(TCBToInsert, TCBtoadd it to after) // So calling insert(compute, measure) adds compute after measure void insertNode(struct TCB* node, struct TCB* precNode, struct TCB* head, struct TCB* tail) { // Since C lacks default parameters, // The user has to input NULL as 2nd arg if not specified if (NULL == precNode){ precNode = tail; } if(NULL == head){ // If the head pointer is pointing to nothing head = node; // set the head and tail pointers to point to this node tail = node; } else if (tail == precNode) { // otherwise, head is not NULL, add the node to the end of the list tail->next = node; node->prev = tail; // note that the tail pointer is still pointing // to the prior last node at this point tail = node; // update the tail pointer } else { TCB* curr = precNode->next; precNode->next = node; curr->prev = node; node->next=curr; node->prev = precNode; } return; } <file_sep>#ifndef DATASTRUCTS_H #define DATASTRUCTS_H #include <stdio.h> #include "Bool.h" // implemented as linked list typedef struct { // Raw char (*temperatureRawBuf)[16]; char (*bloodPressRawBuf)[40]; char (*pulseRateRawBuf)[24]; char (*respirationRateRawBuf)[16]; // Measurement seleciton Bool *tempSelection; Bool *bpSelection; Bool *pulseSelection; Bool *respSelection; // Variables to update values unsigned int *globalTime; unsigned int *measureInterval; // TCB *MeasureTCB; // TCB* ComputeTCB; } MeasureData; typedef struct { // Corrected char (*tempCorrectedBuf)[32]; char (*bloodPressCorrectedBuf)[48]; char (*pulseRateCorrectedBuf)[24]; char (*respirationRateCorrectedBuf)[16]; Bool *tempSelection; Bool *bpSelection; Bool *pulseSelection; Bool *respSelection; unsigned int *globalTime; unsigned int *computeInterval; } ComputeData; typedef struct { // Measured Raw data char (*temperatureRawBuf)[16]; char (*bloodPressRawBuf)[40]; char (*pulseRateRawBuf)[24]; char (*respirationRateRawBuf)[16]; char (*batteryState)[3]; char (*tempCorrectedBuf)[32]; char (*bloodPressCorrectedBuf)[48]; char (*pulseRateCorrectedBuf)[24]; char (*respirationRateCorrectedBuf)[16]; // Warning flags Bool *pulseWarning; Bool *pulseAlarm; Bool *tempWarning; Bool *tempAlarm; Bool *sysWarning; Bool *diasWarning; Bool *sysAlarm; Bool *respAlarm; Bool *batteryLow; unsigned int *globalTime; unsigned int *warningInterval; Bool *sysAlarmAcknowledge; unsigned int *sysAlarmTimer; Bool *tempAlarmAcknowledge; unsigned int *tempAlarmTimer; Bool *pulseAlarmAcknowledge; unsigned int *pulseAlarmTimer; Bool *respAlarmAcknowledge; unsigned int *respAlarmTimer; } WarningAlarmData; typedef struct { // Warning flags Bool *pulseWarning; Bool *pulseAlarm; Bool *tempWarning; Bool *tempAlarm; Bool *sysWarning; Bool *diasWarning; Bool *sysAlarm; Bool *respAlarm; Bool *batteryLow; /* unsigned char *bpOutOfRange; unsigned char *tempOutOfRange; unsigned char *pulseOutOfRange; */ // Data to be displayed char (*tempCorrectedBuf)[32]; char (*bloodPressCorrectedBuf)[48]; char (*pulseRateCorrectedBuf)[24]; char (*respirationRateCorrectedBuf)[16]; char (*batteryState)[3]; // Specified by lab spec, more fields to be added Bool *tempSelection; Bool *bpSelection; Bool *pulseSelection; Bool *respSelection; Bool *justPressed; unsigned int *globalTime; unsigned int *displayInterval; unsigned long *timeNow; Bool *sysAlarmAcknowledge; unsigned int *sysAlarmTimer; Bool *tempAlarmAcknowledge; unsigned int *tempAlarmTimer; Bool *pulseAlarmAcknowledge; unsigned int *pulseAlarmTimer; Bool *respAlarmAcknowledge; unsigned int *respAlarmTimer; Bool *sysFlash; Bool *diasFlash; Bool *tempFlash; Bool *pulseFlash; unsigned long *lastSysFlash; unsigned long *lastDiasFlash; unsigned long *lastTempFlash; unsigned long *lastPulseFlash; } TFTData; typedef struct { Bool *tempSelection; Bool *bpSelection; Bool *pulseSelection; Bool *respSelection; char (*tempCorrectedBuf)[32]; char (*bloodPressCorrectedBuf)[48]; char (*pulseRateCorrectedBuf)[24]; char (*respirationRateCorrectedBuf)[16]; unsigned int *globalTime; } ComData; typedef struct { char (*batteryState)[3]; // pointer to char array of size 5 unsigned int *globalTime; unsigned int *statusInterval; } StatusData; typedef struct TCB TCB; // This line is to be able to use TCB as a field inside TCB struct TCB { void *taskDataPtr; void (*taskPtr)(void*); struct TCB* next; // TCB* next struct TCB* prev; // TCB* prev }; #endif <file_sep>#include <Arduino.h> #include "DataStructs.h" // send a String to PS and receive a data packet from the PS void communicationSC(char *str, void *dataStruct) { // send process Serial1.write(str, 13); Serial1.flush(); // Wait print to complete // receive process if (str[0] == 'M') { char measureIn[14]; while ((Serial1.available() < 12)) { } Serial1.readBytes(measureIn, 12); Serial.print("This is measureIn: "); Serial.println(measureIn); // Store values in the measureIn to measureStruct MeasureData* mData = (MeasureData*) dataStruct; // Add statements checking if a variable is being tracked currently float oldpulse = (float) 100*((*(mData->pulseRateRawBuf))[0] - '0') + 10*((*(mData->pulseRateRawBuf))[1] - '0') + ((*(mData->pulseRateRawBuf))[2])- '0'; float oldtemp = (float) 10*((*(mData->temperatureRawBuf))[0] - '0') + ((*(mData->temperatureRawBuf))[1]) - '0'; float oldresp = (float) 10*((*(mData->respirationRateRawBuf))[0] - '0') + ((*(mData->respirationRateRawBuf))[1])- '0'; float pulse = (float) 100*(measureIn[7] - '0') + 10*(measureIn[8] - '0') + (measureIn[9])- '0'; float temp = (float) 10*(measureIn[0] - '0') + (measureIn[1] - '0'); float resp = (float) 10*(measureIn[10] - '0') + (measureIn[11])- '0'; Serial.print("This is oldpulse: "); Serial.println(oldpulse); Serial.print("This is pulse: "); Serial.println(pulse); Serial.print("This is oldtemp: "); Serial.println(oldtemp); Serial.print("This is temp: "); Serial.println(temp); Serial.print("This is oldresp: "); Serial.println(oldresp); Serial.print("This is resp: "); Serial.println(resp); if ((*(mData->tempSelection)) == TRUE && (temp > 1.15*oldtemp || temp < 0.85*oldtemp)){ //Serial.println("Do we enter the if gate?"); //Serial.print("tempraw before: "); Serial.println(*(mData->temperatureRawBuf)); for (int i = 7; i > 0; i--){ (*(mData->temperatureRawBuf))[2*i] = (*(mData->temperatureRawBuf))[2*(i-1)]; // temp (*(mData->temperatureRawBuf))[2*i+1] = (*(mData->temperatureRawBuf))[2*(i-1)+1]; } (*(mData->temperatureRawBuf))[0] = measureIn[0]; (*(mData->temperatureRawBuf))[1] = measureIn[1]; //Serial.print("tempraw after: "); Serial.println(*(mData->temperatureRawBuf)); } Serial.print("bpRaw before: "); Serial.println(*(mData->bloodPressRawBuf)); if ((*(mData->bpSelection)) == TRUE){ for (int i = 7; i > 0; i--){ (*(mData->bloodPressRawBuf))[3*i] = (*(mData->bloodPressRawBuf))[3*(i-1)]; // temp (*(mData->bloodPressRawBuf))[3*i+1] = (*(mData->bloodPressRawBuf))[3*(i-1)+1]; (*(mData->bloodPressRawBuf))[3*i+2] = (*(mData->bloodPressRawBuf))[3*(i-1)+2]; (*(mData->bloodPressRawBuf))[24+2*i] = (*(mData->bloodPressRawBuf))[24+2*(i-1)]; (*(mData->bloodPressRawBuf))[24+2*i+1] = (*(mData->bloodPressRawBuf))[24+2*(i-1)+1]; } (*(mData->bloodPressRawBuf))[0] = measureIn[2]; (*(mData->bloodPressRawBuf))[1] = measureIn[3]; (*(mData->bloodPressRawBuf))[2] = measureIn[4]; (*(mData->bloodPressRawBuf))[24] = measureIn[5]; (*(mData->bloodPressRawBuf))[25] = measureIn[6]; } Serial.print("bpRaw after: "); Serial.println(*(mData->bloodPressRawBuf)); if ((*(mData->pulseSelection)) == TRUE && (pulse> 1.15*oldpulse || pulse < 0.85*oldpulse)){ for (int i = 7; i > 0; i--){ (*(mData->pulseRateRawBuf))[3*i] = (*(mData->pulseRateRawBuf))[3*(i-1)]; // temp (*(mData->pulseRateRawBuf))[3*i+1] = (*(mData->pulseRateRawBuf))[3*(i-1)+1]; (*(mData->pulseRateRawBuf))[3*i+2] = (*(mData->pulseRateRawBuf))[3*(i-1)+2]; } (*(mData->pulseRateRawBuf))[0] = measureIn[7]; (*(mData->pulseRateRawBuf))[1] = measureIn[8]; (*(mData->pulseRateRawBuf))[2] = measureIn[9]; } Serial.print("PulseRaw after: "); Serial.println(*(mData->pulseRateRawBuf)); if ((*(mData->respSelection)) == TRUE && (resp > 1.15*oldresp || resp < 0.85*oldresp)){ for (int i = 7; i > 0; i--){ (*(mData->respirationRateRawBuf))[2*i] = (*(mData->respirationRateRawBuf))[2*(i-1)]; // temp (*(mData->respirationRateRawBuf))[2*i+1] = (*(mData->respirationRateRawBuf))[2*(i-1)+1]; } (*(mData->respirationRateRawBuf))[0] = measureIn[10]; (*(mData->respirationRateRawBuf))[1] = measureIn[11]; } Serial.print("respRaw after: "); Serial.println(*(mData->respirationRateRawBuf)); } else if (str[0] =='C') { char computeIn[17]; Serial.println("communication compute"); while ((Serial1.available() < 15)) { } Serial1.readBytes(computeIn, 15); ComputeData* cData = (ComputeData*) dataStruct; float oldpulse = (float) 100*((*(cData->pulseRateCorrectedBuf))[0] - '0') + 10*((*(cData->pulseRateCorrectedBuf))[1] - '0') + ((*(cData->pulseRateCorrectedBuf))[2])- '0'; float oldtemp = (float) 10*((*(cData->tempCorrectedBuf))[0] - '0') + ((*(cData->tempCorrectedBuf))[1]) - '0' + ((*(cData->tempCorrectedBuf))[3] - '0')/10; float oldresp = (float) 10*((*(cData->respirationRateCorrectedBuf))[0] - '0') + ((*(cData->respirationRateCorrectedBuf))[1])- '0'; float pulse = (float) 100*(computeIn[10] - '0') + 10*(computeIn[11] - '0') + (computeIn[12])- '0'; float temp = (float) 10*(computeIn[0] - '0') + (computeIn[1] - '0') + (computeIn[3] - '0')/10; float resp = (float) 10*(computeIn[13] - '0') + (computeIn[14])- '0'; Serial.println("Data received"); Serial.println(computeIn); Serial.println("Data printed"); // TODO: store values in the computeIn to computeStruct // need to wait until top level code is set /* (*(cData->tempCorrectedBuf))[0] = computeIn[0]; // temp (*(cData->tempCorrectedBuf))[1] = computeIn[1]; (*(cData->tempCorrectedBuf))[2] = computeIn[2]; (*(cData->tempCorrectedBuf))[3] = computeIn[3]; (*(cData->bloodPressCorrectedBuf))[0] = computeIn[4]; // sys (*(cData->bloodPressCorrectedBuf))[1] = computeIn[5]; (*(cData->bloodPressCorrectedBuf))[2] = computeIn[6]; (*(cData->bloodPressCorrectedBuf))[24] = computeIn[7]; //dias (*(cData->bloodPressCorrectedBuf))[25] = computeIn[8]; (*(cData->bloodPressCorrectedBuf))[26] = computeIn[9]; (*(cData->pulseRateCorrectedBuf))[0] = computeIn[10]; // pulse (*(cData->pulseRateCorrectedBuf))[1] = computeIn[11]; (*(cData->pulseRateCorrectedBuf))[2] = computeIn[12]; (*(cData->respirationRateCorrectedBuf))[0] = computeIn[13]; (*(cData->respirationRateCorrectedBuf))[1] = computeIn[14]; */ if ((*(cData->tempSelection)) == TRUE && (temp > 1.15*oldtemp || temp < 0.85*oldtemp)){ for (int i = 7; i > 0; i--) { (*(cData->tempCorrectedBuf))[4 * i] = (*(cData->tempCorrectedBuf))[4 * (i - 1)]; // temp (*(cData->tempCorrectedBuf))[4 * i + 1] = (*(cData->tempCorrectedBuf))[4 * (i - 1) + 1]; (*(cData->tempCorrectedBuf))[4 * i + 2] = (*(cData->tempCorrectedBuf))[4 * (i - 1) + 2]; (*(cData->tempCorrectedBuf))[4 * i + 3] = (*(cData->tempCorrectedBuf))[4 * (i - 1) + 3]; } (*(cData->tempCorrectedBuf))[0] = computeIn[0]; // temp (*(cData->tempCorrectedBuf))[1] = computeIn[1]; (*(cData->tempCorrectedBuf))[2] = computeIn[2]; (*(cData->tempCorrectedBuf))[3] = computeIn[3]; } if ((*(cData->bpSelection)) == TRUE) { for (int i = 7; i > 0; i--) { (*(cData->bloodPressCorrectedBuf))[3 * i] = (*(cData->bloodPressCorrectedBuf))[3 * (i - 1)]; // Sys (*(cData->bloodPressCorrectedBuf))[3 * i + 1] = (*(cData->bloodPressCorrectedBuf))[3 * (i - 1) + 1]; (*(cData->bloodPressCorrectedBuf))[3 * i + 2] = (*(cData->bloodPressCorrectedBuf))[3 * (i - 1) + 2]; (*(cData->bloodPressCorrectedBuf))[24 + 3 * i] = (*(cData->bloodPressCorrectedBuf))[24 + 3 * (i - 1)]; // Dias (*(cData->bloodPressCorrectedBuf))[24 + 3 * i + 1] = (*(cData->bloodPressCorrectedBuf))[24 + 3 * (i - 1) + 1]; (*(cData->bloodPressCorrectedBuf))[24 + 3 * i + 2] = (*(cData->bloodPressCorrectedBuf))[24 + 3 * (i - 1) + 2]; } (*(cData->bloodPressCorrectedBuf))[0] = computeIn[4]; // sys (*(cData->bloodPressCorrectedBuf))[1] = computeIn[5]; (*(cData->bloodPressCorrectedBuf))[2] = computeIn[6]; (*(cData->bloodPressCorrectedBuf))[24] = computeIn[7]; //dias (*(cData->bloodPressCorrectedBuf))[25] = computeIn[8]; (*(cData->bloodPressCorrectedBuf))[26] = computeIn[9]; } if ((*(cData->pulseSelection)) == TRUE && (pulse> 1.15*oldpulse || pulse < 0.85*oldpulse)){ for (int i = 7; i > 0; i--) { (*(cData->pulseRateCorrectedBuf))[3 * i] = (*(cData->pulseRateCorrectedBuf))[3 * (i - 1)]; // pulse (*(cData->pulseRateCorrectedBuf))[3 * i + 1] = (*(cData->pulseRateCorrectedBuf))[3 * (i - 1) + 1]; (*(cData->pulseRateCorrectedBuf))[3 * i + 2] = (*(cData->pulseRateCorrectedBuf))[3 * (i - 1) + 2]; } (*(cData->pulseRateCorrectedBuf))[0] = computeIn[10]; // pulse (*(cData->pulseRateCorrectedBuf))[1] = computeIn[11]; (*(cData->pulseRateCorrectedBuf))[2] = computeIn[12]; } if ((*(cData->respSelection)) == TRUE&& (resp > 1.15*oldresp || resp < 0.85*oldresp)){ for (int i = 7; i > 0; i--) { (*(cData->respirationRateCorrectedBuf))[2 * i] = (*(cData->respirationRateCorrectedBuf))[2 * (i - 1)]; // temp (*(cData->respirationRateCorrectedBuf))[2 * i + 1] = (*(cData->respirationRateCorrectedBuf))[2 * (i - 1) + 1]; } (*(cData->respirationRateCorrectedBuf))[0] = computeIn[13]; (*(cData->respirationRateCorrectedBuf))[1] = computeIn[14]; } } else if (str[0] == 'S') { char statusIn[5]; while (Serial1.available() < 3) { } Serial1.readBytes(statusIn, 3); Serial.println(statusIn); StatusData* sData = (StatusData*) dataStruct; (*(sData->batteryState))[0] = statusIn[0]; (*(sData->batteryState))[1] = statusIn[1]; (*(sData->batteryState))[2] = statusIn[2]; } } <file_sep>#include "DataStructs.h" #include "warningSC.h" #include "Bool.h" #include <Arduino.h> // ADD METHOD TO CHECK RESP OFF void annunciate(void *warningAlarmStruct) { WarningAlarmData *wData = (WarningAlarmData*) warningAlarmStruct; if ((*(wData->globalTime) % *(wData->warningInterval)) != 0){ return; } int batterystate = 100*((*(wData->batteryState))[0] - '0')+ 10*((*(wData->batteryState))[1] - '0') + ((*(wData->batteryState))[2]) - '0'; int sys = 100*((*(wData->bloodPressCorrectedBuf))[0] - '0')+ 10*((*(wData->bloodPressCorrectedBuf))[1] - '0') + ((*(wData->bloodPressCorrectedBuf))[2]) - '0'; int dias = 100*((*(wData->bloodPressCorrectedBuf))[24] - '0')+ 10*((*(wData->bloodPressCorrectedBuf))[25] - '0') + ((*(wData->bloodPressCorrectedBuf))[26]) - '0'; int pulse = 100*((*(wData->pulseRateCorrectedBuf))[0] - '0') + 10*((*(wData->pulseRateCorrectedBuf))[1] - '0') + ((*(wData->pulseRateCorrectedBuf))[2])- '0'; float temp = 10*((*(wData->tempCorrectedBuf))[0] - '0') + ((*(wData->tempCorrectedBuf))[1] - '0') + 0.1 * ((*(wData->tempCorrectedBuf)[3])- '0'); int resp = 10*((*(wData->respirationRateCorrectedBuf))[0] - '0') + ((*(wData->respirationRateCorrectedBuf))[1]- '0'); Serial.print("Batterystate: "); Serial.println(batterystate); Serial.print("Sys: "); Serial.println(sys); Serial.print("Dias: "); Serial.println(dias); Serial.print("Pulse: "); Serial.println(pulse); Serial.print("Temp: "); Serial.println(temp); Serial.print("Resp: "); Serial.println(resp); // Battery *(wData->batteryLow) = ((batterystate < 40) ? TRUE : FALSE); // syst if (sys > 156 || sys < 96){ // ALARM RANGE if (*(wData->sysAlarmAcknowledge)){ (*(wData->sysAlarmTimer))++; if (*(wData->sysAlarmTimer) > 5){ *(wData->sysAlarm) = TRUE; *(wData->sysAlarmAcknowledge) = FALSE; *(wData->sysAlarmTimer) = 0; } } else { *(wData->sysAlarm) = TRUE; *(wData->sysAlarmTimer) = 0; } } else if (sys > 136 || sys < 114){ // WARNING RANGE if (*(wData->sysAlarm)){ *(wData->sysAlarm) = FALSE; *(wData->sysAlarmTimer) = 0; } if (*(wData->sysAlarmAcknowledge)){ *(wData->sysAlarmAcknowledge) = FALSE; } *(wData->sysWarning) = TRUE; } else { // NORMAL RANGE if (*(wData->sysAlarm)){ *(wData->sysAlarm) = FALSE; *(wData->sysAlarmTimer) = 0; } if (*(wData->sysAlarmAcknowledge)){ *(wData->sysAlarmAcknowledge) = FALSE; } *(wData->sysWarning) = FALSE; } // dias if (dias > 84 || dias < 66){ // WARNING RANGE *(wData->diasWarning) = TRUE; } else { // NORMAL RANGE *(wData->diasWarning) = FALSE; } // pulserate if (pulse > 115 || pulse < 51){ // ALARM RANGE if (*(wData->pulseAlarmAcknowledge)){ (*(wData->pulseAlarmTimer))++; if (*(wData->pulseAlarmTimer) > 5){ *(wData->pulseAlarm) = TRUE; *(wData->pulseAlarmAcknowledge) = FALSE; *(wData->pulseAlarmTimer) = 0; } } else { *(wData->pulseAlarm) = TRUE; *(wData->pulseAlarmTimer) = 0; } } else if (pulse > 105 || pulse < 57){ // WARNING RANGE if (*(wData->pulseAlarm)){ *(wData->pulseAlarm) = FALSE; *(wData->pulseAlarmTimer) = 0; } if (*(wData->pulseAlarmAcknowledge)){ *(wData->pulseAlarmAcknowledge) = FALSE; } *(wData->pulseWarning) = TRUE; } else { // NORMAL RANGE if (*(wData->pulseAlarm)){ *(wData->pulseAlarm) = FALSE; *(wData->pulseAlarmTimer) = 0; } if (*(wData->pulseAlarmAcknowledge)){ *(wData->pulseAlarmAcknowledge) = FALSE; } *(wData->pulseWarning) = FALSE; } // Temperature if (temp > 43.5 || temp < 30.7){ // ALARM RANGE if (*(wData->tempAlarmAcknowledge)){ (*(wData->tempAlarmTimer))++; if (*(wData->tempAlarmTimer) > 5){ *(wData->tempAlarm) = TRUE; *(wData->tempAlarmAcknowledge) = FALSE; *(wData->tempAlarmTimer) = 0; } } else { *(wData->tempAlarm) = TRUE; *(wData->tempAlarmTimer) = 0; } } else if (temp > 39.7 || temp < 34.3){ // WARNING RANGE if (*(wData->tempAlarm)){ *(wData->tempAlarm) = FALSE; *(wData->tempAlarmTimer) = 0; } if (*(wData->tempAlarmAcknowledge)){ *(wData->tempAlarmAcknowledge) = FALSE; } *(wData->tempWarning) = TRUE; } else { // NORMAL RANGE if (*(wData->tempAlarm)){ *(wData->tempAlarm) = FALSE; *(wData->tempAlarmTimer) = 0; } if (*(wData->tempAlarmAcknowledge)){ *(wData->tempAlarmAcknowledge) = FALSE; } *(wData->tempWarning) = FALSE; } // Respiratory rate if (resp > 23 || resp < 11){ // ALARM RANGE if (*(wData->respAlarmAcknowledge)){ (*(wData->respAlarmTimer))++; if (*(wData->respAlarmTimer) > 5){ *(wData->respAlarm) = TRUE; *(wData->respAlarmAcknowledge) = FALSE; *(wData->respAlarmTimer) = 0; } } else { *(wData->respAlarm) = TRUE; *(wData->respAlarmTimer) = 0; } } else { // NORMAL RANGE if (*(wData->respAlarm)){ *(wData->respAlarm) = FALSE; *(wData->respAlarmTimer) = 0; } if (*(wData->respAlarmAcknowledge)){ *(wData->respAlarmAcknowledge) = FALSE; } } } <file_sep>#ifdef __cplusplus extern "C" { #endif #include "Bool.h" #include "DataStructs.h" //#include "schedulerSC.h" #ifdef __cplusplus } #endif #include "warningSC.h" #include "computeSC.h" #include "TFTKeypad.h" #include "batteryStatusSC.h" #include "measureSC.h" TCB* head; TCB* tail; TCB MeasureTCB; TCB ComputeTCB; TCB tftTCB; TCB WarningAlarmTCB; TCB StatusTCB; unsigned int globalTime = 0; // Change this to millis Bool sysMeasureComplete = FALSE; Bool diaMeasureComplete = FALSE; Bool tempIncrease = FALSE; Bool bpIncrease = FALSE; unsigned int numOfMeasureCalls = 0; const unsigned int measureInterval = 5; const unsigned int computeInterval = 5; const unsigned int displayInterval = 5; const unsigned int warningInterval = 1; const unsigned int statusInterval = 5; char bloodPressCorrectedBuf[48] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char tempCorrectedBuf[32] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char pulseRateCorrectedBuf[24] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char respirationRateCorrectedBuf[16]={'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; // Maybe change the size of this here and everywhere else char bloodPressRawBuf[40] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char temperatureRawBuf[16] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char pulseRateRawBuf[24] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char respirationRateRawBuf[16] = {'0','0','0','0','0','0','0','0', '0','0','0','0','0','0','0','0'}; char batteryState[3] = {'0','0','0'}; double vReal[256]; double vImag[256]; double freqBuf[16]; Bool pulseWarning = FALSE; Bool pulseAlarm = FALSE; Bool tempWarning = FALSE; Bool tempAlarm = FALSE; Bool sysWarning = FALSE; Bool diasWarning = FALSE; Bool sysAlarm = FALSE; Bool respAlarm = FALSE; Bool batteryLow = FALSE; /* Bool bpHigh = FALSE; Bool bpLow = FALSE; Bool tempOff = FALSE; Bool pulseOff = FALSE; Bool batteryLow = FALSE; Bool sysAlarm = FALSE; Bool respOff = FALSE; */ Bool tempSelection = TRUE; Bool bpSelection = TRUE; Bool pulseSelection = TRUE; Bool respSelection = TRUE; Bool EKGSelection = TRUE; Bool sysAlarmAcknowledge = TRUE; Bool tempAlarmAcknowledge = TRUE; Bool pulseAlarmAcknowledge = TRUE; Bool respAlarmAcknowledge = TRUE; unsigned int sysAlarmTimer = 0; unsigned int tempAlarmTimer = 0; unsigned int pulseAlarmTimer = 0; unsigned int respAlarmTimer = 0; Bool sysFlash = FALSE; Bool diasFlash = FALSE; Bool tempFlash = FALSE; Bool pulseFlash = FALSE; unsigned long lastSysFlash = 0; unsigned long lastDiasFlash = 0; unsigned long lastTempFlash = 0; unsigned long lastPulseFlash = 0; unsigned long timeNow = 0; Bool justPressed = FALSE; Bool displayOff = FALSE; MeasureData mData; ComputeData cData; TFTData dData; WarningAlarmData wData; StatusData stData; EKGCapData ecData; EKGProData epData; void setup(void) { Serial1.begin(9600); //Serial.begin(9600); // Add variables to measure struct mData.globalTime = &globalTime; mData.measureInterval = &measureInterval; // Raw data mData.bloodPressRawBuf = &bloodPressRawBuf; mData.pulseRateRawBuf = &pulseRateRawBuf; mData.temperatureRawBuf = &temperatureRawBuf; mData.respirationRateRawBuf = &respirationRateRawBuf; mData.vReal = &vReal; mData.vImag = &vImag; // measure selections mData.tempSelection = &tempSelection; mData.bpSelection = &bpSelection; mData.pulseSelection = &pulseSelection; mData.respSelection = &respSelection; // Add variables to compute struct cData.globalTime = &globalTime; cData.computeInterval = &computeInterval; cData.tempSelection = &tempSelection; cData.bpSelection = &bpSelection; cData.pulseSelection = &pulseSelection; cData.respSelection = &respSelection; cData.tempCorrectedBuf = &tempCorrectedBuf; cData.bloodPressCorrectedBuf = &bloodPressCorrectedBuf; cData.pulseRateCorrectedBuf = &pulseRateCorrectedBuf; cData.respirationRateCorrectedBuf = &respirationRateCorrectedBuf; cData.freqBuf = &freqBuf; cData.vReal = &vReal; cData.vImag = &vImag; // Add variables to display struct dData.globalTime = &globalTime; dData.displayInterval = &displayInterval; dData.bloodPressCorrectedBuf = &bloodPressCorrectedBuf; dData.pulseRateCorrectedBuf = &pulseRateCorrectedBuf; dData.tempCorrectedBuf = &tempCorrectedBuf; dData.respirationRateCorrectedBuf = &respirationRateCorrectedBuf; dData.freqBuf = &freqBuf; dData.pulseWarning = &pulseWarning; dData.pulseAlarm = &pulseAlarm; dData.tempWarning = &tempWarning; dData.tempAlarm = &tempAlarm; dData.sysWarning = &sysWarning; dData.diasWarning = &diasWarning; dData.sysAlarm = &sysAlarm; dData.respAlarm = &respAlarm; dData.batteryLow = &batteryLow; dData.sysAlarmAcknowledge = &sysAlarmAcknowledge; dData.sysAlarmTimer = &sysAlarmTimer; dData.tempAlarmAcknowledge = &tempAlarmAcknowledge; dData.tempAlarmTimer = &tempAlarmTimer; dData.pulseAlarmAcknowledge = &pulseAlarmAcknowledge; dData.pulseAlarmTimer = &pulseAlarmTimer; dData.respAlarmAcknowledge = &respAlarmAcknowledge; dData.respAlarmTimer = &respAlarmTimer; dData.batteryState = &batteryState; dData.displayInterval = &displayInterval; dData.tempSelection = &tempSelection; dData.bpSelection = &bpSelection; dData.pulseSelection = &pulseSelection; dData.respSelection = &respSelection; dData.EKGSelection = &EKGSelection; dData.sysAlarm = &sysAlarm; dData.timeNow = &timeNow; dData.justPressed = &justPressed; dData.lastSysFlash = &lastSysFlash; dData.sysFlash = &sysFlash; dData.lastDiasFlash = &lastDiasFlash; dData.diasFlash = &diasFlash; dData.lastTempFlash = &lastTempFlash; dData.tempFlash = &tempFlash; dData.lastPulseFlash = &lastPulseFlash; dData.pulseFlash = &pulseFlash; dData.displayOff = &displayOff; // Add values to warning/alarm struct wData.globalTime = &globalTime; wData.warningInterval = &warningInterval; // Raw Data wData.bloodPressRawBuf = &bloodPressRawBuf; wData.pulseRateRawBuf = &pulseRateRawBuf; wData.temperatureRawBuf = &temperatureRawBuf; /* * Is mData.respirationRateRawBuf = &respirationRateRawBuf; * supposed to be here?? */ wData.respirationRateRawBuf = &respirationRateRawBuf; /* * Should it be wData.respirationRateRawBuf = &respirationRateRawBuf;? */ wData.bloodPressCorrectedBuf = &bloodPressCorrectedBuf; wData.pulseRateCorrectedBuf = &pulseRateCorrectedBuf; wData.tempCorrectedBuf = &tempCorrectedBuf; wData.respirationRateCorrectedBuf = &respirationRateCorrectedBuf; wData.batteryState = &batteryState; wData.pulseWarning = &pulseWarning; wData.pulseAlarm = &pulseAlarm; wData.tempWarning = &tempWarning; wData.tempAlarm = &tempAlarm; wData.sysWarning = &sysWarning; wData.diasWarning = &diasWarning; wData.sysAlarm = &sysAlarm; wData.respAlarm = &respAlarm; wData.batteryLow = &batteryLow; wData.sysAlarmAcknowledge = &sysAlarmAcknowledge; wData.sysAlarmTimer = &sysAlarmTimer; wData.tempAlarmAcknowledge = &tempAlarmAcknowledge; wData.tempAlarmTimer = &tempAlarmTimer; wData.pulseAlarmAcknowledge = &pulseAlarmAcknowledge; wData.pulseAlarmTimer = &pulseAlarmTimer; wData.respAlarmAcknowledge = &respAlarmAcknowledge; wData.respAlarmTimer = &respAlarmTimer; ecData.vReal = &vReal; ecData.vImag = &vImag; epData.vReal = &vReal; epData.vImag = &vImag; epData.freqBuf = &freqBuf; // Add data to status struct stData.globalTime = &globalTime; stData.statusInterval = &statusInterval; stData.batteryState = &batteryState; // Initialize the TCBs MeasureTCB.taskPtr = &measurerSC; MeasureTCB.taskDataPtr = (void*)&mData; MeasureTCB.prev = NULL; MeasureTCB.next = &StatusTCB; ComputeTCB.taskPtr = &computeSC; ComputeTCB.taskDataPtr = (void*)&cData; ComputeTCB.prev = NULL; // Compute is by default not part of the queue ComputeTCB.next = NULL; StatusTCB.taskPtr = &batteryStatusSC; StatusTCB.taskDataPtr = (void*)&stData; StatusTCB.prev = &MeasureTCB; StatusTCB.next = &WarningAlarmTCB; WarningAlarmTCB.taskPtr = &annunciate; WarningAlarmTCB.taskDataPtr = (void*)&wData; WarningAlarmTCB.prev = &StatusTCB; WarningAlarmTCB.next = &tftTCB; tftTCB.taskPtr = &displayLoop; tftTCB.taskDataPtr = (void*)&dData; tftTCB.prev = &WarningAlarmTCB; tftTCB.next = NULL; // Initialize the taskQueue head = &MeasureTCB; tail = &tftTCB; setupDisplay(&tftTCB); //Serial.println("End of setup"); delay(100); /* while (1) { if (Serial.available() > 0) { char inbyte = Serial.read(); if (inbyte == 'I') { break; } } } Serial.println("EE 474 Medical Monitoring System"); Serial.println("Patient: someone"); Serial.println("Doctors: <NAME>, Zixiang"); */ } void loop(void) { //Serial.println("Start of loop: are we here?"); timeNow = millis(); TCB* curr = head; TCB* oldcurr; while (curr != tail){ //Serial.println("Task begun");delay(50); //Serial.println("Inside task loop"); (*(curr->taskPtr))(curr->taskDataPtr); if ((curr == &MeasureTCB) && (globalTime % measureInterval == 0)){ //Serial.println("adding compute"); insertNode(&ComputeTCB, &MeasureTCB, head, tail); //Serial.println("compute added"); } oldcurr = curr; curr = curr->next; if ((oldcurr == &ComputeTCB) && (globalTime % measureInterval == 0)){ deleteNode(&ComputeTCB,head,tail); } } // While loop ends before tail is executed // So we call it one last time to run through everything (*(curr->taskPtr))(curr->taskDataPtr); //Serial.println("Done with loop"); delay(50); // Delay one second globalTime++; } void deleteNode(struct TCB* node, struct TCB* head, struct TCB* tail) { TCB* curr; TCB* prevNode; TCB* nextNode; if (node == head){ // Node is head // 1. Set head->next to head curr = head; head = head->next; // 2. Set internal pointers to NULL curr->next = NULL; } else if (node == tail){ // Node is tail // 1. Set tail->prev to tail curr = tail; tail = tail->prev; // 2. Set internal pointer to NULL curr->prev = NULL; } else { // Node is somewhere in between // 1. Find node curr = head->next; while(node != curr){ curr = curr->next; } // 2. Node found, update neighbor pointers, set internal pointers to NULL prevNode = curr->prev; nextNode = curr->next; prevNode->next = nextNode; nextNode->prev = prevNode; curr->next = NULL; curr->prev = NULL; } return; } // Do insert(TCBToInsert, TCBtoadd it to after) // So calling insert(compute, measure) adds compute after measure void insertNode(struct TCB* node, struct TCB* precNode, struct TCB* head, struct TCB* tail) { // Since C lacks default parameters, // The user has to input NULL as 2nd arg if not specified if (NULL == precNode){ precNode = tail; } if(NULL == head){ // If the head pointer is pointing to nothing head = node; // set the head and tail pointers to point to this node tail = node; } else if (tail == precNode) { // otherwise, head is not NULL, add the node to the end of the list tail->next = node; node->prev = tail; // note that the tail pointer is still pointing // to the prior last node at this point tail = node; // update the tail pointer } else { TCB* curr = precNode->next; precNode->next = node; curr->prev = node; node->next=curr; node->prev = precNode; } return; } void serialEvent() { while (Serial.available() > 0) { char inbyte = Serial.read(); if (inbyte == 'P') { Serial.println("Paused"); while (inbyte != 'S') { if (Serial.available() > 0) { inbyte = Serial.read(); } } Serial.println("Resumed"); } /* else if (inbyte == 'S') { // schecule measure } */ else if (inbyte == 'D') { displayOff = (displayOff) ? FALSE : TRUE; if (displayOff){ Serial.println("Display switched off"); } else { Serial.println("Display switched on"); } } else if (inbyte == 'M') { // print all measure data Serial.println("Printing latest measured data"); Serial.print("Blood pressure: "); Serial.print(bloodPressRawBuf[0]);Serial.print(bloodPressRawBuf[1]); Serial.print(bloodPressRawBuf[2]); Serial.print (" / "); Serial.print(bloodPressRawBuf[24]); Serial.println(bloodPressRawBuf[25]); Serial.print("Body temperature: "); Serial.print(temperatureRawBuf[0]); Serial.println(temperatureRawBuf[1]); Serial.print("Pulse rate: "); Serial.print(pulseRateRawBuf[0]);Serial.print(pulseRateRawBuf[1]);Serial.println(pulseRateRawBuf[2]); Serial.print("Respiratory rate: "); Serial.print(respirationRateRawBuf[0]); Serial.println(respirationRateRawBuf[1]); Serial.print("EKG rate: "); Serial.println(freqBuf[0]); Serial.println("All the latest measured data printed"); } else if (inbyte == 'W') { // print all warning-alarm data Serial.println("\nPrinting latest warning/alarm data"); Serial.print("Blood pressure: "); Serial.print(bloodPressCorrectedBuf[0]);Serial.print(bloodPressCorrectedBuf[1]);Serial.print(bloodPressCorrectedBuf[2]); Serial.print (" / "); Serial.print(bloodPressCorrectedBuf[24]); Serial.print(bloodPressCorrectedBuf[25]); Serial.print(bloodPressCorrectedBuf[26]); if (sysAlarm) { Serial.print(" ALARM: Systolic out of range "); } else if (sysWarning || diasWarning) { Serial.print(" WARNING: "); if (sysWarning && diasWarning){ Serial.print("Systolic & Diastolic out of range"); } else if(sysWarning){ Serial.print("Systolic out of range"); } else { Serial.print("Diastolic out of range"); } } Serial.println(""); Serial.print("Body temperature: "); Serial.print(tempCorrectedBuf[0]); Serial.print(tempCorrectedBuf[1]);Serial.print(tempCorrectedBuf[2]);Serial.print(tempCorrectedBuf[3]); if (tempAlarm){ Serial.print(" ALARM: Temperature out of range "); } else if (tempWarning) { Serial.print(" Warning: Temperature out of range "); } Serial.println(""); Serial.print("Pulse rate: "); Serial.print(pulseRateCorrectedBuf[0]);Serial.print(pulseRateCorrectedBuf[1]);Serial.print(pulseRateCorrectedBuf[2]); if (pulseAlarm){ Serial.print(" ALARM: Pulserate out of range "); } else if (pulseWarning) { Serial.print(" Warning: Pulserate out of range "); } Serial.println(""); Serial.print("Respiratory rate: "); Serial.print(respirationRateCorrectedBuf[0]); Serial.print(respirationRateCorrectedBuf[1]); if (respAlarm){ Serial.print(" ALARM: Respiratory rate out of range"); } Serial.println(""); Serial.print("EKG rate: "); Serial.println(freqBuf[0]); Serial.println("All the latest warning/alarm data printed"); } else { Serial.println("Invalid Input"); } } } <file_sep>#ifndef DATASTRUCTSPS_H #define DATASTRUCTSPS_H #include <stdio.h> #include "Bool.h" typedef struct { // Raw unsigned int *temperatureRaw; unsigned int *systolicPressRaw; unsigned int *diastolicPressRaw; unsigned int *pulseRateRaw; // Flags for simulating Bool *sysMeasureComplete; Bool *diaMeasureComplete; Bool *tempIncrease; Bool *bpIncrease; // Flags for selection Bool *tempSelection; Bool *bpSelection; Bool *pulseSelection; // For simulation unsigned int *numOfMeasureCalls; } MeasureDataPS; typedef struct { // Raw unsigned int *temperatureRaw; unsigned int *systolicPressRaw; unsigned int *diastolicPressRaw; unsigned int *pulseRateRaw; // Corrected float *tempCorrected; unsigned int *systolicPressCorrected; unsigned int *diastolicPressCorrected; unsigned int *pulseRateCorrected; // Flags Bool *tempSelection; Bool *bpSelection; Bool *pulseSelection; } ComputeDataPS; /* typedef struct { unsigned int *globalTime; unsigned int *displayInterval; unsigned char **tempCorrected; unsigned char **sysPressCorrected; unsigned char **diasCorrected; unsigned char **prCorrected; unsigned short *batteryState; Bool *bpHigh; Bool *bpLow; Bool *tempOff; Bool *pulseOff; Bool *batteryLow; unsigned char *bpOutOfRange; unsigned char *tempOutOfRange; unsigned char *pulseOutOfRange; double *tempNumeric; unsigned int *sysNumeric; unsigned int *diasNumeric; unsigned int *pulseNumeric; unsigned int *temperatureRaw; unsigned int *systolicPressRaw; unsigned int *diastolicPressRaw; unsigned int *pulseRateRaw; } DisplayData; */ typedef struct { // Raw data unsigned int *temperatureRaw; unsigned int *systolicPressRaw; unsigned int *diastolicPressRaw; unsigned int *pulseRateRaw; unsigned short *batteryState; // warning & alarm flags Bool *bpOutOfRange; Bool *tempOutOfRange; Bool *pulseOutOfRange; Bool *bpHigh; Bool *bpAlarmHigh; unsigned int *bpAlarmCount; Bool *bpOff; Bool *tempOff; Bool *pulseOff; Bool *batteryLow; Bool *bpSelection; Bool *tempSelection; Bool *pulseSelection; } WarningAlarmDataPS; typedef struct { unsigned short *batteryState; } StatusDataPS; typedef struct { unsigned int *globalTime; } PeripheralComPS; /* typedef struct SchedulerStruct { // None for this lab // may be used for future labs } SchedulerData; */ typedef struct { void *taskDataPtr; void (*taskPtr)(void*); } TCB; #endif <file_sep>#ifndef DATASTRUCTS_H #define DATASTRUCTS_H #include <stdio.h> #include "Bool.h" typedef struct { unsigned int *globalTime; unsigned int *measureInterval; unsigned int *temperatureRaw; unsigned int *systolicPressRaw; unsigned int *diastolicPressRaw; unsigned int *pulseRateRaw; Bool *sysMeasureComplete; Bool *diaMeasureComplete; Bool *tempIncrease; Bool *bpIncrease; unsigned int *numOfMeasureCalls; } MeasureData; typedef struct { unsigned int *globalTime; unsigned int *computeInterval; // Raw unsigned int *temperatureRaw; unsigned int *systolicPressRaw; unsigned int *diastolicPressRaw; unsigned int *pulseRateRaw; // Corrected unsigned char **tempCorrected; unsigned char **sysPressCorrected; unsigned char **diasCorrected; unsigned char **prCorrected; double *tempNumeric; unsigned int *sysNumeric; unsigned int *diasNumeric; unsigned int *pulseNumeric; } ComputeData; typedef struct { unsigned int *globalTime; unsigned int *displayInterval; unsigned char **tempCorrected; unsigned char **sysPressCorrected; unsigned char **diasCorrected; unsigned char **prCorrected; unsigned short *batteryState; Bool *bpHigh; Bool *bpLow; Bool *tempOff; Bool *pulseOff; Bool *batteryLow; unsigned char *bpOutOfRange; unsigned char *tempOutOfRange; unsigned char *pulseOutOfRange; double *tempNumeric; unsigned int *sysNumeric; unsigned int *diasNumeric; unsigned int *pulseNumeric; unsigned int *temperatureRaw; unsigned int *systolicPressRaw; unsigned int *diastolicPressRaw; unsigned int *pulseRateRaw; } DisplayData; typedef struct { unsigned int *globalTime; unsigned int *statusInterval; unsigned int *warningInterval; unsigned int *temperatureRaw; unsigned int *systolicPressRaw; unsigned int *diastolicPressRaw; unsigned int *pulseRateRaw; unsigned short *batteryState; unsigned char *bpOutOfRange; unsigned char *tempOutOfRange; unsigned char *pulseOutOfRange; Bool *bpHigh; Bool *bpLow; Bool *tempOff; Bool *pulseOff; Bool *batteryLow; double *tempNumeric; unsigned int *sysNumeric; unsigned int *diasNumeric; unsigned int *pulseNumeric; } WarningAlarmData; typedef struct { unsigned int *globalTime; unsigned short *batteryState; unsigned int *statusInterval; } StatusData; /* typedef struct SchedulerStruct { // None for this lab // may be used for future labs } SchedulerData; */ typedef struct { void *taskDataPtr; void (*taskPtr)(void*); } TCB; #endif <file_sep>#ifdef __cplusplus extern "C" { #endif #include "Bool.h" #include "DataStructs.h" #include "warningSC.h" //#include "schedulerSC.h" #ifdef __cplusplus } #endif #include "computeSC.h" #include "TFTKeypad.h" #include "batteryStatusSC.h" #include "measureSC.h" TCB* head; TCB* tail; TCB MeasureTCB; TCB ComputeTCB; TCB tftTCB; TCB WarningAlarmTCB; TCB StatusTCB; unsigned int globalTime = 0; // Change this to millis Bool sysMeasureComplete = FALSE; Bool diaMeasureComplete = FALSE; Bool tempIncrease = FALSE; Bool bpIncrease = FALSE; unsigned int numOfMeasureCalls = 0; const unsigned int measureInterval = 5; const unsigned int computeInterval = 5; const unsigned int displayInterval = 5; const unsigned int warningInterval = 1; const unsigned int statusInterval = 5; char bloodPressCorrectedBuf[48] = {}; char tempCorrectedBuf[32] = {}; char pulseRateCorrectedBuf[24] = {}; char bloodPressRawBuf[40] = {}; char temperatureRawBuf[16] = {}; char pulseRateRawBuf[24] = {}; char batteryState[3]; /* unsigned char bpOutOfRange = 0; unsigned char tempOutOfRange = 0; unsigned char pulseOutOfRange = 0; */ Bool bpHigh = FALSE; Bool bpLow = FALSE; Bool tempOff = FALSE; Bool pulseOff = FALSE; Bool batteryLow = FALSE; Bool sysAlarm = FALSE; Bool tempSelection = TRUE; Bool bpSelection = TRUE; Bool pulseSelection = TRUE; Bool alarmAcknowledge = TRUE; // type TBD unsigned int alarmTimer = 0; unsigned long timeNow = 0; Bool justPressed = FALSE; MeasureData mData; ComputeData cData; TFTData dData; WarningAlarmData wData; StatusData stData; void setup(void) { Serial1.begin(9600); Serial.begin(9600); // Add variables to measure struct mData.globalTime = &globalTime; mData.measureInterval = &measureInterval; // Raw data mData.bloodPressRawBuf = &bloodPressRawBuf; mData.pulseRateRawBuf = &pulseRateRawBuf; mData.temperatureRawBuf = &temperatureRawBuf; // measure selections mData.tempSelection = &tempSelection; mData.bpSelection = &bpSelection; mData.pulseSelection = &pulseSelection; // mData.MeasureTCB = &MeasureTCB; // mData.ComputeTCB = &ComputeTCB; // Add variables to compute struct cData.globalTime = &globalTime; cData.computeInterval = &computeInterval; cData.tempSelection = &tempSelection; cData.bpSelection = &bpSelection; cData.pulseSelection = &pulseSelection; cData.tempCorrectedBuf = &tempCorrectedBuf; cData.bloodPressCorrectedBuf = &bloodPressCorrectedBuf; cData.pulseRateCorrectedBuf = &pulseRateCorrectedBuf; // Add variables to display struct dData.globalTime = &globalTime; dData.displayInterval = &displayInterval; dData.bloodPressCorrectedBuf = &bloodPressCorrectedBuf; dData.pulseRateCorrectedBuf = &pulseRateCorrectedBuf; dData.tempCorrectedBuf = &tempCorrectedBuf; dData.bpHigh = &bpHigh; dData.bpLow = &bpLow; dData.tempOff = &tempOff; dData.pulseOff = &pulseOff; /* dData.bpOutOfRange = &bpOutOfRange; dData.pulseOutOfRange = &pulseOutOfRange; dData.tempOutOfRange = &tempOutOfRange; */ dData.batteryLow = &batteryLow; dData.batteryState = &batteryState; dData.displayInterval = &displayInterval; dData.tempSelection = &tempSelection; dData.bpSelection = &bpSelection; dData.pulseSelection = &pulseSelection; dData.alarmAcknowledge = &alarmAcknowledge; dData.alarmTimer = &alarmTimer; dData.sysAlarm = &sysAlarm; dData.timeNow = &timeNow; dData.justPressed = &justPressed; // Add values to warning/alarm struct wData.globalTime = &globalTime; wData.warningInterval = &warningInterval; // Raw Data wData.bloodPressRawBuf = &bloodPressRawBuf; wData.pulseRateRawBuf = &pulseRateRawBuf; wData.temperatureRawBuf = &temperatureRawBuf; wData.bloodPressCorrectedBuf = &bloodPressCorrectedBuf; wData.pulseRateCorrectedBuf = &pulseRateCorrectedBuf; wData.tempCorrectedBuf = &tempCorrectedBuf; /* wData.bpOutOfRange = &bpOutOfRange; wData.pulseOutOfRange = &pulseOutOfRange; wData.tempOutOfRange = &tempOutOfRange; */ wData.batteryState = &batteryState; wData.bpHigh = &bpHigh; wData.bpLow = &bpLow; wData.tempOff = &tempOff; wData.pulseOff = &pulseOff; wData.batteryLow = &batteryLow; wData.sysAlarm = &sysAlarm; wData.alarmAcknowledge = &alarmAcknowledge; wData.alarmTimer = &alarmTimer; // Add data to status struct stData.globalTime = &globalTime; stData.statusInterval = &statusInterval; stData.batteryState = &batteryState; // Initialize the TCBs MeasureTCB.taskPtr = &measurerSC; MeasureTCB.taskDataPtr = (void*)&mData; MeasureTCB.prev = NULL; MeasureTCB.next = &StatusTCB; ComputeTCB.taskPtr = &computeSC; ComputeTCB.taskDataPtr = (void*)&cData; ComputeTCB.prev = NULL; // Compute is by default not part of the queue ComputeTCB.next = NULL; StatusTCB.taskPtr = &batteryStatusSC; StatusTCB.taskDataPtr = (void*)&stData; StatusTCB.prev = &MeasureTCB; StatusTCB.next = &WarningAlarmTCB; WarningAlarmTCB.taskPtr = &annunciate; WarningAlarmTCB.taskDataPtr = (void*)&wData; WarningAlarmTCB.prev = &StatusTCB; WarningAlarmTCB.next = &tftTCB; tftTCB.taskPtr = &displayLoop; tftTCB.taskDataPtr = (void*)&dData; tftTCB.prev = &WarningAlarmTCB; tftTCB.next = NULL; // Initialize the taskQueue head = &MeasureTCB; tail = &tftTCB; setupDisplay(&tftTCB); //Serial.println("End of setup"); } void loop(void) { //Serial.println("Start of loop: are we here?"); timeNow = millis(); TCB* curr = head; TCB* oldcurr; while (curr != tail){ //Serial.println("Task begun");delay(50); (*(curr->taskPtr))(curr->taskDataPtr); if ((curr == &MeasureTCB) && (globalTime % measureInterval == 0)){ insertNode(&ComputeTCB, &MeasureTCB, head, tail); } oldcurr = curr; curr = curr->next; if ((oldcurr == &ComputeTCB) && (globalTime % measureInterval == 0)){ deleteNode(&ComputeTCB,head,tail); } } // While loop ends before tail is executed // So we call it one last time to run through everything (*(curr->taskPtr))(curr->taskDataPtr); // Delay one second globalTime++; Serial.print("Latest measured temp value: "); Serial.print(temperatureRawBuf[0]); Serial.print(temperatureRawBuf[1]); Serial.print(temperatureRawBuf[2]); Serial.println(temperatureRawBuf[3]); Serial.print("Current corrected temp value: "); Serial.print(tempCorrectedBuf[0]); Serial.print(tempCorrectedBuf[1]); Serial.print(tempCorrectedBuf[2]); Serial.println(tempCorrectedBuf[3]); Serial.print("Current corrected pulse value: "); Serial.print(pulseRateCorrectedBuf[0]); Serial.print(pulseRateCorrectedBuf[1]); Serial.println(pulseRateCorrectedBuf[2]); } void deleteNode(struct TCB* node, struct TCB* head, struct TCB* tail) { TCB* curr; TCB* prevNode; TCB* nextNode; if (node == head){ // Node is head // 1. Set head->next to head curr = head; head = head->next; // 2. Set internal pointers to NULL curr->next = NULL; } else if (node == tail){ // Node is tail // 1. Set tail->prev to tail curr = tail; tail = tail->prev; // 2. Set internal pointer to NULL curr->prev = NULL; } else { // Node is somewhere in between // 1. Find node curr = head->next; while(node != curr){ curr = curr->next; } // 2. Node found, update neighbor pointers, set internal pointers to NULL prevNode = curr->prev; nextNode = curr->next; prevNode->next = nextNode; nextNode->prev = prevNode; curr->next = NULL; curr->prev = NULL; } return; } // Do insert(TCBToInsert, TCBtoadd it to after) // So calling insert(compute, measure) adds compute after measure void insertNode(struct TCB* node, struct TCB* precNode, struct TCB* head, struct TCB* tail) { // Since C lacks default parameters, // The user has to input NULL as 2nd arg if not specified if (NULL == precNode){ precNode = tail; } if(NULL == head){ // If the head pointer is pointing to nothing head = node; // set the head and tail pointers to point to this node tail = node; } else if (tail == precNode) { // otherwise, head is not NULL, add the node to the end of the list tail->next = node; node->prev = tail; // note that the tail pointer is still pointing // to the prior last node at this point tail = node; // update the tail pointer } else { TCB* curr = precNode->next; precNode->next = node; curr->prev = node; node->next=curr; node->prev = precNode; } return; } <file_sep>#include <stdio.h> #include "peripheralCom.h" #include <Arduino.h> int globalCounter; // send a String to PS and receive a data packet from the PS void communicationSC(char *data, void *dataStruct) { // send process Serial.write(data); // send // always call warningAlarm if (data[0] == 'M') { } else if (data[0] == 'C'){ } else if (data[0] == 'B'){ } // receive process // TODO: implement } <file_sep>void EKGProcess(void *EKGStruct);<file_sep>#include "DataStructs.h" #include <stdio.h> #include "TFTKeypad.h" #include "Bool.h" // IMPORTANT: Elegoo_TFTLCD LIBRARY MUST BE SPECIFICALLY // CONFIGURED FOR EITHER THE TFT SHIELD OR THE BREAKOUT BOARD. // SEE RELEVANT COMMENTS IN Elegoo_TFTLCD.h FOR SETUP. //Technical support:<EMAIL> //void drawDefaultMode(); #include <Elegoo_GFX.h> // Core graphics library #include <Elegoo_TFTLCD.h> // Hardware-specific library #include <TouchScreen.h> //void drawAnnunciate(); // Should be covered by using headerfile //void drawMenu(); // The control pins for the LCD can be assigned to any digital or // analog pins...but we'll use the analog pins as this allows us to // double up the pins with the touch screen (see the TFT paint example). #define LCD_CS A3 // Chip Select goes to Analog 3 #define LCD_CD A2 // Command/Data goes to Analog 2 #define LCD_WR A1 // LCD Write goes to Analog 1 #define LCD_RD A0 // LCD Read goes to Analog 0 #define LCD_RESET A4 // Can alternately just connect to Arduino's reset pinheader at the end of the board). // Assign human-readable names to some common 16-bit color values: #define BLACK 0x0000 #define BLUE 0x001F #define RED 0xF800 #define GREEN 0x07E0 #define CYAN 0x07FF #define MAGENTA 0xF81F #define YELLOW 0xFFE0 #define WHITE 0xFFFF #define ORANGE 0xFD20 // Color definitions #define ILI9341_BLACK 0x0000 /* 0, 0, 0 */ #define ILI9341_NAVY 0x000F /* 0, 0, 128 */ #define ILI9341_DARKGREEN 0x03E0 /* 0, 128, 0 */ #define ILI9341_DARKCYAN 0x03EF /* 0, 128, 128 */ #define ILI9341_MAROON 0x7800 /* 128, 0, 0 */ #define ILI9341_PURPLE 0x780F /* 128, 0, 128 */ #define ILI9341_OLIVE 0x7BE0 /* 128, 128, 0 */ #define ILI9341_LIGHTGREY 0xC618 /* 192, 192, 192 */ #define ILI9341_DARKGREY 0x7BEF /* 128, 128, 128 */ #define ILI9341_BLUE 0x001F /* 0, 0, 255 */ #define ILI9341_GREEN 0x0440 /* 0, 255, 0 */ #define ILI9341_CYAN 0x07FF /* 0, 255, 255 */ #define ILI9341_RED 0xF800 /* 255, 0, 0 */ #define ILI9341_MAGENTA 0xF81F /* 255, 0, 255 */ #define ILI9341_YELLOW 0xFFE0 /* 255, 255, 0 */ #define ILI9341_WHITE 0xFFFF /* 255, 255, 255 */ #define ILI9341_ORANGE 0xFD20 /* 255, 165, 0 */ #define ILI9341_GREENYELLOW 0xAFE5 /* 173, 255, 47 */ #define ILI9341_PINK 0xF81F /******************* UI details */ int mode = 0; // 0 = Default, 1 = Menu, 2=Annunciate #define MODE_BUTTON_X 60 #define MODE_BUTTON_Y 40 #define MODE_BUTTON_W 90 #define MODE_BUTTON_H 38 #define MODE_BUTTON_SPACING_X 30 #define MODE_BUTTON_SPACING_Y 20 #define MODE_BUTTON_TEXTSIZE 2 #define MENU_BUTTON_X 120 #define MENU_BUTTON_Y 160 #define MENU_BUTTON_W 200 #define MENU_BUTTON_H 38 #define MENU_BUTTON_SPACING_X 30 #define MENU_BUTTON_SPACING_Y 28 #define MENU_BUTTON_TEXTSIZE 2.8 #define ACKN_BUTTON_X 120 #define ACKN_BUTTON_Y 260 #define ACKN_BUTTON_W 220 #define ACKN_BUTTON_H 50 #define ACKN_BUTTON_SPACING_X 30 #define ACKN_BUTTON_SPACING_Y 8 #define ACKN_BUTTON_TEXTSIZE 3 #define YP A2 // must be an analog pin, use "An" notation! #define XM A3 // must be an analog pin, use "An" notation! #define YM 8 // can be a digital pin #define XP 9 // can be a digital pin //Touch For New ILI9341 TP #define TS_MINX 70 #define TS_MAXX 920 #define TS_MINY 120 #define TS_MAXY 900 // We have a status line for like, is FONA working #define STATUS_X 65 #define STATUS_Y 10 Elegoo_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET); TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300); Elegoo_GFX_Button buttons[4]; Elegoo_GFX_Button menubuttons[6]; Elegoo_GFX_Button acknbuttons[1]; /* create the buttons */ // buttonlabels[num_buttons][length of array] char buttonlabels[4][20] = {"Menu", "Annunc.", "Exp1", "Exp2"}; uint16_t buttoncolors[4] = {ILI9341_NAVY, ILI9341_NAVY, ILI9341_NAVY, ILI9341_NAVY}; char menubuttonlabels[6][20] = {"BP: ON", "Temp: ON", "Pulse: ON", "BP: OFF", "Temp: OFF", "Pulse:OFF"}; uint16_t menubuttoncolors[6] = {ILI9341_LIGHTGREY, ILI9341_LIGHTGREY, ILI9341_LIGHTGREY, ILI9341_DARKGREY, ILI9341_DARKGREY, ILI9341_DARKGREY }; char acknbuttonlabels[1][20] = {"Acknowl."}; uint16_t acknbuttoncolors[1] = {ILI9341_GREEN}; uint16_t identifier; // global variable to be reached from all functions void setupDisplay(void *tftStruct) { Serial.begin(9600); Serial.println(F("TFT LCD test")); #ifdef USE_Elegoo_SHIELD_PINOUT Serial.println(F("Using Elegoo 2.8\" TFT Arduino Shield Pinout")); #else Serial.println(F("Using Elegoo 2.8\" TFT Breakout Board Pinout")); #endif Serial.print("TFT size is "); Serial.print(tft.width()); Serial.print("x"); Serial.println(tft.height()); tft.reset(); identifier = tft.readID(); if (identifier == 0x9325) { Serial.println(F("Found ILI9325 LCD driver")); } else if (identifier == 0x9328) { Serial.println(F("Found ILI9328 LCD driver")); } else if (identifier == 0x4535) { Serial.println(F("Found LGDP4535 LCD driver")); } else if (identifier == 0x7575) { Serial.println(F("Found HX8347G LCD driver")); } else if (identifier == 0x9341) { Serial.println(F("Found ILI9341 LCD driver")); } else if (identifier == 0x8357) { Serial.println(F("Found HX8357D LCD driver")); } else if (identifier == 0x0101) { identifier = 0x9341; Serial.println(F("Found 0x9341 LCD driver")); } else { Serial.print(F("Unknown LCD driver chip: ")); Serial.println(identifier, HEX); Serial.println(F("If using the Elegoo 2.8\" TFT Arduino shield, the line:")); Serial.println(F(" #define USE_Elegoo_SHIELD_PINOUT")); Serial.println(F("should appear in the library header (Elegoo_TFT.h).")); Serial.println(F("If using the breakout board, it should NOT be #defined!")); Serial.println(F("Also if using the breakout, double-check that all wiring")); Serial.println(F("matches the tutorial.")); identifier = 0x9341; } tft.begin(identifier); tft.setRotation(0); drawDefaultMode(tftStruct); } void drawDefaultMode(void *tftStruct) { TFTData *dData = (TFTData*) tftStruct; *(dData->justPressed) = FALSE; tft.fillScreen(BLACK); // create default mode buttons for (uint8_t row = 0; row < 2; row++) { for (uint8_t col = 0; col < 2; col++) { buttons[col + row * 2].initButton(&tft, MODE_BUTTON_X + col * (MODE_BUTTON_W + MODE_BUTTON_SPACING_X), MODE_BUTTON_Y + row * (MODE_BUTTON_H + MODE_BUTTON_SPACING_Y), // x, y, w, h, outline, fill, text MODE_BUTTON_W, MODE_BUTTON_H, ILI9341_WHITE, buttoncolors[col + row * 2], ILI9341_WHITE, buttonlabels[col + row * 2], MODE_BUTTON_TEXTSIZE); buttons[col + row * 2].drawButton(); } } } int bpon; int tempon; int pulseon; int bpvar; int tempvar; int pulsevar; void drawMenu(void *tftStruct) { TFTData *dData = (TFTData*) tftStruct; *(dData->justPressed) = FALSE; bpon = *(dData->bpSelection); tempon = *(dData->tempSelection); pulseon = *(dData->pulseSelection); // create default mode buttons bpvar = ((bpon == 1) ? 0 : 3); tempvar = ((tempon == 1) ? 1 : 4); pulsevar = ((pulseon == 1) ? 2 : 5); menubuttons[bpvar].initButton(&tft, MENU_BUTTON_X, MENU_BUTTON_Y, // x, y, w, h, outline, fill, text MENU_BUTTON_W, MENU_BUTTON_H, ILI9341_WHITE, menubuttoncolors[bpvar], ILI9341_WHITE, menubuttonlabels[bpvar], MENU_BUTTON_TEXTSIZE); menubuttons[bpvar].drawButton(); menubuttons[tempvar].initButton(&tft, MENU_BUTTON_X, MENU_BUTTON_Y + MENU_BUTTON_H + MENU_BUTTON_SPACING_Y, // x, y, w, h, outline, fill, text MENU_BUTTON_W, MENU_BUTTON_H, ILI9341_WHITE, menubuttoncolors[tempvar], ILI9341_WHITE, menubuttonlabels[tempvar], MENU_BUTTON_TEXTSIZE); menubuttons[tempvar].drawButton(); menubuttons[pulsevar].initButton(&tft, MENU_BUTTON_X, MENU_BUTTON_Y + 2 * (MENU_BUTTON_H + MENU_BUTTON_SPACING_Y), // x, y, w, h, outline, fill, text MENU_BUTTON_W, MENU_BUTTON_H, ILI9341_WHITE, menubuttoncolors[pulsevar], ILI9341_WHITE, menubuttonlabels[pulsevar], MENU_BUTTON_TEXTSIZE); menubuttons[pulsevar].drawButton(); } #define MINPRESSURE 10 #define MAXPRESSURE 1000 unsigned long startTime; void displayLoop(void *tftStruct) { TFTData *dData = (TFTData*) tftStruct; if(*(dData->globalTime) % *(dData->displayInterval) == 0){ *(dData->justPressed) = TRUE; } while (millis() < (*(dData->timeNow)) + 1000) { TFTData *dData = (TFTData*) tftStruct; digitalWrite(13, HIGH); TSPoint p = ts.getPoint(); digitalWrite(13, LOW); pinMode(XM, OUTPUT); pinMode(YP, OUTPUT); if (*(dData->justPressed) == TRUE) { drawDefaultMode(tftStruct); if (mode == 1) { drawMenu(tftStruct); } else if (mode == 2) { drawAnnunciate(tftStruct); } *(dData->justPressed) = FALSE; } int dx; int dy; if (p.z > MINPRESSURE && p.z < MAXPRESSURE) { // scale from 0->1023 to tft.width p.y = (map(p.y, TS_MINX, TS_MAXX, tft.width(), 0)); p.x = (tft.height() - map(p.x, TS_MINY, TS_MAXY, tft.height(), 0)); // // Mapping to match actual screen dx = (unsigned int16_t) p.y; dy = (unsigned int32_t) p.x; dx = (unsigned int32_t) (dx - 6) * 232 / 210; dy = (unsigned int32_t) (dy + 5) * 320 / 345; Serial.print(dx); Serial.print(", "); Serial.println(dy); } else { dx = -100; dy = -200; p.z = -1; } // go thru all the buttons, checking if they were pressed for (uint8_t b = 0; b < 4; b++) { if (buttons[b].contains(dx, dy)) { Serial.print("Pressing: "); Serial.println(buttonlabels[b]); buttons[b].press(true); // tell the button it is pressed Serial.print(dx); Serial.print(", "); Serial.println(dy); *(dData->justPressed) = TRUE; } else { buttons[b].press(false); // tell the button it is NOT pressed } } if (mode == 1) { for (uint8_t b = 0; b < 3; b++) { if (menubuttons[b].contains(dx, dy)) { Serial.print("Pressing: "); Serial.println(menubuttonlabels[b]); menubuttons[b].press(true); // tell the button it is pressed Serial.print(dx); Serial.print(", "); Serial.println(dy); *(dData->justPressed) = TRUE; } else { menubuttons[b].press(false); // tell the button it is NOT pressed } } } else if (mode == 2) { if (acknbuttons[0].contains(dx, dy)) { Serial.print("Pressing: "); Serial.println(acknbuttonlabels[0]); acknbuttons[0].press(true); // tell the button it is pressed Serial.print(dx); Serial.print(", "); Serial.println(dy); *(dData->justPressed) = TRUE; } else { acknbuttons[0].press(false); // tell the button it is NOT pressed } } // now we can ask the buttons if their state has changed for (uint8_t b = 0; b < 4; b++) { if (buttons[b].justReleased()) { // Serial.print("Released: "); Serial.println(b); buttons[b].drawButton(); // draw normal } if (buttons[b].justPressed()) { buttons[b].drawButton(true); // draw invert! buttons[b].press(false); if (b < 4) { mode = b + 1; // Set mode to default 0 = Default, 1 = Menu, 2=Annunciate } delay(100); } } if (mode == 1) { for (uint8_t b = 0; b < 6; b++) { if (menubuttons[b].justReleased()) { // Serial.print("Released: "); Serial.println(b); menubuttons[b].drawButton(); // draw normal } if (menubuttons[b].justPressed()) { menubuttons[b].press(false); menubuttons[b].drawButton(true); // draw invert! if (b == 0 || b == 3) { bpon = ((bpon == 0) ? 1 : 0); } else if (b == 1 || b == 4) { tempon = ((tempon == 0) ? 1 : 0); } else if (b == 2 || b == 5) { pulseon = ((pulseon == 0) ? 1 : 0); } *(dData->bpSelection) = bpon; *(dData->tempSelection) = tempon; *(dData->pulseSelection) = pulseon; mode = 1; // 0 = Default, 1 = Menu, 2=Annunciate delay(100); } } } if (mode == 2) { if (acknbuttons[0].justReleased()) { // Serial.print("Released: "); Serial.println(b); acknbuttons[0].drawButton(); // draw normal } if (acknbuttons[0].justPressed()) { acknbuttons[0].press(false); acknbuttons[0].drawButton(true); // draw invert! // Check if alarm is ringing // If so, acknowledge // Else, do nothing if (*(dData->sysAlarm)) { *(dData->alarmAcknowledge) = TRUE; *(dData->alarmTimer) = 0; *(dData->sysAlarm) = FALSE; delay(100); } } } } } void drawAnnunciate(void *tftStruct) { TFTData *dData = (TFTData*) tftStruct; *(dData->justPressed) = FALSE; // create default mode buttonstft.setCursor(0, 0); // print low and high presure if (*(dData->bpSelection)) { tft.setCursor(0, 150); if (*(dData->sysAlarm)) { tft.setTextColor(RED); } else if (*(dData->bpHigh)) { tft.setTextColor(ORANGE); } else { tft.setTextColor(GREEN); } tft.print((*(dData->bloodPressCorrectedBuf))[0]); tft.print((*(dData->bloodPressCorrectedBuf))[1]); tft.print((*(dData->bloodPressCorrectedBuf))[2]); tft.setTextColor(WHITE); tft.print("/"); if (*(dData->bpLow)) { tft.setTextColor(ORANGE); } else { tft.setTextColor(GREEN); } tft.print((*(dData->bloodPressCorrectedBuf))[24]); tft.print((*(dData->bloodPressCorrectedBuf))[25]); tft.print((*(dData->bloodPressCorrectedBuf))[26]); tft.setTextColor(WHITE); tft.println(" mm Hg"); } else { tft.setCursor(0, 150); tft.setTextColor(GREEN); tft.print("--"); tft.setTextColor(WHITE); tft.print("/"); tft.setTextColor(GREEN); tft.print("--"); tft.setTextColor(WHITE); tft.println(" mm Hg"); } // print temp if (*(dData->tempSelection)) { if (*(dData->tempOff)) { tft.setTextColor(ORANGE); } else { tft.setTextColor(GREEN); } tft.print((*(dData->tempCorrectedBuf))[0]); tft.print((*(dData->tempCorrectedBuf))[1]); tft.print((*(dData->tempCorrectedBuf))[2]); tft.print((*(dData->tempCorrectedBuf))[3]); tft.setTextColor(WHITE); tft.print("C "); } else { tft.print("--.-"); tft.setTextColor(WHITE); tft.print("C "); } // print pulserate if (*(dData->pulseSelection)) { if (*(dData->pulseOff)) { tft.setTextColor(ORANGE); } else { tft.setTextColor(GREEN); } tft.print((*(dData->pulseRateCorrectedBuf))[0]); tft.print((*(dData->pulseRateCorrectedBuf))[1]); tft.print((*(dData->pulseRateCorrectedBuf))[2]); tft.setTextColor(WHITE); tft.println(" BPM "); } else { tft.setTextColor(GREEN); tft.print("---"); tft.setTextColor(WHITE); tft.println(" BPM "); } // print battery if (*(dData->batteryLow)) { tft.setTextColor(RED); } else { tft.setTextColor(GREEN); } tft.print((*(dData->batteryState))[0]); tft.print((*(dData->batteryState))[1]); tft.print((*(dData->batteryState))[2]); tft.setTextColor(WHITE); tft.print(" Charges"); acknbuttons[0].initButton(&tft, ACKN_BUTTON_X, ACKN_BUTTON_Y, // x, y, w, h, outline, fill, text ACKN_BUTTON_W, ACKN_BUTTON_H, ILI9341_WHITE, acknbuttoncolors[0], ILI9341_WHITE, acknbuttonlabels[0], ACKN_BUTTON_TEXTSIZE); acknbuttons[0].drawButton(); } <file_sep>#define M_PI = 3.1415926535; #include "DataStructs.h" #include <Arduino.h> #include "EKGCapture.h" void EKGCapture(void *EKGStruct) { MeasureData* eData = (MeasureData*) EKGStruct; double freq = analogRead(EKG_PIN) * 2 * M_PI; unsigned int fs_period = round(1000000 * (1.0 / FS)); for (int i = 0; i < 256; i++) { //unsigned long microsecond = micros(); (*(eData->vReal))[i] = 3.3 * sin(2 * M_PI * freq * i / FS); (*(eData->vImag))[i] = 0; } } <file_sep>#ifndef DATASTRUCTSPS_H #define DATASTRUCTSPS_H #include <stdio.h> #include "Bool.h" typedef struct { // Raw unsigned int *temperatureRaw; unsigned int *systolicPressRaw; unsigned int *diastolicPressRaw; unsigned int *pulseRateRaw; unsigned int *respirationRaw; // Flags for simulating Bool *sysMeasureComplete; Bool *diaMeasureComplete; Bool *bpIncrease; // Flags for selection Bool *tempSelection; Bool *bpSelection; Bool *pulseSelection; Bool *respSelection; // For simulation unsigned int *bloodPressure; unsigned int *numOfMeasureCalls; int *patient; } MeasureDataPS; typedef struct { // Raw unsigned int *temperatureRaw; unsigned int *systolicPressRaw; unsigned int *diastolicPressRaw; unsigned int *pulseRateRaw; unsigned int *respirationRaw; // Corrected float *tempCorrected; unsigned int *systolicPressCorrected; unsigned int *diastolicPressCorrected; unsigned int *pulseRateCorrected; unsigned int *respirationCorrected; // Flags Bool *tempSelection; Bool *bpSelection; Bool *pulseSelection; Bool *respSelection; } ComputeDataPS; typedef struct { unsigned short *batteryState; } StatusDataPS; #endif <file_sep>#include "DataStructs.h" #include "measureSC.h"; #include "communicationSC.h" #include "Bool.h" #include <Arduino.h> //int globalCounter; // TCB MeasureTCB; // TCB ComputeTCB; void measurerSC(void *measureStruct) { MeasureData *mData = (MeasureData*) measureStruct; //Serial.println(*(mData->globalTime)); //Serial.println(*(mData->measureInterval)); if ((*(mData->globalTime) % (*(mData->measureInterval))) != 0){ return; } // create the command string to be sent to the PS char str[13]; str[0] = 'M'; str[1] = (*(mData->bpSelection) ? 'B' : 'b'); str[2] = (*(mData->tempSelection) ? 'T' : 't'); str[3] = (*(mData->pulseSelection) ? 'P' : 'p'); str[4] = (*(mData->respSelection) ? 'R' : 'r'); str[5] = 'M'; str[6] = 'e'; str[7] = 'a'; str[8] = 's'; str[9] = 'u'; str[10] = 'r'; str[11] = 'e'; str[12] = '>'; Serial.println(str); communicationSC(str, measureStruct); Serial.println("Done with communication - measure"); } <file_sep>#ifndef SCHEDULERSC_H #define SCHEDULERSC_H #include "DataStructs.h" void scheduler(struct TCB* head, struct TCB* tail, unsigned long globalTime); void deleteNode(struct TCB* node, struct TCB* head, struct TCB* tail); void insertNode(struct TCB* node,struct TCB* precNode, struct TCB* head, struct TCB* tail); #endif <file_sep>#ifndef WARNINGSC_H #define WARNINGSC_H #include "Bool.h" void annunciate(void *warningAlarmStruct); #endif <file_sep>void batteryStatusPS(void *statusStruct);<file_sep>#include <math.h> #include <stdio.h> #include "DataStructs.h" void measureData(void *measureStruct); void measureTemp(unsigned int *temperature, Bool *tempIncrease, unsigned int *numOfMeasureCalls); void measureSysPres(unsigned int *sysPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *numOfMeasureCalls); void measureDiaPres(unsigned int *diaPres, Bool *sysMeasureComplete, Bool *diaMeasureComplete, unsigned int *numOfMeasureCalls); void measurePulseRate(unsigned int *pulseRate, Bool *bpIncrease, unsigned int *numOfMeasureCalls); void computeData(void *computeStruct); void displayData(void *displayStruct); void annuciate(void *warningAlarmStruct); void batteryStatus(void *statusStruct); void schedule(TCB **tasks); void delay_ms(unsigned long time_in_ms); void setupDisplay(void); <file_sep>#include "DataStructsPs.h" #include <math.h> void computePS(void *computeStruct) { ComputeDataPS *cData = (ComputeDataPS*) computeStruct; float temp = 5 + 0.75 * (*(cData->temperatureRaw)); unsigned int systolicPres = (unsigned int) 9 + 2 * (*(cData->systolicPressRaw)); unsigned int diastolicPres = (unsigned int) floor(6 + 1.5 * (*(cData->diastolicPressRaw))); unsigned int pr = (unsigned int) 8 + 3 * (*(cData->pulseRateRaw)); *(cData->tempCorrected) = temp; *(cData->systolicPressCorrected) = systolicPres; *(cData->diastolicPressCorrected) = diastolicPres; *(cData->pulseRateCorrected) = pr; }
9edf640f3ad5370e022ffb7e4a6fc60f7fe264fb
[ "C", "C++" ]
49
C
lzx97/Embedded-System
8674e72b73ebb693df4c9d00cdcd250a75adbc91
a46234d394e2e1efe4b492d635b5b7c456530d5a
refs/heads/master
<file_sep>package com.ansen.frameanimation.sample; import android.app.Activity; import android.content.res.TypedArray; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.ansen.frameanimation.AdvanceFrameAnimation; import com.ansen.frameanimation.FrameAnimation; import com.ansen.frameanimation.R; public class AnimationThree extends Activity { private static final String TAG = "ansen"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.two); final ImageView image = (ImageView) findViewById(R.id.image); // 每50ms一帧 循环播放动画 final AdvanceFrameAnimation frameAnimation = new AdvanceFrameAnimation(image, getRes(), 50, false); frameAnimation.setAnimationListener(new AdvanceFrameAnimation.AnimationListener() { @Override public void onAnimationStart() { Log.d(TAG, "start"); } @Override public void onAnimationEnd() { Log.d(TAG, "end"); System.gc(); finish(); } @Override public void onAnimationRepeat() { Log.d(TAG, "repeat"); } }); image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 实现点击 暂停和继续播放动画 if (frameAnimation.isPause()) { Log.d(TAG, "restart"); frameAnimation.restartAnimation(); } else { Log.d(TAG, "pause"); frameAnimation.pauseAnimation(); } } }); } /** * 获取需要播放的动画资源 */ private int[] getRes() { TypedArray typedArray = getResources().obtainTypedArray(R.array.c); int len = typedArray.length(); int[] resId = new int[len]; for (int i = 0; i < len; i++) { resId[i] = typedArray.getResourceId(i, -1); } typedArray.recycle(); return resId; } } <file_sep>package com.ansen.frameanimation.sample; import android.app.Activity; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.support.annotation.Nullable; import android.widget.ImageView; import com.ansen.frameanimation.R; /** * Created by Ansen on 2017/3/24 09:28. * * @E-mail: <EMAIL> * @Blog: http://blog.csdn.net/qq_25804863 * @Github: https://github.com/ansen360 * @PROJECT_NAME: FrameAnimation * @PACKAGE_NAME: com.ansen.frameanimation.sample * @Description: TODO */ public class AnimationOne extends Activity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.one); ImageView image = (ImageView) findViewById(R.id.image); AnimationDrawable animationDrawable = (AnimationDrawable) image.getDrawable(); animationDrawable.setOneShot(true); animationDrawable.start(); } } <file_sep>package com.ansen.frameanimation.sample; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.ansen.frameanimation.R; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void clickOne(View v) { startActivity(new Intent(this, AnimationOne.class)); } public void clickTwo(View v) { startActivity(new Intent(this, AnimationTwo.class)); } public void clickThree(View v) { startActivity(new Intent(this, AnimationThree.class)); } }
3b49a97011818b50c68013dd1ebbbfee68922e65
[ "Java" ]
3
Java
kataCai/FrameAnimation
b2f362512f1871320e3af84cca0dc7ce82847f0b
797c177e59ff056ebe82700f5a7263e0e15195e4
refs/heads/master
<repo_name>purplejacket/Efficient-Test-Driven-Rails-Development<file_sep>/spec/models/failing_spec.rb require 'spec_helper' describe "A failing test in order to verify TeamCity" do it "fails" do "apples".should == "oranges" end end
23d54de18aa767185a24873cfa7df31e1814406a
[ "Ruby" ]
1
Ruby
purplejacket/Efficient-Test-Driven-Rails-Development
83be954c1f98901fe8d88724e1701090e233b984
543b081919e36a997bed31996337c01e04a5ac40
refs/heads/master
<repo_name>Alex-135-135/Repository<file_sep>/priject/app.jsx import ReactDOM from 'react-dom' import React from 'react' import './styles/index.css'; import 'antd/dist/antd.css'; import Main from './src/components/Main.jsx' ReactDOM.render(<Main />, document.getElementById('root'));<file_sep>/angular-phonecat-master/app/phone-detail/phone-detail.component.js 'use strict'; console.log(JSON.parse(localStorage.getItem('basketData'))); angular. module('phoneDetail'). component('phoneDetail', { templateUrl: 'phone-detail/phone-detail.template.html', controller: ['Phone', function BasketListController() { }] }) .controller('deleteFromBasket', $scope => { $scope.phones = JSON.parse(localStorage.getItem('basketData')) if($scope.phones.length==0){ $scope.qwert= 'Корзина пуста'; } $scope.deleteFromBasket = id => { $scope.phones = $scope.phones.filter(i => i.id !== id); if($scope.phones.length==0){$scope.qwert= 'Корзина пуста';} localStorage.setItem('basketData', JSON.stringify($scope.phones)); toastr.success('Товар видалено корзини'); } $scope.addGoods = id => { let arr = $scope.phones.filter(i => i.id == id); arr[0].count++; localStorage.setItem('basketData', JSON.stringify($scope.phones)); } $scope.deleteGoods = id => { let arr = $scope.phones.filter(i => i.id == id); arr[0].count>1 ? arr[0].count-- : arr[0].count; localStorage.setItem('basketData', JSON.stringify($scope.phones)); } }); <file_sep>/angular-phonecat-master/app/phone-list/phone-list.component.js 'use strict'; angular. module('phoneList'). component('phoneList', { templateUrl: 'phone-list/phone-list.template.html', controller: ['Phone', function PhoneListController(i) { this.phones = i.query(); this.addInBasket = phone => { const arr = JSON.parse(localStorage.getItem('basketData')) || []; let current = arr.find(i => i.id === phone.id); current ? current.count++ : arr.push({...phone, count: 1}); localStorage.setItem('basketData', JSON.stringify(arr)); toastr.success('Товар додано до корзини'); } } ] });<file_sep>/weather/README.md # weather ### Development ``` npm i ``` ``` npm run server (running with node) ``` or ``` npm start (just front side) ``` Open http://localhost:8000 <file_sep>/priject/src/data.js export const data = [{ key: 1, date: '12.07.2018', username: 'Alex-135-125', dailyPlan: 'some text', futurePlan: 'also some text', }, { key: 2, date: '12.07.2018', username: 'Alex-135-125', dailyPlan: 'some text', futurePlan: 'also some text', }, { key: 3, date: '12.07.2018', username: 'Alex-135-125', dailyPlan: 'some text', futurePlan: 'also some text', }]; export const columns = [{ title: 'Date', dataIndex: 'date', key: 'date' }, { title: 'Username', dataIndex: 'username', key: 'username', }, { title: 'Daily plan', dataIndex: 'dailyPlan', key: 'dailyPlan', }, { title: 'Future plan', dataIndex: 'futurePlan', key: 'futurePlan', }]; <file_sep>/weather/app/api/api.component.js 'use strict'; let lat, lon; let tempUnit = 'C'; let currentTempInCelsius; angular. module('api'). component('api', { templateUrl: 'api/api.template.html', controller: ['Phone', function PhoneListController() { }] }) .controller('deleteFromBasket', ($scope, $http, $timeout) => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { let lat = "lat=" + position.coords.latitude; let lon = "lon=" + position.coords.longitude; $scope.getWeather(lat, lon); }); } else { console.log("Geolocation is not supported by this browser."); } $scope.getWeather = (lat, lon) => { let urlString = "http://api.openweathermap.org/data/2.5/weather?cnt=5&" + lat + "&"+ lon + "&units=metric&APPID=f6c490f5420f241b364e02736ca2a3da"; $http({method: 'GET', url: urlString}).             then( $scope.success = response => { $scope.city = (response.data.name + ", "); $scope.country = response.data.sys.country; currentTempInCelsius = Math.round(response.data.main.temp * 10) / 10; $scope.temp = currentTempInCelsius + " " + String.fromCharCode(176); $scope.tempunit = tempUnit; $scope.desc = "//openweathermap.org/img/w/"+response.data.weather[0].icon+".png";         }); } }); <file_sep>/priject/src/components/AddButton1.jsx import React, { Component } from 'react'; import 'antd/dist/antd.css'; import { Button, Modal, Form, Input, DatePicker } from 'antd'; import moment from 'moment'; const FormItem = Form.Item; const CollectionCreateForm = Form.create()( class extends Component { render() { const { visible, onCancel, onCreate, form } = this.props; const { getFieldDecorator } = form; return ( <Modal style={{top: 0}} visible={visible} title="Adding" okText="Add" onCancel={onCancel} onOk={onCreate} > <Form layout="vertical"> <FormItem label="Date"> {getFieldDecorator('date', { rules: [{ required: true, message: 'Must be filled!' }], })( <DatePicker selected={moment()} /> )} </FormItem> <FormItem label="Username"> {getFieldDecorator('username', { rules: [{ required: true, message: 'Must be filled!' }], })( <Input /> )} </FormItem> <FormItem label="Daily Plan"> {getFieldDecorator('dailyPlan', { rules: [{ required: true, message: 'Must be filled!' }], })( <Input /> )} </FormItem> <FormItem label="Future Plan"> {getFieldDecorator('futurePlan', { rules: [{ required: true, message: 'Must be filled!' }], })( <Input /> )} </FormItem> </Form> </Modal> ); } } ); class AddButton1 extends Component { state = { visible: false, } showModal = () => { this.setState({ visible: true }); } handleCancel = () => { this.setState({ visible: false }); } handleCreate = () => { const form = this.formRef.props.form; form.validateFields((err, values) => { if (err) { return; } //var date1 = values.date._d; //delete values.date; //var values1 = date1 + values; console.log('Received values of form: ', values ); this.props.onClick(values); form.resetFields(); this.setState({ visible: false }); }); } saveFormRef = (formRef) => { this.formRef = formRef; } render() { return ( <div> <Button type="primary" style={{top: -48}} onClick={this.showModal}>Add</Button> <CollectionCreateForm wrappedComponentRef={this.saveFormRef} visible={this.state.visible} onCancel={this.handleCancel} onCreate={this.handleCreate} /> </div> ); } } export default AddButton1
7baee01eb63621a8c72939c57bf335c5c3c0735e
[ "JavaScript", "Markdown" ]
7
JavaScript
Alex-135-135/Repository
0b1acf0429eb233514be94f3455f21e95d71f553
226364576895975433691742a7b2e716e1024de8
refs/heads/master
<file_sep>import React, { useState } from 'react' function StateArraySample() { const [dates, setDates] = useState([]); const add = () => { const d = new Date(); setDates([...dates, d.toLocaleTimeString()]); } return ( <> <button onClick={() => add()}>Add Date</button> <ul> { dates.map((item,key) => (<li>{item}</li>)) } </ul> </> ) } export default StateArraySample <file_sep>import React, { useState } from 'react' function StateSample() { console.log('State sample component render!!'); //Dizideki ilk parametre tanımladığın değişken. İkinci parametre bunu değiştirecek TEK FONKSİYON. use state içerindeki değer ise sizin değişkeninizin default değeri const [country, setCountry] = useState('USA'); const [sayac, setSayac] = useState(0); return ( <> <h1>{country}</h1> <button onClick={() => setCountry('Turkey')}>Change Country</button> <hr></hr> <h1>{sayac}</h1> <button onClick={() => setSayac(sayac + 1)}>Change Sayac</button> </> ) } export default StateSample <file_sep>import React, { useEffect, useState } from 'react' function Categorylist() { console.log('Category list component render!!'); const [categories, setCategories] = useState([]); useEffect(() => { fetch('https://northwind.vercel.app/api/categories') .then((res) => res.json()) .then((data) => { setCategories(data); }) }, []) return ( <> <h1>Categories</h1> <ul> { categories.map((item, key) => <li>{item.name}</li>) } </ul> </> ) } export default Categorylist <file_sep>import React, { useState } from 'react' import MemoHook2 from './MemoHook2' function MemoHook() { const [sayac, setSayac] = useState(0) return ( <> <h1>{sayac}</h1> <button onClick={() => setSayac(sayac + 1)}>Increase</button> <MemoHook2></MemoHook2> </> ) } export default MemoHook <file_sep>import React from 'react' function JsxEventSample() { let name = 'Çağatay'; const hello = () => { alert(' Hello Camel! '); } return ( <> <span>{name}</span> {/* <button onClick={hello}>Merhaba!</button> */} <hr></hr> <button onClick={() => hello()}>Merhaba !</button> </> ) } export default JsxEventSample <file_sep> import { useState } from 'react'; function WebUser() { const [avgPoints, setAvgPoints] = useState(0) let points = [3, 5, 6, 1, 6]; let webuser = { name: 'Çağatay', surname: 'Yıldız', city: 'İstanbul', country: 'TR' }; const calc = () => { var sum = 0; for (var i = 0; i < points.length; i++) { sum += points[i] } var avg = sum / points.length; setAvgPoints(avg); } return ( <> <span>Avg: {avgPoints}</span> <WebUserPoints points={points} title='Çağatay' ></WebUserPoints> <Detail user={webuser} calc={calc}></Detail> </> ) } export default WebUser export function WebUserPoints(props) { let { points, title } = props; return ( <> <h1>{title}</h1> <ul> { points.map((item, key) => (<li>{item * 1.5}</li>)) } </ul> </> ) } export function Detail(props) { let { user } = props return ( <> <span>{user.name?.toUpperCase()}</span> <hr></hr> <span>{user.surname.toUpperCase()}</span> <button onClick={() => props.calc()}>Calc Avg</button> </> ) } <file_sep>import React, { useRef } from 'react' function SelectorSample() { const h1Element = useRef(null) //Butona bastığında h1 in rengi tomato olsun let pStlye = { color:'aqua', backgroundColor:'red' } const changeColor = () => { document.getElementById('title').style.color = 'tomato'; h1Element.current.style.color = 'yellow'; } return ( <> <p style={pStlye}>lorem morem aman da aman</p> <h1 ref={h1Element}>Volkan</h1> <h1 id='title'>Çağatay</h1> <button onClick={() => changeColor()}>Change Color</button> </> ) } export default SelectorSample <file_sep>import React from 'react' function BaButton(props) { let buttonCss = { color: props.color } return ( <> <button style={buttonCss}>{props.title}</button> </> ) } export default BaButton <file_sep>Proje clone landıktan sonra proje dizininde npm install komutunu çalıştırıp paketleri yüklemelisiniz. böylelikle node module sizde oluşacaktır * Component isimlerini büyük harfle başlat! * rfce kısayoluyla component oluşturulabilir * Fragment kullanımı önemli! * React ext : ES7 React/Redux/GraphQL/React-Native Arrow Functions https://www.w3schools.com/js/js_arrow_function.asp https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions?retiredLocale=tr Templates Uygulama ( Gourmet Catering Template ) https://www.w3schools.com/w3css/w3css_templates.asp html to jsx https://transform.tools/html-to-jsx https://magic.reactjs.net/htmltojsx.htm Ödev - 1 Arrow function makalelerine bak neden key hatası alıyoruz ( maplerde) onu çöz fiyatı 8 den yüksek olan yemekleri kırmızı renkte göster React key https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js/43892905#43892905 https://kentcdodds.com/blog/understanding-reacts-key-prop React Tools ext https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi React router package https://reactrouter.com/web/guides/quick-start React Forms https://react-hook-form.com/ https://formik.org/ Redux https://www.youtube.com/watch?v=kwGIgfbYWrQ <file_sep>import React from 'react' function ProductDetail(props) { return ( <> <h2>Özellikler</h2> <ul> { props.ozellikler.map((item, key) => (<li key={key}>{item}</li>)) } </ul> <button onClick={() => props.add()}>Sepete Ekle</button> </> ) } export default ProductDetail <file_sep>import React, { useState } from 'react' function StateSample2() { const [laoding, setLaoding] = useState(false); const [username, setUsername] = useState(''); const getData = () => { setLaoding(true); setTimeout(() => { setUsername('Çağatay'); setLaoding(false); }, 3000); } return ( <> { laoding == true ? (<span>loading...</span>) : ( <><h1>{username}</h1> <button onClick={() => getData()}>get username</button></> ) } </> ) } export default StateSample2 <file_sep>import React, { useEffect, useState } from 'react' import { useParams } from 'react-router-dom' import { apiUrl } from '../env/config'; function EmployeeDetail() { const {id} = useParams(); const [employeeDetail, setEmployee] = useState({}); useEffect(() => { fetch(apiUrl + '/api/suppliers/' + id) .then((res) => res.json()) .then((data) => { setEmployee(data); }) }, []) return ( <> <h1>Employee Detail Page - {id}</h1> <span>Company Name: {employeeDetail.companyName}</span> <hr></hr> <span>Contact Name: {employeeDetail.contactName}</span> <hr></hr> <span>Contact Title: {employeeDetail.contactTitle}</span> </> ) } export default EmployeeDetail <file_sep>import React from 'react' function Header() { return ( <> <h1 style={{color:'tomato'}}>Sitenin header bölümü</h1> </> ) } export default Header <file_sep>import React from 'react' import BaButton from '../props/BaButton' function Home() { return ( <div> Home Page <BaButton title='<NAME>' color='tomato'></BaButton> </div> ) } export default Home <file_sep>import { BrowserRouter, Switch, Route, Link } from 'react-router-dom'; import SelectorSample from './cssSamples/SelectorSample'; import About from './routersample/About' import Contact from './routersample/Contact' import EmployeeDetail from './routersample/EmployeeDetail'; import Employees from './routersample/Employees'; import Home from './routersample/Home' import NoMatch from './routersample/NoMatch'; import CustomerList from './uygulamalar/ornek-3/CustomerList'; import 'antd/dist/antd.css'; import { Layout, Menu, Breadcrumb } from 'antd'; import Productstable from './antDesignSample/Productstable'; import AddProduct from './antDesignSample/AddProduct'; import Siteproductpage from './contextSample/Siteproductpage'; import CartDetail from './contextSample/CartDetail'; import { CartProvider } from './store/context/CartContext'; import LayoutEffectSampe from './otherHooks/LayoutEffectSampe'; import MemoHook from './otherHooks/MemoHook'; const { Header, Content, Footer } = Layout; function App() { return ( <> <CartProvider> <BrowserRouter> <Layout> <Header style={{ position: 'fixed', zIndex: 1, width: '100%' }}> <div className="logo" /> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['2']}> <Menu.Item key="1"><Link to='/'>Home</Link></Menu.Item> <Menu.Item key="2"><Link to='/products'>Products</Link></Menu.Item> <Menu.Item key="3"><Link to='/addproduct'>Add Product</Link></Menu.Item> <Menu.Item key="4"><Link to='/siteproducts'>Site Products</Link></Menu.Item> <Menu.Item key="6"><Link to='/layouteffectsample'>Layout Effect</Link></Menu.Item> <Menu.Item key="7"><Link to='/memohooksample'>Memo Hook</Link></Menu.Item> </Menu> </Header> <Content className="site-layout" style={{ padding: '0 50px', marginTop: 64 }}> <div className="site-layout-background" style={{ padding: 24, minHeight: 380 }}> <Switch> <Route exact path='/'> <Home></Home> </Route> <Route path='/selectorsample'> <SelectorSample></SelectorSample> </Route> <Route path='/bout'> <About></About> </Route> <Route path='/customers'> <CustomerList></CustomerList> </Route> <Route path='/contact'> <Contact></Contact> </Route> <Route path='/home'> <Home></Home> </Route> <Route exact path='/employees'> <Employees></Employees> </Route> <Route path='/employees/:id'> <EmployeeDetail></EmployeeDetail> </Route> <Route path='/products'> <Productstable></Productstable> </Route> <Route path='/addproduct'> <AddProduct></AddProduct> </Route> <Route path='/siteproducts'> <Siteproductpage></Siteproductpage> </Route> <Route path='/layouteffectsample'> <LayoutEffectSampe></LayoutEffectSampe> </Route> <Route path='/memohooksample'> <MemoHook></MemoHook> </Route> <Route path="*"> <NoMatch /> </Route> </Switch> </div> </Content> <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by <NAME></Footer> </Layout> </BrowserRouter> </CartProvider> </> ) } export default App; <file_sep>import { useState } from "react" function StateErrorSample() { const [sayac, setSayac] = useState(0); // setSayac(sayac + 1) return ( <> <h1>{sayac}</h1> {/* <button onClick={setSayac(sayac + 1)}>Change</button> */} </> ) } export default StateErrorSample <file_sep>import React from 'react' import About from './About' import Contact from './Contact' import Project from './Project' function Content() { return ( <div className="w3-content w3-padding" style={{ maxWidth: 1564 }}> <Project></Project> <About></About> <Contact></Contact> </div> ) } export default Content <file_sep>import React from 'react' function Mapsample() { let metalGroups = [ { name:'<NAME>', country:'England', year:1975 }, { name:'Gojira', country:'France', year:1996 }, { name:'<NAME>', country:'USA', year:2003 }, { name:'Rammstein', country:'Deutchland', year:1994 } ] // Yıl 2000 üstündeyse renk kırmızı olsun return ( <div> <ul> { metalGroups.map((item,key) => item.year > 2000 ? (<li style={{color:'tomato'}}>{item.name}</li>) : (<li>{item.name}</li>) ) } </ul> </div> ) } export default Mapsample <file_sep>import React, { useEffect, useLayoutEffect, useState } from 'react' function LayoutEffectSampe() { const [sayac, setSayac] = useState(0) //önce html render olur sonra çalışır! useEffect(() => { setSayac(10) }, []); //önce uselayouteffect çalışır sonra html gelir useLayoutEffect(async () => { setSayac(6); }, []) return ( <> <h1>Sayaç: {sayac}</h1> </> ) } export default LayoutEffectSampe <file_sep>import React from 'react' import ProductDetail from './ProductDetail' import ProductHeader from './ProductHeader' //prop la bir obje gidebilir, metinsel değer gidebilir, numeric değer gidebilir, array gidebilir, function Product() { let productdetail = { name:'IPhone', price:10000, ozellikler:['Suya dayanıklılık','x px kamera','şarj aleti paralı'] }; const addCart = () => { alert('Ürün sepete eklendi! ') } return ( <> {/* <ProductHeader title='IPhone' description='lorem morem ipsum mipsum'></ProductHeader> */} <ProductHeader product={productdetail}></ProductHeader> <ProductDetail ozellikler={productdetail.ozellikler} add={addCart}></ProductDetail> </> ) } export default Product <file_sep>import React, { useState } from 'react' function AddCategory() { const [categoryName, setCategoryName] = useState(''); const add = () => { let requestOptions = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "POST", body: JSON.stringify({ categoryName: categoryName }) }; fetch('https://northwind.vercel.app/api/categories', requestOptions) .then((res) => res.json()) .then((data) => { console.log('Data eklendi!', data); }) } return ( <> <div> <input type='text' onChange={(e) => setCategoryName(e.target.value)} value={categoryName} ></input> <button onClick={() => add()}>Add</button> </div> </> ) } export default AddCategory <file_sep>import React, { useEffect, useState } from 'react' import { apiUrl } from '../env/config'; import AddProductPage from './AddProductPage'; import ProductListPage from './ProductListPage'; function ProductPage() { const [products, setProducts] = useState([]); useEffect(() => { getProducts(); }, []) const getProducts = () => { fetch(apiUrl + '/api/products') .then((res) => res.json()) .then((data) => { setProducts(data); }) } // bu fonksiyon dışarıdan aldığı datayı servise bırakır! const add = (data) => { let requestOptions = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "POST", body: JSON.stringify(data) }; fetch( apiUrl + '/api/products', requestOptions) .then((res) => res.json()) .then((data) => { console.log('Product eklendi!', data); getProducts(); }) } const deleteProduct = (id) => { let requestOptions = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "DELETE" }; fetch(apiUrl + '/api/products/' + id, requestOptions) .then((res) => res.json()) .then((data)=>{ console.log('DELETED!!'); getProducts(); }) } return ( <> <AddProductPage addProduct={add}></AddProductPage> <hr></hr> <ProductListPage products={products} deleteProduct={deleteProduct}></ProductListPage> </> ) } export default ProductPage <file_sep>import React from 'react' function IfElseSample() { let onlineDurum = false; let user = { name: 'Çağatay' } return ( <> { // onlineDurum == true ? (<span>Kullanıcı Online!</span>) : (<></>) onlineDurum == true ? (<span>Kullanıcı Online!</span>) : (<span>Kullanıcı offline!</span>) } <hr></hr> { user && <span>Bu hayatın heyecanı meyecanı yok ! </span> } </> ) } export default IfElseSample <file_sep>import React, { useEffect, useState } from 'react' function EffectSample() { const [sayac, setSayac1] = useState(0); const [sayac2, setSayac2] = useState(0); console.log('Effect sample component render!'); //Component render olduktan sonra 1 kereliğe mahsus çalışır useEffect(() => { console.log('Use effect hook 1 kereliğe mahsus çalıştı!'); }, []); useEffect(() => { console.log('Sadece sayac state değiştiğinde çalışır'); }, [sayac]) useEffect(() => { console.log('Herhangi bir state değiştiğinde'); }) return ( <> <div> <span>{sayac}</span> <button onClick={() => setSayac1(sayac + 1)}>Increase - 1</button> </div> <div> <span>{sayac2}</span> <button onClick={() => setSayac2(sayac2 + 1)}>Increase - 2</button> </div> </> ) } export default EffectSample <file_sep>import React, { useEffect, useState } from 'react' import { apiUrl } from '../../env/config'; function CustomerList() { const [customers, setCustomers] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { fetch(apiUrl + '/api/customers') .then((res) => res.json()) .then((data) => { setTimeout(() => { setCustomers(data); setLoading(false); }, 1500); }) }, []); const deleteCustomer = (id) => { let result = window.confirm('Silmek istediğinizden emin misiniz?'); if(result){ // silme işlemi yap console.log('Silme işlemi yap!'); } else{ } } return ( <> {/* <button onClick={()=>{if(window.confirm('Silmek İstediğinize Emin Misiniz?')) deleteCustomers(item.id)}}>Delete</button> */} { loading == true ? (<span>loading....</span>) : <></> } <ul> { customers.map((item, key) => ( <> <li>{item.companyName}</li> <button onClick={() => deleteCustomer(item.id)}>Delete</button> </> )) } </ul> </> ) } export default CustomerList <file_sep>import React, { useState } from 'react' function AddProductPage(props) { const [name, setName] = useState(''); const [price, setPrice] = useState(0); const [stock, setStock] = useState(0); const add = () => { let newProduct = { name:name, unitPrice:price, unitsInStock:stock }; props.addProduct(newProduct); } return ( <> <div> <label>Name:</label> <input type='text' value={name} onChange={(e) => setName(e.target.value)}></input> </div> <div> <label>Price:</label> <input type='text' value={price} onChange={(e) => setPrice(e.target.value)}></input> </div> <div> <label>Stock:</label> <input type='text' value={stock} onChange={(e) => setStock(e.target.value)}></input> </div> <div> <button onClick={() => add()}>Add</button> </div> </> ) } export default AddProductPage
fb195c118e677c345a8ba1485a55a239f502076d
[ "JavaScript", "Text" ]
26
JavaScript
kalecaner/baboost-react-tutorial
f95e56794260c7932ca01d14864d715e88d7af29
46df46cc42348255261fe282b5c9d8d11ab96a66
refs/heads/master
<file_sep>const db = require('./db') users = { 1000: { acno: 1000, username: "jio", password: "jio", balance: 5000, transaction: [] }, 1001: { acno: 1001, username: "sam", password: "sam", balance: 4000, transaction: [] }, 1002: { acno: 1002, username: "ram", password: "ram", balance: 6000, transaction: [] }, 1003: { acno: 1003, username: "raju", password: "<PASSWORD>", balance: 7000, transaction: [] }, 1004: { acno: 1004, username: "lio", password: "lio", balance: 9000, transaction: [] } } const register = (acno, username, password) => { return db.User.findOne({ acno }) .then(user => { if (user) { return { statusCode: 422, status: false, message: "User exist...Please LogIn" } } else { const newUser = new db.User({ acno, username, password, balance: 0, transaction: [] }) newUser.save() return { statusCode: 200, status: true, message: "successfully registed" } } }) } const authentication = (req, acno, pswd) => { return db.User.findOne({ acno, password: <PASSWORD> }) .then(user => { if (user) { req.session.currentAcc = user.acno console.log(user); return { statusCode: 200, status: true, message: "successfully logedIn", userName: user.username, currentAcc: user.acno } } return { statusCode: 422, status: false, message: "invalid account number or password" } }) } const deposit = (acno, pswd, amount) => { return db.User.findOne({ acno, password: <PASSWORD> }).then(user => { if (user) { var amt = parseInt(amount) user.balance += amt user.transaction.push({ amount: amt, type: "CREDIT" }) user.save() return { statusCode: 200, status: true, message: `${amt} successfully deposited, available balance is ${user.balance} ` } } else { return { statusCode: 422, status: false, message: "invalid account details" } } }) } const withdraw = (req, acno, pswd, amount) => { return db.User.findOne({ acno, password: <PASSWORD> }).then(user => { if (user) { if (req.session.currentAcc != user.acno) { return { statusCode: 422, status: false, message: "invalid session" } } var amt = parseInt(amount) if (user.balance >= amt) { user.balance -= amt user.transaction.push({ amount: amt, type: "DEBIT" }) user.save() return { statusCode: 200, status: true, message: `${amt} successfully debited, available balance is ${user.balance} ` } } else { return { statusCode: 422, status: false, message: "insufficient balance" } } } else { return { statusCode: 422, status: false, message: "invalid account details" } } }) } const getTransaction = (acno) => { return db.User.findOne({ acno // acno: req.session.currentAcc }).then(user=>{ if(user){ return { statusCode: 200, status: true, transaction: user.transaction } } else{ return { statusCode: 422, status: false, message: "invalid operations" } } }) } const deleteAcc= (acno)=>{ return db.User.deleteOne({acno}) .then(user=>{ if(!user){ return { statusCode: 422, status: false, message: "invalid operations" } } else{ return { statusCode: 200, status: true, message: ` successfully debited account no: ${acno} ` } } }) } module.exports = { register, authentication, deposit, withdraw, getTransaction,deleteAcc }
197ddd6c4b1e51997774fcb9e6ebebaf455b18c2
[ "JavaScript" ]
1
JavaScript
dhanyapushkaran/BankAppServer
b06d6b0ee5e550fa15fde0c10adbe8659132cd4f
8e6429884c1b05be0e5630ea20142a868839affc
refs/heads/master
<file_sep>using System; using System.IO; using System.Collections.Generic; using System.Text; //сделать отсчет времени между ударами компьютера namespace BattleShip { public enum Direction { Up, Left, None } class Program { const string FilePath = @"C:\Users\Valentine\Desktop\ShipWorld.txt"; const int SizeField = 10; const int MissValue = 6; const int HitValue = 8; const int CountHitForWin = 20; static void Main(string[] args) { int[,] playerField = FieldArrayFilling(ReadFile(FilePath)); int[,] enemyField = FieldEnemy(); int[,] enemyFieldForPlayer = FieldEnemy(); Data data = new Data(); enemyField = RandomShipsEnemy(enemyField); FieldOutput(playerField, enemyFieldForPlayer); DebugField(enemyField); data.FieldForEnemy = CreatingListcoordinatesForEnemyAttack(); StepPlayer(enemyFieldForPlayer, enemyField, playerField, data); Console.ReadLine(); } static List<Coordenate> CreatingListcoordinatesForEnemyAttack() { List<Coordenate> tempList = new List<Coordenate>(); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { tempList.Add(new Coordenate(i, j)); } } return tempList; } static void StepPlayer(int[,] enemyFieldForPlayer, int[,] enemyField, int[,] playerField, Data data) { if (CheckWiner(data)) { return; } int y; int x; Console.WriteLine(); Console.Write("Enter X coordinate for the attack (1-SizeField): "); string tmpy = Console.ReadLine(); Console.Write("Enter Y coordinate for the attack (1-SizeField): "); string tmpx = Console.ReadLine(); if (!int.TryParse(tmpy, out y) || !int.TryParse(tmpx, out x) || y <= 0 || y > 10 || x <= 0 || x > 10) { FieldOutput(playerField, enemyFieldForPlayer); Console.WriteLine("You did not enter the coordinate correctly, try again!"); StepPlayer(enemyFieldForPlayer, enemyField, playerField, data); return; } x -= 1; y -= 1; if (enemyFieldForPlayer[x, y] != 0) { FieldOutput(playerField, enemyFieldForPlayer); Console.WriteLine("You have already attacked at these coordinates, try again!"); StepPlayer(enemyFieldForPlayer, enemyField, playerField, data); return; } if (enemyField[x, y] == 0) { enemyFieldForPlayer[x, y] = MissValue; FieldOutput(playerField, enemyFieldForPlayer); Console.WriteLine("Sorry, but you missed..."); StepEnemy(enemyFieldForPlayer, enemyField, playerField, data); } else { enemyFieldForPlayer[x, y] = enemyField[x, y]; List<Coordenate> coordsDecks = KillCheckForPlayer(new Coordenate(x, y), enemyFieldForPlayer); if (coordsDecks.Count == enemyField[x, y]) { coordsDecks = StartEndShip(FindDirection(coordsDecks), coordsDecks); enemyFieldForPlayer = MarkBorderFoeEnemyField(enemyFieldForPlayer, coordsDecks); } FieldOutput(playerField, enemyFieldForPlayer); ResultConsoleOutput(coordsDecks, enemyFieldForPlayer); data.CountPlayer++; StepPlayer(enemyFieldForPlayer, enemyField, playerField, data); } } static int[,] MarkBorderFoeEnemyField(int[,] field, List<Coordenate> coordDecks) { if (coordDecks.Count == 0) { return field; } int count = 0; for (int i = coordDecks[0].X - 1; i <= coordDecks[coordDecks.Count - 1].X + 1; i++) { if (i >= 0 && i < 10) { for (int j = coordDecks[0].Y - 1; j <= coordDecks[coordDecks.Count - 1].Y + 1; j++) { if (j >= 0 && j < 10 && field[i, j] == 0) { field[i, j] = MissValue; count++; } } } } return field; } static void ResultConsoleOutput(List<Coordenate> killDecks, int[,] fieldEnemy) { Console.WriteLine(); if (killDecks.Count > 0 && fieldEnemy[killDecks[0].X, killDecks[0].Y] == killDecks.Count) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("You killed {0} deck ship!", killDecks.Count); Console.ForegroundColor = ConsoleColor.Gray; } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Fine! You hit!"); Console.ForegroundColor = ConsoleColor.Gray; } } static List<Coordenate> KillCheckForPlayer(Coordenate coord, int[,] field) { int countDeck = field[coord.X, coord.Y]; Direction dir = Direction.None; if (coord.X + 1 < 10 && field[coord.X, coord.Y] == field[coord.X + 1, coord.Y]) { dir = Direction.Up; } else if (coord.X - 1 >= 0 && field[coord.X, coord.Y] == field[coord.X - 1, coord.Y]) { dir = Direction.Up; } else if (coord.Y + 1 < 10 && field[coord.X, coord.Y] == field[coord.X, coord.Y + 1]) { dir = Direction.Left; } else if (coord.Y - 1 >= 0 && field[coord.X, coord.Y] == field[coord.X, coord.Y - 1]) { dir = Direction.Left; } return DecksCheck(field, countDeck, coord, dir); } static List<Coordenate> DecksCheck(int[,] field, int countDeck, Coordenate coord, Direction dir) { List<Coordenate> coordenatesDecks = new List<Coordenate>(); switch (dir) { case Direction.Up: for (int i = coord.X - countDeck - 1; i <= coord.X + countDeck - 1; i++) { if ((i >= 0 && i < 10) && field[i, coord.Y] == countDeck) { coordenatesDecks.Add(new Coordenate(i, coord.Y)); } } break; case Direction.Left: for (int i = coord.Y - countDeck - 1; i <= coord.Y + countDeck - 1; i++) { if ((i >= 0 && i < 10) && field[coord.X, i] == countDeck) { coordenatesDecks.Add(new Coordenate(coord.X, i)); } } break; } return coordenatesDecks; } static void StepEnemy(int[,] enemyFieldForPlayer, int[,] enemyField, int[,] playerField, Data data) { if (CheckWiner(data)) { return; } Coordenate coord = new Coordenate(0, 0); Random rand = new Random(); if (data.Touch) { data.LikelyCoordinatesForEnemy = SearchNeighboring(data); if (data.LikelyCoordinatesForEnemy.Count == 0) { data.Touch = false; } coord = data.LikelyCoordinatesForEnemy[rand.Next(0, data.LikelyCoordinatesForEnemy.Count)]; data.LikelyCoordinatesForEnemy.Remove(coord); data.FieldForEnemy.Remove(coord); } else { coord = data.FieldForEnemy[rand.Next(0, data.FieldForEnemy.Count)]; data.FieldForEnemy.Remove(coord); } AttackEnemy(enemyFieldForPlayer, enemyField, playerField, data, coord); } static void AttackEnemy(int[,] enemyFieldForPlayer, int[,] enemyField, int[,] playerField, Data data, Coordenate hitCoord) { if (playerField[hitCoord.X, hitCoord.Y] == 0) { playerField[hitCoord.X, hitCoord.Y] = MissValue; FieldOutput(playerField, enemyFieldForPlayer); Console.WriteLine("Fortunately, the enemy missed!"); StepPlayer(enemyFieldForPlayer, enemyField, playerField, data); } else { int countDecks = 0; if (data.Touch) { data.TouchCount++; if (data.TouchCount == playerField[hitCoord.X, hitCoord.Y]) { data.Touch = false; data.Dir = data.Dir == Direction.None ? FindDirection(data.DecksShip) : data.Dir; data.DecksShip.Add(hitCoord); data.DecksShip = StartEndShip(data.Dir, data.DecksShip); countDecks = data.DecksShip.Count; playerField = MarkBorders(playerField, data.DecksShip[0], data.DecksShip[data.DecksShip.Count - 1], data); } else { data.Dir = data.Dir == Direction.None ? FindDirection(data.DecksShip) : data.Dir; data.DecksShip.Add(hitCoord); data.DecksShip = StartEndShip(data.Dir, data.DecksShip); } } else if (IntegrityCheck(playerField, hitCoord.X, hitCoord.Y)) { data.Touch = true; data.TouchCount = 1; data.DecksShip = new List<Coordenate>(); data.DecksShip.Add(hitCoord); data.Dir = Direction.None; } else { countDecks = 1; playerField = MarkBorders(playerField, hitCoord, hitCoord, data); } playerField[hitCoord.X, hitCoord.Y] = HitValue; FieldOutput(playerField, enemyFieldForPlayer); if (countDecks != 0) { WriteHitEnemyPLeyersShip(countDecks); } else { Console.WriteLine("You hit!"); } data.CountEnemy++; StepEnemy(enemyFieldForPlayer, enemyField, playerField, data); } } static void WriteHitEnemyPLeyersShip(int countDecks) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Your {0} decker ship is destroyed!", countDecks); Console.ForegroundColor = ConsoleColor.Gray; Console.ReadLine(); } static List<Coordenate> SearchNeighboring(Data data) { Coordenate temp = data.DecksShip[0]; List<Coordenate> tempList = new List<Coordenate>(); foreach (Coordenate c in data.FieldForEnemy) { if (data.Dir == Direction.None && CheckNeighborhoodWithPoint(temp, c) && !tempList.Contains(c)) { tempList.Add(c); } } for (int i = 0; i < 2; i++) { foreach (Coordenate c in data.FieldForEnemy) { if (CheckExtremePoint(temp, c, data.Dir) && !tempList.Contains(c)) { tempList.Add(c); } } temp = data.DecksShip[data.DecksShip.Count - 1]; } return tempList; } static bool CheckNeighborhoodWithPoint(Coordenate mainPoint, Coordenate checkPoint) { return (checkPoint.X == mainPoint.X && (checkPoint.Y == mainPoint.Y + 1 || checkPoint.Y == mainPoint.Y - 1)) || (checkPoint.Y == mainPoint.Y && (checkPoint.X == mainPoint.X + 1 || checkPoint.X == mainPoint.X - 1)); } static bool CheckExtremePoint(Coordenate mainPoint, Coordenate checkPoint, Direction dir) { if (dir == Direction.Up && (checkPoint.Y == mainPoint.Y && (checkPoint.X == mainPoint.X + 1 || checkPoint.X == mainPoint.Y - 1))) { return true; } if (dir == Direction.Left && (checkPoint.X == mainPoint.X && (checkPoint.Y == mainPoint.Y + 1 || checkPoint.Y == mainPoint.Y - 1))) { return true; } return false; } static Direction FindDirection(List<Coordenate> coords) { Direction dir = Direction.None; if (coords.Count <= 1) { return dir; } if (coords[0].X - coords[1].X > 0 || coords[0].X - coords[1].X < 0) { dir = Direction.Up; } else if (coords[0].Y - coords[1].Y > 0 || coords[0].Y - coords[1].Y < 0) { dir = Direction.Left; } return dir; } static bool IntegrityCheck(int[,] field, int x, int y) { return field[x, y] > 1 && field[x, y] != 0; } static int[,] MarkBorders(int[,] field, Coordenate start, Coordenate end, Data data) { for (int i = data.FieldForEnemy.Count - 1; i > 0; i--) { if ((data.FieldForEnemy[i].X >= start.X - 1 && data.FieldForEnemy[i].X <= end.X + 1) && (data.FieldForEnemy[i].Y >= start.Y - 1 && data.FieldForEnemy[i].Y <= end.Y + 1)) { field[data.FieldForEnemy[i].X, data.FieldForEnemy[i].Y] = MissValue; data.FieldForEnemy.Remove(data.FieldForEnemy[i]); } } return field; } static List<Coordenate> StartEndShip(Direction dir, List<Coordenate> coordDecks) { if (coordDecks.Count <= 1) { return coordDecks; } Coordenate temp; if (dir == Direction.Up) { for (int i = 0; i < coordDecks.Count; i++) { for (int j = i + 1; j < coordDecks.Count; j++) { if (coordDecks[j].X < coordDecks[i].X) { temp = coordDecks[i]; coordDecks[i] = coordDecks[j]; coordDecks[j] = temp; } } } } else if (dir == Direction.Left) { for (int i = 0; i < coordDecks.Count; i++) { for (int j = i + 1; j < coordDecks.Count; j++) { if (coordDecks[j].Y < coordDecks[i].Y) { temp = coordDecks[i]; coordDecks[i] = coordDecks[j]; coordDecks[j] = temp; } } } } return coordDecks; } static bool CheckWiner(Data data) { if (data.CountPlayer == CountHitForWin) { Console.WriteLine("The game is over! You won!"); return true; } if (data.CountEnemy == CountHitForWin) { Console.WriteLine("The game is over! You lose!"); return true; } return false; } static string[] ReadFile(string puth) { StreamReader sr = new StreamReader(puth); string[] temp = new string[SizeField]; for (int i = 0; i < SizeField; i++) { temp[i] = sr.ReadLine(); } return temp; } static int[,] FieldArrayFilling(string[] lines) { int[,] coordinates = new int[SizeField, SizeField]; for (int i = 0; i < lines.Length; i++) { for (int j = 0; j < lines[i].Length; j++) { coordinates[i, j] = int.Parse(lines[i][j].ToString()); } } return coordinates; } static int[,] FieldEnemy() { string[] field = new string[SizeField]; StringBuilder sb = new StringBuilder(""); for (int i = 0; i < SizeField; i++) { sb.Clear(); for (int j = 0; j < SizeField; j++) { sb.Append("0"); } field[i] = sb.ToString(); } return FieldArrayFilling(field); } static int[,] RandomShipsEnemy(int[,] enemyField) { int numberEmpty = 7; enemyField = SpawnShips(enemyField, 4, 1, numberEmpty); enemyField = SpawnShips(enemyField, 3, 2, numberEmpty); enemyField = SpawnShips(enemyField, 2, 3, numberEmpty); enemyField = SpawnShips(enemyField, 1, 4, numberEmpty); for (int i = 0; i < SizeField; i++) { for (int j = 0; j < SizeField; j++) { if (enemyField[i, j] == numberEmpty) { enemyField[i, j] = 0; } } } return enemyField; } static int[,] SpawnShips(int[,] enemyField, int countDeck, int countShips, int numberEmpty) { Random rand = new Random(); int[,] temp = null; for (int i = 0; i < countShips; i++) { while (temp == null) { temp = SetDeckShip(enemyField, rand.Next(0, SizeField), rand.Next(0, SizeField), countDeck, HorizontalAndVertical(), numberEmpty); } enemyField = temp; temp = null; } return enemyField; } static int HorizontalAndVertical() { Random rand = new Random(); return rand.Next(0, 1000) > 500 ? 1 : 0; } static int[,] SetDeckShip(int[,] enemyField, int x, int y, int numberDeck, int horVer, int numberEmpty) { if (enemyField[x, y] != 0) { return null; } else { if (horVer == 1) { enemyField = HorizontalSpawn(enemyField, numberDeck, numberEmpty, x, y); } else { enemyField = VerticalSpawn(enemyField, numberDeck, numberEmpty, x, y); } } return enemyField; } static int[,] HorizontalSpawn(int[,] field, int countDeck, int numberEmpty, int x, int y) { bool stop = false; int count = 0; int start = y; for (int i = 0; i < countDeck; i++) { if (y + i >= SizeField || field[x, y + i] == numberEmpty) { stop = true; break; } count++; } if (stop) { for (int i = 0; i < countDeck - count; i++) { if (y - i <= 0 || field[x, y - i] == numberEmpty) { return null; } start -= 1; } } for (int i = start; i < start + countDeck; i++) { field[x, i] = countDeck; } for (int i = start - 1; i < start + countDeck + 1; i++) { for (int j = x - 1; j <= x + 1; j++) { if (i >= 0 && i < SizeField && j >= 0 && j < SizeField && field[j, i] != countDeck) { field[j, i] = numberEmpty; } } } return field; } static int[,] VerticalSpawn(int[,] field, int countDeck, int numberEmpty, int x, int y) { bool stop = false; int count = 0; int start = x; for (int i = 0; i < countDeck; i++) { if (x + i >= SizeField || field[x + i, y] == numberEmpty) { stop = true; break; } count++; } if (stop) { for (int i = 0; i < countDeck - count; i++) { if (x - i <= 0 || field[x - i, y] == numberEmpty) { return null; } start -= 1; } } for (int i = start; i < start + countDeck; i++) { field[i, y] = countDeck; } for (int i = start - 1; i < start + countDeck + 1; i++) { for (int j = y - 1; j <= y + 1; j++) { if (i >= 0 && i < SizeField && j >= 0 && j < SizeField && field[i, j] != countDeck) { field[i, j] = numberEmpty; } } } return field; } static int ParameterSetting(int count, int coord) { return coord + count; } static void FieldOutput(int[,] playerField, int[,] enemyField) { Console.Clear(); WriteCoordenates(); WriteCoordenates(); Console.WriteLine(); Console.WriteLine(); for (int i = 0; i < SizeField; i++) { if (i < 9) { Console.Write(i + 1 + " "); } else { Console.Write(i + 1 + " "); } WriteLineField(i, playerField, ConsoleColor.DarkBlue, ConsoleColor.DarkRed, ConsoleColor.Yellow, true); Console.Write(" "); WriteLineField(i, enemyField, ConsoleColor.DarkBlue, ConsoleColor.DarkRed, ConsoleColor.DarkGreen, false); Console.Write(" "); Console.Write(i + 1); Console.WriteLine(); } } static void WriteLineField(int x, int[,] field, ConsoleColor colorFone, ConsoleColor colorMiss, ConsoleColor colorHit, bool playerField) { Console.BackgroundColor = colorFone; for (int j = 0; j < SizeField; j++) { if (field[x, j] == MissValue) { WriteCoordenate(colorFone, colorMiss, x, j, field); } else if ((playerField && field[x, j] == HitValue) || (!playerField && field[x, j] != 0)) { WriteCoordenate(colorFone, colorHit, x, j, field); } else { WriteCoordenate(colorFone, colorFone, x, j, field); } } Console.BackgroundColor = ConsoleColor.Black; } static void WriteCoordenate(ConsoleColor colorFone, ConsoleColor colorCoord, int x, int y, int[,] field) { Console.BackgroundColor = colorCoord; Console.Write(field[x, y] + " "); Console.BackgroundColor = colorFone; } static void WriteCoordenates() { Console.Write(" "); for (int j = 0; j < SizeField; j++) { Console.Write(j + 1 + " "); } } //The field debug method, in order to find out how the enemy has placed the ships. static void DebugField(int[,] field = null) { for (int i = 0; i < SizeField; i++) { Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine(); Console.BackgroundColor = ConsoleColor.DarkBlue; for (int j = 0; j < SizeField; j++) { if (field[i, j] == MissValue) { Console.BackgroundColor = ConsoleColor.DarkRed; Console.Write(field[i, j] + " "); Console.BackgroundColor = ConsoleColor.DarkBlue; } else if (field[i, j] != 0) { Console.BackgroundColor = ConsoleColor.DarkGreen; Console.Write(field[i, j] + " "); Console.BackgroundColor = ConsoleColor.DarkBlue; } else { Console.Write(field[i, j] + " "); } } Console.BackgroundColor = ConsoleColor.Black; } Console.WriteLine(); Console.ReadLine(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BattleShip { public struct Coordenate { public Coordenate(int x, int y) { X = x; Y = y; } public int X; public int Y; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BattleShip { public class Data { public int CountPlayer = 0; public int CountEnemy = 0; public List<Coordenate> FieldForEnemy; public bool Touch = false; public int TouchCount = 0; //public Coordenate OneTouch; //public Coordenate EndTouch; public List<Coordenate> LikelyCoordinatesForEnemy; public Direction Dir; public List<Coordenate> DecksShip; } }
b12376b2ab3d1e50728b91f15f479ec45a6f9ccc
[ "C#" ]
3
C#
Valentinchik/BottleShip
4ef0f0b182b20e7b79be3df6fd8aa758c481dd64
152634ce7556ef5ed8c9e0cf2ab7abf403d68934
refs/heads/master
<file_sep># Parse Cloud Code The cloud code for parse focusing on crawling the information of Tickleapp and its opponent daily. # Install Parse Run the following script in terminal. ```shell $ curl -s https://www.parse.com/downloads/cloud_code/installer.sh | sudo /bin/bash ``` # Initialization - Clone the repo. - Rename ```.parse.local.dist``` to ```.parse.local``` - Add the ```applicationId``` in ```.parse.local``` - Rename ```global.json.dist``` in the ```config``` folder to ```global.json``` - Add the ```applicationId``` and ```masterKey``` in ```global.json``` # Development - Run ```$ parse develop "Tickle Dashboard"``` in Terminal. Now the parse app will automatically deploy when you make any file change. # Scheduling Parse Cloud Job In order to hide the private information of our keys. Make sure you set the ```Parameter``` in scheduling panel when adding new job. The desired format is: ```json { "consumerSecret": "YOUR_TWITTER_COMSUMER_SECRET_KEY", "oauth_consumer_key": "YOUR_TWITTER_COMSUMER_KEY", "tokenSecret": "YOUR_TWITTER_ACCESS_TOKEN_SECRET_KEY", "oauth_token": "YOUR_TWITTER_ACCESS_TOKEN_KEY" } ```<file_sep># Dashing ### Description This is the Dashboard for multiple analytics metrics of our interested twitter accounts(screenName). ![screen shot 2015-11-18 at 9 47 40 am](https://cloud.githubusercontent.com/assets/2673743/11230375/5b5d10e8-8dd9-11e5-942c-eba2b2283f65.png) ### There are five main widget: - Daily followers growth - Daily mentioned - If a tweet is contains screenName of this account, and - If a tweet is not tweet by its owner, and - If a tweet is original tweets, and - Then this tweet is counted as one mentioned - Daily shared - If a tweet is not tweet by its owner, and - If a tweet is original tweets, and - media url contains - vine - instagram - youtube.com - youtu.be - twitter - Daily retweeted - Each tweets calculation task of a screenName we will have a query window, normally contains 3200 of tweets(constrained by Twitter API). Of course, the historical tweets of one account is far more than 3200 tweets. The calculation will add up each tweets metrics within this window and every historical tweets - Daily favorited - same as retweeted ### Dashboard Tools - shopify/Dashing - HighStock - adelevie/parse-ruby-client ### File structure - dashing/ - jobs/ - Ruby backend's jobs - dashboards/ - Dashboards layout - widgets/ - individual widgets - assets - javascripts - application.coffee - javascript entry point - config.ru - ruby entry point, where OAuth lives ### Usage - Set up ENV Path of the following - ENV['RACK_COOKIE_SECRET'] - random key - ENV['GOOGLE_KEY'] - google app public key - ENV['GOOGLE_SECRET'] - google app secret key - ENV['PARSE_API_KEY'] - ENV['PARSE_APPLICATION_ID'] - ENV['TWITTER_CONSUMER_KEY'] - ENV['TWITTER_CONSUMER_SECRET'] - ENV['TWITTER_ACCESS_TOKEN'] - ENV['TWITTER_ACCESS_TOKEN_SECRET'] - In terminal, run ```dashing start``` ### Deploying - In root directory, run ```git subtree push --prefix dashing heroku-dashboard master``` , 'dashing' is the sub-directory name, 'heroku-dashboard' is your heroku git(you have to set the remote link), 'master' is the heroku default branch # Dashboard Parse Worker ### Description This Parse Cloud code and be run in pure NodeJS environment. We deploy it on Heroku [tickle-dashboard-worker](https://dashboard.heroku.com/apps/tickle-dashboard-worker/resources) and set with a scheduler running every hour. ### Usage In local environment, we use [parse-cloud-runner](https://github.com/tickleapp/parse-cloudcode-runner) as a NodeJS wrapper. - Set the following code after require of ```./cloud/main.js``` ```javascript if (typeof Parse === 'undefined') { var Parse = require('parse-cloudcode-runner').Parse; Parse.initialize({PARSE_APPLICATION_ID}, {PARSE_JAVASCRIPT_KEY}, {PARSE_MASTER_KEY}); } ``` - In "twitterParser" job, set ```javascript consumerSecret : {consumerSecret}, oauth_consumer_key : {oauth_consumer_key}, tokenSecret : {tokenSecret}, oauth_token : {oauth_token}, ``` - Run the following in Terminal - ```./node_modules/.bin/parse-cloudcode-runner testParseSave -t job``` ### Deploying In root directory, run ```git subtree push --prefix parse heroku-worker master``` , 'parse' is the sub-directory name, 'heroku-worker' is your heroku git(you have to set the remote link), 'master' is the heroku default branch # Educator Cralwer ### Description: This Crawler using [cgiffard/simplecraler](https://github.com/cgiffard/node-simplecrawler), and PhantomJS to crawl the following websites: - http://events.codeweek.eu/ - http://day.scratch.mit.edu/ #### Euro Code week The links to be crawled structure like this ```http://events.codeweek.eu/view/{evebt_number}``` Hence, we push a list of url, ```http://events.codeweek.eu/view/1``` ~ ```http://events.codeweek.eu/view/20000```, for example. And let the PhantonJS run. ##### Code Snippet: ```javascript var baseUrl = "http://events.codeweek.eu/view/" var range = 20000, offset = 2661; for (var i = offset ; i < range ; i++) { euroCodeCrawler.queueURL(baseUrl+i); phantomQueue.push(baseUrl+i); } processQueue(phantom, function() {}, getEuroLinks); ``` #### ScratchDay The links to be crwaled of ScratchDay structured like this ```http://day.scratch.mit.edu/events/search/?search_location={Country}``` We utilized this countried array ```javascript var countries = ["Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"]; ``` to compose the links. Different from Euro Code week, these links are the list pages of events that near the query location. One have to click on the item to enter event page. Here's where SimpleCrawler comes in hand, the crawler will traverse every link apears on the page, and recursive until there's no more un-visited links. #### Before Run The crawler make use of Google Map API, run the following in terminal > export GMAP_PRIVAT_KEY={your_gmap_key} ### Usage: #### for crawling ScratchDay > node index.js -s #### for crawling EU Code Week > node index.js -e ### Output The output will be located in ```output``` as ```scratch-day-{date}.csv``` or ```euro-code-week-{date}.csv``` <file_sep>require 'twitter' require 'json' require 'pp' twitter = Twitter::REST::Client.new do |config| config.consumer_key = ENV['TWITTER_CONSUMER_KEY'] config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET'] config.access_token = ENV['TWITTER_ACCESS_TOKEN'] config.access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET'] end search_term = URI::encode('@tickleapp') SCHEDULER.every '30s', :first_in => 0 do |job| begin timelines = Array.new users = ["tickleapp", "wonderworkshop", "spheroedu", "gotynker", "hopscotch", "codehs", "kodable", "codeorg", "scratch", "trinketapp"] users.each do |user| timeline = twitter.user(user); pp user if timeline hash = { name: timeline.screen_name, follower: timeline.followers_count, favorites: timeline.favourites_count, tweets: timeline.statuses_count, description: timeline.description, profile_image_url: timeline.profile_image_url, profile_banner_url: timeline.profile_banner_url } timelines.push hash end end send_event('users', data: timelines) end end SCHEDULER.every '10m', :first_in => 0 do |job| begin tweets = twitter.search("#{search_term}") if tweets tweets = tweets.map do |tweet| { name: tweet.user.name, body: tweet.text, avatar: tweet.user.profile_image_url_https } end send_event('twitter_mentions', comments: tweets) end rescue Twitter::Error puts "\e[33mFor the twitter widget to work, you need to put in your twitter API keys in the jobs/twitter.rb file.\e[0m" end end <file_sep>var _ = require('underscore'); var sleep = require('sleep'); var oauth = require("cloud/libs/oauth.js"); if (typeof Parse === 'undefined') { var Parse = require('parse-cloudcode-runner').Parse; Parse.initialize(process.env.PARSE_APPLICATION_ID, process.env.PARSE_JAVASCRIPT_KEY, process.env.PARSE_MASTER_KEY); } /** * Twitter Object constructor. * * @param params * @constructor */ var Twitter = function (params) { this.tableName = params.tableName; this.screenNames = params.screenNames; this.tweetsPerPage = params.tweetsPerPage; this.tweetsPerSearchPage = params.tweetsPerSearchPage; this.maxQueryTweets = params.maxQueryTweets; this.mentionsTable = params.mentionsTable; this.timelineTable = params.timelineTable; // Setup twitter app keys for Twitter API this.consumerSecret = params.consumerSecret; this.oauth_consumer_key = params.oauth_consumer_key; this.tokenSecret = params.tokenSecret; this.oauth_token = params.oauth_token; this.ts = new Date().getTime() / 1000; this.timestamp = Math.floor(this.ts).toString(); this.twitterAccessor = { consumerSecret: this.consumerSecret, tokenSecret: this.tokenSecret }; // Metrics counter this.counters = { totalTweets: 0, totalFavorited: 0, totalRetweeted: 0, originalTweets: 0, totalReplies: 0, totalRetweets: 0, totalReplied: 0, totalMetioned: 0, totalOriginalMetioned: 0, totalOriginalSharedTwitter: 0, totalOriginalSharedOther: 0, totalSharedTwitter: 0, totalSharedOther: 0 }; this.data = []; this.mentionedTweets = []; this.tweets = []; this.test = []; }; Twitter.prototype = { // Implementation of Twitter oauth authentication initializeApi: function (url) { var urlLink = url; // Setup shared vars for Twitter API var nonce = oauth.nonce(32); var twitterParams = { oauth_version: "1.0", oauth_consumer_key: this.oauth_consumer_key, oauth_token: this.oauth_token, oauth_timestamp: this.timestamp, oauth_nonce: nonce, oauth_signature_method: "HMAC-SHA1" }; var message = { method: "GET", action: urlLink, parameters: twitterParams }; oauth.SignatureMethod.sign(message, this.twitterAccessor); var sig = oauth.getParameter(message.parameters, "oauth_signature") + "="; var encodedSig = oauth.percentEncode(sig); return 'OAuth oauth_consumer_key="' + this.oauth_consumer_key + '", oauth_nonce=' + nonce + ', oauth_signature=' + encodedSig + ', oauth_signature_method="HMAC-SHA1", oauth_timestamp=' + this.timestamp + ',oauth_token="' + this.oauth_token + '", oauth_version="1.0"'; }, /** * getIncrementSinceId * * since id is a big number in string format, ex: 654328939449848 * * we want to make this number add integer 1 and get newer timestring. * * @param sinceId * @returns {string} */ getIncrementSinceId: function (sinceId) { var i, currentDigit, index = 1, borrowDigit = true, length = sinceId.length; function setCharAt(str, index, chr) { if (index > str.length - 1) { return str; } return str.substr(0, index) + chr + str.substr(index + 1); } while (borrowDigit) { i = length - index; currentDigit = sinceId[i]; currentDigit = parseInt(currentDigit) + 1; if (currentDigit < 10) { borrowDigit = false; sinceId = setCharAt(sinceId, i, currentDigit.toString()); continue; } sinceId = setCharAt(sinceId, i, "0"); index += 1; } return sinceId; }, /** * getDecrementMaxId * * max id is a big number in string format, ex: 654328939449848 * * we want to make this number minus integer 1 and get older timestring. * * @param sinceId * @returns {string} */ getDecrementMaxId: function (maxIdStr) { var i, currentDigit, index = 1, borrowDigit = true, length = maxIdStr.length; function setCharAt(str, index, chr) { if (index > str.length - 1) { return str; } return str.substr(0, index) + chr + str.substr(index + 1); } while (borrowDigit) { i = length - index; currentDigit = maxIdStr[i]; currentDigit = parseInt(currentDigit) - 1; if (currentDigit >= 0) { borrowDigit = false; maxIdStr = setCharAt(maxIdStr, i, currentDigit.toString()); continue; } maxIdStr = setCharAt(maxIdStr, i, "0"); index += 1; } return maxIdStr; }, /** * queryUserTimelineApiCallback * * pair function with, `queryUserTimelineApi`, make a recursive call to `queryUserTimelineApi` if more tweets need to be query next. * * @param recordLength * @param nextMaxId * @param screenName * @param promise * @returns {*} */ queryUserTimelineApiCallback: function (recordLength, nextMaxId, screenName, promise) { if (this.counters.totalTweets <= this.maxQueryTweets && recordLength > 0) { return this.queryUserTimelineApi(nextMaxId, screenName, promise); } else { //console.log("RecordLength: " + recordLength); // When there's no further page left this.data[screenName].favorited = this.counters.totalFavorited; this.data[screenName].retweeted = this.counters.totalRetweeted; this.data[screenName].replies = this.counters.totalReplies; this.data[screenName].tweets = this.counters.originalTweets - this.counters.totalReplies; this.data[screenName].retweets = this.counters.totalRetweets; this.data[screenName].totalTweets = this.counters.totalTweets; //console.log((new Date().getTime() / 1000) + " " + JSON.stringify(this.data[screenName])); return Parse.Promise.as(); //promise.resolve(); } }, /** * queryUserTimelineApi * * called by performUserTweetsAnalytics, search for tweets by input screenName * * @param maxId * @param screenName * @param promise * @returns {promise} */ queryUserTimelineApi: function (maxId, screenName, promise) { var that = this; //var promise = promise || new Parse.Promise(); // Initialize max_id maxId = maxId || 0; // Prepare concatenating for max_id query string var maxIdStr = (maxId === 0) ? '' : '&max_id=' + maxId; var url = "https://api.twitter.com/1.1/statuses/user_timeline.json?include_rts=1&screen_name=" + screenName + "&count=" + that.tweetsPerPage + maxIdStr; var apiAuthorizationHeaders = that.initializeApi(url); return Parse.Cloud.httpRequest({ method: "GET", url: url, headers: { Authorization: apiAuthorizationHeaders }}).then(function (httpResponse) { var i, nextMaxId = 0; var results = JSON.parse(httpResponse.text); that.counters.totalTweets += results.length; for (i = 0; i < results.length; i++) { // Calculating metrics if (typeof(results[i].retweeted_status) === 'undefined') { that.counters.totalFavorited += results[i].favorite_count; that.counters.totalRetweeted += results[i].retweet_count; that.counters.originalTweets += 1; // Saving tweets to data object that.data[screenName].tweetsDetails.push(results[i]); } else { that.counters.totalRetweets += 1; } if (results[i].in_reply_to_screen_name !== null) { that.counters.totalReplies += 1; } } // Search for older tweets if (results.length !== 0) { nextMaxId = that.getDecrementMaxId(results[results.length - 1].id_str); } return that.queryUserTimelineApiCallback(results.length, nextMaxId, screenName, promise); }, function (httpResponse) { console.log("Twitter API error code: " + httpResponse.status); console.log(JSON.stringify(httpResponse)); }); //return promise; }, /** * performUserTweetsAnalytics * * @returns {Promise} */ performUserTweetsAnalytics: function () { var that = this; var promise = Parse.Promise.as(); _.each(that.screenNames, function (screenName) { promise = promise.then(function () { // Reset all counters for (var key in that.counters) { that.counters[key] = 0; } console.log((new Date().getTime() / 1000) + " performUserTweetsAnalytics ScreenName: " + screenName); return that.queryUserTimelineApi(null, screenName); }); // promise }); // _.each return promise; }, /** * getFormatedMention * * get populated data of mention object * * @param data * @param name * @returns {*} */ getFormatedMention: function (data, name) { var mentioningPrototype = Parse.Object.extend(this.mentionsTable); var mention = new mentioningPrototype(); mention.set("created_at", data.created_at); mention.set("id_str", data.id_str); mention.set("text", data.text); mention.set("source", data.source); mention.set("mentioning", name); mention.set("in_reply_to_screen_name", data.in_reply_to_screen_name); mention.set("in_reply_to_status_id", data.in_reply_to_status_id); mention.set("in_reply_to_status_id_str", data.in_reply_to_status_id_str); mention.set("in_reply_to_user_id", data.in_reply_to_user_id); mention.set("in_reply_to_user_id_str", data.in_reply_to_user_id_str); mention.set("in_reply_to_screen_name", data.in_reply_to_screen_name); mention.set("user_id_str", data.user.id_str); mention.set("user_screen_name", data.user.screen_name); mention.set("user_location", data.user.location); mention.set("entities_hashtags", JSON.stringify(data.entities.hashtags)); mention.set("entities_user_mentions", JSON.stringify(data.entities.user_mentions)); mention.set("entities_urls", JSON.stringify(data.entities.urls)); mention.set("entities_media", JSON.stringify(data.entities.media)); return mention; }, /** * querySearchApiCallback * * pair with querySearchApi, recursively call querySerchApi if more tweets left. Else resolve promise. * * @param direction * @param recordLength * @param nextMaxId * @param nextSinceId * @param screenName * @param promise * @returns {*|Parse.Promise} */ querySearchApiCallback: function (direction, recordLength, nextMaxId, nextSinceId, screenName, promise) { if (this.counters.totalTweets <= this.maxQueryTweets && recordLength > 0) { //console.log("RecordLength: " + recordLength); return this.querySearchApi(direction, nextMaxId, nextSinceId, screenName, promise); } else { console.log("RecordLength: " + this.counters.totalTweets); //console.log((new Date().getTime() / 1000) + " " + JSON.stringify(this.data[screenName])); promise.resolve(); } }, /** * querySearchApi * * search for tweets of particular user(screenName), include_entities means including media information. * * @param direction * @param maxId * @param sinceId * @param screenName * @param promise * @returns {*|Parse.Promise} */ querySearchApi: function (direction, maxId, sinceId, screenName, promise) { var that = this; var promise = promise || new Parse.Promise(); // Initialize max_id maxId = (maxId == null) ? '' : maxId; sinceId = (sinceId == null) ? '' : sinceId; // Prepare concatenating for max_id query string var maxIdStr = (maxId === '') ? '' : '&max_id=' + maxId; var sinceIdStr = (sinceId === '') ? '' : '&since_id=' + sinceId; var url = "https://api.twitter.com/1.1/search/tweets.json?q=" + encodeURIComponent("@") + screenName + "&count=" + that.tweetsPerSearchPage + maxIdStr + sinceIdStr + "&include_entities=true"; var apiAuthorizationHeaders = that.initializeApi(url); Parse.Cloud.httpRequest({ method: "GET", url: url, headers: { Authorization: apiAuthorizationHeaders }, success: function (httpResponse) { var i, nextMaxId = null, nextSinceId = null; var results = JSON.parse(httpResponse.text).statuses; var data = that.mentionedTweets; //console.log(results.length); for (i = 0; i < results.length; i++) { that.counters.totalTweets += 1; //console.log(results[i].entities.urls); data.push(that.getFormatedMention(results[i], screenName)); } if (results.length !== 0 && direction === 'backward') { nextMaxId = that.getDecrementMaxId(results[results.length - 1].id_str); //console.log("Next Max Id: " + nextMaxId); } else if (results.length !== 0 && direction === 'forward') { nextSinceId = that.getIncrementSinceId(results[0].id_str); //console.log("Next Since Id: " + nextSinceId); } return that.querySearchApiCallback(direction, results.length, nextMaxId, nextSinceId, screenName, promise); }, error: function (httpResponse) { console.log("Twitter API error code: " + httpResponse.status); promise.reject(JSON.stringify(httpResponse)); } }); // httpRequest return promise; }, performMentioningSearch: function (direction) { var that = this; var promise = Parse.Promise.as(); direction = direction || "backward"; if (["forward", "backward"].indexOf(direction) === -1) { return promise; } _.each(that.screenNames, function (screenName) { promise = promise.then(function () { // Reset all counters for (var key in that.counters) { that.counters[key] = 0; } console.log((new Date().getTime() / 1000) + " performMentioningSearch ScreenName: " + screenName); return Parse.Promise.as(screenName).then(function (name) { var mentioningPrototype = Parse.Object.extend(that.mentionsTable); var query = new Parse.Query(mentioningPrototype); if (direction == "forward") { query.descending("id_str"); } else { query.ascending("id_str"); } query.equalTo("mentioning", name); query.limit(1); return query.find().then(function (result) { var idStr = ''; var idHandler = { maxId: null, sinceId: null }; if (result.length !== 0) { idStr = result[0].get("id_str"); //console.log("Indexing id_str for " + name + " : " + idStr); if (direction === "forward") { idHandler.sinceId = that.getIncrementSinceId(idStr); } else { idHandler.maxId = that.getDecrementMaxId(idStr); } } return Parse.Promise.as(idHandler); }); }).then(function (idHandler) { if (idHandler.maxId == null && idHandler.sinceId == null) { return Parse.Promise.as(); } return that.querySearchApi(direction, idHandler.maxId, idHandler.sinceId, screenName, null).then(function () { return Parse.Promise.as(); }); }); }); // promise }); // _.each return promise; }, /** * initDataObject * * @param name */ initDataObject: function (name) { this.data[name] = { screen_name: '', following: '', followers: '', favorites: '', favorited: '', listed: '', tweets: '', replies: '', retweets: '', retweeted: '', totalTweets: '', metioned: '', replied: '', shared: '', tweetsDetails: [] }; }, /** * performScreenNamesLookup * * get users' information * * @returns {*} */ performScreenNamesLookup: function () { var that = this; var url = "https://api.twitter.com/1.1/users/lookup.json?screen_name=" + this.screenNames.join(); var apiAuthorizationHeaders = that.initializeApi(url); return Parse.Cloud.httpRequest({ method: "GET", url: url, headers: { Authorization: apiAuthorizationHeaders }, success: function (httpResponse) { var i, name; var data = that.data; var results = JSON.parse(httpResponse.text); for (i = 0; i < results.length; i++) { name = results[i].screen_name.toLowerCase(); if (!(name in data)) { that.initDataObject(name); } data[name].screen_name = results[i].screen_name.toLowerCase(); data[name].following = results[i].friends_count; data[name].followers = results[i].followers_count; data[name].favorites = results[i].favourites_count; data[name].listed = results[i].listed_count; } }, error: function (httpResponse) { console.log('Request failed with response code ' + JSON.stringify(httpResponse)); } }); // httpRequest }, /** * savingUserTimelineStatus * * @returns {*} */ savingUserTimelineStatus: function () { var that = this; var promise = Parse.Promise.as(0); var i; for (i = 0; i < that.screenNames.length; i++) { promise = promise.then(function (k) { var name = that.screenNames[k]; console.log((new Date().getTime() / 1000) + " \Saving timeline: " + name); var userTimelinePrototype = Parse.Object.extend(that.timelineTable); var user = new userTimelinePrototype(); user.set("screen_name", that.data[name].screen_name); user.set("following", that.data[name].following ? that.data[name].following : 0); user.set("followers", that.data[name].followers ? that.data[name].followers : 0); user.set("favorites", that.data[name].favorites ? that.data[name].favorites : 0); user.set("favorited", that.data[name].favorited ? that.data[name].favorited : 0); user.set("listed", that.data[name].listed ? that.data[name].listed : 0); user.set("tweets", that.data[name].tweets ? that.data[name].tweets : 0); user.set("replies", that.data[name].replies ? that.data[name].replies : 0); user.set("retweets", that.data[name].retweets ? that.data[name].retweets : 0); user.set("retweeted", that.data[name].retweeted ? that.data[name].retweeted : 0); user.set("totalTweets", that.data[name].totalTweets ? that.data[name].totalTweets : 0); user.set("replied", that.data[name].totalReplied ? that.data[name].totalReplied : 0); user.set("mentioned", that.data[name].totalMetioned ? that.data[name].totalMetioned : 0); user.set("original_mentioned", that.data[name].totalOriginalMetioned ? that.data[name].totalOriginalMetioned : 0); user.set("shared_twitter", that.data[name].totalSharedTwitter ? that.data[name].totalSharedTwitter : 0); user.set("shared_other", that.data[name].totalSharedOther ? that.data[name].totalSharedOther : 0); user.set("original_shared_twitter", that.data[name].totalOriginalSharedTwitter ? that.data[name].totalOriginalSharedTwitter : 0); user.set("original_shared_other", that.data[name].totalOriginalSharedOther ? that.data[name].totalOriginalSharedOther : 0); user.set("historicalRetweet", that.data[name].historicalRetweet ? that.data[name].historicalRetweet : 0); user.set("historicalFavorite", that.data[name].historicalFavorite ? that.data[name].historicalFavorite : 0); user.set("oldestIdStrOfCurrentSearchWindow", that.data[name].oldestIdStrOfCurrentSearchWindow ? that.data[name].oldestIdStrOfCurrentSearchWindow : 0); user.set("newestIdStrOfCurrentSearchWindow", that.data[name].newestIdStrOfCurrentSearchWindow ? that.data[name].newestIdStrOfCurrentSearchWindow : 0); return user.save().then(function (objs) { console.log((new Date().getTime() / 1000) + " Saved " + name + " timeline."); return Parse.Promise.as(k + 1); }, function (e) { console.error(e); }); }); } return promise; }, /** * assignExistedTweetObjectId * * search if tweet existed, if true, assigning parse objectId to it before save. * * @param name */ assignExistedTweetObjectId: function (name) { var that = this; var tweetsPrototype = Parse.Object.extend("Tweets"); var skipStep = 1000; var queryCallback = function (length, date) { //console.log("In callback: length: " + length + ", skip: " + skip); if (length === skipStep) { return doQuery(date); } else { return Parse.Promise.as(); } }; var doQuery = function (date) { var i, j; var query = new Parse.Query(tweetsPrototype); query.select("objectId", "id_str", "screen_name"); query.equalTo("screen_name", name); query.lessThan("createdAt", date); query.limit(1000); return query.find().then(function (results) { for (i = 0; i < results.length; i++) { for (j = 0; j < that.length; j++) { if (that[j].id_str === results[i].get("id_str")) { that[j].objectId = results[i].id; } } } if (results.length != 0) { date = results[results.length-1].get("createdAt"); } return queryCallback(results.length, date); }); }; return doQuery(new Date()); }, /** * savingMentionsOnParse * * save all mentioning tweets * * @returns {*} */ savingMentionsOnParse: function () { var that = this; var beforeSaveTs = new Date().getTime() / 1000; // Perform Saving return Parse.Object.saveAll(that.mentionedTweets, { success: function (objs) { console.log((new Date().getTime() / 1000) + " Saved " + objs.length); }, error: function (e) { console.log("Saving tweets failed."); return Parse.Promise.as().reject("Saving tweets failed."); } }).then(function (objs) { var logPrototype = Parse.Object.extend("Logs"); var log = new logPrototype(); log.set("saving", objs.length); log.set("type", "mentions"); log.set("time", Math.floor((new Date().getTime() / 1000 - beforeSaveTs)).toString()); return Parse.Promise.as(); }); }, /** * calculatingMentioning * * count the state of mentioned, replied, shared media metrics of tweets mentioned particular user(screenName) * * @returns {*} */ calculatingMentioning: function () { var that = this; var promise = Parse.Promise.as(); var mentioningPrototype = Parse.Object.extend(that.mentionsTable); var skipStep = 1000; _.each(that.screenNames, function (screenName) { promise = promise.then(function () { // Reset all counters for (var key in that.counters) { that.counters[key] = 0; } console.log((new Date().getTime() / 1000) + " calculatingMentioning ScreenName: " + screenName); var queryCallback = function (length, date) { console.log("In callback: length: " + length); if (length === skipStep) { return doQuery(date); } else { that.data[screenName].totalReplied = that.counters.totalReplied; that.data[screenName].totalMetioned = that.counters.totalMetioned; that.data[screenName].totalOriginalMetioned = that.counters.totalOriginalMetioned; that.data[screenName].totalSharedTwitter = that.counters.totalSharedTwitter; that.data[screenName].totalSharedOther = that.counters.totalSharedOther; that.data[screenName].totalOriginalSharedTwitter = that.counters.totalOriginalSharedTwitter; that.data[screenName].totalOriginalSharedOther = that.counters.totalOriginalSharedOther; return Parse.Promise.as(); } }; var doQuery = function (date) { var query = new Parse.Query(mentioningPrototype); query.equalTo("mentioning", screenName); query.lessThan("createdAt", date); query.limit(1000); return query.find().then(function (results) { console.log((new Date().getTime() / 1000) + "mentioning result: " + results.length); for (var i = 0; i < results.length; i++) { if (results[i].get("user_screen_name") != screenName) { that.countMentioned(results[i]); that.countReplied(results[i]); that.countSharedTwitter(results[i]); that.countSharedOther(results[i]); } } return queryCallback(results.length, results[results.length-1].get("createdAt")); }, function(e) { console.log(JSON.stringify(e)); }); }; return doQuery(new Date()); }).then(function () { //console.log("Replied: " + that.counters.totalReplied); //console.log("Mentioned: " + that.counters.totalMetioned); //console.log("Original Mentioned(Not Retweet): " + that.counters.totalOriginalMetioned); //console.log("Original Shared Other(Not Retweet): " + that.counters.totalOriginalSharedOther); //console.log("Original Shared Twitter(Not Retweet): " + that.counters.totalOriginalSharedTwitter); //console.log("Shared Twitter: " + that.counters.totalSharedTwitter); //console.log("Shared Other: " + that.counters.totalSharedOther); //console.log("------------------------------"); }); // promise }); // _.each return promise; }, /** * batchSavingRecords * * saving on parse can be tricky since we cannot exceeed the request/sec policy. Thus, we exploit setTimeout method * to sleep through enough time. * * @param data * @returns {*} */ batchSavingRecords: function (data) { var that = this; var promise = Parse.Promise.as({"index": 0, "ts": (new Date).getTime()}); var perBatch = 20; var threshold = 1000; pages = Math.floor(data.length / perBatch); pages = (data.length % perBatch) > 0 ? pages + 1 : pages; console.log((new Date().getTime() / 1000) + " Total Tweets: " + data.length); console.log((new Date().getTime() / 1000) + " Total Pages: " + pages); for (var i = 0 ; i < pages ; i++) { promise = promise.then(function (k) { var spliceAmount = data.length > perBatch ? perBatch : data.length; var dataToSave = data.splice(0, spliceAmount); var pagePromise = new Parse.Promise(); Parse.Object.saveAll(dataToSave).then( function (objs) { var ts = (new Date).getTime(); var diff = ts - k.ts; console.log("Diff:" + diff, k.index); if (diff < threshold) { var toSleep = threshold - diff; console.log(toSleep); try { setTimeout(function(){ console.log("Saved Page. " + k.index); pagePromise.resolve({"index": k.index+1, "ts": (new Date).getTime()}); }, toSleep); } catch (e) { console.log(JSON.stringify(e)); } } else { pagePromise.resolve({"index": k.index+1, "ts": (new Date).getTime()}); } }).then(function(length) { return Parse.Promise.as(k+1); }, function(e) { console.log(JSON.stringify(e)); return Parse.Promise.as().reject("Saving tweets failed."); }); return pagePromise; }); } return promise; }, /** * queryOlderTweets * * read out the previous tweets * * @param name * @param maxId */ queryOlderTweets: function(name, maxId) { var that = this; var tweetsPrototype = Parse.Object.extend("Tweets"); var skipStep = 1000; var oldData = []; var queryCallback = function (length, date) { console.log("In callback: length: " + length ); if (length === skipStep) { return doQuery(date); } else { return Parse.Promise.as(oldData); } }; var doQuery = function (date) { var i, j; var query = new Parse.Query(tweetsPrototype); query.select("objectId", "id_str", "screen_name", "favorite_count", "retweet_count", "createdAt"); query.equalTo("screen_name", name); query.lessThan("createdAt", date); query.limit(1000); return query.find().then(function (results) { _.each(results, function(d) { if (d.get("id_str") < maxId) { oldData = oldData.concat(d); } }); console.log(results.length); if (results.length != 0) { date = results[results.length-1].get("createdAt"); } return queryCallback(results.length, date); }, function(e) { console.log(JSON.stringify(e)); }); }; return doQuery(new Date()); }, /** * calculateHistoricalMetrics * * read out historical tweets and perform metrics calculation * * @returns {*} */ calculateHistoricalMetrics: function() { var that = this; var promise = Parse.Promise.as(0); var n; for (n = 0; n < that.screenNames.length; n++) { promise = promise.then(function (nameIndex) { var name, length, data, maxId, favorited_num = 0, retweeted_num = 0; name = that.screenNames[nameIndex]; length = that.data[name].tweetsDetails.length; if (length == 0) { return Parse.Promise.as(nameIndex+1); } data = that.data[name].tweetsDetails; // sort id_str in "Ascending", before getting the search window boundry of id_str data.sort(function(a, b){ if(a.id_str < b.id_str) return 1; if(a.id_str > b.id_str) return -1; return 0; }); // Set oldest id_str of current search window that.data[name].oldestIdStrOfCurrentSearchWindow = maxId = data[length - 1].id_str; that.data[name].newestIdStrOfCurrentSearchWindow = data[0].id_str; data.map(function(d) { favorited_num += d.favorite_count; retweeted_num += d.retweet_count; }); return Parse.Promise.when(that.queryOlderTweets(name, maxId)).then(function(result) { result.map(function(d) { favorited_num += d.get("favorite_count"); retweeted_num += d.get("retweet_count"); }); that.data[name].historicalRetweet = retweeted_num; that.data[name].historicalFavorite = favorited_num; return Parse.Promise.as(nameIndex+1); }); }); } return promise; }, updateTweetsObjectId: function () { var tweetsPrototype = Parse.Object.extend("Tweets"); var that = this; var promise = Parse.Promise.as(0); var n; for (n = 0; n < that.screenNames.length; n++) { promise = promise.then(function (nameIndex) { var name = that.screenNames[nameIndex]; console.log(name); var length = that.data[name].tweetsDetails.length; console.log((new Date().getTime() / 1000) + " Prepare saving " + length + " tweets of - " + name); var i, beforeSaveTs = new Date().getTime() / 1000, tweets = [], assignIdPromise; assignIdPromise = that.assignExistedTweetObjectId.call(that.data[name].tweetsDetails, name).then(function () { for (i = 0; i < length; i++) { // Collects tweets to push var item = new tweetsPrototype(); item.id = that.data[name].tweetsDetails[i].objectId; item.set("text", that.data[name].tweetsDetails[i].text); item.set("source", that.data[name].tweetsDetails[i].source); item.set("retweet_count", that.data[name].tweetsDetails[i].retweet_count); item.set("created_at", that.data[name].tweetsDetails[i].created_at); item.set("favorite_count", that.data[name].tweetsDetails[i].favorite_count); item.set("retweeted", that.data[name].tweetsDetails[i].retweeted); item.set("id_str", that.data[name].tweetsDetails[i].id_str); item.set("entities", that.data[name].tweetsDetails[i].entities); item.set("screen_name", name); //console.log(that.data[name].tweetsDetails[i].favorite_count, that.data[name].tweetsDetails[i].objectId); //console.log(item.get("favorite_count")); tweets.push(item); } that.tweets = that.tweets.concat(tweets); return Parse.Promise.as(nameIndex+1); }); return assignIdPromise; }); // promise } // for loop return promise; }, /** * countMentioned * * @param data */ countMentioned: function (data) { if (data.get("in_reply_to_status_id") == null && data.get("in_reply_to_user_id") == null) { this.counters.totalMetioned += 1; if (data.get("text").indexOf("RT @") == -1) { this.counters.totalOriginalMetioned += 1; } } }, /** * countReplied * * @param data */ countReplied: function (data) { if (data.get("in_reply_to_status_id") || data.get("in_reply_to_user_id")) { this.counters.totalReplied += 1; } }, /** * countSharedTwitter * * User upload image or video by twitter. * * @param data */ countSharedTwitter: function (data) { // Calculate medias shared with Twitter Webapp if (data.get("entities_media")) { this.counters.totalSharedTwitter += 1; if (data.get("text").indexOf("RT @") == -1) { this.counters.totalOriginalSharedTwitter += 1; } } }, /** * countSharedOther * * Other media resource, other than upload using twitter. Including resource like youtube, instagram, vimeo and vine. * * @param data */ countSharedOther: function (data) { // Calculate medias shared with other services var urlsStr = typeof data.get("entities_urls") != "undefined" ? data.get("entities_urls") : "[]"; var urls = JSON.parse(urlsStr); var b_mediaCounted = false; for (var url_i = 0; url_i < urls.length; url_i++) { if (urls[url_i].expanded_url.indexOf("youtube.com") >= 0 || urls[url_i].expanded_url.indexOf("youtu.be") >= 0 || urls[url_i].expanded_url.indexOf("instagram.com") >= 0 || urls[url_i].expanded_url.indexOf("youtu.be") >= 0 || urls[url_i].expanded_url.indexOf("vimeo.com") >= 0 || urls[url_i].expanded_url.indexOf("vine.co") >= 0 ) { this.counters.totalSharedOther += 1; if (data.get("text").indexOf("RT @") == -1) { this.counters.totalOriginalSharedOther += 1; } } // Backward Compatible: some of the "entities_media" was stored in "entities_urls" column... It was previous mistake if (urls[url_i].type && !b_mediaCounted) { this.counters.totalSharedTwitter += 1; if (data.get("text").indexOf("RT @") == -1) { this.counters.totalOriginalSharedTwitter += 1; } // Count only once for multiple images/videos b_mediaCounted = true; } } } }; /** * JOB: twitterParser * * Parse users' timeline information by selected screen_name. Search users' tweets, performing favorited and retweeted * metrics. Search for mentioning and shared, save tweets on parse database. * * 1. performScreenNamesLookup * API: https://api.twitter.com/1.1/users/lookup.json?screen_name={$screen_name} * Purpose: User's information such as followers and tweets count etc.. * * 2. performUserTweetsAnalytics * API: https://api.twitter.com/1.1/statuses/user_timeline.json?include_rts=1&screen_name={$screen_name} * Purpose: Calculated user's own tweets * * 3. performMentioningSearch * API: https://api.twitter.com/1.1/search/tweets.json?q=foo * Purpose: Search for tweets that mentioning current user * * 4. savingMentionsOnParse * Purpose: Saved the cached tweets on Parse. * * 5. calculatingMentioning * Purpose: Perform calculation. * * 6. savingUserTimelineStatus * Purpose: Saving user timeline information. * * 7. updateTweetsObjectId * Purpose: Update rest of the information such as favorite_count and retweet_count * * 8. batchSavingRecords * Purpose: Save all the new tweets by the query user(ex: from tickleapp) */ Parse.Cloud.job("twitterParser", function (request, status) { Parse.Cloud.useMasterKey(); var that = this; var twitterParser = new Twitter( { // Parse Table name tableName: "user_status", mentionsTable: "metioning_history", timelineTable: "twitter_user_timeline", // screen_name to process screenNames: ["tickleapp", "wonderworkshop", "spheroedu", "gotynker", "hopscotch", "codehs", "kodable", "codeorg", "scratch", "trinketapp"], // NodeJs env setting, may be set in heroku dashboard consumerSecret : process.env.COMSUMER_SECRET, oauth_consumer_key : process.env.OAUTH_CONSUMER_KEY, tokenSecret : process.env.TOKEN_SECRET, oauth_token : process.env.OAUTH_TOKEN, tweetsPerPage: 200, tweetsPerSearchPage: 100, maxQueryTweets: 3200 } ); twitterParser.status = status; // Parsing Procedure Parse.Promise.when( twitterParser.performScreenNamesLookup() ).then(function () { console.log((new Date().getTime() / 1000) + " Finished performScreenNamesLookup."); return Parse.Promise.when(twitterParser.performUserTweetsAnalytics()); }).then(function () { console.log((new Date().getTime() / 1000) + " Finished performUserTweetsAnalytics."); return Parse.Promise.when(twitterParser.calculateHistoricalMetrics()); }).then(function () { console.log((new Date().getTime() / 1000) + " Finished calculateHistoricalMetrics."); return Parse.Promise.when(twitterParser.performMentioningSearch("forward")); }).then(function () { console.log((new Date().getTime() / 1000) + " Finished performMentioningSearch."); return Parse.Promise.when(twitterParser.savingMentionsOnParse()); }).then(function () { console.log((new Date().getTime() / 1000) + " Finished savingMentionsOnParse."); return Parse.Promise.when(twitterParser.calculatingMentioning()); }).then(function () { console.log((new Date().getTime() / 1000) + " Finished calculatingMentioning."); return Parse.Promise.when(twitterParser.savingUserTimelineStatus()); }).then(function () { console.log((new Date().getTime() / 1000) + " Finished savingUserTimelineStatus."); return Parse.Promise.when(twitterParser.updateTweetsObjectId()); }).then(function () { console.log((new Date().getTime() / 1000) + " Finished updateTweetsObjectId."); return twitterParser.batchSavingRecords(twitterParser.tweets); }); }); /** * JOB: testParseSave * * Unused Job, mainly the boilerplate of our saving method in Parse.com cloud function. Since we have limited request * per seconds, controlling save request is crucial. * * 'setTimeout' function is actually not functioning on Parse.com, however, we host our Cloud Job on heroku with pure Node.js Env. * */ Parse.Cloud.job("testParseSave", function (request, status) { Parse.Cloud.useMasterKey(); var i, pages, promise; var testPrototype = Parse.Object.extend("test"); var perBatch = 20; var data = []; for (i = 0; i < 3000 ; i++ ) { var test = new testPrototype(); test.set("ts", (new Date).getTime()); data.push(test); } // Calculation of total pages pages = Math.floor(data.length / perBatch); pages = (data.length % perBatch) > 0 ? pages + 1 : pages; promise = Parse.Promise.as({"index": 0, "ts": (new Date).getTime()}); for (i = 0; i < pages ; i++) { promise = promise.then(function(k) { var spliceAmount = data.length > perBatch ? perBatch : data.length; var dataToSave = data.splice(0, spliceAmount); var pagePromise = new Parse.Promise(); Parse.Object.saveAll(dataToSave).then( function(objs) { var ts = (new Date).getTime(); var diff = ts - k.ts; var threshold = 1000; console.log("Diff:" + diff, k.index); if (diff < threshold) { var toSleep = threshold - diff; console.log(toSleep); try { setTimeout(function(){ console.log("Saved Page. " + k.index); pagePromise.resolve({"index": k.index+1, "ts": (new Date).getTime()}); }, toSleep); } catch (e) { console.log(JSON.stringify(e)); } } else { pagePromise.resolve({"index": k.index+1, "ts": (new Date).getTime()}); } }, function(e) { console.log(JSON.stringify(e)); return promise.reject("Save error"); } ); return pagePromise; }); } Parse.Promise.when(promise).then( function() { console.log("Batch Save success."); }, function(e) { console.log(JSON.stringify(e)); } ); });<file_sep>source 'https://rubygems.org' gem 'dashing' ## Remove this if you don't need a twitter widget. gem 'twitter', '>= 5.9.0' gem 'rest-client' gem 'parse-ruby-client', git: 'https://github.com/adelevie/parse-ruby-client.git' gem "omniauth-google-oauth2" gem 'google-id-token', git: 'https://github.com/Nerian/google-id-token.git'<file_sep>var http = require('http'); var express = require('express'); var bodyParser = require('body-parser'); var ParseCloud = require('parse-cloud-express'); var Parse = ParseCloud.Parse; Parse.initialize('C7HX2LIkyy7gVxQWWfNMg6rWLYm03wPa9kIdI3T8', 'JOltyNQUQm0on6E04QrY2XICKogArMdE5eemQh0h', 'zLCPWgxcnuNR4T10ZLeM8YBbzN6RxAwtUxgt7rcc'); Parse.Cloud.useMasterKey(); var i, pages, promise; var testPrototype = Parse.Object.extend("test"); var perBatch = 20; var data = []; for (i = 0; i < 3000 ; i++ ) { var test = new testPrototype(); test.set("ts", (new Date).getTime()); data.push(test); } // Calculation of total pages pages = Math.floor(data.length / perBatch); pages = (data.length % perBatch) > 0 ? pages + 1 : pages; promise = Parse.Promise.as({"index": 0, "ts": (new Date).getTime()}); for (var j= 0; j < pages ; j++) { promise = promise.then(function(k) { var spliceAmount = data.length > perBatch ? perBatch : data.length; var dataToSave = data.splice(0, spliceAmount); var pagePromise = new Parse.Promise(); Parse.Object.saveAll(dataToSave).then( function(objs) { var ts = (new Date).getTime(); var diff = ts - k.ts; var threshold = 1000; console.log("Diff:" + diff, k.index); if (diff < threshold) { var toSleep = threshold - diff; console.log(toSleep); try { setTimeout(function(){ console.log("Saved Page. " + k.index); pagePromise.resolve({"index": k.index+1, "ts": (new Date).getTime()}); }, toSleep); } catch (e) { console.log(JSON.stringify(e)); } } else { pagePromise.resolve({"index": k.index+1, "ts": (new Date).getTime()}); } }, function(e) { console.log(JSON.stringify(e)); return promise.reject("Save error"); } ); return pagePromise; }); } Parse.Promise.when(promise).then( function() { console.log("Batch Save success."); }, function(e) { console.log(JSON.stringify(e)); } );<file_sep>require 'omniauth-google-oauth2' require 'google-id-token' require 'sinatra' enable :sessions def logger; settings.logger end def user_credentials # Build a per-request oauth credential based on token stored in session # which allows us to use a shared API client. @authorization ||= ( auth = settings.authorization.dup auth.redirect_uri = to('/oauth2callback') auth.update_token!(session) auth ) end set :views, "#{settings.root}/dashboards" configure do log_file = File.open('p.log', 'a+') log_file.sync = true logger = Logger.new(log_file) logger.level = Logger::DEBUG set :session_secret, ENV['RACK_COOKIE_SECRET'] ||= 'super secret' use Rack::Session::Cookie, :key => 'rack.session', :path => '/', :expire_after => 86400, :secret => ENV['RACK_COOKIE_SECRET'] set :logger, logger end get '/' do if (session[:access_token].nil? && session[:expires_at].nil?) redirect to('/auth/google_oauth2') else redirect to('/twitter') end end get '/auth/:provider/callback' do content_type 'text/plain' auth = request.env['omniauth.auth'].to_hash # Validate access token by google api endpoint validator = GoogleIDToken::Validator.new jwt = validator.check(auth['extra']['id_token'], auth['extra']['id_info']['aud'], auth['extra']['id_info']['azp']) if jwt # if valid then set seesion ky session[:access_token] = auth['credentials']['token'] session[:expires_at] = auth['credentials']['expires_at'] redirect to('/twitter') else # Put error pp "Cannot validate: #{validator.problem}" end end get '/auth/failure' do content_type 'text/plain' request.env['omniauth.auth'].to_hash.inspect rescue "No Data" end get '/twitter' do if (session[:access_token].nil? && session[:expires_at].nil?) redirect to('/auth/google_oauth2') end erb :layout, :layout => false do erb :twitter end end # Delay loading Hack, in order to make routing works # See: https://github.com/Shopify/dashing/issues/138#issuecomment-24894956 require 'dashing' use OmniAuth::Builder do # For additional provider examples please look at 'omni_auth.rb' provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], { :hd => ["wantoto.com", "tickleapp.com"] } end map Sinatra::Application.assets_prefix do run Sinatra::Application.sprockets end run Sinatra::Application<file_sep>require 'parse-ruby-client' require 'json' require 'rest-client' require 'pp' ENV['TZ']='UTC' def groupDataByDate(data) # sort by timestamp data.sort! {|x, y| x[0].to_i<=>y[0].to_i} # Convert accumlated data into differentiated data, ex: the number of follower grow every date, however, we want to show differentiated number of every day diff = Array.new data.each_index { |i| if (i - 1).to_i >= 0 diff.push [data[i][0], data[i][1] - data[(i - 1).to_i][1]] else diff.push [data[i][0], 0] end } # Grouping by date group = Hash.new diff.each do |ts, data| timeStr = Time.at(ts/1000).to_datetime.strftime "%Y-%m-%d" if !group.include? timeStr group[timeStr] = 0 end group[timeStr] = group[timeStr] + data end # Format grouping data result = Array.new group.each do |dateKey, num| result.push [DateTime.parse(dateKey).to_time.to_i * 1000, num] end result end # mergeMetrics # -------- # # Merge the new calculted shared data into the old one def mergeMetrics(target, metrics, pageMetrics) pageMetrics[target].each do |name, timesStrings| # Init non-existing screen_name if !metrics[target].include? name metrics[target][name] = Hash.new end timesStrings.each do |timeStr, number| # Init grouping by Date if !metrics[target][name].include? timeStr metrics[target][name][timeStr] = 0 end metrics[target][name][timeStr] += number end end end # getTimelineData # -------- # # Get data from Parse.com # # @param {object} Parse object # @return {string} Parse table name def getTimelineData(client, table) result = Array.new metrics = Hash.new metrics["shared"] = Hash.new metrics["mentioned"] = Hash.new skip = 0 maxCreatedAtTime = 0; loop do # Parse only allow fetching 1000 records with one query page = client.query(table).tap do |q| q.order_by = "createdAt" q.order = :descending q.limit = 1000 if maxCreatedAtTime != 0 pp maxCreatedAtTime q.less_than("createdAt", maxCreatedAtTime) end end.get if page.length != 0 maxCreatedAtTime = page[page.length - 1]["createdAt"] pp page[page.length - 1]["createdAt"] pp page[page.length - 2]["createdAt"] pp page[page.length - 3]["createdAt"] end # Blocks given means we should do the calculation on the fly when getting data from Parse.com if block_given? pageMetrics = Hash.new # Current page's metric is calculated by block given pageMetrics = yield page # Merge the new calculted shared data into the old one mergeMetrics("shared", metrics, pageMetrics); # Merge the new calculted mentioned data into the old one mergeMetrics("mentioned", metrics, pageMetrics); # Reset pageMetrics = Hash.new else # If No Calculation Needs to be done result += page end break if page.length == 0 page = nil; end if result.empty? then metrics else result end end # claculateShared # -------- # # Grouping raw tweets into a two dimentional array with in [name][tweetTimeString], the value indicates the number of tweets containing media # # @param {array} tweets The raw tweets # @return {array} Grouped by name and date def claculateShared(tweets) sharedArray = Hash.new for tweet in tweets name = tweet["mentioning"] timestamp = DateTime.parse(tweet["created_at"]).to_time.to_i * 1000 timeStr = Time.at(timestamp/1000).to_datetime.strftime "%Y-%m-%d" # Init non-existing screen_name if !sharedArray.include? name sharedArray[name] = Hash.new end # Init grouping by Date if !sharedArray[name].include? timeStr sharedArray[name][timeStr] = 0 end # Exclude Retweet an Tweet mentioning himself if !tweet["text"].include?('RT @') && (tweet["user_screen_name"] != name) # Tweets containing image or video if !tweet["entities_media"].nil? sharedArray[name][timeStr] += 1 end # We count resource like youtube, instagram, vimeo, vine if !tweet["entities_urls"].nil? urls = JSON.parse(tweet["entities_urls"]) for url in urls if (url['expanded_url'].include?('youtube.com') || url['expanded_url'].include?('youtu.be') || url['expanded_url'].include?('instagram.com') || url['expanded_url'].include?('vimeo.com') || url['expanded_url'].include?('vine.co')) sharedArray[name][timeStr] += 1 break end end end end end sharedArray end # claculateMentioned # -------- # # Grouping raw tweets into a two dimentional array with in [name][tweetTimeString], the value indicates the number of tweets that mentioning each user # # @param {array} tweets The raw tweets # @return {array} Grouped by name and date def claculateMentioned(tweets) mentionedArray = Hash.new for tweet in tweets name = tweet["mentioning"] timestamp = DateTime.parse(tweet["created_at"]).to_time.to_i * 1000 timeStr = Time.at(timestamp/1000).to_datetime.strftime "%Y-%m-%d" # Init non-existing screen_name if !mentionedArray.include? name mentionedArray[name] = Hash.new end # Init grouping by Date if !mentionedArray[name].include? timeStr mentionedArray[name][timeStr] = 0 end # Exclude Retweet an Tweet mentioning himself if !tweet["in_reply_to_status_id"].nil? && !tweet["text"].include?('RT @') && (tweet["user_screen_name"] != name) mentionedArray[name][timeStr] += 1 end end mentionedArray end # groupeHashIntoKeyData # -------- # # The data required by Highstock widget should be format in this form {"name"=> {screenName}, "data" => {timestamp}} # # @param {array} tweets The raw tweets # @return {array} Array of hash def groupeHashIntoKeyData(inputHash) groupedArray = Array.new # Format grouping data inputHash.each do |key, array| result = Array.new array.each do |dateKey, num| result.push [DateTime.parse(dateKey).to_time.to_i * 1000, num] end # Sorting timestamp result.sort! {|x, y| x[0].to_i<=>y[0].to_i} hash = {"name"=>key, "data"=>result} groupedArray.push hash end groupedArray end # sendParseDataset # -------- # # Main function # def sendParseDataset # All the data used by this script is fetch by Parse API # Hence, you might need to set up your PARSE_APPLICATION_ID and PARSE_API_KEY in ENV client = Parse.create :application_id => ENV["PARSE_APPLICATION_ID"], # required :api_key => ENV["PARSE_API_KEY"], # required :quiet => false # optional, defaults to false timeline = Array.new mentionedAndShared = Hash.new # Get Data from Parse.com, we provides a block which calculate the fetched data on the fly mentionedAndShared = getTimelineData(client, "metioning_history") { |tweets| metrics = Hash.new metrics["mentioned"] = claculateMentioned(tweets) metrics["shared"] = claculateShared(tweets) metrics } # Caculated Mentioning Tweets mentionedAndShared["mentioned"] = groupeHashIntoKeyData(mentionedAndShared["mentioned"]); mentionedAndShared["mentioned"].sort! {|x, y| x['name']<=>y['name']} send_event('mentioned', { data: mentionedAndShared["mentioned"].to_json }) send_event('accummentioned', { data: mentionedAndShared["mentioned"].to_json }) # Reset mentionedAndShared["mentioned"] = Hash.new # Caculated Mentioning Shared mentionedAndShared["shared"] = groupeHashIntoKeyData(mentionedAndShared["shared"]); mentionedAndShared["shared"].sort! {|x, y| x['name']<=>y['name']} send_event('shared', { data: mentionedAndShared["shared"].to_json }) send_event('accumshared', { data: mentionedAndShared["shared"].to_json }) # Reset mentionedAndShared["shared"] = Hash.new # Get Data from Parse.com of users' historical status timeline = getTimelineData(client, "twitter_user_timeline") retweetedTimeline = Hash.new favoriteTimeLine = Hash.new followers = Hash.new retweetedChartData = Array.new favoritedChartData = Array.new followerChartData = Array.new # Grouping data by "screen_name" for record in timeline name = record["screen_name"] timestamp = DateTime.parse(record["createdAt"]).to_time.to_i * 1000 if !retweetedTimeline.include? name retweetedTimeline[name] = [] end if !favoriteTimeLine.include? name favoriteTimeLine[name] = [] end if !followers.include? name followers[name] = [] end if record["historicalRetweet"] && record["historicalRetweet"] != 0 retweeted = record["historicalRetweet"] retweetedTimeline[name].push [timestamp, retweeted] end if record["historicalFavorite"] && record["historicalFavorite"] != 0 favorited = record["historicalFavorite"] favoriteTimeLine[name].push [timestamp, favorited] end if record["followers"] && record["followers"] != 0 follower = record["followers"] followers[name].push [timestamp, follower] end end retweetedTimeline.each do |key, array| hash = {"name"=>key, "data"=>(groupDataByDate array)} retweetedChartData.push hash end favoriteTimeLine.each do |key, array| hash = {"name"=>key, "data"=>(groupDataByDate array)} favoritedChartData.push hash end followers.each do |key, array| hash = {"name"=>key, "data"=>(groupDataByDate array)} followerChartData.push hash end retweetedChartData.sort! {|x, y| x['name']<=>y['name']} favoritedChartData.sort! {|x, y| x['name']<=>y['name']} followerChartData.sort! {|x, y| x['name']<=>y['name']} send_event('retweeted', { data: retweetedChartData.to_json }) send_event('favorited', { data: favoritedChartData.to_json }) send_event('followers', { data: followerChartData.to_json }) retweetedTimeline = Hash.new favoriteTimeLine = Hash.new followers = Hash.new retweetedChartData = Array.new favoritedChartData = Array.new followerChartData = Array.new timeline = Array.new end SCHEDULER.every '300s', :first_in => 0 do |job| sendParseDataset end
42728fbcd3e628e600907cab1e2806512395b54c
[ "Markdown", "JavaScript", "Ruby" ]
8
Markdown
bblurock/Twitter-Tweets-Metric-Dashboard
b2b24853303dec9760d64dae062aed59270917bb
affe6881004e74aff06884474b2c4f7d88d9e023
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { LoginComponent } from '../login/login.component' import { MainComponent } from '../main/main.component' import { ModalregComponent } from '../modalreg/modalreg.component' import { Router } from '@angular/router' @Component({ selector: 'app-modallog', templateUrl: './modallog.component.html', styleUrls: ['./modallog.component.scss'], providers: [MainComponent] }) export class ModallogComponent implements OnInit { constructor(private LoginComponent: LoginComponent, private router: Router, public mainComponent: MainComponent) { } regForm = new FormGroup({ Username: new FormControl(''), Password: new FormControl(''), }); error: boolean = false; main: boolean = false; container; userLogArray: any = []; enter() { this.userLogArray.forEach(element => { if (element.username == this.regForm.value.Username) { if (element.password == this.regForm.value.Password) { this.router.navigate(['/main']) } } }); if (this.regForm.value.Username !== "" && this.regForm.value.Password !== "") { } else { this.error = true; } } closeModalLog() { this.LoginComponent.modalWindowLog = false; this.container = document.getElementsByClassName("container")[0]; this.container.style.filter = "blur(0px)"; } ngOnInit(): void { if (localStorage.getItem("array")) { this.userLogArray = JSON.parse(localStorage.getItem("array")); } } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ModallogComponent } from '../modallog/modallog.component'; import { ModalregComponent } from '../modalreg/modalreg.component'; import { FormControl, FormGroup } from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { constructor() { } regForm = new FormGroup({ Username: new FormControl(''), Password: new FormControl(''), }); modalWindowReg: boolean = false; modalWindowLog: boolean = false; main: boolean = false; container; openRegModal() { this.modalWindowReg = true; this.container = document.getElementsByClassName("container")[0]; this.container.style.filter = "blur(2px)"; } closeLog() { this.modalWindowLog = false; this.container = document.getElementsByClassName("container")[0]; this.container.style.filter = "blur(0px)"; } openLogModal() { this.modalWindowLog = true; this.container = document.getElementsByClassName("container")[0]; this.container.style.filter = "blur(2px)"; } ngOnInit(): void { } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; // import { Router } from '@angular/router'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LoginComponent } from './login/login.component'; import { MainComponent } from './main/main.component'; import { ModalComponent } from './modal/modal.component'; import { FormsModule, ReactiveFormsModule} from '@angular/forms'; import { ModalregComponent } from './modalreg/modalreg.component'; import { ModallogComponent } from './modallog/modallog.component'; @NgModule({ declarations: [ AppComponent, LoginComponent, MainComponent, ModalComponent, ModalregComponent, ModallogComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, ], providers: [MainComponent, LoginComponent], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component, OnInit, ElementRef, ViewChild, ViewChildren } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { MainComponent } from '../main/main.component' @Component({ selector: 'app-modal', templateUrl: './modal.component.html', styleUrls: ['./modal.component.scss'] }) export class ModalComponent implements OnInit { @ViewChildren('dateInput') dateInput: HTMLElement; addedItems = []; error: boolean = false; constructor(public MainComponent: MainComponent) { } patternDate = "(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" itemForm = new FormGroup({ Task: new FormControl(''), Date: new FormControl('', [Validators.required, Validators.pattern(this.patternDate)]), Description: new FormControl(''), }); getItems() { if (this.itemForm.value.Task !== "" && this.itemForm.value.Date !== "" && this.itemForm.value.Description !== "" && this.itemForm.valid) { this.error = false; let itemObj = { "task": this.itemForm.value.Task, "date": this.itemForm.value.Date, "description": this.itemForm.value.Description, "edit": false }; this.addedItems = this.addedItems || []; this.addedItems.push(itemObj); localStorage.setItem("arr", JSON.stringify(this.addedItems)); this.itemForm.reset(); this.MainComponent.modalWindow = false; this.MainComponent.itemArray = JSON.parse(localStorage.getItem("arr")); } else { this.error = true; } } closeModal() { this.MainComponent.modalWindow = false; } ngOnInit(): void { this.addedItems = JSON.parse(localStorage.getItem("arr")); } } <file_sep># Task-Manager Manage your tasks faster and make your work efficient with the help of task manager app <file_sep>import { Component, OnInit, ViewChild, ElementRef, ViewChildren, QueryList } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { ModalComponent } from '../modal/modal.component'; @Component({ selector: 'app-main', templateUrl: './main.component.html', styleUrls: ['./main.component.scss'], }) export class MainComponent implements OnInit { constructor() { } itemArray: any = []; modalWindow: boolean = false; editForm = new FormGroup({ task: new FormControl(''), date: new FormControl(''), description: new FormControl(''), }); addItem() { this.modalWindow = true; } deleteItem(i) { this.itemArray.splice(i, 1); localStorage.clear(); localStorage.setItem("arr", JSON.stringify(this.itemArray)); } editItem(i) { this.editForm.controls['task'].patchValue(this.itemArray[i].task); this.editForm.controls['date'].patchValue(this.itemArray[i].date); this.editForm.controls['description'].patchValue(this.itemArray[i].description); this.itemArray[i].edit = true; } saveItem(i) { this.itemArray[i].date = this.editForm.value.date; this.itemArray[i].description = this.editForm.value.description; this.itemArray[i].task = this.editForm.value.task; this.itemArray[i].edit = false; localStorage.setItem("arr", JSON.stringify(this.itemArray)); } ngOnInit(): void { if (localStorage.getItem("arr")) { this.itemArray = JSON.parse(localStorage.getItem("arr")); } } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { LoginComponent } from '../login/login.component' import { ModallogComponent } from '../modallog/modallog.component' @Component({ selector: 'app-modalreg', templateUrl: './modalreg.component.html', styleUrls: ['./modalreg.component.scss'], providers: [] }) export class ModalregComponent implements OnInit { constructor(private LoginComponent: LoginComponent) { } regForm = new FormGroup({ Username: new FormControl(''), Password: new FormControl(''), }); error: boolean = false; container; userArray: any = []; register() { if (this.regForm.value.Username !== "" && this.regForm.value.Password !== "") { this.error = false; let userObj = { "username": this.regForm.value.Username, "password": <PASSWORD>, }; this.userArray = this.userArray || []; this.userArray.push(userObj); localStorage.setItem("array", JSON.stringify(this.userArray)); this.regForm.reset(); this.LoginComponent.modalWindowReg = false; this.container = document.getElementsByClassName("container")[0]; this.container.style.filter = "blur(0px)"; } else { this.error = true; } } closeModalReg() { this.LoginComponent.modalWindowReg = false; this.container = document.getElementsByClassName("container")[0]; this.container.style.filter = "blur(0px)"; } ngOnInit(): void { if (localStorage.getItem('array')) { this.userArray = JSON.parse(localStorage.getItem("array")); } } }
5ce7183608ebcf500a9b4de4e264fe7ab174de13
[ "Markdown", "TypeScript" ]
7
TypeScript
Oleh-KO/Task-Manager
6864bddff0a59eeb4795b640ffe9f82ed2320708
574c68b4e867603a040cba056ac3888e69edab74
refs/heads/master
<file_sep> // HOMEWORK CLASS 8 - // TASK 1 // function testNumber(num){ // return new Promise((resolve, reject)=>{ // if (num === 10) { // reject ("That is not a requered value") // } // setTimeout(() => { // resolve ("Bingo!") // }, 2000); // }) // } // testNumber(10) // .then(success => { // console.log(success) // }) // .catch(error => console.log(`ERROR: ${error}`)) // TASK 2 // Osven ako prviot element ne e string ne vlaga vo reject, break ne mi pomaga let words = ['hi','there', 'how','are', 'you', 'doing']; function caps(array){ return array.map(word => {return word.toUpperCase()}) }; const isNotString = currentvalue => currentvalue === String(currentvalue) let changeAllToCaps = (array) => { return new Promise((resolve, reject) => { if (array.every(isNotString)=== false){ reject("Something went wrong") } else { setTimeout(() => { resolve(caps(array)) }, 2000); } }) } // changeAllToCaps(words) // .then(data => { // console.log(data); // }) // .catch(err => console.log(err)) // changeAllToCaps(words) // .then( success => { // console.log(success, words)}) // .catch(error => console.log(`ERROR: ${error}`)) function order(array){ return new Promise((resolve, reject) =>{ if (array.length < 2) { reject ('There are not enough words'); } else { setTimeout(() => { resolve (array.sort()) }, 2000); } }) } async function runFunctions(array){ const allCapital = await changeAllToCaps(array) console.log(await order(allCapital)); console.log(`Everything is done for ${Math.round(performance.now())} ms`); } runFunctions(words) <file_sep>//WITH OBJECTS function Person (firstName, lastName, age){ this.firstName = firstName; this.lastName = lastName; this.age = age; this.getFullName = function(){ console.log(`This is ${this.firstName} ${this.lastName}.`); } } const person1 = new Person ("Lile", "Andova", 33); function Student(firstName, lastName, age, academyName, studentId){ Object.setPrototypeOf(this, new Person(firstName, lastName, age)) this.academyName = academyName; this.studentId = studentId this.study = function(){ console.log(`The student ${this.firstName} is studying in the "${this.academyName}" academy.`); } } const student1 = new Student ("Natasha", "Paneva", 22, "SEDC", 58992); const student2 = new Student ("Lina", "Paneva", 16, "ESRA", 63992); console.log(student1); console.log(student2); function DesignStudent(firstName, lastName, age, studentId, studentOfTheMonth){ Object.setPrototypeOf(this, new Student(firstName, lastName, age, "Design", studentId)) this.studentOfTheMonth = studentOfTheMonth === undefined ? false : true; this.attendAdobeExam = function(){ console.log(`The student ${firstName}is doing an adobe exam!`); } } const student3 = new DesignStudent("Ane", "Vasileva", 21, 12431, true); console.log(student3); function CodeStudent(firstName, lastName, age, studentId){ Object.setPrototypeOf(this, new Student(firstName, lastName, age, "Code", studentId)) this.hasIndividualProject = false; this.hasGroupProject = false; this.doProject = function(type){ if (type === "group") { this.hasGroupProject = true; this.hasIndividualProject = false; } if (type === "individual") { this.hasGroupProject = false this.hasIndividualProject = true; } } } const student4 = new CodeStudent ("Dani", "Petrova", 19, 9783); console.log(student4); function NetworkStudent(firstName, lastName, age, studentId, academyPart){ Object.setPrototypeOf(this, new Student(firstName, lastName, age, "Network", studentId)) this.academyPart= academyPart; this.attendCiscoExam = function(){ console.log(`The student ${firstName} is doing a cisco exam!`); } } const student5 = new NetworkStudent("Ole", "Ansarova", 24, 9828, 3); console.log(student5); Person.prototype.currentAcademy = function(student){ console.log(student.academyName); } student5.currentAcademy(student3); student4.currentAcademy(student2); student1.currentAcademy(student1); student2.currentAcademy(student4); student3.currentAcademy(student5); person1.currentAcademy(student3); //WITH CLASSES // class Person { // constructor (firstName, lastName, age){ // this.firstName = firstName; // this.lastName = lastName; // this.age = age; // } // getFullName(){ // console.log(`This is ${this.firstName} ${this.lastName}.`); // } // } // const person1 = new Person ("Lile", "Andova", 33) // class Student extends Person { // constructor (firstName, lastName, age, academyName, studentId){ // super (firstName, lastName, age) // this.academyName = academyName; // this.studentId = studentId; // } // study(){ // console.log(`The student ${this.firstName} is studying in the "${this.academyName}" academy.`); // } // } // const student1 = new Student ("Natasha", "Paneva", 22, "SEDC", 58992); // const student2 = new Student ("Lina", "Paneva", 16, "ESRA", 63992); // console.log(student1); // console.log(student2); // class DesignStudent extends Student{ // constructor(firstName, lastName, age, studentId, studentOfTheMonth){ // super(firstName, lastName, age, "Design", studentId) // this.studentOfTheMonth = studentOfTheMonth === undefined ? false : true; // } // attendAdobeExam(){ // console.log(`The student ${firstName}is doing an adobe exam!`); // } // } // const student3 = new DesignStudent("Ane", "Vasileva", 21, 12431, true); // console.log(student3); // class CodeStudent extends Student { // constructor(firstName, lastName, age, studentId){ // super(firstName, lastName, age, "Code", studentId) // this.hasIndividualProject = false; // this.hasGroupProject = false; // } // doProject(){ // if (type === "group") { // this.hasGroupProject = true; // this.hasIndividualProject = false; // } // if (type === "individual") { // this.hasGroupProject = false // this.hasIndividualProject = true; // } // } // } // const student4 = new CodeStudent ("Dani", "Petrova", 19, 9783); // console.log(student4); // class NetworkStudent extends Student { // constructor (firstName, lastName, age, studentId, academyPart){ // super(firstName, lastName, age, "Network", studentId) // this.academyPart= academyPart; // } // attendCiscoExam(){ // console.log(`The student ${firstName} is doing a cisco exam!`); // } // } // const student5 = new NetworkStudent("Ole", "Ansarova", 24, 9828, 3); // console.log(student5); // Person.prototype.currentAcademy = function(student){ // console.log(student.academyName); // } // student5.currentAcademy(student3); // student4.currentAcademy(student2); // student1.currentAcademy(student1); // student2.currentAcademy(student4); // student3.currentAcademy(student5); // person1.currentAcademy(student3);
c55c5b8d498950fab4ace4f5899f503e37cc3a3d
[ "JavaScript" ]
2
JavaScript
natepaneva/Homeworks-js
401f0c5eb5595bfaccdcbefdf3a5dc558226152c
a5036499f4b7ac3eb6e6a33db7dd23e31d29e11f
refs/heads/master
<repo_name>tomerGolany/ecg_pytorch<file_sep>/ecg_pytorch/gan_models/models/ode_gan.py import torch.nn as nn import torch.nn.functional as F class DCGenerator(nn.Module): def __init__(self): super(DCGenerator, self).__init__() ngf = 64 ## # Conv Transpose 1d: # Input: (N, Cin, Lin) --> Output: (N, Cout, Lout) # Lout = (Lin -1) * s -2 * p + k ## self.main = nn.Sequential( # shape in = [N, 50, 1] nn.ConvTranspose1d(100, ngf * 32, kernel_size=4, stride=1, padding=0, bias=False), nn.BatchNorm1d(ngf * 32), nn.ReLU(True), # shape in = [N, 64*4, 4] nn.ConvTranspose1d(ngf * 32, ngf * 16, 4, 1, 0, bias=False), nn.BatchNorm1d(ngf * 16), nn.ReLU(True), # shape in = [N, 64*2, 7] nn.ConvTranspose1d(ngf * 16, ngf * 8, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf * 8), nn.ReLU(True), nn.ConvTranspose1d(ngf * 8, ngf * 4, 3, 2, 1, bias=False), nn.BatchNorm1d(ngf * 4), nn.ReLU(True), nn.ConvTranspose1d(ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf * 2), nn.ReLU(True), nn.ConvTranspose1d(ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf), nn.ReLU(True), nn.ConvTranspose1d(ngf, 1, 4, 2, 1, bias=False), ) def forward(self, x): x = x.view(-1, 100, 1) x = self.main(x) x = x.view(-1, 216) return x class DCXGenerator(nn.Module): def __init__(self): super(DCXGenerator, self).__init__() ngf = 64 ## # Conv Transpose 1d: # Input: (N, Cin, Lin) --> Output: (N, Cout, Lout) # Lout = (Lin -1) * s -2 * p + k ## self.main = nn.Sequential( # shape in = [N, 50, 1] nn.ConvTranspose1d(100, ngf * 32, kernel_size=4, stride=1, padding=0, bias=False), nn.BatchNorm1d(ngf * 32), nn.ReLU(True), # shape in = [N, 64*4, 4] nn.ConvTranspose1d(ngf * 32, ngf * 16, 4, 1, 0, bias=False), nn.BatchNorm1d(ngf * 16), nn.ReLU(True), # shape in = [N, 64*2, 7] nn.ConvTranspose1d(ngf * 16, ngf * 8, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf * 8), nn.ReLU(True), nn.ConvTranspose1d(ngf * 8, ngf * 4, 3, 2, 1, bias=False), nn.BatchNorm1d(ngf * 4), nn.ReLU(True), nn.ConvTranspose1d(ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf * 2), nn.ReLU(True), nn.ConvTranspose1d(ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf), nn.ReLU(True), nn.ConvTranspose1d(ngf, 1, 4, 2, 1, bias=False), ) def forward(self, x): x = x.view(-1, 100, 1) x = self.main(x) x = x.view(-1, 216) return x class DCYGenerator(nn.Module): def __init__(self): super(DCYGenerator, self).__init__() ngf = 64 ## # Conv Transpose 1d: # Input: (N, Cin, Lin) --> Output: (N, Cout, Lout) # Lout = (Lin -1) * s -2 * p + k ## self.main = nn.Sequential( # shape in = [N, 50, 1] nn.ConvTranspose1d(100, ngf * 32, kernel_size=4, stride=1, padding=0, bias=False), nn.BatchNorm1d(ngf * 32), nn.ReLU(True), # shape in = [N, 64*4, 4] nn.ConvTranspose1d(ngf * 32, ngf * 16, 4, 1, 0, bias=False), nn.BatchNorm1d(ngf * 16), nn.ReLU(True), # shape in = [N, 64*2, 7] nn.ConvTranspose1d(ngf * 16, ngf * 8, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf * 8), nn.ReLU(True), nn.ConvTranspose1d(ngf * 8, ngf * 4, 3, 2, 1, bias=False), nn.BatchNorm1d(ngf * 4), nn.ReLU(True), nn.ConvTranspose1d(ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf * 2), nn.ReLU(True), nn.ConvTranspose1d(ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf), nn.ReLU(True), nn.ConvTranspose1d(ngf, 1, 4, 2, 1, bias=False), ) def forward(self, x): x = x.view(-1, 100, 1) x = self.main(x) x = x.view(-1, 216) return x class ODEParamsGenerator(nn.Module): def __init__(self): super(ODEParamsGenerator, self).__init__() self.fc1 = nn.Linear(100, 50) self.bn1 = nn.BatchNorm1d(num_features=50) self.fc2 = nn.Linear(50, 25) self.bn2 = nn.BatchNorm1d(num_features=25) self.fc3 = nn.Linear(25, 15) def forward(self, noise_input): x = F.leaky_relu(self.bn1(self.fc1(noise_input)), inplace=True) x = F.sigmoid(self.bn2(self.fc2(x))) x = self.fc3(x) return x class ODEGenerator(nn.Module): def __init__(self): super(ODEGenerator, self).__init__() self.ode_params_generator = ODEParamsGenerator() self.conv_generator = DCGenerator() self.x_signal_generator = DCXGenerator() self.y_signal_generator = DCYGenerator() def forward(self, noise_input): fake_ecg = self.conv_generator(noise_input) ode_params = self.ode_params_generator(noise_input) x_signal =self.x_signal_generator(noise_input) y_signal = self.y_signal_generator(noise_input) return ode_params, fake_ecg, x_signal, y_signal <file_sep>/ecg_pytorch/data_reader/dataset_configs.py """Module to define available dataset configurations.""" from enum import Enum from ecg_pytorch.data_reader import heartbeat_types class PartitionNames(Enum): train = 0 test = 1 class DatasetConfigs(object): def __init__(self, partition, classified_heartbeat, one_vs_all, lstm_setting, over_sample_minority_class, under_sample_majority_class, only_take_heartbeat_of_type): """Create a new DatasetConfigs object which has configurations on how to create the ecg dataset. :param partition: To which dataset partition it belongs. can be train or test. :param classified_heartbeat: Which heartbeat is classified. Only used for One vs. All settings. :param one_vs_all: boolean that indicates weather we are using multi-class classification or one vs. all. :param lstm_setting: boolean that indicates weather we are using lstm setting in the model or not. :param over_sample_minority_class: boolean that indicates if the dataset should over sample the minority class. Only used for one Vs. all setting. :param under_sample_majority_class: boolean that indicates if the dataset should under sample the majority class. Only used for ons vs. all setting. :param only_take_heartbeat_of_type: if not None, the dataset should contain only heartbeats from the specified type. """ if partition not in PartitionNames.__members__: raise ValueError("Invalid partition name: {}".format(partition)) if classified_heartbeat not in heartbeat_types.AAMIHeartBeatTypes.__members__: raise ValueError("Invalid target heartbeat: {}".format(classified_heartbeat)) if one_vs_all not in [True, False]: raise ValueError("Expected boolean type for argument one vs. all. Got instead: {}".format(one_vs_all)) if lstm_setting not in [True, False]: raise ValueError("Expected boolean type for argument lstm setting. Got instead: {}".format(lstm_setting)) if over_sample_minority_class not in [True, False]: raise ValueError("Expected boolean type for argument over sample minority class. " "Got instead: {}".format(over_sample_minority_class)) if under_sample_majority_class not in [True, False]: raise ValueError("Expected boolean type for argument under sample majority class. " "Got instead: {}".format(under_sample_majority_class)) if only_take_heartbeat_of_type is None: self.only_take_heartbeat_of_type = only_take_heartbeat_of_type elif only_take_heartbeat_of_type in heartbeat_types.AAMIHeartBeatTypes.__members__: self.only_take_heartbeat_of_type = only_take_heartbeat_of_type elif only_take_heartbeat_of_type == heartbeat_types.OTHER_HEART_BEATS: self.only_take_heartbeat_of_type = only_take_heartbeat_of_type else: raise ValueError("Invalid argument for parameter only take heartbeat of type: {}" .format(only_take_heartbeat_of_type)) self.partition = partition self.classified_heartbeat = classified_heartbeat self.one_vs_all = one_vs_all self.lstm_setting = lstm_setting self.over_sample_minority_class = over_sample_minority_class self.under_sample_majority_class = under_sample_majority_class <file_sep>/ecg_pytorch/data_reader/ecg_mit_bih_test.py import unittest from ecg_pytorch.data_reader import ecg_mit_bih import logging class TestECGMitBihDataset(unittest.TestCase): def test_keys(self): ecg_mit_bih_ds = ecg_mit_bih.ECGMitBihDataset() train = ecg_mit_bih_ds.train_heartbeats test = ecg_mit_bih_ds.test_heartbeats for hb in train: self.assertIn('aami_label_str', hb) for hb in test: self.assertIn('aami_label_str', hb) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) unittest.main() <file_sep>/ecg_pytorch/gan_models/models/vanila_gan.py import torch.nn as nn import torch.nn.functional as F class VGenerator(nn.Module): def __init__(self, ngpu): super(VGenerator, self).__init__() self.ngpu = ngpu self.fc1 = nn.Linear(100, 128) self.fc2 = nn.Linear(128, 216) def forward(self, x): x = x.view(-1, 100) x = F.relu(self.fc1(x)) x = self.fc2(x) return x class VDiscriminator(nn.Module): def __init__(self, ngpu): super(VDiscriminator, self).__init__() self.ngpu = ngpu self.fc1 = nn.Linear(216, 128) self.fc2 = nn.Linear(128, 1) def forward(self, x): x = F.relu(self.fc1(x)) x = F.sigmoid(self.fc2(x)) return x<file_sep>/ecg_pytorch/gan_models/generate_data_from_train_gan.py import torch import numpy as np from ecg_pytorch.gan_models.models import dcgan from ecg_pytorch.gan_models.models import ode_gan_aaai from ecg_pytorch.gan_models import checkpoint_paths import matplotlib.pyplot as plt from bokeh.plotting import figure, output_file, show def generate_data_from_trained_gan(generator_model, num_of_samples_to_generate, checkpoint_path): """ :param generator_model: :param num_of_samples_to_generate: :param checkpoint_path: :return: """ checkpoint = torch.load(checkpoint_path, map_location='cpu') generator_model.load_state_dict(checkpoint['generator_state_dict']) generator_model.eval() # discriminator_model.load_state_dict(checkpoint['discriminator_state_dict']) with torch.no_grad(): input_noise = torch.Tensor(np.random.normal(0, 1, (num_of_samples_to_generate, 100))) output_g = generator_model(input_noise) output_g = output_g.numpy() return output_g """ checkpoint = torch.load(checkpoint_path) generator_model.load_state_dict(checkpoint['generator_state_dict']) # discriminator_model.load_state_dict(checkpoint['discriminator_state_dict']) with torch.no_grad(): input_noise = torch.Tensor(np.random.normal(0, 1, (num_beats_to_add, 100))) output_g = generator_model(input_noise) output_g = output_g.numpy() """ def generate_N_beat_from_DCSimGAN(): chk_path = checkpoint_paths.BEAT_AND_MODEL_TO_CHECKPOINT_PATH['N']['ODE_GAN'] generator_model = ode_gan_aaai.DCGenerator(0) fake_beat = generate_data_from_trained_gan(generator_model, 1, chk_path) return fake_beat def generate_S_beat_from_DCSimGAN(): chk_path = checkpoint_paths.BEAT_AND_MODEL_TO_CHECKPOINT_PATH['S']['ODE_GAN'] generator_model = ode_gan_aaai.DCGenerator(0) fake_beat = generate_data_from_trained_gan(generator_model, 1, chk_path) return fake_beat def generate_V_beat_from_DCSimGAN(): chk_path = checkpoint_paths.BEAT_AND_MODEL_TO_CHECKPOINT_PATH['V']['ODE_GAN'] generator_model = ode_gan_aaai.DCGenerator(0) fake_beat = generate_data_from_trained_gan(generator_model, 1, chk_path) return fake_beat def generate_F_beat_from_DCSimGAN(): chk_path = checkpoint_paths.BEAT_AND_MODEL_TO_CHECKPOINT_PATH['F']['ODE_GAN'] generator_model = ode_gan_aaai.DCGenerator(0) fake_beat = generate_data_from_trained_gan(generator_model, 1, chk_path) return fake_beat def generate_N_beat_from_DCGAN(): chk_path = checkpoint_paths.BEAT_AND_MODEL_TO_CHECKPOINT_PATH['N']['DCGAN'] generator_model = dcgan.DCGenerator(0) fake_beat = generate_data_from_trained_gan(generator_model, 1, chk_path) return fake_beat def plot_beat(b): p = figure(x_axis_label='Sample number (360 Hz)', y_axis_label='Voltage[mV]') time = np.arange(0, 216) p.line(time, b[0], line_width=2, line_color="black") output_file("N_DCGAN.html") # p.legend.location = "bottom_right" show(p) if __name__ == "__main__": # generator_model = dcgan.DCGenerator(0) # one_beat = generate_data_from_trained_gan(generator_model, 1, '/Users/tomer.golany/PycharmProjects/ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_dcgan/checkpoint_epoch_0_iters_201') # print(one_beat.shape) # print(type(one_beat)) # plt.plot(one_beat[0].numpy()) # plt.show() fake_beat = generate_N_beat_from_DCGAN() plot_beat(fake_beat)<file_sep>/ecg_pytorch/classifiers/run_one_vs_all.py import pickle from ecg_pytorch import train_configs from tensorboardX import SummaryWriter from ecg_pytorch.gan_models import checkpoint_paths from ecg_pytorch.train_configs import ECGTrainConfig, GeneratorAdditionalDataConfig import os import logging import shutil from ecg_pytorch.classifiers.models import lstm from ecg_pytorch.classifiers.models import fully_connected from ecg_pytorch.classifiers import run_sequence_model import numpy as np import torch base_path = train_configs.base BEAT_TO_INDEX = {'N': 0, 'S': 1, 'V': 2, 'F': 3, 'Q': 4} def train_multiple_one_vs_all(beat_type, gan_type, device): summary_model_dir = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/tensorboard/{}/lstm_one_vs_all_{}_summary_final3/'.format( beat_type, gan_type) writer = SummaryWriter(summary_model_dir) # # Retrieve Checkpoint path: # if gan_type in ['DCGAN', 'ODE_GAN', 'VANILA_GAN', 'VANILA_GAN_ODE']: ck_path = checkpoint_paths.BEAT_AND_MODEL_TO_CHECKPOINT_PATH[beat_type][gan_type] else: ck_path = None # # Define summary values: # mean_auc_values = [] var_auc_values = [] best_auc_values = [] best_auc_for_each_n = {} # # Run with different number of additional data from trained generator: # for n in [0, 500, 800, 1000, 1500, 3000, 5000, 7000, 10000, 15000]: # # Train configurations: # logging.info("Train with additional {} beats".format(n)) model_dir = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/tensorboard/{}/lstm_one_vs_all_{}_{}/'.format( beat_type, str(n), gan_type) gen_details = GeneratorAdditionalDataConfig(beat_type=beat_type, checkpoint_path=ck_path, num_examples_to_add=n, gan_type=gan_type) train_config = ECGTrainConfig(num_epochs=5, batch_size=20, lr=0.0002, weighted_loss=False, weighted_sampling=False, device=device, add_data_from_gan=True, generator_details=gen_details, train_one_vs_all=True) # # Run 10 times each configuration: # total_runs = 0 best_auc_per_run = [] while total_runs < 1: if os.path.isdir(model_dir): logging.info("Removing model dir") shutil.rmtree(model_dir) # # Initialize the network each run: # net = lstm.ECGLSTM(5, 512, 2, 2).to(device) # # Train the classifier: # best_auc_scores = run_sequence_model.train_classifier(net, model_dir=model_dir, train_config=train_config) best_auc_per_run.append(best_auc_scores[0]) writer.add_scalar('auc_with_additional_{}_beats'.format(n), best_auc_scores[0], total_runs) # if best_auc_scores[BEAT_TO_INDEX[beat_type]] >= 0.88: # logging.info("Found desired AUC: {}".format(best_auc_scores)) # break total_runs += 1 best_auc_for_each_n[n] = best_auc_per_run mean_auc_values.append(np.mean(best_auc_per_run)) var_auc_values.append(np.var(best_auc_per_run)) best_auc_values.append(max(best_auc_per_run)) writer.add_scalar('mean_auc', np.mean(best_auc_per_run), n) writer.add_scalar('max_auc', max(best_auc_per_run), n) writer.close() # # Save data in pickle: # all_results = {'best_auc_for_each_n': best_auc_for_each_n, 'mean': mean_auc_values, 'var': var_auc_values, 'best': best_auc_values} pickle_file_path = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/pickles_results/{}_{}_lstm_one_vs_all.pkl'.format( beat_type, gan_type) with open(pickle_file_path, 'wb') as handle: pickle.dump(all_results, handle, protocol=pickle.HIGHEST_PROTOCOL) def train_multiple_one_vs_all_ff(beat_type, gan_type, device): summary_model_dir = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/tensorboard/{}/ff_one_vs_all_{}_summary_final3/'.format( beat_type, gan_type) writer = SummaryWriter(summary_model_dir) # # Retrieve Checkpoint path: # if gan_type in ['DCGAN', 'ODE_GAN', 'VANILA_GAN', 'VANILA_GAN_ODE']: ck_path = checkpoint_paths.BEAT_AND_MODEL_TO_CHECKPOINT_PATH[beat_type][gan_type] else: ck_path = None # # Define summary values: # mean_auc_values = [] var_auc_values = [] best_auc_values = [] best_auc_for_each_n = {} # # Run with different number of additional data from trained generator: # for n in [0, 500, 800, 1000, 1500, 3000, 5000, 7000, 10000, 15000]: # # Train configurations: # logging.info("Train with additional {} beats".format(n)) model_dir = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/tensorboard/{}/ff_one_vs_all_{}_{}/'.format( beat_type, str(n), gan_type) gen_details = GeneratorAdditionalDataConfig(beat_type=beat_type, checkpoint_path=ck_path, num_examples_to_add=n, gan_type=gan_type) train_config = ECGTrainConfig(num_epochs=5, batch_size=20, lr=0.0002, weighted_loss=False, weighted_sampling=False, device=device, add_data_from_gan=True, generator_details=gen_details, train_one_vs_all=True) # # Run 10 times each configuration: # total_runs = 0 best_auc_per_run = [] while total_runs < 1: if os.path.isdir(model_dir): logging.info("Removing model dir") shutil.rmtree(model_dir) # # Initialize the network each run: # # net = lstm.ECGLSTM(5, 512, 2, 2).to(device) net = fully_connected.FF().to(device) # # Train the classifier: # best_auc_scores = run_sequence_model.train_classifier(net, model_dir=model_dir, train_config=train_config) best_auc_per_run.append(best_auc_scores[0]) writer.add_scalar('auc_with_additional_{}_beats'.format(n), best_auc_scores[0], total_runs) # if best_auc_scores[BEAT_TO_INDEX[beat_type]] >= 0.88: # logging.info("Found desired AUC: {}".format(best_auc_scores)) # break total_runs += 1 best_auc_for_each_n[n] = best_auc_per_run mean_auc_values.append(np.mean(best_auc_per_run)) var_auc_values.append(np.var(best_auc_per_run)) best_auc_values.append(max(best_auc_per_run)) writer.add_scalar('mean_auc', np.mean(best_auc_per_run), n) writer.add_scalar('max_auc', max(best_auc_per_run), n) writer.close() # # Save data in pickle: # all_results = {'best_auc_for_each_n': best_auc_for_each_n, 'mean': mean_auc_values, 'var': var_auc_values, 'best': best_auc_values} pickle_file_path = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/pickles_results/{}_{}_ff_one_vs_all.pkl'.format( beat_type, gan_type) with open(pickle_file_path, 'wb') as handle: pickle.dump(all_results, handle, protocol=pickle.HIGHEST_PROTOCOL) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) beat_type = 'N' # gan_type = 'SIMULATOR' # gan_type = 'ODE_GAN' gan_type = 'DCGAN' # gan_type = 'VANILA_GAN' # gan_type = 'VANILA_GAN_ODE' # gan_type = 'NOISE' device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") train_multiple_one_vs_all_ff(beat_type, gan_type, device) <file_sep>/ecg_pytorch/classifiers/main.py import torchvision.transforms as transforms from ecg_pytorch.data_reader import ecg_dataset import torch.optim as optim import torch.nn as nn import torch from ecg_pytorch.classifiers.models import cnn from tensorboardX import SummaryWriter from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt from sklearn.utils.multiclass import unique_labels import numpy as np from torch.utils.data.sampler import Sampler from sklearn.metrics import roc_curve, auc from ecg_pytorch.classifiers.models import fully_connected from ecg_pytorch.gan_models.models import dcgan from ecg_pytorch.gan_models.models import ode_gan_aaai import shutil import os import logging from ecg_pytorch.gan_models.models.old_ode_combined import CombinedGenerator as CG from ecg_pytorch.gan_models import checkpoint_paths import pickle base_local = '/Users/tomer.golany/PycharmProjects/' base_remote = '/home/<EMAIL>/' base_niv_remote = '/home/nivgiladi/tomer/' BEAT_TO_INDEX = {'N': 0, 'S': 1, 'V': 2, 'F': 3, 'Q': 4} def plt_roc_curve(y_true, y_pred, classes, writer, total_iters): """ :param y_true:[[1,0,0,0,0], [0,1,0,0], [1,0,0,0,0],...] :param y_pred: [0.34,0.2,0.1] , 0.2,...] :param classes:5 :return: """ fpr = {} tpr = {} roc_auc = {} roc_auc_res = [] n_classes = len(classes) for i in range(n_classes): fpr[classes[i]], tpr[classes[i]], _ = roc_curve(y_true[:, i], y_pred[:, i]) roc_auc[classes[i]] = auc(fpr[classes[i]], tpr[classes[i]]) roc_auc_res.append(roc_auc[classes[i]]) fig = plt.figure() lw = 2 plt.plot(fpr[classes[i]], tpr[classes[i]], color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[classes[i]]) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic beat {}'.format(classes[i])) plt.legend(loc="lower right") writer.add_figure('test/roc_curve_beat_{}'.format(classes[i]), fig, total_iters) plt.close() fig.clf() fig.clear() return roc_auc_res def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if not title: if normalize: title = 'Normalized confusion matrix' else: title = 'Confusion matrix, without normalization' # Compute confusion matrix cm = confusion_matrix(y_true, y_pred) # Only use the labels that appear in the data classes = classes[unique_labels(y_true, y_pred)] if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) fig, ax = plt.subplots() im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) # We want to show all ticks... ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), # ... and label them with the respective list entries xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], fmt), ha="center", va="center", color="white" if cm[i, j] > thresh else "black") fig.tight_layout() return fig, ax def train_classifier(net, batch_size, model_dir, n=0, ch_path=None, beat_type=None, gan_type=None): """ :param network: :return: """ best_auc_scores = [0, 0, 0, 0] if os.path.isdir(model_dir): shutil.rmtree(model_dir) composed = transforms.Compose([ecg_dataset.ToTensor()]) dataset = ecg_dataset.EcgHearBeatsDataset(transform=composed) # gNet = CG(0, 'cpu') if n != 0: if gan_type == 'DCGAN': gNet = dcgan.DCGenerator(0) elif gan_type == 'ODE_GAN': gNet = ode_gan_aaai.DCGenerator(0) else: raise ValueError("Unknown gan type {}".format(gan_type)) # gNet = ode_gan_aaai.DCGenerator(0) dataset.add_beats_from_generator(gNet, n, ch_path, beat_type) # gNet = dcgan.DCGenerator(0) # checkpoint_path = '/Users/tomer.golany/PycharmProjects/ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_dcgan_V_beat/' \ # 'checkpoint_epoch_22_iters_1563' # dataset.add_beats_from_generator(gNet, 15000, # checkpoint_path, # 'V') # weights_for_balance = dataset.make_weights_for_balanced_classes() # weights_for_balance = torch.DoubleTensor(weights_for_balance) # sampler = torch.utils.data.sampler.WeightedRandomSampler( # weights=weights_for_balance, # num_samples=len(weights_for_balance), # replacement=True) dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=1, shuffle=True) testset = ecg_dataset.EcgHearBeatsDatasetTest(transform=composed) testdataloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=True, num_workers=1) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(net.parameters(), lr=0.0001) writer = SummaryWriter(model_dir) total_iters = 0 for epoch in range(4): # loop over the dataset multiple times for i, data in enumerate(dataloader): total_iters += 1 # get the inputs # ecg_batch = data['cardiac_cycle'].view(-1, 1, 216).float() ecg_batch = data['cardiac_cycle'].float() b_size = ecg_batch.shape[0] labels = data['label'] labels_class = torch.max(labels, 1)[1] # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = net(ecg_batch) outputs_class = torch.max(outputs, 1)[1] accuracy = (outputs_class == labels_class).sum().float() / b_size loss = criterion(outputs, torch.max(labels, 1)[1]) loss.backward() optimizer.step() writer.add_scalars('Cross_entropy_loss', {'Train batches loss': loss.item()}, total_iters) writer.add_scalars('Accuracy', {'Train batches accuracy': accuracy.item()}, total_iters) # print statistics print("Epoch {}. Iteration {}.\t Batch loss = {:.2f}. Accuracy = {:.2f}".format(epoch + 1, i, loss.item(), accuracy.item())) if total_iters % 50 == 0: fig, _ = plot_confusion_matrix(labels_class.numpy(), outputs_class.numpy(), np.array(['N', 'S', 'V', 'F', 'Q'])) writer.add_figure('train/confusion_matrix', fig, total_iters) if total_iters % 200 == 0: with torch.no_grad(): labels_total_one_hot = np.array([]).reshape((0, 5)) outputs_preds = np.array([]).reshape((0, 5)) labels_total = np.array([]) outputs_total = np.array([]) loss_hist = [] for _, test_data in enumerate(testdataloader): # ecg_batch = test_data['cardiac_cycle'].view(-1, 1, 216).float() ecg_batch = test_data['cardiac_cycle'].float() labels = test_data['label'] labels_class = torch.max(labels, 1)[1] outputs = net(ecg_batch) loss = criterion(outputs, torch.max(labels, 1)[1]) loss_hist.append(loss.item()) outputs_class = torch.max(outputs, 1)[1] labels_total_one_hot = np.concatenate((labels_total_one_hot, labels.numpy())) labels_total = np.concatenate((labels_total, labels_class.numpy())) outputs_total = np.concatenate((outputs_total, outputs_class.numpy())) outputs_preds = np.concatenate((outputs_preds, outputs.numpy())) outputs_total = outputs_total.astype(int) labels_total = labels_total.astype(int) fig, _ = plot_confusion_matrix(labels_total, outputs_total, np.array(['N', 'S', 'V', 'F', 'Q'])) # Accuracy and Loss: accuracy = sum((outputs_total == labels_total)) / len(outputs_total) writer.add_scalars('Accuracy', {'Test set accuracy': accuracy}, global_step=total_iters) writer.add_figure('test/confusion_matrix', fig, total_iters) loss = sum(loss_hist) / len(loss_hist) writer.add_scalars('Cross_entropy_loss', {'Test set loss': loss}, total_iters) auc_roc = plt_roc_curve(labels_total_one_hot, outputs_preds, np.array(['N', 'S', 'V', 'F', 'Q']), writer, total_iters) for i_auc in range(4): if auc_roc[i_auc] > best_auc_scores[i_auc]: best_auc_scores[i_auc] = auc_roc[i_auc] torch.save({ 'net': net.state_dict() }, model_dir + '/checkpoint_epoch_iters_{}'.format(total_iters)) writer.close() return best_auc_scores def train_mult(beat_type, gan_type): # # Retrieve Checkpoint path: # ck_path = checkpoint_paths.BEAT_AND_MODEL_TO_CHECKPOINT_PATH[beat_type][gan_type] # # Define summary values: # mean_auc_values = [] var_auc_values = [] best_auc_values = [] best_auc_for_each_n = {} # # Run with different number of additional data from trained generator: # for n in [0, 500, 800, 1000, 1500, 3000, 5000, 7000, 10000, 15000]: model_dir = 'tensorboard/{}/add_{}_{}_fc/'.format(beat_type, str(n), gan_type) # # Run 10 times each configuration: # num_runs = 0 best_auc_per_run = [] while num_runs < 10: # # Initialize the network each run: # net = fully_connected.FF() # # Train the classifier: # best_auc_scores = train_classifier(net, 50, model_dir=model_dir, n=n, ch_path=ck_path, beat_type=beat_type, gan_type=gan_type) best_auc_per_run.append(best_auc_scores[BEAT_TO_INDEX[beat_type]]) num_runs += 1 best_auc_for_each_n[n] = best_auc_per_run mean_auc_values.append(np.mean(best_auc_per_run)) var_auc_values.append(np.var(best_auc_per_run)) best_auc_values.append(max(best_auc_per_run)) # # Save data in pickle: # all_results = {'best_auc_for_each_n': best_auc_for_each_n, 'mean': mean_auc_values, 'var': var_auc_values, 'best': best_auc_values} pickle_file_path = base_niv_remote + 'ecg_pytorch/ecg_pytorch/classifiers/pickles_results/{}_{}_fc.pkl'.format( beat_type, gan_type) with open(pickle_file_path, 'wb') as handle: pickle.dump(all_results, handle, protocol=pickle.HIGHEST_PROTOCOL) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) beat_type = 'N' gan_type = 'ODE_GAN' train_mult(beat_type, gan_type) <file_sep>/ecg_pytorch/dynamical_model/test_equations.py from ecg_pytorch.dynamical_model import equations from ecg_pytorch.dynamical_model.ode_params import ODEParams import torch import math from matplotlib import pyplot as plt import pickle from ecg_pytorch.data_reader.ecg_dataset import EcgHearBeatsDataset, EcgHearBeatsDatasetTest import numpy as np from bokeh.plotting import figure, output_file, show from bokeh.models import ColumnDataSource, LabelSet def create_good_sample(): ode_params = ODEParams('cpu') input_params = torch.nn.Parameter( torch.tensor([1.2, 0.25, -60.0 * math.pi / 180.0, -5.0, 0.1, -15.0 * math.pi / 180.0, 30.0, 0.1, 0.0 * math.pi / 180.0, -7.5, 0.1, 15.0 * math.pi / 180.0, 0.75, 0.4, 90.0 * math.pi / 180.0])).view(1, 15) x = torch.tensor(-0.417750770388669) y = torch.tensor(-0.9085616622823985) z = torch.tensor(-0.004551233843726818) t = torch.tensor(0.0) x_signal = [x] y_signal = [y] z_signal = [z] for i in range(215): f_x = equations.d_x_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_y = equations.d_y_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_z = equations.d_z_d_t(x, y, z, t, input_params, ode_params) t += 1 / 360 x_signal.append(x + ode_params.h * f_x) y_signal.append(y + ode_params.h * f_y) z_signal.append(z + ode_params.h * f_z) x = x + ode_params.h * f_x y = y + ode_params.h * f_y z = z + ode_params.h * f_z res = [v.detach().item() for v in z_signal] # # Plot: # wave_values = [0.0075, -0.011, 0.042, -0.016, 0.0139] wave_locations = [33, 59, 69, 79, 123] source = ColumnDataSource(data=dict(time=[30, 55, 65, 75, 119], voltage=[0.0075, -0.015, 0.0424, -0.019, 0.0139], waves=['P', 'Q', 'R', 'S', 'T'])) p = figure(x_axis_label='sample # (360HZ)', y_axis_label='voltage [mV]', x_range=(0, 216)) time = np.arange(0, 216) p.line(time, res, line_width=2, line_color='green') p.scatter(x=wave_locations, y=wave_values, size=8, legend='P, Q, R, S, T wave events') labels = LabelSet(x='time', y='voltage', text='waves', level='glyph', x_offset=5, y_offset=5, source=source, render_mode='canvas') p.add_layout(labels) p.legend.location = "bottom_right" show(p) def create_sample(): ode_params = ODEParams('cpu') ode_params.h = torch.tensor(1 / 216).to('cpu') params = [0.7, 0.25, -0.5 * math.pi, -7.0, 0.1, -15.0 * math.pi / 180.0, 30.0, 0.1, 0.0 * math.pi / 180.0, -3.0, 0.1, 15.0 * math.pi / 180.0, 0.2, 0.4, 160.0 * math.pi / 180.0] input_params = torch.tensor(params).view(1, 15) x = torch.tensor(-0.417750770388669) y = torch.tensor(-0.9085616622823985) z = torch.tensor(-0.004551233843726818) t = torch.tensor(0.0) x_signal = [x] y_signal = [y] z_signal = [z] for i in range(215): f_x = equations.d_x_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_y = equations.d_y_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_z = equations.d_z_d_t(x, y, z, t, input_params, ode_params) t += 1 / 360 x_signal.append(x + ode_params.h * f_x) y_signal.append(y + ode_params.h * f_y) z_signal.append(z + ode_params.h * f_z) x = x + ode_params.h * f_x y = y + ode_params.h * f_y z = z + ode_params.h * f_z res = [v.detach().item() for v in z_signal] ecg_data = EcgHearBeatsDataset(beat_type='N') rael_sample = ecg_data[55]['cardiac_cycle'] rael_sample = np.interp(rael_sample, (rael_sample.min(), rael_sample.max()), (min(res), max(res))) # print(res) print(len(res)) plt.plot(res, label='ode') plt.plot(rael_sample, label='N_beat') plt.legend() plt.title('sample output from ode') plt.show() # create a new plot with a title and axis labels p = figure(title="ode", x_axis_label='#samples', y_axis_label='V') time = np.arange(0, 216) # add a line renderer with legend and line thickness p.line(time, rael_sample, legend="real", line_width=2) p.line(time, res, legend="fake", line_width=2, line_color="black") p.legend.location = "bottom_right" # show the results show(p) def create_S_sample(): ecg_data = EcgHearBeatsDataset(beat_type='S') beats = ecg_data.train n = 1 # for 2 random indices #index = np.random.choice(len(beats), n, replace=False) index = [331] print(index) random_s_beats = beats[index] # # Generate S beat from simulator: # ode_params = ODEParams('cpu') ode_params.h = torch.tensor(1 / 216).to('cpu') params = [0.2, 0.25, -0.5 * math.pi, -1.0, 0.1, -15.0 * math.pi / 180.0, 30.0, 0.1, 0.0 * math.pi / 180.0, -10.0, 0.1, 15.0 * math.pi / 180.0, 0.2, 0.4, 160.0 * math.pi / 180.0] input_params = torch.tensor(params).view(1, 15) x = torch.tensor(-0.417750770388669) y = torch.tensor(-0.9085616622823985) z = torch.tensor(-0.004551233843726818) t = torch.tensor(0.0) x_signal = [x] y_signal = [y] z_signal = [z] for i in range(215): f_x = equations.d_x_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_y = equations.d_y_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_z = equations.d_z_d_t(x, y, z, t, input_params, ode_params) t += 1 / 360 x_signal.append(x + ode_params.h * f_x) y_signal.append(y + ode_params.h * f_y) z_signal.append(z + ode_params.h * f_z) x = x + ode_params.h * f_x y = y + ode_params.h * f_y z = z + ode_params.h * f_z res = [v.detach().item() for v in z_signal] p = figure(title="S beats", x_axis_label='#samples', y_axis_label='V') for b in random_s_beats: # create a new plot with a title and axis labels time = np.arange(0, 216) # add a line renderer with legend and line thickness real_sample = b['cardiac_cycle'] real_sample = np.interp(real_sample, (real_sample.min(), real_sample.max()), (min(res), max(res))) p.line(time, real_sample, legend='real', line_width=2, line_color='green') p.line(time, res, legend="fake", line_width=2, line_color="black") p.legend.location = "bottom_right" # show the results show(p) def create_F_sample(): ecg_data = EcgHearBeatsDatasetTest(beat_type='F') beats = ecg_data.test n = 1 # for 2 random indices index = np.random.choice(len(beats), n, replace=False) index = [186] print(index) random_s_beats = beats[index] # # Generate F beat from simulator: # ode_params = ODEParams('cpu') ode_params.h = torch.tensor(1 / 216).to('cpu') params = [0.8, 0.25, -0.5 * math.pi, -10.0, 0.1, -15.0 * math.pi / 180.0, 30.0, 0.1, 0.03 * math.pi / 180.0, -10.0, 0.1, 15.0 * math.pi / 180.0, 0.5, 0.2, 160.0 * math.pi / 180.0] input_params = torch.tensor(params).view(1, 15) x = torch.tensor(-0.417750770388669) y = torch.tensor(-0.9085616622823985) z = torch.tensor(-0.004551233843726818) t = torch.tensor(0.0) x_signal = [x] y_signal = [y] z_signal = [z] for i in range(215): f_x = equations.d_x_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_y = equations.d_y_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_z = equations.d_z_d_t(x, y, z, t, input_params, ode_params) t += 1 / 360 x_signal.append(x + ode_params.h * f_x) y_signal.append(y + ode_params.h * f_y) z_signal.append(z + ode_params.h * f_z) x = x + ode_params.h * f_x y = y + ode_params.h * f_y z = z + ode_params.h * f_z res = [v.detach().item() for v in z_signal] p = figure(title="F beats", x_axis_label='#samples', y_axis_label='Voltage') for b in random_s_beats: # create a new plot with a title and axis labels time = np.arange(0, 216) # add a line renderer with legend and line thickness real_sample = b['cardiac_cycle'] real_sample = np.interp(real_sample, (real_sample.min(), real_sample.max()), (min(res), max(res))) p.line(time, real_sample, legend='real', line_width=2, line_color='green') p.line(time, res, legend="fake", line_width=2, line_color="black") p.legend.location = "bottom_right" # show the results show(p) def create_V_sample(): ecg_data = EcgHearBeatsDatasetTest(beat_type='V') beats = ecg_data.test n = 1 # for 2 random indices index = np.random.choice(len(beats), n, replace=False) # index = [2439] print(index) random_s_beats = beats[index] # # Generate V beat from simulator: # ode_params = ODEParams('cpu') ode_params.h = torch.tensor(1 / 216).to('cpu') #params = [1.2, 0.25, -60.0 * math.pi / 180.0, -5.0, 0.1, -15.0 * math.pi / 180.0, # 30.0, 0.1, 0.0 * math.pi / 180.0, -7.5, 0.1, 15.0 * math.pi / 180.0, 0.75, 0.4, # 90.0 * math.pi / 180.0] params = [0.1, 0.6, -0.5 * math.pi, 0.0, 0.1, -15.0 * math.pi / 180.0, 30.0, 0.1, 0.00 * math.pi / 180.0, -10.0, 0.1, 15.0 * math.pi / 180.0, 0.5, 0.2, 160.0 * math.pi / 180.0] input_params = torch.tensor(params).view(1, 15) x = torch.tensor(-0.417750770388669) y = torch.tensor(-0.9085616622823985) z = torch.tensor(-0.004551233843726818) t = torch.tensor(0.0) x_signal = [x] y_signal = [y] z_signal = [z] for i in range(215): f_x = equations.d_x_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_y = equations.d_y_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_z = equations.d_z_d_t(x, y, z, t, input_params, ode_params) t += 1 / 360 x_signal.append(x + ode_params.h * f_x) y_signal.append(y + ode_params.h * f_y) z_signal.append(z + ode_params.h * f_z) x = x + ode_params.h * f_x y = y + ode_params.h * f_y z = z + ode_params.h * f_z res = [v.detach().item() for v in z_signal] p = figure(title="V beats", x_axis_label='#samples', y_axis_label='Voltage') for b in random_s_beats: # create a new plot with a title and axis labels time = np.arange(0, 216) # add a line renderer with legend and line thickness real_sample = b['cardiac_cycle'] real_sample = np.interp(real_sample, (real_sample.min(), real_sample.max()), (min(res), max(res))) p.line(time, real_sample, legend='real', line_width=2, line_color='green') p.line(time, res, legend="fake", line_width=2, line_color="black") p.legend.location = "bottom_right" # show the results show(p) if __name__ == "__main__": # create_good_sample() # create_sample() # create_S_sample() # create_F_sample() create_V_sample()<file_sep>/ecg_pytorch/data_reader/ecg_dataset_pytorch.py from torch.utils.data import Dataset import numpy as np import torch from ecg_pytorch.data_reader import pickle_data from ecg_pytorch.dynamical_model import typical_beat_params, equations from ecg_pytorch.data_reader import ecg_mit_bih from ecg_pytorch.data_reader import dataset_configs, heartbeat_types import logging class EcgHearBeatsDatasetPytorch(Dataset): """ECG heart beats dataset for Pytorch usage.""" def __init__(self, configs, transform=None): """Creates a new EcgHearBeatsDatasetPytorch object. :param configs: dataset_configs.DatasetConfigs object which determines the dataset configurations. :param transform: pytorch different transformations. """ if not isinstance(configs, dataset_configs.DatasetConfigs): raise ValueError("configs input is not of type DatasetConfigs. instead: {}".format(type(configs))) self.configs = configs mit_bih_dataset = ecg_mit_bih.ECGMitBihDataset() if configs.partition == dataset_configs.PartitionNames.train: self.data = mit_bih_dataset.train_heartbeats else: assert configs.partition == dataset_configs.PartitionNames.test self.data = mit_bih_dataset.test_heartbeats if configs.only_take_heartbeat_of_type is not None: self.data = np.array([sample for sample in self.data if sample['aami_label_str'] == configs.only_take_heartbeat_of_type]) # consts: self.transform = transform def __len__(self): return len(self.data) def len_beat(self, beat_type): if beat_type not in heartbeat_types.AAMIHeartBeatTypes.__members__: raise ValueError("Invalid heart-beat type: {}".format(beat_type)) return len(np.array([sample for sample in self.data if sample['aami_label_str'] == beat_type])) def __getitem__(self, idx): sample = self.data[idx] if self.configs.lstm_setting: heartbeat = np.array([sample['cardiac_cycle'][i:i + 5] for i in range(0, 215, 5)]) else: heartbeat = sample['cardiac_cycle'] heartbeat_label_str = sample['aami_label_str'] if not self.configs.one_vs_all: sample = {'cardiac_cycle': heartbeat, 'beat_type': heartbeat_label_str, 'label': np.array(sample['aami_label_one_hot'])} else: if heartbeat_label_str == self.configs.classified_heartbeat: sample = {'cardiac_cycle': heartbeat, 'beat_type': heartbeat_label_str, 'label': np.array([1, 0])} else: sample = {'cardiac_cycle': heartbeat, 'beat_type': heartbeat_label_str, 'label': np.array([0, 1])} if self.transform: sample = self.transform(sample) return sample def add_beats_from_generator(self, generator_model, num_beats_to_add, checkpoint_path, beat_type): logging.info("Adding data from generator: {}. number of beats to add: {}\t" "checkpoint path: {}\t beat type: {}".format(generator_model, num_beats_to_add, checkpoint_path, beat_type)) checkpoint = torch.load(checkpoint_path) generator_model.load_state_dict(checkpoint['generator_state_dict']) # discriminator_model.load_state_dict(checkpoint['discriminator_state_dict']) with torch.no_grad(): input_noise = torch.Tensor(np.random.normal(0, 1, (num_beats_to_add, 100))) output_g = generator_model(input_noise) output_g = output_g.numpy() output_g = np.array( [{'cardiac_cycle': x, 'aami_label_str': beat_type, 'aami_label_one_hot': self.beat_type_to_one_hot_label[beat_type]} for x in output_g]) # plt.plot(output_g[0]['cardiac_cycle']) # plt.show() self.additional_data_from_gan = output_g self.train = np.concatenate((self.train, output_g)) print("Length of train samples after adding from generator is {}".format(len(self.train))) def add_beats_from_simulator(self, num_beats_to_add, beat_type): beat_params = typical_beat_params.beat_type_to_typical_param[beat_type] noise_param = (np.random.normal(0, 0.1, (num_beats_to_add, 15))) params = 0.01 * noise_param + beat_params sim_beats = equations.generate_batch_of_beats_numpy(params) sim_beats = np.array( [{'cardiac_cycle': x, 'beat_type': beat_type, 'label': self.beat_type_to_one_hot_label[beat_type]} for x in sim_beats]) self.additional_data_from_simulator = sim_beats self.train = np.concatenate((self.train, sim_beats)) print("Length of train samples after adding from simulator is {}".format(len(self.train))) return sim_beats def add_noise(self, n, beat_type): input_noise = np.random.normal(0, 1, (n, 216)) input_noise = np.array( [{'cardiac_cycle': x, 'beat_type': beat_type, 'label': self.beat_type_to_one_hot_label[beat_type]} for x in input_noise]) self.train = np.concatenate((self.train, input_noise)) class Scale(object): def __call__(self, sample): heartbeat, label = sample['cardiac_cycle'], sample['label'] heartbeat = scale_signal(heartbeat) return {'cardiac_cycle': heartbeat, 'label': label, 'beat_type': sample['beat_type']} def scale_signal(signal, min_val=-0.01563, max_val=0.042557): """ :param min: :param max: :return: """ # Scale signal to lie between -0.4 and 1.2 mV : scaled = np.interp(signal, (signal.min(), signal.max()), (min_val, max_val)) # zmin = min(signal) # zmax = max(signal) # zrange = zmax - zmin # # for (i=1; i <= Nts; i++) # scaled = [(z - zmin) * max_val / zrange + min_val for z in signal] return scaled # class EcgHearBeatsDatasetTest(Dataset): # """ECG heart beats dataset.""" # # def __init__(self, transform=None, beat_type=None, one_vs_all=None, lstm_setting=True): # # _, _, self.test = pickle_data.load_ecg_input_from_pickle() # mit_bih_dataset = ecg_mit_bih.ECGMitBihDataset() # self.train = mit_bih_dataset.train_heartbeats # self.test = mit_bih_dataset.test_heartbeats # # self.test = self.test + self.train # self.lstm_setting = lstm_setting # self.one_vs_all = False # if beat_type is not None and one_vs_all is None: # self.test = np.array([sample for sample in self.test if sample['aami_label_str'] == beat_type]) # # if one_vs_all is not None: # self.beat_type = beat_type # self.one_vs_all = True # self.num_of_classes = 2 # else: # self.num_of_classes = 5 # self.transform = transform # # def __len__(self): # return len(self.test) # # def __getitem__(self, idx): # sample = self.test[idx] # # if self.lstm_setting: # lstm_beat = np.array([sample['cardiac_cycle'][i:i + 5] for i in range(0, 215, 5)]) # [43, 5] # else: # lstm_beat = sample['cardiac_cycle'] # tag = sample['aami_label_str'] # # sample = {'cardiac_cycle': lstm_beat, 'beat_type': tag, 'label': np.array(sample['label'])} # if not self.one_vs_all: # sample = {'cardiac_cycle': lstm_beat, 'beat_type': tag, 'label': np.array(sample['aami_label_one_hot'])} # else: # if tag == self.beat_type: # sample = {'cardiac_cycle': lstm_beat, 'beat_type': tag, 'label': np.array([1, 0])} # else: # sample = {'cardiac_cycle': lstm_beat, 'beat_type': tag, 'label': np.array([0, 1])} # if self.transform: # sample = self.transform(sample) # return sample # # def len_beat(self, beat_Type): # return len(np.array([sample for sample in self.test if sample['aami_label_str'] == beat_Type])) # # def print_statistics(self): # count = np.array([self.len_beat('N'), self.len_beat('S'), self.len_beat('V'), # self.len_beat('F'), self.len_beat('Q')]) # print("Beat N: #{}\t Beat S: #{}\t Beat V: #{}\n Beat F: #{}\t Beat Q: #{}".format(count[0], count[1], count[2], # count[3], count[4])) class ToTensor(object): """Convert ndarrays in sample to Tensors.""" def __call__(self, sample): heartbeat, label = sample['cardiac_cycle'], sample['label'] return {'cardiac_cycle': (torch.from_numpy(heartbeat)).double(), 'label': torch.from_numpy(label), 'beat_type': sample['beat_type']} <file_sep>/ecg_pytorch/dynamical_model/Euler/euler.py from ecg_pytorch.dynamical_model.Euler.single_step import single_step_euler import torch import math import matplotlib.pyplot as plt import numpy as np import torch.nn as nn from ecg_pytorch.dynamical_model.ode_params import ODEParams # from ecg_pytorch.data_reader import ecg_dataset import torchvision.transforms as transforms class Euler(nn.Module): def __init__(self, device_name): super(Euler, self).__init__() self.device_name = device_name def forward(self, x, v0): # x = x.view(x.size(0), -1) x = euler(x, self.device_name, v0) # x = down_sample(x) # x = x.view(-1, 1, 216) x = scale_signal(x) return x def scale_signal(ecg_signal, min_val=-0.01563, max_val=0.042557): """ :param min: :param max: :return: """ res = [] for beat in ecg_signal: # Scale signal to lie between -0.4 and 1.2 mV : zmin = min(beat) zmax = max(beat) zrange = zmax - zmin scaled = [(z - zmin) * max_val / zrange + min_val for z in beat] scaled = torch.stack(scaled) res.append(scaled) res = torch.stack(res) return res def down_sample(ecg_signal): res = [] for beat in ecg_signal: i = 0 down_sampled_ecg = [] q = int(514 / 216) while i < 514: # j += 1 if len(down_sampled_ecg) == 216: break down_sampled_ecg.append(beat[i]) i += q # q = int(np.rint(self.ecg_params.getSf() / self.ecg_params.getSfEcg())) down_sampled_ecg = torch.stack(down_sampled_ecg) res.append(down_sampled_ecg) res = torch.stack(res) return res def euler(params_batch, device_name, v0): ode_params = ODEParams(device_name) # params = params_batch x = torch.tensor(-0.417750770388669).to(device_name) y = torch.tensor(-0.9085616622823985).to(device_name) # z = torch.tensor(-0.004551233843726818).to(device_name) res = [] # print(len(params_batch)) for j, params in enumerate(params_batch): z = torch.tensor(v0[j]).to(device_name) t = torch.tensor(0.0).to(device_name) x_next, y_next, z_next = single_step_euler(ode_params, x, y, z, t, params, device_name) x_t = [x_next] y_t = [y_next] z_t = [z_next] for i in range(215): t += 1 / 216 x_next, y_next, z_next = single_step_euler(ode_params, x_next, y_next, z_next, t, params, device_name) x_t.append(x_next) y_t.append(y_next) z_t.append(z_next) # z_res = [] z_t = torch.stack(z_t) # z_t += torch.Tensor(np.random.normal(0, 0.0001, 216)) res.append(z_t) res = torch.stack(res) return res # def test_euler_with_different_inits(): # composed = transforms.Compose([ecg_dataset.Scale(), ecg_dataset.ToTensor()]) # dataset = ecg_dataset.EcgHearBeatsDataset(transform=composed, beat_type='N') # dataloader = torch.utils.data.DataLoader(dataset, batch_size=2, # shuffle=False, num_workers=1) # for i, e in enumerate(dataloader): # # e = dataset[i] # if i == 5: # break # v0 = e['cardiac_cycle'].numpy()[:, 0] # print("v0 = {}".format(v0)) # input = np.array(( # ([1.2, 0.25, -60.0 * math.pi / 180.0, -5.0, 0.1, -15.0 * math.pi / 180.0, # 30.0, 0.1, 0.0 * math.pi / 180.0, -7.5, 0.1, 15.0 * math.pi / 180.0, 0.75, 0.4, # 90.0 * math.pi / 180.0]))).reshape((1, 15)) # # a1 = torch.nn.Parameter(torch.Tensor(input), requires_grad=True) # a2 = torch.nn.Parameter(torch.Tensor(input), requires_grad=True) # third_tensor = torch.cat((a1, a2), 0) # res = euler(third_tensor, "cpu", v0) # print(res.shape) # res0 = res.detach().numpy()[0] # plt.figure() # plt.plot(res0, label='ode beat') # plt.plot(e['cardiac_cycle'][0].numpy(), label="real") # plt.legend() # plt.show() # # res1 = res.detach().numpy()[1] # plt.figure() # plt.plot(res1, label='ode beat') # plt.plot(e['cardiac_cycle'][1].numpy(), label="real") # plt.legend() # plt.title("verf") # plt.show() if __name__ == "__main__": # params = torch.nn.Parameter( # torch.tensor([1.2, 0.25, -60.0 * math.pi / 180.0, -5.0, 0.1, -15.0 * math.pi / 180.0, # 30.0, 0.1, 0.0 * math.pi / 180.0, -7.5, 0.1, 15.0 * math.pi / 180.0, 0.75, 0.4, # 90.0 * math.pi / 180.0])) # # input = np.array(( # ([1.2, 0.25, -60.0 * math.pi / 180.0, -5.0, 0.1, -15.0 * math.pi / 180.0, # 30.0, 0.1, 0.0 * math.pi / 180.0, -7.5, 0.1, 15.0 * math.pi / 180.0, 0.75, 0.4, # 90.0 * math.pi / 180.0]))).reshape((1,15)) # # a1 = torch.nn.Parameter(torch.Tensor(input), requires_grad=True) # a2 = torch.nn.Parameter(torch.Tensor(input), requires_grad=True) # print(a1.shape) # # input = torch.nn.Parameter(torch.Tensor([input]), requires_grad=True) # third_tensor = torch.cat((a1, a2), 0) # # print(third_tensor) # ngpu = 0 # device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu") # res = euler(third_tensor, device, 0.0) # # # print(res[1][-1].backward()) # # print(a2.grad) # # print(res.shape) # # res = [x.detach().numpy() for x in res[1]] # plt.plot(res) # plt.show() # test_euler_with_different_inits() pass<file_sep>/ecg_pytorch/dynamical_model/equations.py import torch import logging import math from ecg_pytorch.dynamical_model.ode_params import ODEParams, ODEParamsNumpy import time from matplotlib import pyplot as plt import numpy as np def d_x_d_t(y, x, t, rrpc, delta_t): alpha = 1 - ((x * x) + (y * y)) ** 0.5 cast = (t / delta_t).type(torch.IntTensor) tensor_temp = 1 + cast tensor_temp = tensor_temp % len(rrpc) if rrpc[tensor_temp] == 0: logging.info("***inside zero***") omega = (2.0 * math.pi / 1e-3) else: omega = (2.0 * math.pi / rrpc[tensor_temp]) f_x = alpha * x - omega * y return f_x def d_x_d_t_numpy(y, x, t, rrpc, delta_t): alpha = 1 - ((x * x) + (y * y)) ** 0.5 cast = int(t / delta_t) tensor_temp = 1 + cast tensor_temp = tensor_temp % len(rrpc) if rrpc[tensor_temp] == 0: logging.info("***inside zero***") omega = (2.0 * math.pi / 1e-3) else: omega = (2.0 * math.pi / rrpc[tensor_temp]) f_x = alpha * x - omega * y return f_x def d_y_d_t(y, x, t, rrpc, delta_t): alpha = 1 - ((x * x) + (y * y)) ** 0.5 cast = (t / delta_t).type(torch.IntTensor) tensor_temp = 1 + cast tensor_temp = tensor_temp % len(rrpc) if rrpc[tensor_temp] == 0: logging.info("***inside zero***") omega = (2.0 * math.pi / 1e-3) else: omega = (2.0 * math.pi / rrpc[tensor_temp]) f_y = alpha * y + omega * x return f_y def d_y_d_t_numpy(y, x, t, rrpc, delta_t): alpha = 1 - ((x * x) + (y * y)) ** 0.5 cast = int(t / delta_t) tensor_temp = 1 + cast tensor_temp = tensor_temp % len(rrpc) if rrpc[tensor_temp] == 0: logging.info("***inside zero***") omega = (2.0 * math.pi / 1e-3) else: omega = (2.0 * math.pi / rrpc[tensor_temp]) f_y = alpha * y + omega * x return f_y def d_z_d_t(x, y, z, t, params, ode_params): """ :param x: :param y: :param z: :param t: :param params: :param ode_params: Nx15 :return: """ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # device = 'cpu' A = ode_params.A f2 = ode_params.f2 a_p, a_q, a_r, a_s, a_t = params[:, 0], params[:, 3], params[:, 6], params[:, 9], params[:, 12] b_p, b_q, b_r, b_s, b_t = params[:, 1], params[:, 4], params[:, 7], params[:, 10], params[:, 13] theta_p, theta_q, theta_r, theta_s, theta_t = params[:, 2], params[:, 5], params[:, 8], params[:, 11], params[:, 14] a_p = a_p.view(-1, 1) a_q = a_q.view(-1, 1) a_r = a_r.view(-1, 1) a_s = a_s.view(-1, 1) a_t = a_t.view(-1, 1) b_p = b_p.view(-1, 1) b_q = b_q.view(-1, 1) b_r = b_r.view(-1, 1) b_s = b_s.view(-1, 1) b_t = b_t.view(-1, 1) theta_p = theta_p.view(-1, 1) theta_q = theta_q.view(-1, 1) theta_r = theta_r.view(-1, 1) theta_s = theta_s.view(-1, 1) theta_t = theta_t.view(-1, 1) logging.debug("theta p shape: {}".format(theta_p.shape)) theta = torch.atan2(y, x) logging.debug("theta shape: {}".format(theta.shape)) logging.debug("delta before mod: {}".format((theta - theta_p).shape)) delta_theta_p = torch.fmod(theta - theta_p, 2 * math.pi) logging.debug("delta theta shape: {}".format(delta_theta_p.shape)) delta_theta_q = torch.fmod(theta - theta_q, 2 * math.pi) delta_theta_r = torch.fmod(theta - theta_r, 2 * math.pi) delta_theta_s = torch.fmod(theta - theta_s, 2 * math.pi) delta_theta_t = torch.fmod(theta - theta_t, 2 * math.pi) z_p = a_p * delta_theta_p * \ torch.exp((- delta_theta_p * delta_theta_p / (2 * b_p * b_p))) z_q = a_q * delta_theta_q * \ torch.exp((- delta_theta_q * delta_theta_q / (2 * b_q * b_q))) z_r = a_r * delta_theta_r * \ torch.exp((- delta_theta_r * delta_theta_r / (2 * b_r * b_r))) z_s = a_s * delta_theta_s * \ torch.exp((- delta_theta_s * delta_theta_s / (2 * b_s * b_s))) z_t = a_t * delta_theta_t * \ torch.exp((- delta_theta_t * delta_theta_t / (2 * b_t * b_t))) z_0_t = (A * torch.sin(2 * math.pi * f2 * t)) z_p = z_p.to(device) z_q = z_q.to(device) z_r = z_r.to(device) z_s = z_s.to(device) z_t = z_t.to(device) z_0_t = z_0_t.to(device) f_z = -1 * (z_p + z_q + z_r + z_s + z_t) - (z - z_0_t) return f_z def d_z_d_t_numpy(x, y, z, t, params, ode_params): A = ode_params.A f2 = ode_params.f2 a_p, a_q, a_r, a_s, a_t = params[:, 0], params[:, 3], params[:, 6], params[:, 9], params[:, 12] b_p, b_q, b_r, b_s, b_t = params[:, 1], params[:, 4], params[:, 7], params[:, 10], params[:, 13] theta_p, theta_q, theta_r, theta_s, theta_t = params[:, 2], params[:, 5], params[:, 8], params[:, 11], params[:, 14] a_p = a_p.reshape((-1, 1)) a_q = a_q.reshape((-1, 1)) a_r = a_r.reshape((-1, 1)) a_s = a_s.reshape((-1, 1)) a_t = a_t.reshape((-1, 1)) b_p = b_p.reshape((-1, 1)) b_q = b_q.reshape((-1, 1)) b_r = b_r.reshape((-1, 1)) b_s = b_s.reshape((-1, 1)) b_t = b_t.reshape((-1, 1)) theta_p = theta_p.reshape((-1, 1)) theta_q = theta_q.reshape((-1, 1)) theta_r = theta_r.reshape((-1, 1)) theta_s = theta_s.reshape((-1, 1)) theta_t = theta_t.reshape((-1, 1)) logging.debug("theta p shape: {}".format(theta_p.shape)) theta = np.arctan2(y, x) logging.debug("theta shape: {}".format(theta.shape)) logging.debug("delta before mod: {}".format((theta - theta_p).shape)) delta_theta_p = np.fmod(theta - theta_p, 2 * math.pi) logging.debug("delta theta shape: {}".format(delta_theta_p.shape)) delta_theta_q = np.fmod(theta - theta_q, 2 * math.pi) delta_theta_r = np.fmod(theta - theta_r, 2 * math.pi) delta_theta_s = np.fmod(theta - theta_s, 2 * math.pi) delta_theta_t = np.fmod(theta - theta_t, 2 * math.pi) z_p = a_p * delta_theta_p * \ np.exp((- delta_theta_p * delta_theta_p / (2 * b_p * b_p))) z_q = a_q * delta_theta_q * \ np.exp((- delta_theta_q * delta_theta_q / (2 * b_q * b_q))) z_r = a_r * delta_theta_r * \ np.exp((- delta_theta_r * delta_theta_r / (2 * b_r * b_r))) z_s = a_s * delta_theta_s * \ np.exp((- delta_theta_s * delta_theta_s / (2 * b_s * b_s))) z_t = a_t * delta_theta_t * \ np.exp((- delta_theta_t * delta_theta_t / (2 * b_t * b_t))) z_0_t = (A * np.sin(2 * math.pi * f2 * t)) z_p = z_p z_q = z_q z_r = z_r z_s = z_s z_t = z_t z_0_t = z_0_t f_z = -1 * (z_p + z_q + z_r + z_s + z_t) - (z - z_0_t) return f_z def generate_batch_of_beats_numpy(params): ode_params = ODEParamsNumpy() x = np.array([-0.417750770388669 for _ in range(params.shape[0])]).reshape((-1, 1)) y = np.array([-0.9085616622823985 for _ in range(params.shape[0])]).reshape((-1, 1)) z = np.array([-0.004551233843726818 for _ in range(params.shape[0])]).reshape((-1, 1)) t = 0.0 x_signal = [x] y_signal = [y] z_signal = [z] start = time.time() for i in range(215): f_x = d_x_d_t_numpy(y, x, t, ode_params.rrpc, ode_params.h) f_y = d_y_d_t_numpy(y, x, t, ode_params.rrpc, ode_params.h) f_z = d_z_d_t_numpy(x, y, z, t, params, ode_params) t += 1 / 512 x_signal.append(x + ode_params.h * f_x) y_signal.append(y + ode_params.h * f_y) z_signal.append(z + ode_params.h * f_z) x = x + ode_params.h * f_x y = y + ode_params.h * f_y z = z + ode_params.h * f_z end = time.time() logging.info("Time to generate batch: {}".format(end - start)) z_signal = np.stack(z_signal).reshape((216, -1)).transpose() return z_signal def test_equations(): ode_params = ODEParams('cpu') input_params = torch.nn.Parameter( torch.tensor([1.2, 0.25, -60.0 * math.pi / 180.0, -5.0, 0.1, -15.0 * math.pi / 180.0, 30.0, 0.1, 0.0 * math.pi / 180.0, -7.5, 0.1, 15.0 * math.pi / 180.0, 0.75, 0.4, 90.0 * math.pi / 180.0])).view(1, 15) x = torch.tensor(-0.417750770388669) y = torch.tensor(-0.9085616622823985) z = torch.tensor(-0.004551233843726818) t = torch.tensor(0.0) x_signal = [x] y_signal = [y] z_signal = [z] start = time.time() for i in range(215): f_x = d_x_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_y = d_y_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_z = d_z_d_t(x, y, z, t, input_params, ode_params) t += 1 / 512 logging.debug("f_z shape: {}".format(f_z.shape)) x_signal.append(x + ode_params.h * f_x) y_signal.append(y + ode_params.h * f_y) z_signal.append(z + ode_params.h * f_z) x = x + ode_params.h * f_x y = y + ode_params.h * f_y z = z + ode_params.h * f_z end = time.time() logging.info("time: {}".format(end - start)) res = [v.detach().numpy() for v in z_signal] print(len(res)) plt.plot(res) plt.show() # logging.DEBUG("Z: {}".format([x.detach().item() for x in z_signal])) # logging.DEBUG("X: {}".format([x.detach().item() for x in x_signal])) # logging.DEBUG("Y: {}".format([x.detach().item() for x in y_signal])) def test_equations_on_batch(): ode_params = ODEParams('cpu') input = np.array(( ([1.2, 0.25, -60.0 * math.pi / 180.0, -5.0, 0.1, -15.0 * math.pi / 180.0, 30.0, 0.1, 0.0 * math.pi / 180.0, -7.5, 0.1, 15.0 * math.pi / 180.0, 0.75, 0.4, 90.0 * math.pi / 180.0]))).reshape((1,15)) a1 = torch.nn.Parameter(torch.Tensor(input), requires_grad=True) a2 = torch.nn.Parameter(torch.Tensor(input), requires_grad=True) print(a1.shape) input_params = torch.cat((a1, a2), 0) print("Input params shape: {}".format(input_params.shape)) x = torch.tensor([-0.417750770388669, -0.417750770388669]).view(2, 1) y = torch.tensor([-0.9085616622823985, -0.9085616622823985]).view(2, 1) z = torch.tensor([-0.004551233843726818, 0.03]).view(2, 1) t = torch.tensor(0.0) x_signal = [x] y_signal = [y] z_signal = [z] start = time.time() for i in range(215): f_x = d_x_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_y = d_y_d_t(y, x, t, ode_params.rrpc, ode_params.h) f_z = d_z_d_t(x, y, z, t, input_params, ode_params) t += 1 / 512 logging.info("f_z shape: {}".format(f_z.shape)) logging.info("f_y shape: {}".format(f_y.shape)) logging.info("f_x shape: {}".format(f_x.shape)) x_signal.append(x + ode_params.h * f_x) y_signal.append(y + ode_params.h * f_y) z_signal.append(z + ode_params.h * f_z) x = x + ode_params.h * f_x y = y + ode_params.h * f_y z = z + ode_params.h * f_z end = time.time() logging.info("time: {}".format(end - start)) z_signal = torch.stack(z_signal) logging.info('z_signal shape: {}'.format(z_signal.shape)) res = [v[0].detach().numpy() for v in z_signal] print(len(res)) print(res[0]) plt.plot(res) plt.show() res = [v[1].detach().numpy() for v in z_signal] print(len(res)) print(res[0]) plt.plot(res) plt.show() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) # test_equations() test_equations_on_batch()<file_sep>/README.md # ecg_pytorch ECG heartbeat classification Pytorch implementation for ECG heartbeat classification using Generative approaches. ## Online Demo [<img src="complete">](complete) [link](complete) ## Prerequisites - Python 3.3+ - [yPtorch](https://github.com/tensorflow/tensorflow/tree/r0.12) - Add more... ## Usage First, download dataset with: $ python .... To train a model with downloaded dataset: $ python ... $ python ... To test with an existing model: $ python main.py ... $ python main.py ... ## Results ![result](assets/training.gif) ### DCGAN After 6th epoch: ![result3](assets/result_16_01_04_.png) After 10th epoch: ![result4](assets/test_2016-01-27%2015:08:54.png) ### PGAN ![custom_result1](web/img/change5.png) ![custom_result1](web/img/change2.png) ![custom_result2](web/img/change4.png) ### ODEGAN MNIST codes are written by [@PhoenixDai](https://github.com/PhoenixDai). ![mnist_result1](assets/mnist1.png) ![mnist_result2](assets/mnist2.png) ![mnist_result3](assets/mnist3.png) More results can be found [here](./assets/) and [here](./web/img/). ## Training details Details of the loss of Discriminator and Generator. ![d_loss](assets/d_loss.png) ![g_loss](assets/g_loss.png) Details of the histogram of true and fake result of discriminator. ![d_hist](assets/d_hist.png) ![d__hist](assets/d__hist.png) ## Related works - ... ## Author <NAME> <file_sep>/setup.py """ Install command: pip --user install -e . """ from setuptools import find_packages from setuptools import setup REQUIRED_PACKAGES = ['matplotlib', 'numpy', 'bokeh', 'tensorboardX', 'sklearn', 'torchvision', 'torch', 'wfdb', 'google-api-python-client', 'google-auth-httplib2', 'google-auth-oauthlib', 'opencv-python'] setup(name='ecg_pytorch', version='0.1', install_requires=REQUIRED_PACKAGES, description='Deep learning methods for ECG classifications', url='http://github.com/tomergolany/ecg_pytorch', author='<NAME>', author_email='<EMAIL>', license='Technion', packages=find_packages(), include_package_data=True, zip_safe=False) <file_sep>/ecg_pytorch/dynamical_model/ode_params.py import torch from ecg_pytorch.dynamical_model import utils class ODEParams: def __init__(self, device_name): self.A = torch.tensor(0.005).to(device_name) # mV self.f1 = torch.tensor(0.1).to(device_name) # mean 1 self.f2 = torch.tensor(0.25).to(device_name) # mean 2 self.c1 = torch.tensor(0.01).to(device_name) # std 1 self.c2 = torch.tensor(0.01).to(device_name) # std 2 self.rrpc = utils.generate_omega_function(self.f1, self.f2, self.c1, self.c2) self.rrpc = torch.tensor(self.rrpc).to(device_name).float() self.h = torch.tensor(1 / 216).to(device_name) class ODEParamsNumpy: def __init__(self): self.A = 0.005 # mV self.f1 = 0.1 # mean 1 self.f2 = 0.25 # mean 2 self.c1 = 0.01 # std 1 self.c2 = 0.01 # std 2 self.rrpc = utils.generate_omega_function(self.f1, self.f2, self.c1, self.c2) self.h = 1 / 216 <file_sep>/ecg_pytorch/classifiers/inference/video_writer.py """Module that writes ecg signal videos for visualization.""" import cv2 import matplotlib.pyplot as plt from ecg_pytorch.classifiers.inference import run_inference from ecg_pytorch.classifiers.models import deep_residual_conv import tqdm N_COLOR = (255, 128, 0) S_COLOR = (51, 255, 510) V_COLOR = (0, 0, 255) F_COLOR = (255, 51, 255) Q_COLOR = (255, 0, 0) CLASS_TO_COLOR = {'N': N_COLOR, 'S': S_COLOR, 'V': V_COLOR, 'F': F_COLOR, 'Q': Q_COLOR, 'Other': Q_COLOR} class ECGVideo(object): def __init__(self, beat_type, model, model_chk, patient_number): self.fourcc = cv2.VideoWriter_fourcc('P', 'N', 'G', ' ') self.ecg_inference_obj = run_inference.ECGInferenceOneVsAll(beat_type, model, model_chk, patient_number) self.patient_number = patient_number self.beat_type = beat_type # out = cv2.VideoWriter('test/patient_{}_inference_fc.avi'.format(patient_number), fourcc, 4, (640, 480)) def write(self): out = cv2.VideoWriter('test/patient_{}_inference.avi'.format(self.patient_number), self.fourcc, 4, (640, 480)) ground_truths, predictions, classes_ind, predicted_classes_str, cardiac_cycles, gts_class_str = \ self.ecg_inference_obj.predict() i = 0 for heartbeat, gt_one_hot, pred_one_hot, pred_class_str, true_class in tqdm.tqdm(zip(cardiac_cycles, ground_truths, predictions, predicted_classes_str, gts_class_str)): i += 1 plt.figure() plt.plot(heartbeat) plt.xlabel('Sample # (360 HZ)') plt.ylabel('Voltage') plt.savefig('temp.png') img = cv2.imread('temp.png', cv2.IMREAD_UNCHANGED) font = cv2.FONT_HERSHEY_SIMPLEX pt_print = "Patient: {}".format(self.patient_number) true_class_print = "Ground truth beat: {}".format(true_class) prdicted_beat_print = "Prediction: {}".format(pred_class_str) scores_print = "Scores: {}: {:.2f} Others: {:.2f}".format(self.beat_type, pred_one_hot[0], pred_one_hot[1]) beat_num_print = "Beat #{}".format(i) truce_class_color = CLASS_TO_COLOR[true_class] pred_class_color = CLASS_TO_COLOR[pred_class_str] cv2.putText(img, pt_print, (300, 30), font, 0.5, (0, 0, 0), 1, cv2.LINE_AA) cv2.putText(img, true_class_print, (10, 30), font, 0.5, truce_class_color, 1, cv2.LINE_AA) cv2.putText(img, prdicted_beat_print, (500, 30), font, 0.5, pred_class_color, 1, cv2.LINE_AA) cv2.putText(img, scores_print, (84, 70), font, 0.32, (0, 0, 255), 1, cv2.LINE_AA) cv2.putText(img, beat_num_print, (10, 450), font, 0.5, (0, 0, 0), 1, cv2.LINE_AA) out.write(img) plt.close() plt.clf() out.release() if __name__ == "__main__": model_chk = '/Users/tomer.golany/PycharmProjects/ecg_pytorch/ecg_pytorch/classifiers/tensorboard/s_resnet_raw_v2/vgan_1000/checkpoint_epoch_iters_2685' net = deep_residual_conv.Net(2) p = '118' ecg_video = ECGVideo('S', net, model_chk, p) ecg_video.write() <file_sep>/ecg_pytorch/data_reader/patient.py import numpy as np import os import logging # from matplotlib import pyplot as plt # from bokeh.io import output_file, show # from bokeh.layouts import row # from bokeh.plotting import figure from ecg_pytorch import train_configs from ecg_pytorch.data_reader import heartbeat_types import wfdb import pandas as pd DATA_DIR = train_configs.base + 'ecg_pytorch/ecg_pytorch/data_reader/text_files/' train_set = [101, 106, 108, 109, 112, 114, 115, 116, 118, 119, 122, 124, 201, 203, 205, 207, 208, 209, 215, 220, 223, 230] # DS1 train_set = [str(x) for x in train_set] test_set = [100, 103, 105, 111, 113, 117, 121, 123, 200, 202, 210, 212, 213, 214, 219, 221, 222, 228, 231, 232, 233, 234] # DS2 test_set = [str(x) for x in test_set] class Patient(object): """Patient object represents a patient from the MIT-BIH AR database. Attributes: """ def __init__(self, patient_number): """Init Patient object from corresponding text file. :param patient_number: string which represents the patient number. """ logging.info("Creating patient {}...".format(patient_number)) self.patient_number = patient_number self.signals, self.additional_fields = self.get_raw_signals() self.mit_bih_labels_str, self.labels_locations, self.labels_descriptions = self.get_annotations() self.heartbeats = self.slice_heartbeats() logging.info("Completed patient {}.\n\n".format(patient_number)) @DeprecationWarning def read_raw_data(self): """Read patient's data file. :return: """ dat_file = os.path.join(DATA_DIR, self.patient_number + '.txt') if not os.path.exists(dat_file): raise AssertionError("{} doesn't exist.".format(dat_file)) time = [] voltage1 = [] voltage2 = [] with open(dat_file, 'r') as fd: for line in fd: line = line.split() time.append(line[0]) voltage1.append(float(line[1])) voltage2.append(float(line[2])) tags_file = os.path.join(DATA_DIR, self.patient_number + '_tag.txt') if not os.path.exists(dat_file): raise AssertionError("{} doesn't exist.".format(tags_file)) tags_time = [] tags = [] r_peaks_indexes = [] with open(tags_file, 'r') as fd: for line in fd: line = line.split() tags_time.append(line[0]) tags.append(line[2]) r_peaks_indexes.append(int(line[1])) return time, voltage1, voltage2, tags_time, tags, r_peaks_indexes def get_raw_signals(self): """Get raw signal using the wfdb package. :return: signals : numpy array A 2d numpy array storing the physical signals from the record. fields : dict A dictionary containing several key attributes of the read record: - fs: The sampling frequency of the record - units: The units for each channel - sig_name: The signal name for each channel - comments: Any comments written in the header """ signals, fields = wfdb.rdsamp(self.patient_number, pb_dir='mitdb', warn_empty=True) logging.info("Patient {} additional info: {}".format(self.patient_number, fields)) return signals, fields def get_annotations(self): """Get signal annotation using the wfdb package. :return: """ ann = wfdb.rdann(self.patient_number, 'atr', pb_dir='mitdb', return_label_elements=['symbol', 'label_store', 'description'], summarize_labels=True) mit_bih_labels_str = ann.symbol labels_locations = ann.sample labels_description = ann.description return mit_bih_labels_str, labels_locations, labels_description def slice_heartbeats(self): """Slice heartbeats from the raw signal. :return: """ sampling_rate = self.additional_fields['fs'] # 360 samples per second logging.info("Sampling rate: {}".format(sampling_rate)) assert sampling_rate == 360 before = 0.2 # 0.2 seconds == 0.2 * 10^3 miliseconds == 200 ms after = 0.4 # --> 400 ms # # Find lead 2 position: # lead_pos = None for i, lead in enumerate(self.additional_fields['sig_name']): if lead == 'MLII': lead_pos = i if lead_pos is None: raise AssertionError("Didn't find lead 2 position. LEADS: {}".format(self.additional_fields['sig_name'])) logging.info("LEAD 2 position: {}".format(lead_pos)) ecg_signal = self.signals[:, lead_pos] r_peak_locations = self.labels_locations # convert seconds to samples before = int(before * sampling_rate) # Number of samples per 200 ms. after = int(after * sampling_rate) # number of samples per 400 ms. len_of_signal = len(ecg_signal) heart_beats = [] for ind, r_peak in enumerate(r_peak_locations): start = r_peak - before if start < 0: logging.info("Skipping beat {}".format(ind)) continue end = r_peak + after if end > len_of_signal - 1: logging.info("Skipping beat {}".format(ind)) break heart_beats_dict = {} heart_beat = np.array(ecg_signal[start:end]) heart_beats_dict['patient_number'] = self.patient_number heart_beats_dict['cardiac_cycle'] = heart_beat aami_label_str = heartbeat_types.convert_heartbeat_mit_bih_to_aami(self.mit_bih_labels_str[ind]) aami_label_ind = heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class(self.mit_bih_labels_str[ind]) heart_beats_dict['mit_bih_label_str'] = self.mit_bih_labels_str[ind] heart_beats_dict['aami_label_str'] = aami_label_str heart_beats_dict['aami_label_ind'] = aami_label_ind heart_beats_dict['aami_label_one_hot'] = heartbeat_types.convert_to_one_hot(aami_label_ind) heart_beats_dict['beat_ind'] = ind heart_beats_dict['lead'] = 'MLII' heart_beats.append(heart_beats_dict) return heart_beats def get_heartbeats_of_type(self, aami_label_str): """ :param aami_label_str: :return: """ return [hb for hb in self.heartbeats if hb['aami_label_str'] == aami_label_str] def num_heartbeats(self, aami_label_str): """ :param aami_label_str: :return: """ return len(self.get_heartbeats_of_type(aami_label_str)) def heartbeats_summaries(self): """Create summaries: :return: """ heartbeat_summaries = [] for hb_aami in heartbeat_types.AAMIHeartBeatTypes: hb_summary = {} hb_summary['heartbeat_aami_str'] = hb_aami.name num_hb = self.num_heartbeats(hb_aami.name) hb_summary['number_of_beats'] = num_hb heartbeat_summaries.append(hb_summary) total_summary = {} total_summary['heartbeat_aami_str'] = 'ALL' total_summary['number_of_beats'] = len(self.heartbeats) heartbeat_summaries.append(total_summary) return pd.DataFrame(heartbeat_summaries) def get_patient_df(self): """Get data frame with patient details per heartbeat. :return: pandas dataframe. """ df = pd.DataFrame(self.heartbeats) df.drop(columns=['cardiac_cycle'], inplace=True) return df if __name__ == "__main__": logging.basicConfig(level=logging.INFO) p_100 = Patient('114') df = p_100.get_patient_df() # print(df) print(p_100.heartbeats_summaries()) # heartbeats = p_100.heartbeats # # logging.info("Total number of heartbeats: {}\t #N: {}\t #S: {}\t, #V: {}, #F: {}\t #Q: {}" # .format(len(heartbeats), p_100.num_heartbeats('N'), p_100.num_heartbeats('S'), p_100.num_heartbeats('V'), # p_100.num_heartbeats('F'), p_100.num_heartbeats('Q'))) # time = list(range(216)) # for i in range(100): # p = figure(x_axis_label='Sample number (360 Hz)', y_axis_label='Voltage[mV]') # p.line(time, N_b[i], line_width=2, line_color="green") # output_file("N_{}_real.html".format(i)) # show(p) # plt.plot(N_b[i]) # plt.show() <file_sep>/ecg_pytorch/data_reader/ecg_mit_bih.py """Preprocessing the MIT-BIH dataset""" from ecg_pytorch import train_configs from ecg_pytorch.data_reader import patient from ecg_pytorch.data_reader import heartbeat_types import pandas as pd import logging DATA_DIR = train_configs.base + 'ecg_pytorch/ecg_pytorch/data_reader/text_files/' train_set = [101, 106, 108, 109, 112, 114, 115, 116, 118, 119, 122, 124, 201, 203, 205, 207, 208, 209, 215, 220, 223, 230] # DS1 train_set = [str(x) for x in train_set] test_set = [100, 103, 105, 111, 113, 117, 121, 123, 200, 202, 210, 212, 213, 214, 219, 221, 222, 228, 231, 232, 233, 234] # DS2 test_set = [str(x) for x in test_set] class ECGMitBihDataset(object): def __init__(self): self.train_patients = [patient.Patient(p) for p in train_set] self.test_patients = [patient.Patient(p) for p in test_set] self.train_heartbeats = self.concat_heartbeats(self.train_patients) self.test_heartbeats = self.concat_heartbeats(self.test_patients) @staticmethod def concat_heartbeats(patients): heartbeats = [] for p in patients: heartbeats += p.heartbeats return heartbeats def get_heartbeats_of_type(self, aami_label_str, partition): """ :param aami_label_str: :return: """ if partition == 'train': return [hb for hb in self.train_heartbeats if hb['aami_label_str'] == aami_label_str] elif partition == 'test': return [hb for hb in self.test_heartbeats if hb['aami_label_str'] == aami_label_str] else: raise ValueError("Undefined partition: {}".format(partition)) def num_heartbeats(self, aami_label_str, partition): """ :param aami_label_str: :return: """ return len(self.get_heartbeats_of_type(aami_label_str, partition)) def heartbeats_summaries(self, partition): """Create summaries: :return: """ heartbeat_summaries = [] for hb_aami in heartbeat_types.AAMIHeartBeatTypes: hb_summary = {} hb_summary['heartbeat_aami_str'] = hb_aami.name num_hb = self.num_heartbeats(hb_aami.name, partition) hb_summary['number_of_beats'] = num_hb heartbeat_summaries.append(hb_summary) total_summary = {} total_summary['heartbeat_aami_str'] = 'ALL' if partition == 'train': total_summary['number_of_beats'] = len(self.train_patients) elif partition == 'test': total_summary['number_of_beats'] = len(self.test_patients) heartbeat_summaries.append(total_summary) return pd.DataFrame(heartbeat_summaries) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) ecg_ds = ECGMitBihDataset() print(ecg_ds.heartbeats_summaries('train')) print(ecg_ds.heartbeats_summaries('test'))<file_sep>/ecg_pytorch/gan_models/visualization.py """Visualize output from trained generators.""" from ecg_pytorch.gan_models import checkpoint_paths from bokeh.io import output_file, show from bokeh.layouts import row from bokeh.plotting import figure from ecg_pytorch.gan_models import generate_data_from_train_gan from ecg_pytorch.gan_models.models import dcgan from ecg_pytorch.data_reader import ecg_dataset def compare_real_vs_fake(beat_type, real_beat, fake_beat): output_file("{}_fake_vs_real_dcgan.html".format(beat_type)) time = list(range(216)) # create a new plot s1 = figure(title=None) s1.line(time, real_beat, legend="Real beat", line_width=2, color="navy", alpha=0.5) # create another one s2 = figure(title=None) s2.line(time, fake_beat, legend="Fake beat", line_width=2, color="firebrick", alpha=0.5) # put the results in a row show(row(s1, s2)) def visualize_real_beat(beat_type): time = list(range(216)) dataset = ecg_dataset.EcgHearBeatsDataset(beat_type=beat_type) real_n_beat = dataset.train[200]['cardiac_cycle'] p = figure(x_axis_label='Sample number (360 Hz)', y_axis_label='Voltage[mV]') p.line(time,real_n_beat, line_width=2, line_color="green") output_file("N_{}_real.html".format(200)) show(p) # # DCGAN: # # # Visualize fake N beat against real N beat: # # gNET = dcgan.DCGenerator(0) # fake_n_beat = generate_data_from_train_gan.generate_data_from_trained_gan(gNET, 1, checkpoint_paths.DCGAN_N_CHK) # fake_n_beat = fake_n_beat.numpy()[0] # dataset = ecg_dataset.EcgHearBeatsDataset(beat_type='N') # real_n_beat = dataset.train[200]['cardiac_cycle'] # compare_real_vs_fake('N', real_n_beat, fake_n_beat) beat_type = 'N' visualize_real_beat(beat_type) <file_sep>/ecg_pytorch/train_configs.py from collections import namedtuple niv_remote = '/home/nivgiladi/tomer/' local_base = '/Users/tomer.golany/PycharmProjects/' nlp_base = '/home/<EMAIL>/' tomer_remote = '/home/tomer/tomer/' niv2_remote = '/home/tomer/' niv3_remote = '/media/drive/' yochai_remote = '/home/yochaiz/tomergolany/' google_remote = '/usr/local/google/home/tomergolany/' colab_remote = '/content/' base = colab_remote ECGTrainConfig = namedtuple('ECGTrainConfig', 'num_epochs batch_size lr weighted_loss weighted_sampling device add_data_' 'from_gan generator_details train_one_vs_all') GeneratorAdditionalDataConfig = namedtuple('GeneratorAdditionalDataConfig', 'beat_type checkpoint_path num_examples_to_' 'add gan_type') <file_sep>/ecg_pytorch/classifiers/compare_models_IAAI.py from bokeh.plotting import figure, output_file, show # Run tensorboard with --samples_per_plugin images=100 # Prepare data: num_samples_added_from_gan = [0, 500, 800, 1000, 1500, 3000, 5000, 7000, 10000, 15000] ## # FC network # ## fc_auc_N = [0.85, 0.86, 0.86, 0.86, 0.87, 0.88, 0.88, 0.88, 0.88, 0.88] fc_auc_S = [0.81, 0.82, 0.84, 0.87, 0.88, 0.89, 0.89, 0.89, 0.9, 0.9] fc_auc_V = [0.95, 0.96, 0.96, 0.96, 0.97, 0.97, 0.97, 0.97, 0.98, 0.98] fc_auc_F = [0.5, 0.73, 0.78, 0.82, 0.84, 0.86, 0.86, 0.91, 0.92, 0.93] ## # LSTM network # ## lstm_auc_N = [0.87, 0.88, 0.9, 0.9, 0.89, 0.89, 0.91, 0.91, 0.91, 0.91] lstm_auc_S = [0.82, 0.87, 0.89, 0.87, 0.89, 0.89, 0.89, 0.92, 0.91, 0.91] lstm_auc_V = [0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.98] lstm_auc_F = [0.95, 0.96, 0.95, 0.96, 0.96, 0.96, 0.95, 0.95, 0.96, 0.96] # # Beat N Comparision: # p = figure(# title="Average AUC comparison on classifying heartbeat of type N - Normal beats", x_axis_label='# Synthetic examples added', y_axis_label='AUC of ROC') # add a line renderer with legend and line thickness p.line(num_samples_added_from_gan, fc_auc_N, line_width=2) p.circle(num_samples_added_from_gan, fc_auc_N, size=8, legend="DCGAN + FF") p.line(num_samples_added_from_gan, lstm_auc_N, line_width=2, line_color="orange") p.triangle(num_samples_added_from_gan, lstm_auc_N, size=8, fill_color="orange", legend="DCGAN + LSTM") output_file("N.html") p.legend.location = "bottom_right" # show the results show(p) # # Beat S Comparision: # p = figure(# title="Average AUC comparison on classifying heartbeat of type S - Supraventricular ectopic beats", x_axis_label='# Synthetic examples added', y_axis_label='AUC of ROC') output_file("S.html") # add a line renderer with legend and line thickness p.line(num_samples_added_from_gan, fc_auc_S, line_width=2) p.circle(num_samples_added_from_gan, fc_auc_S,legend="DCGAN + FF", size=8) p.line(num_samples_added_from_gan, lstm_auc_S, line_width=2, line_color="orange") p.triangle(num_samples_added_from_gan, lstm_auc_S, legend="DCGAN + LSTM", size=8, fill_color="orange") p.legend.location = "bottom_right" show(p) # # Beat V Comparision: # p = figure(# title="Average AUC comparison on classifying heartbeat of type V - Normal beats", x_axis_label='# Synthetic examples added', y_axis_label='AUC of ROC') output_file("V.html") # add a line renderer with legend and line thickness p.line(num_samples_added_from_gan, fc_auc_V, line_width=2) p.circle(num_samples_added_from_gan, fc_auc_V, size=8, legend="DCGAN + FF") p.line(num_samples_added_from_gan, lstm_auc_V, line_width=2, line_color="orange") p.triangle(num_samples_added_from_gan, lstm_auc_V, size=8, fill_color="orange", legend="DCGAN + LSTM") p.legend.location = "bottom_right" # show the results show(p) # # Beat F Comparision: # p = figure(# title="Average AUC comparison on classifying heartbeat of type F - Fusion beats", x_axis_label='# Synthetic examples added', y_axis_label='AUC of ROC') output_file("F.html") # add a line renderer with legend and line thickness p.line(num_samples_added_from_gan, fc_auc_F, line_width=2) p.circle(num_samples_added_from_gan, fc_auc_F, size=8, legend="DCGAN + FF") p.line(num_samples_added_from_gan, lstm_auc_F, line_width=2, line_color="orange") p.triangle(num_samples_added_from_gan, lstm_auc_F, size=8, fill_color="orange", legend="DCGAN + LSTM") p.legend.location = "bottom_right" # show the results show(p)<file_sep>/ecg_pytorch/data_reader/ecg_dataset_pytorch_test.py import logging logging.basicConfig(level=logging.INFO) import unittest from ecg_pytorch.data_reader import ecg_dataset_pytorch, dataset_configs, heartbeat_types class TestEcgHearBeatsDatasetPytorch(unittest.TestCase): def test_one_vs_all(self): configs = dataset_configs.DatasetConfigs('train', 'N', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type=None) ds = ecg_dataset_pytorch.EcgHearBeatsDatasetPytorch(configs, transform=ecg_dataset_pytorch.ToTensor) for sample in ds: heartbeat = sample['cardiac_cycle'] label_str = sample['beat_type'] label_one_hot = sample['label'] self.assertEqual(len(label_one_hot), 2) self.assertIn(label_one_hot[0], [0, 1]) self.assertIn(label_one_hot[1], [0, 1]) self.assertIn(label_str, heartbeat_types.AAMIHeartBeatTypes.__members__) if label_str == heartbeat_types.AAMIHeartBeatTypes.N.name: self.assertEqual(label_one_hot, [1, 0]) else: self.assertEqual(label_one_hot, [0, 1]) if __name__ == '__main__': unittest.main() <file_sep>/ecg_pytorch/data_reader/heartbeat_types.py """Util functions to process the data.""" from enum import Enum OTHER_HEART_BEATS = "Others" class MitBihArrhythmiaHeartBeatTypes(Enum): """MIT-BIH Arrhythmia heartbeats annotations. The annotations are defined here: https://archive.physionet.org/physiobank/annotations.shtml Code Description N Normal beat (displayed as "·" by the PhysioBank ATM, LightWAVE, pschart, and psfd) L Left bundle branch block beat R Right bundle branch block beat B Bundle branch block beat (unspecified) A Atrial premature beat a Aberrated atrial premature beat J Nodal (junctional) premature beat S Supraventricular premature or ectopic beat (atrial or nodal) V Premature ventricular contraction r R-on-T premature ventricular contraction F Fusion of ventricular and normal beat e Atrial escape beat j Nodal (junctional) escape beat n Supraventricular escape beat (atrial or nodal) E Ventricular escape beat / Paced beat f Fusion of paced and normal beat Q Unclassifiable beat ? Beat not classified during learning """ N = 0 L = 1 R = 2 e = 3 j = 4 A = 5 a = 6 J = 7 S = 8 V = 9 E = 10 F = 11 Q = 12 class AAMIHeartBeatTypes(Enum): """AAMI heartbeat annotation types. AAMI classes MIT-BIH heartbeats Non-ectopic beats (N) Normal beats (N) Left bundle branch block beats (L) Right bundle branch block beats (R) Nodal (junctional) escape beats (j) Atrial escape beats (e) SVEB: Supra ventricular ectopic beats (S) Aberrated atrial premature beats (a) Supraventricular premature beats (S) Atrial premature beat (A) Nodal (junctional) premature beats (J) VEB: Ventricular ectopic Ventricular escape beats (E) beats (V) Premature ventricular contraction (V) Fusion beats (F) Fusion of ventricular and normal beat (F) Unknown beats (Q) Paced beats (/) Unclassifiable beats (U) Fusion of paced and normal beats (f) """ N = 0 S = 1 V = 2 F = 3 Q = 4 @classmethod def from_name(cls, name): for label in cls: if name == label.name: return label.value raise ValueError("{} is no a valid label.".format(name)) def convert_heartbeat_mit_bih_to_aami(heartbeat_mit_bih): """Converts the heartbeat label character to the corresponding general heartbeat type according to the AAMI standards. See AAMI standards here: :param heartbeat_mit_bih: label character from the MIT-BIH AR database. :return: The corresponding heartbeat label character from the AAMI standard. """ if heartbeat_mit_bih in [MitBihArrhythmiaHeartBeatTypes.N.name, MitBihArrhythmiaHeartBeatTypes.L.name, MitBihArrhythmiaHeartBeatTypes.R.name, MitBihArrhythmiaHeartBeatTypes.e.name, MitBihArrhythmiaHeartBeatTypes.j.name]: return AAMIHeartBeatTypes.N.name elif heartbeat_mit_bih in [MitBihArrhythmiaHeartBeatTypes.A.name, MitBihArrhythmiaHeartBeatTypes.a.name, MitBihArrhythmiaHeartBeatTypes.J.name, MitBihArrhythmiaHeartBeatTypes.S.name]: return AAMIHeartBeatTypes.S.name elif heartbeat_mit_bih in [MitBihArrhythmiaHeartBeatTypes.V.name, MitBihArrhythmiaHeartBeatTypes.E.name]: return AAMIHeartBeatTypes.V.name elif heartbeat_mit_bih in [MitBihArrhythmiaHeartBeatTypes.F.name]: return AAMIHeartBeatTypes.F.name else: return AAMIHeartBeatTypes.Q.name def convert_heartbeat_mit_bih_to_aami_index_class(heartbeat_mit_bih): """Converts the heartbeat label character to the corresponding general heartbeat type according to the AAMI standards index. The possible five indicies are: 0 - N 1 - S 2 - V 3 - F 4 - Q :param heartbeat_mit_bih: heartbeat_mit_bih: label character from the MIT-BIH AR database. :return: he corresponding heartbeat label index from the AAMI standard. """ aami_label_char = convert_heartbeat_mit_bih_to_aami(heartbeat_mit_bih) aami_label_ind = AAMIHeartBeatTypes.from_name(aami_label_char) return aami_label_ind def convert_to_one_hot(label_ind): label_one_hot = [0 for _ in range(5)] label_one_hot[label_ind] = 1 return label_one_hot <file_sep>/ecg_pytorch/classifiers/models/lstm.py import torch.nn as nn import logging class ECGLSTM(nn.Module): def __init__(self, length_of_each_word, number_of_hidden_neurons, num_of_classes, num_of_layers): super(ECGLSTM, self).__init__() self.len_of_word = length_of_each_word self.num_hidden_neurons = number_of_hidden_neurons self.output_size = num_of_classes self.num_of_layesr = num_of_layers self.lstm = nn.LSTM(length_of_each_word, number_of_hidden_neurons, num_of_layers, batch_first=True) self.output_layer = nn.Linear(number_of_hidden_neurons, num_of_classes) def forward(self, sentence): # sentence shape should be [len_of_sentence, batch_size, len_of_each_word] # lstm_out, self.hidden = self.lstm(input.view(len(input), self.batch_size, -1)) # "out" will give you access to all hidden states in the sequence # "hidden" will allow you to continue the sequence and backpropagate, # by passing it as an argument to the lstm at a later time # Add the extra 2nd dimension # print("input shape: {}".format(sentence.shape)) out, hidden = self.lstm(sentence) # If (h_0, c_0) is not provided, both h_0 and c_0 default to zero. # last_output = out[-1] last_output = out[:, -1, :] logging.debug("Shape of last output from LSTM: {}".format(last_output.shape)) # print("out shape: {}".format(out.size())) # out dim should be - [len_of_sentence, batch_size, hidden_size] # reshaped_last_output = out[-1].view(-1, self.num_hidden_neurons) # print("output from last unit: {}".format(reshaped_last_output.shape)) y_pred = self.output_layer(last_output) # y_pred should be shape [batch_size, num_of_classes] # print("y pred shape: {}".format(y_pred.shape)) return y_pred <file_sep>/ecg_pytorch/data_reader/ecg_dataset_lstm_test.py from ecg_pytorch.data_reader.ecg_dataset_pytorch import EcgHearBeatsDataset, ToTensor from matplotlib import pyplot as plt from torchvision import transforms from torch.utils.data import DataLoader import logging def TestEcgDatasetLSTM_1(): ecg_dataset = EcgHearBeatsDataset() fig = plt.figure() for i in range(4): sample = ecg_dataset[i] print(i, sample['cardiac_cycle'].shape, sample['label'].shape, sample['beat_type']) ax = plt.subplot(2, 2, i + 1) plt.tight_layout() ax.set_title('Sample #{}'.format(i)) ax.axis('off') beat = sample['cardiac_cycle'].reshape((43, 5)) beat = beat.flatten() plt.plot(beat) plt.show() def TestIteration(): composed = transforms.Compose([ToTensor()]) ecg_dataset = EcgHearBeatsDataset(transform=composed) for i in range(4): sample = ecg_dataset[i] print(i, sample['cardiac_cycle'].size(), sample['label'].size()) def test_iterate_with_dataloader(): composed = transforms.Compose([ToTensor()]) transformed_dataset = EcgHearBeatsDataset(transform=composed) dataloader = DataLoader(transformed_dataset, batch_size=4, shuffle=True, num_workers=4) # Helper function to show a batch def show_landmarks_batch(sample_batched): """Show image with landmarks for a batch of samples.""" ecg_batch, label_batch = \ sample_batched['cardiac_cycle'], sample_batched['label'] batch_size = len(ecg_batch) for i in range(batch_size): ax = plt.subplot(2, 2, i + 1) plt.tight_layout() ax.set_title('Sample #{}'.format(i)) # ax.axis('off') plt.plot(ecg_batch[i].numpy()) print(label_batch[i]) # plt.scatter(landmarks_batch[i, :, 0].numpy() + i * im_size, # landmarks_batch[i, :, 1].numpy(), # s=10, marker='.', c='r') # # plt.title('Batch from dataloader') for i_batch, sample_batched in enumerate(dataloader): # print(sample_batched['cardiac_cycle'].shape) ecg_lstm_batch = sample_batched['cardiac_cycle'].permute(1, 0, 2) print(i_batch, ecg_lstm_batch.size(), sample_batched['label'].size()) # observe 4th batch and stop. if i_batch == 3: plt.figure() # show_landmarks_batch(sample_batched) # # plt.axis('off') beat = ecg_lstm_batch[:, 0, :] print(beat.shape) beat = beat.flatten() plt.plot(beat.numpy()) plt.show() # plt.ioff() # plt.show() break def test_one_vs_all(): composed = transforms.Compose([ToTensor()]) dataset = EcgHearBeatsDataset(transform=composed, beat_type='N', one_vs_all=True) dataloader = DataLoader(dataset, batch_size=4, shuffle=True, num_workers=4) for i_batch, sample_batched in enumerate(dataloader): ecg_lstm_batch = sample_batched['cardiac_cycle'].view(43, -1, 5) print(i_batch, ecg_lstm_batch.size(), sample_batched['label'].size()) print(sample_batched['label'].numpy()) print(sample_batched['beat_type']) if i_batch == 50: break def test_data_from_simulator(): dataset = EcgHearBeatsDataset() sim_beats = dataset.add_beats_from_simulator(9, 'F') # # Debug: plot some beats: # print(sim_beats.shape) single_beat = sim_beats[5] plt.figure() plt.plot(single_beat) plt.show() if __name__ == "__main__": # TestEcgDatasetLSTM_1() # TestIteration() # test_iterate_with_dataloader() # test_one_vs_all() logging.basicConfig(level=logging.INFO) test_data_from_simulator()<file_sep>/ecg_pytorch/data_reader/heartbeat_types_test.py import unittest from ecg_pytorch.data_reader import heartbeat_types class HeartBeatTypesTest(unittest.TestCase): def test_convert_normal_heartbeat_mit_bih_to_aami(self): self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('N'), 'N') self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('L'), 'N') self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('R'), 'N') self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('e'), 'N') self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('j'), 'N') def test_convert_sveb_heartbeat_mit_bih_to_aami(self): self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('A'), 'S') self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('a'), 'S') self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('J'), 'S') self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('S'), 'S') def test_convert_veb_heartbeat_mit_bih_to_aami(self): self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('V'), 'V') self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('E'), 'V') def test_convert_fusion_heartbeat_mit_bih_to_aami(self): self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('F'), 'F') def test_convert_unknown_heartbeat_mit_bih_to_aami(self): self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('/'), 'Q') self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('U'), 'Q') self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami('f'), 'Q') def test_convert_normal_heartbeat_mit_bih_to_aami_index_class(self): self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('N'), 0) self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('L'), 0) self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('R'), 0) self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('e'), 0) self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('j'), 0) def test_convert_sveb_heartbeat_mit_bih_to_aami_index_class(self): self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('A'), 1) self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('a'), 1) self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('J'), 1) self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('S'), 1) def test_convert_veb_heartbeat_mit_bih_to_aami_index_class(self): self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('V'), 2) self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('E'), 2) def test_convert_fusion_heartbeat_mit_bih_to_aami_index_class(self): self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('F'), 3) def test_convert_unknown_heartbeat_mit_bih_to_aami_index_class(self): self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('/'), 4) self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('U'), 4) self.assertEqual(heartbeat_types.convert_heartbeat_mit_bih_to_aami_index_class('f'), 4) if __name__ == '__main__': unittest.main() <file_sep>/ecg_pytorch/gan_models/main.py from __future__ import print_function import torch import torch.nn as nn import torch.optim as optim import torch.utils.data import torchvision.transforms as transforms import numpy as np import matplotlib.pyplot as plt from ecg_pytorch.data_reader import ecg_dataset_pytorch from tensorboardX import SummaryWriter from ecg_pytorch.gan_models.models import dcgan from ecg_pytorch.gan_models.models import vanila_gan import logging # custom weights initialization called on netG and netD def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: print(classname) nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0) def train_ecg_gan(batch_size, num_train_steps, generator, discriminator, model_dir): # Support for tensorboard: writer = SummaryWriter(model_dir) # 1. create the ECG dataset: # composed = transforms.Compose([ecg_dataset.Scale(), ecg_dataset.Smooth(), ecg_dataset.ToTensor()]) composed = transforms.Compose([ecg_dataset_pytorch.ToTensor()]) dataset = ecg_dataset_pytorch.EcgHearBeatsDataset(transform=composed, beat_type='S', lstm_setting=False) dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=1) print("Size of real dataset is {}".format(len(dataset))) # 2. Create the models: netG = generator netD = discriminator # This is only for the combined generator: # ode_g = generator.ode_generator # z_delta_g = generator.z_delta_generator # Loss functions: cross_entropy_loss = nn.BCELoss() # Optimizers: lr = 0.0002 beta1 = 0.5 writer.add_scalar('Learning_Rate', lr) optimizer_d = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999)) optimizer_g = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999)) # Noise for validation: val_noise = torch.Tensor(np.random.normal(0, 1, (4, 100))) loss_d_real_hist = [] loss_d_fake_hist = [] loss_g_fake_hist = [] norma_grad_g = [] norm_grad_d = [] d_real_pred_hist = [] d_fake_pred_hist = [] epoch = 0 iters = 0 while True: num_of_beats_seen = 0 if iters == num_train_steps: break for i, data in enumerate(dataloader): if iters == num_train_steps: break netD.zero_grad() ecg_batch = data['cardiac_cycle'].float() b_size = ecg_batch.shape[0] # v0 = ecg_batch[:, 0] # For ODE solver initial step. num_of_beats_seen += ecg_batch.shape[0] output = netD(ecg_batch) labels = torch.full((b_size,), 1, device='cpu') ce_loss_d_real = cross_entropy_loss(output, labels) writer.add_scalar('Discriminator/cross_entropy_on_real_batch', ce_loss_d_real.item(), global_step=iters) writer.add_scalars('Merged/losses', {'d_cross_entropy_on_real_batch': ce_loss_d_real.item()}, global_step=iters) ce_loss_d_real.backward() loss_d_real_hist.append(ce_loss_d_real.item()) mean_d_real_output = output.mean().item() d_real_pred_hist.append(mean_d_real_output) noise_input = torch.Tensor(np.random.normal(0, 1, (b_size, 100))) output_g_fake = netG(noise_input) # output_g_fake = netG(noise_input, v0) output = netD(output_g_fake.detach()) labels.fill_(0) ce_loss_d_fake = cross_entropy_loss(output, labels) writer.add_scalar('Discriminator/cross_entropy_on_fake_batch', ce_loss_d_fake.item(), iters) writer.add_scalars('Merged/losses', {'d_cross_entropy_on_fake_batch': ce_loss_d_fake.item()}, global_step=iters) ce_loss_d_fake.backward() loss_d_fake_hist.append(ce_loss_d_fake.item()) mean_d_fake_output = output.mean().item() d_fake_pred_hist.append(mean_d_fake_output) total_loss_d = ce_loss_d_fake + ce_loss_d_real writer.add_scalar(tag='Discriminator/total_loss', scalar_value=total_loss_d.item(), global_step=iters) optimizer_d.step() netG.zero_grad() labels.fill_(1) output = netD(output_g_fake) ce_loss_g_fake = cross_entropy_loss(output, labels) ce_loss_g_fake.backward() loss_g_fake_hist.append(ce_loss_g_fake.item()) writer.add_scalar(tag='Generator/cross_entropy_on_fake_batch', scalar_value=ce_loss_g_fake.item(), global_step=iters) writer.add_scalars('Merged/losses', {'g_cross_entropy_on_fake_batch': ce_loss_g_fake.item()}, global_step=iters) mean_d_fake_output_2 = output.mean().item() optimizer_g.step() print("{}/{}: Epoch #{}: Iteration #{}: Mean D(real_hb_batch) = {}, mean D(G(z)) = {}." .format(num_of_beats_seen, len(dataset), epoch, iters, mean_d_real_output, mean_d_fake_output), end=" ") print("mean D(G(z)) = {} After backprop of D".format(mean_d_fake_output_2)) print("Loss D from real beats = {}. Loss D from Fake beats = {}. Total Loss D = {}". format(ce_loss_d_real, ce_loss_d_fake, total_loss_d), end=" ") print("Loss G = {}".format(ce_loss_g_fake)) # Norma of gradients: gNormGrad = get_gradient_norm_l2(netG) dNormGrad = get_gradient_norm_l2(netD) writer.add_scalar('Generator/gradients_norm', gNormGrad, iters) writer.add_scalar('Discriminator/gradients_norm', dNormGrad, iters) norm_grad_d.append(dNormGrad) norma_grad_g.append(gNormGrad) print( "Generator Norm of gradients = {}. Discriminator Norm of gradients = {}.".format(gNormGrad, dNormGrad)) if iters % 25 == 0: with torch.no_grad(): # with torch.no_grad(): # #output_g = netG(val_noise, v0) # #output_g_ode = ode_g(val_noise, v0) # #output_z_delta = z_delta_g(val_noise) # output_g = netG(val_noise) # fig = plt.figure() # plt.title("Fake beats from Generator. iteration {}".format(i)) # for p in range(4): # plt.subplot(2, 2, p + 1) # plt.plot(output_g[p].detach().numpy(), label="fake beat") # plt.plot(ecg_batch[p].detach().numpy(), label="real beat") # plt.legend() # writer.add_figure('Generator/output_example', fig, iters) # plt.close() # fig = plt.figure() # plt.title("Fake beats from ode Generator only. iteration {}".format(i)) # for p in range(4): # plt.subplot(2, 2, p + 1) # plt.plot(output_g_ode[p].detach().numpy(), label="fake beat") # plt.plot(ecg_batch[p].detach().numpy(), label="real beat") # plt.legend() # writer.add_figure('Generator/ode_g_output', fig, iters) # plt.close() # # fig = plt.figure() # plt.title("Fake beats from z_delta Generator only. iteration {}".format(i)) # for p in range(4): # plt.subplot(2, 2, p + 1) # plt.plot(output_z_delta[p].detach().numpy(), label="fake beat") # plt.plot(ecg_batch[p].detach().numpy(), label="real beat") # plt.legend() # writer.add_figure('Generator/z_delta_g_output', fig, iters) # plt.close() output_g = netG(val_noise) fig = plt.figure() plt.title("Fake beats from Generator. iteration {}".format(i)) for p in range(4): plt.subplot(2, 2, p + 1) plt.plot(output_g[p].detach().numpy(), label="fake beat") plt.plot(ecg_batch[p].detach().numpy(), label="real beat") plt.legend() writer.add_figure('Generator/output_example', fig, iters) plt.close() if iters % 200 == 0: torch.save({ 'epoch': epoch, 'generator_state_dict': netG.state_dict(), 'discriminator_state_dict': netD.state_dict(), 'optimizer_g_state_dict': optimizer_g.state_dict(), 'optimizer_d_state_dict': optimizer_d.state_dict(), 'loss': cross_entropy_loss, }, model_dir + '/checkpoint_epoch_{}_iters_{}'.format(epoch, iters)) iters += 1 epoch += 1 writer.close() def get_gradient_norm_l2(model): total_norm = 0 for p in model.parameters(): param_norm = p.grad.data.norm(2) total_norm += param_norm.item() ** 2 total_norm = total_norm ** (1. / 2) return total_norm if __name__ == "__main__": logging.basicConfig(level=logging.INFO) # netG = Generator(0, "cpu") # netG = DeltaGenerator(0) netG = vanila_gan.VGenerator(0) # netG = dcgan.DCGenerator(0) # netG.apply(weights_init) # netD = Discriminator(0) # netD = dcgan.DCDiscriminator(0) # netD.apply(weights_init) netD = vanila_gan.VDiscriminator(0) model_dir = 'tensorboard/ecg_vanilla_gan_s_beat' train_ecg_gan(50, 2000, netG, netD, model_dir) <file_sep>/ecg_pytorch/classifiers/metrics.py """Evaluation metrics for ECG classification models.""" import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc import numpy as np import logging from sklearn.utils.multiclass import unique_labels from sklearn.metrics import confusion_matrix from bokeh.plotting import figure, output_file, show, ColumnDataSource import os from sklearn.metrics import precision_recall_curve from sklearn.metrics import average_precision_score def plt_roc_curve(y_true, y_pred, classes, writer, total_iters): """Calculate ROC curve from predictions and ground truths. writes the roc curve into tensorboard writer object. :param y_true:[[1,0,0,0,0], [0,1,0,0], [1,0,0,0,0],...] :param y_pred: [0.34,0.2,0.1] , 0.2,...] :param classes:5 :param writer: tensorboardX summary writer. :param total_iters: total number of training iterations when the predictions where generated. :return: List of area-under-curve (AUC) of the ROC curve. """ logging.info("Entering plot_roc_curve function with params: y_true shape = {}. y_pred shape = {}.".format( y_true.shape, y_pred.shape)) fpr = {} tpr = {} roc_auc = {} roc_auc_res = [] n_classes = len(classes) for i in range(n_classes): fpr[classes[i]], tpr[classes[i]], _ = roc_curve(y_true[:, i], y_pred[:, i]) roc_auc[classes[i]] = auc(fpr[classes[i]], tpr[classes[i]]) roc_auc_res.append(roc_auc[classes[i]]) fig = plt.figure() lw = 2 plt.plot(fpr[classes[i]], tpr[classes[i]], color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[classes[i]]) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic beat {}'.format(classes[i])) plt.legend(loc="lower right") writer.add_figure('test/roc_curve_beat_{}'.format(classes[i]), fig, total_iters) plt.close() fig.clf() fig.clear() return roc_auc_res def add_roc_curve_pure_tensorboard(y_true, y_pred, classes, writer, total_iters): # TODO: feature not supported. fpr = {} tpr = {} roc_auc = {} roc_auc_res = [] n_classes = len(classes) for i in range(n_classes): fpr[classes[i]], tpr[classes[i]], probabilities = roc_curve(y_true[:, i], y_pred[:, i]) roc_auc[classes[i]] = auc(fpr[classes[i]], tpr[classes[i]]) roc_auc_res.append(roc_auc[classes[i]]) fpr_i = fpr[classes[i]] tpr_i = tpr[classes[i]] for fp, tp, prob in zip(fpr_i, tpr_i, probabilities): writer.add_scalars('ROC_Curve_at_step_{}_beat_{}'.format(total_iters, classes[i]), {'roc_curve': tp}, fp) def add_roc_curve_bokeh(y_true, y_pred, classes, model_dir, epoch): fpr = {} tpr = {} roc_auc = {} roc_auc_res = [] n_classes = len(classes) for i in range(n_classes): fpr[classes[i]], tpr[classes[i]], probabilities = roc_curve(y_true[:, i], y_pred[:, i]) roc_auc[classes[i]] = auc(fpr[classes[i]], tpr[classes[i]]) roc_auc_res.append(roc_auc[classes[i]]) fpr_i = fpr[classes[i]] tpr_i = tpr[classes[i]] tnr_i = [1 - x for x in fpr_i] output_file(os.path.join(model_dir, "roc_curve_{}_epoch_{}.html".format(classes[i], epoch))) source = ColumnDataSource(data=dict( fpr=fpr_i, tpr=tpr_i, tnr=tnr_i, probs=probabilities, )) TOOLTIPS = [ ("(fpr ,se.(tpr))", "($x, $y)"), ("threshold", "@probs"), ("spe.(tnr)", "@tnr") ] p = figure(plot_width=400, plot_height=400, tooltips=TOOLTIPS, title='Receiver operating characteristic beat {}'.format(classes[i]), x_axis_label='False Positive Rate', y_axis_label='True Positive Rate') p.line('fpr', 'tpr', source=source) show(p) def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues): """This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. :return: Figure which contains confusion matrix. """ logging.info("Entering plot confusion matrix...") logging.info("inputs params: y_true shape: {}, y_pred shape: {}".format(y_true.shape, y_pred.shape)) logging.info("First element ground truth: {}. First element predictions: {}".format(y_true[0], y_pred[0])) if not title: if normalize: title = 'Normalized confusion matrix' else: title = 'Confusion matrix, without normalization' # Compute confusion matrix cm = confusion_matrix(y_true, y_pred) # Only use the labels that appear in the data classes = classes[unique_labels(y_true, y_pred)] normalize = True if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] logging.info("Normalized confusion matrix") else: logging.info('Confusion matrix, without normalization') fig, ax = plt.subplots() im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) # We want to show all ticks... ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), # ... and label them with the respective list entries xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], fmt), ha="center", va="center", color="white" if cm[i, j] > thresh else "black") fig.tight_layout() return fig, ax def plt_precision_recall_curve(y_true, y_pred, classes, writer, total_iters): # For each class precision = dict() recall = dict() n_classes = len(classes) # average_precision = dict() for i in range(n_classes): precision[classes[i]], recall[classes[i]], _ = precision_recall_curve(y_true[:, i], y_pred[:, i]) fig = plt.figure() plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Precision Recall graph') plt.plot(recall[classes[i]], precision[classes[i]]) writer.add_figure('test/precision_recall_beat_{}'.format(classes[i]), fig, total_iters) plt.close() fig.clf() fig.clear() # average_precision[classes[i]] = average_precision_score(y_true[:, i], y_pred[:, i]) # A "micro-average": quantifying score on all classes jointly # precision["micro"], recall["micro"], _ = precision_recall_curve(Y_test.ravel(), # y_score.ravel()) # average_precision["micro"] = average_precision_score(Y_test, y_score, # average="micro") # print('Average precision score, micro-averaged over all classes: {0:0.2f}' # .format(average_precision["micro"])) def plt_precision_recall_bokeh(y_true, y_pred, classes, model_dir, epoch): # For each class precision = dict() recall = dict() n_classes = len(classes) # average_precision = dict() for i in range(n_classes): precision[classes[i]], recall[classes[i]], probs = precision_recall_curve(y_true[:, i], y_pred[:, i]) pre_i = precision[classes[i]] rec_i = recall[classes[i]] output_file(os.path.join(model_dir, "precision_recall_{}_epoch_{}.html".format(classes[i], epoch))) logging.info("saving in {}".format(os.path.join(model_dir, "precision_recall_{}.html".format(classes[i])))) source = ColumnDataSource(data=dict( prec=pre_i, rec=rec_i, probs=probs, )) TOOLTIPS = [ ("(se.(rec),ppv(prec))", "($x, $y)"), ("threshold", "@probs"), ] p = figure(plot_width=400, plot_height=400, tooltips=TOOLTIPS, title='precision recall beat {}'.format(classes[i]), x_axis_label='Recall', y_axis_label='Precision') p.line('rec', 'prec', source=source) show(p) <file_sep>/ecg_pytorch/classifiers/run_sequence_model.py import torch import torch.optim as optim import torch.nn as nn from tensorboardX import SummaryWriter import numpy as np from ecg_pytorch.classifiers.models import lstm, deep_residual_conv from ecg_pytorch.train_configs import ECGTrainConfig, GeneratorAdditionalDataConfig import logging import os import shutil from ecg_pytorch.gan_models import checkpoint_paths import pickle from ecg_pytorch import train_configs from ecg_pytorch.data_reader import dataset_builder from ecg_pytorch.classifiers import metrics base_path = train_configs.base BEAT_TO_INDEX = {'N': 0, 'S': 1, 'V': 2, 'F': 3, 'Q': 4} def init_weights(m): if type(m) == nn.LSTM: torch.nn.init.xavier_uniform(m.weight_hh_l0.data) torch.nn.init.xavier_uniform(m.weight_ih_l0.data) def predict_fn(network_object, data_loader, train_config, criterion, writer, total_iters, best_auc_scores): device = train_config.device logging.info("Performing evaluation:") softmax_layer = nn.Softmax(dim=1) with torch.no_grad(): if train_config.train_one_vs_all: labels_total_one_hot = np.array([]).reshape((0, 2)) outputs_preds = np.array([]).reshape((0, 2)) else: labels_total_one_hot = np.array([]).reshape((0, 5)) outputs_preds = np.array([]).reshape((0, 5)) labels_ind_total = np.array([]) outputs_ind_total = np.array([]) loss_hist = [] for _, test_data in enumerate(data_loader): ecg_batch = test_data['cardiac_cycle'].float().to(device) labels = test_data['label'].to(device) # logging.info("labels shape: {}. first labels in batch: {}".format(labels.shape, labels[0])) labels_ind = torch.max(labels, 1)[1] preds_before_softmax = network_object(ecg_batch) # logging.info( # "output before softmax shape: {}. first in batch: {}".format(preds_before_softmax.shape, # preds_before_softmax[0])) probs_after_softmax = softmax_layer(preds_before_softmax) # logging.info( # "output softmax shape: {}. first in batch: {}".format(probs_after_softmax.shape, # probs_after_softmax[0])) loss = criterion(preds_before_softmax, torch.max(labels, 1)[1]) loss_hist.append(loss.item()) outputs_class = torch.max(preds_before_softmax, 1)[1] labels_total_one_hot = np.concatenate((labels_total_one_hot, labels.cpu().numpy())) labels_ind_total = np.concatenate((labels_ind_total, labels_ind.cpu().numpy())) outputs_ind_total = np.concatenate((outputs_ind_total, outputs_class.cpu().numpy())) outputs_preds = np.concatenate((outputs_preds, probs_after_softmax.cpu().numpy())) outputs_ind_total = outputs_ind_total.astype(int) labels_ind_total = labels_ind_total.astype(int) loss = sum(loss_hist) / len(loss_hist) writer.add_scalars('cross_entropy_loss', {'Test set loss': loss}, total_iters) return labels_ind_total, outputs_ind_total, labels_total_one_hot, outputs_preds def write_summaries(writer, train_config, labels_class, outputs_class, total_iters, data_set_type, best_auc_scores, output_probabilites=None, labels_one_hot=None): if train_config.train_one_vs_all: generator_beat_type = train_config.generator_details.beat_type fig, _ = metrics.plot_confusion_matrix(labels_class, outputs_class, np.array([generator_beat_type, 'Others'])) else: fig, _ = metrics.plot_confusion_matrix(labels_class, outputs_class, np.array(['N', 'S', 'V', 'F', 'Q'])) writer.add_figure('{}/confusion_matrix'.format(data_set_type), fig, total_iters) if data_set_type == 'test': # # Check AUC values: # if train_config.train_one_vs_all: generator_beat_type = train_config.generator_details.beat_type auc_roc = metrics.plt_roc_curve(labels_one_hot, output_probabilites, np.array([generator_beat_type, 'Other']), writer, total_iters) metrics.plt_precision_recall_curve(labels_one_hot, output_probabilites, np.array([generator_beat_type, 'Other']), writer, total_iters) for i_auc in range(2): if auc_roc[i_auc] > best_auc_scores[i_auc]: best_auc_scores[i_auc] = auc_roc[i_auc] else: auc_roc = metrics.plt_roc_curve(labels_one_hot, output_probabilites, np.array(['N', 'S', 'V', 'F', 'Q']), writer, total_iters) metrics.plt_precision_recall_curve(labels_one_hot, output_probabilites, np.array(['N', 'S', 'V', 'F', 'Q']), writer, total_iters) for i_auc in range(4): if auc_roc[i_auc] > best_auc_scores[i_auc]: best_auc_scores[i_auc] = auc_roc[i_auc] def model_fn(network_object, model_dir, train_config=None): """ :param network_object: Network type - Type of recurrent network. :return: """ logging.info("Train configurations: {}".format(train_config)) # with open(os.path.join(model_dir, 'pipeline.config'), 'wb') as fd: # fd.write(str.encode("{}".format(train_config))) num_of_epochs = train_config.num_epochs lr = train_config.lr device = train_config.device batch_size = train_config.batch_size train_data_loader, test_data_loader, best_auc_scores = dataset_builder.build(train_config) if train_config.train_one_vs_all: label_names = np.array([train_config.generator_details.beat_type, 'Others']) else: label_names = np.array(['N', 'S', 'V', 'F', 'Q']) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(network_object.parameters(), lr=lr) writer = SummaryWriter(model_dir, max_queue=1000) total_iters = 0 num_iters_per_epoch = int(np.floor(len(train_data_loader) / batch_size) + batch_size) for epoch in range(num_of_epochs): # loop over the dataset multiple times for i, data in enumerate(train_data_loader): total_iters += 1 ecg_batch = data['cardiac_cycle'].float().to(device) b_size = ecg_batch.shape[0] labels = data['label'].to(device) labels_class = torch.max(labels, 1)[1] labels_str = data['beat_type'] logging.debug("batch labels: {}".format(labels_str)) # zero the parameter gradients network_object.zero_grad() # forward + backward + optimize outputs = network_object(ecg_batch) outputs_class = torch.max(outputs, 1)[1] accuracy = (outputs_class == labels_class).sum().float() / b_size loss = criterion(outputs, torch.max(labels, 1)[1]) loss.backward() optimizer.step() writer.add_scalars('cross_entropy_loss', {'Train batches loss': loss.item()}, total_iters) writer.add_scalars('accuracy', {'Train batches accuracy': accuracy.item()}, total_iters) # # print statistics # if total_iters % 10 == 0: logging.info( "Epoch {}. Iteration {}/{}.\t Batch train loss = {:.2f}. Accuracy batch train = {:.2f}".format( epoch + 1, i, num_iters_per_epoch, loss.item(), accuracy.item())) if total_iters % 300 == 0: write_summaries(writer, train_config, labels_class.cpu().numpy(), outputs_class.cpu().numpy(), total_iters, 'train', best_auc_scores) grad_norm = get_gradient_norm_l2(network_object) writer.add_scalar('gradients_norm', grad_norm, total_iters) logging.info("Norm of gradients = {}.".format(grad_norm)) if total_iters % 200 == 0: labels_ind_total, outputs_ind_total, labels_total_one_hot, outputs_preds = predict_fn(network_object, test_data_loader, train_config, criterion, writer, total_iters, best_auc_scores) accuracy = sum((outputs_ind_total == labels_ind_total)) / len(outputs_ind_total) writer.add_scalars('accuracy', {'Test set accuracy': accuracy}, global_step=total_iters) logging.info("total output preds shape: {}. labels_total_one_hot shape: {}".format(outputs_preds.shape, labels_total_one_hot.shape)) # write_summaries(writer, train_config, labels_ind_total, outputs_ind_total, total_iters, 'test', # best_auc_scores, # outputs_preds, labels_total_one_hot) labels_ind_total, outputs_ind_total, labels_total_one_hot, outputs_preds = predict_fn(network_object, test_data_loader, train_config, criterion, writer, total_iters, best_auc_scores) write_summaries(writer, train_config, labels_ind_total, outputs_ind_total, epoch, 'test', best_auc_scores, outputs_preds, labels_total_one_hot) metrics.add_roc_curve_bokeh(labels_total_one_hot, outputs_preds, label_names, model_dir, epoch) metrics.plt_precision_recall_bokeh(labels_total_one_hot, outputs_preds, label_names, model_dir, epoch) writer.close() torch.save({ 'net': network_object.state_dict() }, model_dir + '/checkpoint_epoch_iters_{}'.format(total_iters)) writer.close() return best_auc_scores def get_gradient_norm_l2(model): total_norm = 0 for p in model.parameters(): param_norm = p.grad.data.norm(2) total_norm += param_norm.item() ** 2 total_norm = total_norm ** (1. / 2) return total_norm def train_mult(beat_type, gan_type, device): summary_model_dir = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/tensorboard/{}/lstm_{}_summary/'.format( beat_type, gan_type) writer = SummaryWriter(summary_model_dir) # # Retrieve Checkpoint path: # if gan_type in ['DCGAN', 'ODE_GAN']: ck_path = checkpoint_paths.BEAT_AND_MODEL_TO_CHECKPOINT_PATH[beat_type][gan_type] else: ck_path = None # # Define summary values: # mean_auc_values = [] var_auc_values = [] best_auc_values = [] best_auc_for_each_n = {} # # Run with different number of additional data from trained generator: # for n in [500, 800, 1000, 1500, 3000, 5000, 7000, 10000, 15000]: # for n in [5000]: # # Train configurations: # model_dir = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/tensorboard/{}/lstm_{}_{}/'.format( beat_type, str(n), gan_type) gen_details = GeneratorAdditionalDataConfig(beat_type=beat_type, checkpoint_path=ck_path, num_examples_to_add=n, gan_type=gan_type) train_config = ECGTrainConfig(num_epochs=5, batch_size=20, lr=0.0002, weighted_loss=False, weighted_sampling=True, device=device, add_data_from_gan=True, generator_details=gen_details, train_one_vs_all=False) # # Run 10 times each configuration: # total_runs = 0 best_auc_per_run = [] while total_runs < 10: if os.path.isdir(model_dir): logging.info("Removing model dir") shutil.rmtree(model_dir) # # Initialize the network each run: # net = lstm.ECGLSTM(5, 512, 5, 2).to(device) # # Train the classifier: # best_auc_scores = train_classifier(net, model_dir=model_dir, train_config=train_config) best_auc_per_run.append(best_auc_scores[BEAT_TO_INDEX[beat_type]]) writer.add_scalar('auc_with_additional_{}_beats'.format(n), best_auc_scores[BEAT_TO_INDEX[beat_type]], total_runs) if best_auc_scores[BEAT_TO_INDEX[beat_type]] >= 0.88: logging.info("Found desired AUC: {}".format(best_auc_scores)) break total_runs += 1 best_auc_for_each_n[n] = best_auc_per_run mean_auc_values.append(np.mean(best_auc_per_run)) var_auc_values.append(np.var(best_auc_per_run)) best_auc_values.append(max(best_auc_per_run)) writer.add_scalar('mean_auc', np.mean(best_auc_per_run), n) writer.add_scalar('max_auc', max(best_auc_per_run), n) writer.close() # # Save data in pickle: # all_results = {'best_auc_for_each_n': best_auc_for_each_n, 'mean': mean_auc_values, 'var': var_auc_values, 'best': best_auc_values} pickle_file_path = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/pickles_results/{}_{}_lstm.pkl'.format( beat_type, gan_type) with open(pickle_file_path, 'wb') as handle: pickle.dump(all_results, handle, protocol=pickle.HIGHEST_PROTOCOL) def find_optimal_checkpoint(chk_dir, beat_type, gan_type, device, num_samples_to_add): model_dir = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/tensorboard/{}/find_optimal_chk_{}_{}_agg/' \ .format(beat_type, str(num_samples_to_add), gan_type) writer = SummaryWriter(model_dir) if not os.path.isdir(chk_dir): raise ValueError("{} not a directory".format(chk_dir)) # # Define summary values: # mean_auc_values = [] best_auc_values = [] final_dict = {} for i, chk_name in enumerate(os.listdir(chk_dir)): if chk_name.startswith('checkpoint'): chk_path = os.path.join(chk_dir, chk_name) # # Train configurations: # model_dir = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/tensorboard/{}/lstm_{}_{}_{}/'.format( beat_type, str(num_samples_to_add), gan_type, chk_name) gen_details = GeneratorAdditionalDataConfig(beat_type=beat_type, checkpoint_path=chk_path, num_examples_to_add=num_samples_to_add, gan_type=gan_type) train_config = ECGTrainConfig(num_epochs=5, batch_size=20, lr=0.0002, weighted_loss=False, weighted_sampling=True, device=device, add_data_from_gan=True, generator_details=gen_details, train_one_vs_all=False) # # Run 10 times each configuration: # total_runs = 0 best_auc_per_run = [] while total_runs < 10: if os.path.isdir(model_dir): logging.info("Removing model dir") shutil.rmtree(model_dir) # # Initialize the network each run: # net = lstm.ECGLSTM(5, 512, 5, 2).to(device) # # Train the classifier: # best_auc_scores = train_classifier(net, model_dir=model_dir, train_config=train_config) best_auc_per_run.append(best_auc_scores[BEAT_TO_INDEX[beat_type]]) writer.add_scalar('best_auc_{}'.format(chk_name), best_auc_scores[BEAT_TO_INDEX[beat_type]], total_runs) total_runs += 1 mean_auc = np.mean(best_auc_per_run) max_auc = max(best_auc_per_run) logging.info("Checkpoint {}: Mean AUC {}. Max AUC: {}".format(chk_name, mean_auc, max_auc)) mean_auc_values.append(mean_auc) best_auc_values.append(max_auc) final_dict[chk_name] = {} final_dict[chk_name]['MEAN'] = mean_auc final_dict[chk_name]['MAX'] = max_auc writer.add_scalar('mean_auc_per_chk', mean_auc, i) writer.add_scalar('max_auc_per_chk', max_auc, i) writer.close() # # Save data in pickle: # pickle_file_path = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/pickles_results/{}_{}_lstm_different_ckps_500.pkl'.format( beat_type, gan_type) with open(pickle_file_path, 'wb') as handle: pickle.dump(final_dict, handle, protocol=pickle.HIGHEST_PROTOCOL) def train_with_noise(): beat_type = 'N' device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu") with open('res_noise_{}.text'.format(beat_type), 'w') as fd: # for n in [500, 800, 1000, 1500, 3000, 5000, 7000, 10000, 15000]: for n in [0]: base_tomer_remote = '/home/nivgiladi/tomer/' model_dir = base_tomer_remote + 'ecg_pytorch/ecg_pytorch/classifiers/tensorboard/noise_{}/lstm_add_{}/'.format( str(n), beat_type) total_runs = 0 BEST_AUC_N = 0 BEST_AUC_S = 0 BEST_AUC_V = 0 BEST_AUC_F = 0 BEST_AUC_Q = 0 # while BEST_AUC_S <= 0.876: while total_runs < 10: if os.path.isdir(model_dir): logging.info("Removing model dir") shutil.rmtree(model_dir) net = lstm.ECGLSTM(5, 512, 5, 2).to(device) gen_details = GeneratorAdditionalDataConfig(beat_type=beat_type, checkpoint_path='', num_examples_to_add=n) train_config = ECGTrainConfig(num_epochs=4, batch_size=16, lr=0.002, weighted_loss=False, weighted_sampling=True, device=device, add_data_from_gan=False, generator_details=gen_details, train_one_vs_all=False) train_classifier(net, model_dir=model_dir, train_config=train_config) total_runs += 1 logging.info("Done after {} runs.".format(total_runs)) logging.info("Best AUC:\n N: {}\tS: {}\tV: {}\tF: {}\tQ: {}".format(BEST_AUC_N, BEST_AUC_S, BEST_AUC_V, BEST_AUC_F, BEST_AUC_Q)) w = "#n: {} .Best AUC:\n N: {}\tS: {}\tV: {}\tF: {}\tQ: {}\n".format(n, BEST_AUC_N, BEST_AUC_S, BEST_AUC_V, BEST_AUC_F, BEST_AUC_Q) fd.write(w) if __name__ == "__main__": model_dir = base_path + 'ecg_pytorch/ecg_pytorch/classifiers/tensorboard/s_resnet_raw_v2/vgan_1000/' if os.path.exists(model_dir): print("Model dir {} already exists! exiting...".format(model_dir)) exit() else: os.makedirs(model_dir) logging.basicConfig(level=logging.INFO, handlers=[logging.FileHandler("{}/logs.log".format(model_dir)), logging.StreamHandler()]) main_device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") logging.info("Devices: {}".format(main_device)) # net = lstm.ECGLSTM(5, 512, 2, 2).to(device) main_net = deep_residual_conv.Net(2).to(main_device) main_gen_details = GeneratorAdditionalDataConfig(beat_type='S', checkpoint_path=checkpoint_paths.VGAN_S_CHK, num_examples_to_add=1000, gan_type=dataset_builder.GanType.VANILA_GAN) train_config_1 = ECGTrainConfig(num_epochs=15, batch_size=300, lr=0.0001, weighted_loss=False, weighted_sampling=False, device=main_device, add_data_from_gan=True, generator_details=main_gen_details, train_one_vs_all=True) model_fn(main_net, model_dir, train_config=train_config_1) <file_sep>/ecg_pytorch/dynamical_model/Euler/single_step.py import torch import math from ecg_pytorch.dynamical_model import utils import time import matplotlib.pyplot as plt class ODEParams: def __init__(self, device_name): # self.h = torch.tensor(1 / 216).to('cpu') self.A = torch.tensor(0.005).to(device_name) # mV self.f1 = torch.tensor(0.1).to(device_name) # mean 1 self.f2 = torch.tensor(0.25).to(device_name) # mean 2 self.c1 = torch.tensor(0.01).to(device_name) # std 1 self.c2 = torch.tensor(0.01).to(device_name) # std 2 self.rrpc = utils.generate_omega_function(self.f1, self.f2, self.c1, self.c2) self.rrpc = torch.tensor(self.rrpc).to(device_name) self.h = torch.tensor(1 / 216).to(device_name) def single_step_euler(ode_params, x_curr, y_curr, z_curr, t_curr, input_params, device_name): h = ode_params.h A = ode_params.A f2 = ode_params.f2 rrpc = ode_params.rrpc.float() a_p = input_params[0] a_q = input_params[3] a_r = input_params[6] a_s = input_params[9] a_t = input_params[12] b_p = input_params[1] b_q = input_params[4] b_r = input_params[7] b_s = input_params[10] b_t = input_params[13] theta_p = input_params[2] theta_q = input_params[5] theta_r = input_params[8] theta_s = input_params[11] theta_t = input_params[14] alpha = 1 - (x_curr * x_curr + y_curr * y_curr) ** 0.5 cast = (t_curr / h).type(torch.IntTensor) tensor_temp = 1 + cast tensor_temp = tensor_temp % len(rrpc) # print(tensor_temp.numpy()) # print(len(rrpc)) #tensor_temp = tf.reshape(tensor_temp, []) if rrpc[tensor_temp] == 0: print("***inside zero***") omega = (2.0 * math.pi / 1e-3) # omega = torch.tensor(math.inf).to(device_name) else: omega = (2.0 * math.pi / rrpc[tensor_temp]).to(device_name) d_x_d_t_next = alpha * x_curr - omega * y_curr d_y_d_t_next = alpha * y_curr + omega * x_curr theta = torch.atan2(y_curr, x_curr) delta_theta_p = torch.fmod(theta - theta_p, 2 * math.pi) delta_theta_q = torch.fmod(theta - theta_q, 2 * math.pi) delta_theta_r = torch.fmod(theta - theta_r, 2 * math.pi) delta_theta_s = torch.fmod(theta - theta_s, 2 * math.pi) delta_theta_t = torch.fmod(theta - theta_t, 2 * math.pi) z_p = a_p * delta_theta_p * \ torch.exp((- delta_theta_p * delta_theta_p / (2 * b_p * b_p))) z_q = a_q * delta_theta_q * \ torch.exp((- delta_theta_q * delta_theta_q / (2 * b_q * b_q))) z_r = a_r * delta_theta_r * \ torch.exp((- delta_theta_r * delta_theta_r / (2 * b_r * b_r))) z_s = a_s * delta_theta_s * \ torch.exp((- delta_theta_s * delta_theta_s / (2 * b_s * b_s))) z_t = a_t * delta_theta_t * \ torch.exp((- delta_theta_t * delta_theta_t / (2 * b_t * b_t))) z_0_t = (A * torch.sin(torch.tensor(2 * math.pi).to(device_name) * f2 * t_curr).to(device_name)).to(device_name) d_z_d_t_next = -1 * (z_p + z_q + z_r + z_s + z_t) - (z_curr - z_0_t) k1_x = h * d_x_d_t_next k1_y = h * d_y_d_t_next k1_z = h * d_z_d_t_next # Calculate next stage: x_next = x_curr + k1_x y_next = y_curr + k1_y z_next = z_curr + k1_z return x_next, y_next, z_next if __name__ == "__main__": ode_params = ODEParams('cpu') input_params = torch.nn.Parameter( torch.tensor([1.2, 0.25, -60.0 * math.pi / 180.0, -5.0, 0.1, -15.0 * math.pi / 180.0, 30.0, 0.1, 0.0 * math.pi / 180.0, -7.5, 0.1, 15.0 * math.pi / 180.0, 0.75, 0.4, 90.0 * math.pi / 180.0])) x = torch.tensor(-0.417750770388669) y = torch.tensor(-0.9085616622823985) z = torch.tensor(-0.004551233843726818) # x = torch.tensor(1.0) # y = torch.tensor(0.0) # z = torch.tensor(0.04) t = torch.tensor(0.0) x_next, y_next, z_next = single_step_euler(ode_params, x, y, z, t, input_params, 'cpu') x_t = [x_next] y_t = [y_next] z_t = [z_next] start = time.time() for i in range(215 * 1): last = z_t[-1] t += 1 / 512 x_next, y_next, z_next = single_step_euler(ode_params, x_next, y_next, z_next, t, input_params, 'cpu') x_t.append(x_next) y_t.append(y_next) z_t.append(z_next) end = time.time() print("time: ", end - start) # last = z_t[-1] # print(last.backward()) # print(input_params.grad) print("Z: {}".format([x.detach().item() for x in z_t])) print("X: {}".format([x.detach().item() for x in x_t])) print("Y: {}".format([x.detach().item() for x in y_t])) print(len(z_t)) print("Max value in the signal: ", max(z_t)) print("Min valuein the signal:", min(z_t)) res = [x.detach().numpy() for x in z_t] print(len(res)) plt.plot(res) plt.show() <file_sep>/ecg_pytorch/dynamical_model/learn_params/main.py import torch from torch import nn from ecg_pytorch.dynamical_model.Euler.euler import euler from ecg_pytorch.data_reader import ecg_dataset import torchvision.transforms as transforms import torch.optim as optim from matplotlib import pyplot as plt class LearnParams(nn.Module): def __init__(self, device_name): super(LearnParams, self).__init__() self.device_name = device_name self.params = nn.Linear(15, 15) def forward(self, x, v0): x = self.params(x) x = euler(x, self.device_name, v0) return x def train(device_name, num_steps, batch_size): # # Get desired real beat: # composed = transforms.Compose([ecg_dataset.Scale()]) dataset = ecg_dataset.EcgHearBeatsDatasetTest(beat_type='V', transform=composed) beats = dataset.test n = 1 # for 2 random indices # index = np.random.choice(len(beats), n, replace=False) index = [2439] print(index) random_v_beats = beats[index][0]['cardiac_cycle'] v0 = random_v_beats[0] random_v_beats = torch.Tensor([random_v_beats for _ in range(batch_size)]) # # Create model: # net = LearnParams(device_name) # # Loss: # mse_loss = nn.MSELoss() opt = optim.Adam(net.parameters(), lr=0.1) # # train: # const_input = torch.Tensor([[1] * 15 for _ in range(batch_size)]) v0_batch = torch.Tensor([v0 for _ in range(batch_size)]) # # to gpu: # net = net.to(device_name) const_input = const_input.to(device_name) v0_batch = v0_batch.to(device_name) random_v_beats = random_v_beats.to(device_name) for i in range(num_steps): net.zero_grad() output = net(const_input, v0_batch) loss = mse_loss(output, random_v_beats) print("Loss: {}".format(loss)) loss.backward() opt.step() if i % 100 == 0: with torch.no_grad(): ode_beat = output.detach().numpy()[0] plt.figure() plt.plot(ode_beat, label='ode') plt.plot(random_v_beats.numpy()[0], label="real") plt.legend() plt.show() plt.clf() plt.close() if __name__ == "__main__": device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") train(device, 2000, 5)<file_sep>/ecg_pytorch/classifiers/models/deep_residual_conv.py """Residual 1d convolution network Based on: "ECG Heartbeat Classification: A Deep Transferable Representation" by : <NAME> and <NAME>. https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8419425 """ import torch.nn as nn import torch.nn.functional as F import numpy as np import torch class ResidualLayer(nn.Module): def __init__(self): super(ResidualLayer, self).__init__() self.conv1 = nn.Conv1d(in_channels=32, out_channels=32, kernel_size=5, padding=2, bias=True) self.conv2 = nn.Conv1d(in_channels=32, out_channels=32, kernel_size=5, padding=2, bias=True) self.bn1 = nn.BatchNorm1d(32) self.bn2 = nn.BatchNorm1d(32) self.pool1 = nn.MaxPool1d(kernel_size=5, stride=2) def forward(self, x): x = self.conv2(F.relu(self.bn1(self.conv1(x)))) + x x = F.relu(self.pool1(self.bn2(x))) return x class Net(nn.Module): def __init__(self, output_size): super(Net, self).__init__() self.conv1 = nn.Conv1d(in_channels=1, out_channels=32, kernel_size=5, padding=2, bias=True) self.bn1 = nn.BatchNorm1d(32) self.res1 = ResidualLayer() self.res2 = ResidualLayer() self.res3 = ResidualLayer() self.res4 = ResidualLayer() self.res5 = ResidualLayer() self.fc1 = nn.Linear(32 * 3, 32) self.fc2 = nn.Linear(32, output_size) def forward(self, x): x = x.view(-1, 1, 216) # print(x.shape) x = self.conv1(x) x = self.bn1(x) # print(x.shape) x = self.res1(x) x = self.res2(x) x = self.res3(x) x = self.res4(x) x = self.res5(x) x = x.view(-1, 32 * 3) x = F.relu(self.fc1(x)) x = self.fc2(x) return x if __name__ == "__main__": # res_layer = ResidualLayer() # inp = np.array([[[0.0 for _ in range(216)] for _ in range(32)]]) # print(inp.shape) # # print(res_layer) # # output = res_layer(torch.from_numpy(inp).float()) # print(output.shape) inp = np.array([[[0.0 for _ in range(216)] for _ in range(1)]]) res_net = Net(5) print(inp.shape) print(res_net) output = res_net(torch.from_numpy(inp).float()) print(output.shape) <file_sep>/ecg_pytorch/classifiers/compare_models.py from bokeh.plotting import figure, output_file, show # Run tensorboard with --samples_per_plugin images=100 # Prepare data: num_samples_added_from_gan = [0, 500, 800, 1000, 1500, 3000, 5000, 7000, 10000, 15000] # # One Vs. ALL settings: # # # DCGAN: # lstm_auc_N_DCGAN = [0.84, 0.87, 0.88, 0.88, 0.63, 0.87, 0.91, 0.81, 0.88, 0.67] lstm_auc_S_DCGAN = [0.65, 0.7831, 0.72, 0.80, 0.82, 0.8, 0.78, 0.83, 0.74, 0.8] lstm_auc_F_DCGAN = [0.93, 0.96, 0.94, 0.95, 0.95,0.95, 0.95, 0.96, 0.95, 0.95] lstm_auc_V_DCGAN = [0.95, 0.97, 0.96, 0.94, 0.7, 0.95, 0.956, 0.957, 0.96, 0.956] # # ODEGAN: # lstm_auc_N_ODEGAN = [0.84, 0.61, 0.87, 0.89, 0.80, 0.71, 0.90, 0.90, 0.915, 0.88] lstm_auc_S_ODEGAN = [0.65, 0.88, 0.80, 0.86, 0.8, 0.83, 0.91, 0.88, 0.85, 0.88] lstm_auc_F_ODEGAN = [0.93, 0.95, 0.9, 0.955, 0.97, 0.93, 0.95, 0.95, 0.947, 0.96] lstm_auc_V_ODEGAN = [0.95, 0.96, 0.945, 0.75, 0.75, 0.966, 0.97, 0.975, 0.91, 0.96] # # Simulator: # lstm_auc_S_SIMULATOR = [0.65, 0.82, 0.86, 0.7, 0.78, 0.88, 0.83, 0.89, 0.86, 0.9] lstm_auc_N_SIMULATOR = [0.84, 0.65, 0.762, 0.51, 0.89, 0.55, 0.88, 0.88, 0.52, 0.77] lstm_auc_F_SIMULATOR = [0.93, 0.935, 0.89, 0.96, 0.86, 0.901, 0.935, 0.92, 0.94, 0.95] lstm_auc_V_SIMULATOR = [0.95, 0.95, 0.97, 0.965, 0.97, 0.87, 0.94, 0.97, 0.8, 0.955] # # Vanila GAN: # lstm_auc_N_VANILA_GAN = [0.84, 0.86, 0.64, 0.89, 0.86, 0.89, 0.64, 0.87, 0.85, 0.89] lstm_auc_S_VANILA_GAN = [0.65, 0.78, 0.73, 0.7, 0.83, 0.80, 0.83, 0.816, 0.811, 0.81] lstm_auc_F_VANILA_GAN = [0.93, 0.91, 0.931, 0.925, 0.935, 0.948, 0.945, 0.945, 0.945, 0.95] lstm_auc_V_VANILA_GAN = [0.95, 0.955, 0.93, 0.95, 0.7, 0.85, 0.97, 0.95, 0.96, 0.96] # # Vanila ODEGAN: # lstm_auc_N_VANILA_ODE_GAN = [0.84, 0.88, 0.9, 0.65, 0.895, 0.89, 0.85, 0.84, 0.885, 0.85] lstm_auc_S_VANILA_ODE_GAN = [0.65, 0.61, 0.82, 0.72, 0.85, 0.77, 0.70, 0.80, 0.82, 0.8] lstm_auc_F_VANILA_ODE_GAN = [0.93, 0.933, 0.90, 0.966, 0.945, 0.97, 0.943, 0.93, 0.943, 0.943] lstm_auc_V_VANILA_ODE_GAN = [0.95, 0.956, 0.943, 0.945, 0.963, 0.953, 0.961, 0.95, 0.957, 0.956] # # Figures: # # # N beat: # p = figure(# title="Average AUC comparison on classifying heartbeat of type N - Normal beats", x_axis_label='# Synthetic examples added', y_axis_label='AUC of ROC') # add a line renderer with legend and line thickness # p.line(num_samples_added_from_gan, fc_auc_N, line_width=2) # p.circle(num_samples_added_from_gan, fc_auc_N, size=8, legend="DCGAN + FF") p.line(num_samples_added_from_gan, lstm_auc_N_DCGAN, line_width=2, line_color="orange") p.circle(num_samples_added_from_gan, lstm_auc_N_DCGAN, size=8, fill_color="orange", legend="DCGAN + LSTM") p.line(num_samples_added_from_gan, lstm_auc_N_ODEGAN, line_width=2, line_color="purple") p.square(num_samples_added_from_gan, lstm_auc_N_ODEGAN, size=8, fill_color="purple", legend="ODEGAN + LSTM") p.line(num_samples_added_from_gan, lstm_auc_N_SIMULATOR, line_width=2, line_color="green") p.asterisk(num_samples_added_from_gan, lstm_auc_N_SIMULATOR, line_width=2, size=15, line_color="green", fill_color="green", legend="Simulator + LSTM") p.line(num_samples_added_from_gan, lstm_auc_N_VANILA_GAN, line_width=2, line_color="blue") p.diamond(num_samples_added_from_gan, lstm_auc_N_VANILA_GAN, line_width=2, size=15, fill_color="blue", legend="Vanilla GAN + LSTM") p.line(num_samples_added_from_gan, lstm_auc_N_VANILA_ODE_GAN, line_width=2, line_color="pink") p.triangle(num_samples_added_from_gan, lstm_auc_N_VANILA_ODE_GAN, legend="Vanilla ODE GAN + LSTM", size=8, fill_color="pink") output_file("N.html") p.legend.location = "bottom_right" # show the results show(p) # # S Beat: # p = figure(# title="Average AUC comparison on classifying heartbeat of type S - Supraventricular ectopic beats", x_axis_label='# Synthetic examples added', y_axis_label='AUC of ROC') output_file("S.html") # add a line renderer with legend and line thickness # p.line(num_samples_added_from_gan, fc_auc_S, line_width=2) # p.circle(num_samples_added_from_gan, fc_auc_S,legend="DCGAN + FF", size=8) # p.line(num_samples_added_from_gan, lstm_auc_S_DCGAN, line_width=2, line_color="orange") # p.triangle(num_samples_added_from_gan, lstm_auc_S_DCGAN, legend="DCGAN + LSTM", size=8, fill_color="orange") p.line(num_samples_added_from_gan, lstm_auc_S_ODEGAN, line_width=2, line_color="green") p.square(num_samples_added_from_gan, lstm_auc_S_ODEGAN, size=8, fill_color="green", legend="SimDCGAN + LSTM") # p.line(num_samples_added_from_gan, lstm_auc_S_SIMULATOR, line_width=2, line_color="green") # p.asterisk(num_samples_added_from_gan, lstm_auc_S_SIMULATOR, line_width=2, size=15, line_color="green", fill_color="green", legend="Simulator + LSTM") # p.line(num_samples_added_from_gan, lstm_auc_S_VANILA_GAN, line_width=2, line_color="blue") # p.diamond(num_samples_added_from_gan, lstm_auc_S_VANILA_GAN, line_width=2, size=15, fill_color="blue", legend="Vanilla GAN + LSTM") p.line(num_samples_added_from_gan, lstm_auc_S_VANILA_ODE_GAN, line_width=2, line_color="blue") p.circle(num_samples_added_from_gan, lstm_auc_S_VANILA_ODE_GAN, line_width=2, size=10, fill_color="blue", legend="SimVGAN + LSTM") # # show the results p.legend.location = "bottom_right" # show(p) # # F Beat: # p = figure(# title="Average AUC comparison on classifying heartbeat of type F - Fusion beats", x_axis_label='# Synthetic examples added', y_axis_label='AUC of ROC') output_file("F.html") # add a line renderer with legend and line thickness # p.line(num_samples_added_from_gan, fc_auc_S, line_width=2) # p.circle(num_samples_added_from_gan, fc_auc_S,legend="DCGAN + FF", size=8) p.line(num_samples_added_from_gan, lstm_auc_F_DCGAN, line_width=2, line_color="orange") p.triangle(num_samples_added_from_gan, lstm_auc_F_DCGAN, legend="DCGAN + LSTM", size=8, fill_color="orange") p.line(num_samples_added_from_gan, lstm_auc_F_ODEGAN, line_width=2, line_color="purple") p.square(num_samples_added_from_gan, lstm_auc_F_ODEGAN, size=8, fill_color="purple", legend="ODEGAN + LSTM") p.line(num_samples_added_from_gan, lstm_auc_F_SIMULATOR, line_width=2, line_color="green") p.asterisk(num_samples_added_from_gan, lstm_auc_F_SIMULATOR, line_width=2, size=15, line_color="green", fill_color="green", legend="Simulator + LSTM") p.line(num_samples_added_from_gan, lstm_auc_F_VANILA_GAN, line_width=2, line_color="blue") p.diamond(num_samples_added_from_gan, lstm_auc_F_VANILA_GAN, line_width=2, size=15, fill_color="blue", legend="Vanilla GAN + LSTM") p.line(num_samples_added_from_gan, lstm_auc_F_VANILA_ODE_GAN, line_width=2, line_color="pink") p.circle(num_samples_added_from_gan, lstm_auc_F_VANILA_ODE_GAN, line_width=2, size=10, fill_color="pink", legend="Vanilla ODE GAN + LSTM") # # show the results p.legend.location = "bottom_right" # show(p) # # V Beat: # p = figure(# title="Average AUC comparison on classifying heartbeat of type F - Fusion beats", x_axis_label='# Synthetic examples added', y_axis_label='AUC of ROC') output_file("V.html") # add a line renderer with legend and line thickness # p.line(num_samples_added_from_gan, fc_auc_S, line_width=2) # p.circle(num_samples_added_from_gan, fc_auc_S,legend="DCGAN + FF", size=8) p.line(num_samples_added_from_gan, lstm_auc_V_DCGAN, line_width=2, line_color="orange") p.triangle(num_samples_added_from_gan, lstm_auc_V_DCGAN, legend="DCGAN + LSTM", size=8, fill_color="orange") p.line(num_samples_added_from_gan, lstm_auc_V_ODEGAN, line_width=2, line_color="purple") p.square(num_samples_added_from_gan, lstm_auc_V_ODEGAN, size=8, fill_color="purple", legend="ODEGAN + LSTM") p.line(num_samples_added_from_gan, lstm_auc_V_SIMULATOR, line_width=2, line_color="green") p.asterisk(num_samples_added_from_gan, lstm_auc_V_SIMULATOR, line_width=2, size=15, line_color="green", fill_color="green", legend="Simulator + LSTM") p.line(num_samples_added_from_gan, lstm_auc_V_VANILA_GAN, line_width=2, line_color="blue") p.diamond(num_samples_added_from_gan, lstm_auc_V_VANILA_GAN, line_width=2, size=15, fill_color="blue", legend="Vanilla GAN + LSTM") p.line(num_samples_added_from_gan, lstm_auc_V_VANILA_ODE_GAN, line_width=2, line_color="pink") p.circle(num_samples_added_from_gan, lstm_auc_V_VANILA_ODE_GAN, line_width=2, size=10, fill_color="pink", legend="Vanilla ODE GAN + LSTM") # # show the results p.legend.location = "bottom_right" # show(p) # ## # # DCGAN results # # ## # # ## # # FC network # # ## # fc_auc_N = [0.85, 0.86, 0.86, 0.86, 0.87, 0.88, 0.88, 0.88, 0.88, 0.88] # fc_auc_S = [0.81, 0.82, 0.84, 0.87, 0.88, 0.89, 0.89, 0.89, 0.9, 0.9] # fc_auc_V = [0.95, 0.96, 0.96, 0.96, 0.97, 0.97, 0.97, 0.97, 0.98, 0.98] # fc_auc_F = [0.5, 0.73, 0.78, 0.82, 0.84, 0.86, 0.86, 0.91, 0.92, 0.93] # fc_auc_Q = [0.86] # # ## # # LSTM network # # ## # lstm_auc_N = [0.87, 0.88, 0.9, 0.9, 0.89, 0.89, 0.91, 0.91, 0.91, 0.91] # lstm_auc_S = [0.82, 0.87, 0.89, 0.87, 0.89, 0.89, 0.89, 0.92, 0.91, 0.91] # lstm_auc_V = [0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.98] # lstm_auc_F = [0.95, 0.96, 0.95, 0.96, 0.96, 0.96, 0.95, 0.95, 0.96, 0.96] # lstm_auc_Q = [0.83] # # # # # ODE GAN - Best scores: # # # ODE_N_lstm = [0.89, 0.9, 0.91, 0.915, 0.921, 0.92, 0.91, 0.91, 0.91, 0.9] # ODE_S_lstm = [0.82, 0.87, 0.88, 0.9, 0.93, 0.87, 0.91, 0.9, 0.91, 0.92] # # ODE_F_lstm = [0.95, 0.96, 0.96, 0.965, 0.96, 0.96, 0.97, 0.96, 0.96, 0.96] # # # # # # Pure data from simulator: # # # SIM_N_lstm = [] # SIM_S_lstm = [0.82, 0.87, 0.82, 0.87, 0.86, 0.87, 0.87, 0.86, 0.84, 0.85] # SIM_V_lstm = [] # SIM_F_lstm = [0.95, 0.96, 0.95, 0.96, 0.95, 0.95, 0.96, 0.95, 0.96, 0.95] # # # # # ODE Gan Combined Version: # # # # # # # # # # # # Beat N Comparision: # # # p = figure(title="Average AUC comparison on classifying heartbeat of type N - Normal beats", # x_axis_label='# Synthetic examples added', y_axis_label='AUC of ROC') # # # add a line renderer with legend and line thickness # p.line(num_samples_added_from_gan, fc_auc_N, line_width=2) # p.circle(num_samples_added_from_gan, fc_auc_N, size=8, legend="DCGAN + FF") # p.line(num_samples_added_from_gan, lstm_auc_N, line_width=2, line_color="orange") # p.circle(num_samples_added_from_gan, lstm_auc_N, size=8, fill_color="orange", legend="DCGAN + LSTM") # p.line(num_samples_added_from_gan, ODE_N_lstm, line_width=2, line_color="purple") # p.square(num_samples_added_from_gan, ODE_N_lstm, size=8, fill_color="purple", legend="ODEGAN + LSTM") # # # p.line(num_samples_added_from_gan, noise_N, legend="Noise", line_width=2, line_color="black") # # p.circle(num_samples_added_from_gan, noise_N, size=8, fill_color="black") # output_file("N.html") # p.legend.location = "bottom_right" # # show the results # show(p) # # # # # Beat S Comparision: # # # p = figure(title="Average AUC comparison on classifying heartbeat of type S - Supraventricular ectopic beats", # x_axis_label='# Synthetic examples added', y_axis_label='AUC of ROC') # output_file("S.html") # # add a line renderer with legend and line thickness # p.line(num_samples_added_from_gan, fc_auc_S, line_width=2) # p.circle(num_samples_added_from_gan, fc_auc_S,legend="DCGAN + FF", size=8) # p.line(num_samples_added_from_gan, lstm_auc_S, line_width=2, line_color="orange") # p.triangle(num_samples_added_from_gan, lstm_auc_S, legend="DCGAN + LSTM", size=8, fill_color="orange") # p.line(num_samples_added_from_gan, ODE_S_lstm, line_width=2, line_color="purple") # p.square(num_samples_added_from_gan, ODE_S_lstm, size=8, fill_color="purple", legend="ODEGAN + LSTM") # p.line(num_samples_added_from_gan, SIM_S_lstm, line_width=2, line_color="green") # p.asterisk(num_samples_added_from_gan, SIM_S_lstm, line_width=2, size=15, line_color="green", fill_color="green", legend="Simulator + LSTM") # # # p.line(num_samples_added_from_gan, noise_N, legend="Noise", line_width=2, line_color="black") # # p.circle(num_samples_added_from_gan, noise_N, size=8, fill_color="black") # # show the results # p.legend.location = "bottom_right" # # show(p) # # # # # Beat V Comparision: # # # p = figure(title="Average AUC comparison on classifying heartbeat of type V - Normal beats", # x_axis_label='# Synthetic examples added', y_axis_label='AUC of ROC') # output_file("V.html") # # add a line renderer with legend and line thickness # p.line(num_samples_added_from_gan, fc_auc_V, legend="Fully Connected", line_width=2) # p.circle(num_samples_added_from_gan, fc_auc_V, size=8) # p.line(num_samples_added_from_gan, lstm_auc_V, legend="LSTM", line_width=2, line_color="orange") # p.circle(num_samples_added_from_gan, lstm_auc_V, size=8, fill_color="orange") # # p.line(num_samples_added_from_gan, noise_N, legend="Noise", line_width=2, line_color="black") # # p.circle(num_samples_added_from_gan, noise_N, size=8, fill_color="black") # # p.legend.location = "bottom_right" # # show the results # show(p) # # # # # Beat F Comparision: # # # p = figure(title="Average AUC comparison on classifying heartbeat of type F - Fusion beats", # x_axis_label='# Synthetic examples added', y_axis_label='AUC of ROC') # output_file("F.html") # # add a line renderer with legend and line thickness # p.line(num_samples_added_from_gan, fc_auc_F, line_width=2) # p.circle(num_samples_added_from_gan, fc_auc_F, size=8, legend="DCGAN + FF") # p.line(num_samples_added_from_gan, lstm_auc_F, line_width=2, line_color="orange") # p.triangle(num_samples_added_from_gan, lstm_auc_F, size=8, fill_color="orange", legend="DCGAN + LSTM") # p.line(num_samples_added_from_gan, ODE_F_lstm, line_width=2, line_color="purple") # p.square(num_samples_added_from_gan, ODE_F_lstm, size=8, fill_color="purple", legend="ODEGAN + LSTM") # # p.line(num_samples_added_from_gan, noise_N, legend="Noise", line_width=2, line_color="black") # # p.circle(num_samples_added_from_gan, noise_N, size=8, fill_color="black") # # p.legend.location = "bottom_right" # # show the results # show(p) <file_sep>/ecg_pytorch/classifiers/models/lstm_test.py from ecg_pytorch.classifiers.models import lstm from ecg_pytorch.data_reader.ecg_dataset_pytorch import ToTensor, EcgHearBeatsDataset from torchvision import transforms from torch.utils.data import DataLoader from matplotlib import pyplot as plt def test_lstm(): composed = transforms.Compose([ToTensor()]) transformed_dataset = EcgHearBeatsDataset(transform=composed) dataloader = DataLoader(transformed_dataset, batch_size=4, shuffle=True, num_workers=4) lstmN = lstm.ECGLSTM(5, 512, 5, 2) for i, data in enumerate(dataloader): ecg_batch = data['cardiac_cycle'].permute(1, 0, 2).float() first_beat = ecg_batch[:, 0, :] print("First beat shape: {}".format(first_beat.shape)) print("First beat label {}".format(data['beat_type'][0])) print("First beat label one hot {}".format(data['label'][0])) first_beat = first_beat.numpy().flatten() plt.plot(first_beat) plt.show() plt.figure() plt.plot(data['orig_beat'][0].numpy()) plt.show() preds = lstmN(ecg_batch) print("Module output shape = {}".format(preds.shape)) print("Preds: {}".format(preds)) break if __name__ == "__main__": test_lstm()<file_sep>/ecg_pytorch/classifiers/models/cnn.py import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv1d(in_channels=1, out_channels=18, kernel_size=3, stride=1, padding=1, bias=True) self.conv2 = nn.Conv1d(in_channels=18, out_channels=36, kernel_size=3, stride=1, padding=1, bias=True) self.conv3 = nn.Conv1d(in_channels=36, out_channels=72, kernel_size=3, stride=1, padding=1, bias=True) self.conv4 = nn.Conv1d(in_channels=72, out_channels=144, kernel_size=3, stride=1, padding=1, bias=True) self.pool = nn.MaxPool1d(2) self.fc1 = nn.Linear(144 * 13, 1024) self.fc2 = nn.Linear(1024, 5) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = self.pool(F.relu(self.conv3(x))) x = self.pool(F.relu(self.conv4(x))) x = x.view(-1, 144 * 13) x = F.tanh(self.fc1(x)) x = self.fc2(x) return x<file_sep>/ecg_pytorch/data_reader/pickle_data.py import pickle from ecg_pytorch import train_configs from ecg_pytorch.data_reader import ecg_mit_bih import logging full_path = train_configs.base + 'ecg_pytorch/ecg_pytorch/data_reader' def load_ecg_input_from_pickle(): with open(full_path + '/train_beats.pickle', 'rb') as handle: train_beats = pickle.load(handle) with open(full_path + '/val_beats.pickle', 'rb') as handle: validation_beats = pickle.load(handle) with open(full_path + '/test_beats.pickle', 'rb') as handle: test_beats = pickle.load(handle) return train_beats, validation_beats, test_beats def save_ecg_mit_bih_to_pickle(): print("start pickling:") with open(full_path + '/ecg_mit_bih.pickle', 'wb') as output: ecg_ds = ecg_mit_bih.ECGMitBihDataset() pickle.dump(ecg_ds, output, pickle.HIGHEST_PROTOCOL) logging.info("Done pickling") if __name__ == "__main__": logging.basicConfig(level=logging.INFO) save_ecg_mit_bih_to_pickle() <file_sep>/ecg_pytorch/data_reader/dataset_configs_test.py import unittest from ecg_pytorch.data_reader import dataset_configs class TestDatasetConfigs(unittest.TestCase): def test_inputs(self): with self.assertRaises(ValueError): dataset_configs.DatasetConfigs('validation', 'N', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='N') ds = dataset_configs.DatasetConfigs('train', 'N', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='N') self.assertEqual(ds.partition, 'train') self.assertEqual(ds.classified_heartbeat, 'N') self.assertEqual(ds.one_vs_all, True) self.assertEqual(ds.lstm_setting, False) self.assertEqual(ds.over_sample_minority_class, False) self.assertEqual(ds.under_sample_majority_class, False) ds = dataset_configs.DatasetConfigs('test', 'N', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='N') self.assertEqual(ds.partition, 'test') ds = dataset_configs.DatasetConfigs('test', 'S', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='N') self.assertEqual(ds.classified_heartbeat, 'S') ds = dataset_configs.DatasetConfigs('test', 'V', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='N') self.assertEqual(ds.classified_heartbeat, 'V') ds = dataset_configs.DatasetConfigs('test', 'F', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='N') self.assertEqual(ds.classified_heartbeat, 'F') ds = dataset_configs.DatasetConfigs('test', 'Q', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='N') self.assertEqual(ds.classified_heartbeat, 'Q') with self.assertRaises(ValueError): dataset_configs.DatasetConfigs('train', 'P', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='N') def test_only_take_hb_of_type(self): with self.assertRaises(ValueError): dataset_configs.DatasetConfigs('train', 'N', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='w') ds = dataset_configs.DatasetConfigs('train', 'N', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type=None) self.assertEqual(ds.only_take_heartbeat_of_type, None) ds = dataset_configs.DatasetConfigs('train', 'N', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='S') self.assertEqual(ds.only_take_heartbeat_of_type, 'S') ds = dataset_configs.DatasetConfigs('train', 'N', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='N') self.assertEqual(ds.only_take_heartbeat_of_type, 'N') ds = dataset_configs.DatasetConfigs('train', 'N', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='V') self.assertEqual(ds.only_take_heartbeat_of_type, 'V') ds = dataset_configs.DatasetConfigs('train', 'N', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='F') self.assertEqual(ds.only_take_heartbeat_of_type, 'F') ds = dataset_configs.DatasetConfigs('train', 'N', one_vs_all=True, lstm_setting=False, over_sample_minority_class=False, under_sample_majority_class=False, only_take_heartbeat_of_type='Q') self.assertEqual(ds.only_take_heartbeat_of_type, 'Q') if __name__ == '__main__': unittest.main() <file_sep>/ecg_pytorch/classifiers/model_lib.py """Library with functions for the train and model defenitions.""" <file_sep>/ecg_pytorch/gan_models/checkpoint_paths.py from ecg_pytorch import train_configs base_path = train_configs.base # # ODE GAN N: # # ODE_GAN_N_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_ode_gan_N_beat' \ # '/checkpoint_epoch_1_iters_600' ODE_GAN_N_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_ode_gan_N_beat' \ '/checkpoint_epoch_8_iters_2500' # ODE_GAN_S_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_ode_gan_S_beat' \ # '/checkpoint_epoch_633_iters_3800' ODE_GAN_S_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_ode_gan_S_beat' \ '/checkpoint_epoch_166_iters_1000' ODE_GAN_F_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_ode_gan_F_beat/' \ 'checkpoint_epoch_933_iters_2800' ODE_GAN_V_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_ode_gan_V_beat/' \ 'checkpoint_epoch_51_iters_1350' # # DCGAN: # DCGAN_N_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_dcgan_N_beat/' \ 'checkpoint_epoch_0_iters_401' DCGAN_S_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_dcgan_s_beat/' \ 'checkpoint_epoch_94_iters_1800' DCGAN_V_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/dcgan_v_beat/' \ 'checkpoint_epoch_21_iters_1600' DCGAN_F_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/' \ 'ecg_dcgan_F_beat/checkpoint_epoch_50_iters_451' # # Vanilla GAN: # VGAN_N_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_vanilla_gan_N_beat/checkpoint_epoch_1_iters_1400' VGAN_S_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_vanilla_gan_s_beat/checkpoint_epoch_94_iters_1800' VGAN_V_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_vanilla_gan_V_beat/checkpoint_epoch_21_iters_1600' VGAN_F_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_vanilla_gan_F_beat/checkpoint_epoch_177_iters_1600' # # Vanilla GAN ODE: # VGAN_ODE_N_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_vanila_ode_gan_N_beat/checkpoint_epoch_15_iters_4800' VGAN_ODE_S_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_vanila_ode_gan_S_beat/checkpoint_epoch_800_iters_4800' VGAN_ODE_F_CHK = base_path +'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_vanila_ode_gan_F_beat/checkpoint_epoch_1600_iters_4800' VGAN_ODE_V_CHK = base_path + 'ecg_pytorch/ecg_pytorch/gan_models/tensorboard/ecg_vanila_ode_gan_V_beat/checkpoint_epoch_200_iters_4800' # # Helper dict: # BEAT_AND_MODEL_TO_CHECKPOINT_PATH = {'N': {'DCGAN': DCGAN_N_CHK, 'ODE_GAN': ODE_GAN_N_CHK, 'VANILA_GAN': VGAN_N_CHK, 'VANILA_GAN_ODE': VGAN_ODE_N_CHK}, 'S': {'DCGAN': DCGAN_S_CHK, 'ODE_GAN': ODE_GAN_S_CHK, 'VANILA_GAN': VGAN_S_CHK, 'VANILA_GAN_ODE': VGAN_ODE_S_CHK}, 'V': {'DCGAN': DCGAN_V_CHK, 'ODE_GAN': ODE_GAN_V_CHK, 'VANILA_GAN': VGAN_V_CHK, 'VANILA_GAN_ODE': VGAN_ODE_V_CHK}, 'F': {'DCGAN': DCGAN_F_CHK, 'ODE_GAN': ODE_GAN_F_CHK, 'VANILA_GAN': VGAN_F_CHK, 'VANILA_GAN_ODE': VGAN_ODE_F_CHK}} <file_sep>/ecg_pytorch/gan_models/models/ode_combined_conv_gan.py import torch.nn as nn from ecg_pytorch.dynamical_model.Euler.euler import Euler import torch import numpy as np import torch.nn.functional as F class ODEGenerator(nn.Module): def __init__(self, ngpu, device): super(ODEGenerator, self).__init__() self.ngpu = ngpu self.euler = Euler(device).to(device) self.fc1 = nn.Linear(50, 25) self.bn1 = nn.BatchNorm1d(num_features=25) self.fc2 = nn.Linear(25, 15) def forward(self, noise_input, v0): x = F.leaky_relu(self.bn1(self.fc1(noise_input)), inplace=True) x = F.sigmoid(self.fc2(x)) x = 0.1 * x + torch.Tensor([1.2, 0.25, - (1 / 3) * np.pi, -5.0, 0.1, - (1 / 12) * np.pi, 20, 0.1, 0.0, -7.5, 0.1, (1 / 12) * np.pi, 0.3, 0.4, (1 / 2) * np.pi]) z_t = self.euler(x.float(), v0) # output shape: NX216 # Try to add learnable noise layer: # z_t = z_t.view(-1, 1, 216) # z_t = return z_t def scale_signal(ecg_signal, min_val=-0.01563, max_val=0.042557): """ :param min: :param max: :return: """ res = [] for beat in ecg_signal: # Scale signal to lie between -0.4 and 1.2 mV : zmin = min(beat) zmax = max(beat) zrange = zmax - zmin scaled = [(z - zmin) * max_val / zrange + min_val for z in beat] scaled = torch.stack(scaled) res.append(scaled) res = torch.stack(res) return res class DeltaGenerator(nn.Module): def __init__(self, ngpu): super(DeltaGenerator, self).__init__() self.ngpu = ngpu ngf = 64 self.main = nn.Sequential( # shape in = [N, 50, 1] nn.ConvTranspose1d(50, ngf * 32, 4, 1, 0, bias=False), nn.BatchNorm1d(ngf * 32), nn.ReLU(True), # shape in = [N, 64*4, 4] nn.ConvTranspose1d(ngf * 32, ngf * 16, 4, 1, 0, bias=False), nn.BatchNorm1d(ngf * 16), nn.ReLU(True), # shape in = [N, 64*2, 7] nn.ConvTranspose1d(ngf * 16, ngf * 8, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf * 8), nn.ReLU(True), nn.ConvTranspose1d(ngf * 8, ngf * 4, 3, 2, 1, bias=False), nn.BatchNorm1d(ngf * 4), nn.ReLU(True), nn.ConvTranspose1d(ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf * 2), nn.ReLU(True), nn.ConvTranspose1d(ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf), nn.ReLU(True), nn.ConvTranspose1d(ngf, 1, 4, 2, 1, bias=False), ) def forward(self, input): input = input.view(-1, 50, 1) x = self.main(input) x = x.view(-1, 216) x = scale_signal(x) return x class CombinedGenerator(nn.Module): def __init__(self, ngpu, device): super(CombinedGenerator, self).__init__() self.ngpu = ngpu self.ode_generator = ODEGenerator(ngpu, device) self.z_delta_generator = DeltaGenerator(ngpu) def forward(self, x, v0): z = self.ode_generator(x, v0) z_delta = self.z_delta_generator(x) total = z + z_delta return total def test_generator(): netG = ODEGenerator(0, "cpu") noise_input = torch.Tensor(np.random.normal(0, 1, (2, 50))) print("Noise shape: {}".format(noise_input.size())) out = netG(noise_input) print(out.shape) print(list(netG.parameters())) if __name__ == "__main__": test_generator()<file_sep>/ecg_pytorch/gan_models/train_ode_gan.py import torch import torch.nn as nn import torch.optim as optim import torch.utils.data import torchvision.transforms as transforms import numpy as np import matplotlib.pyplot as plt from ecg_pytorch.data_reader import ecg_dataset_pytorch from tensorboardX import SummaryWriter from ecg_pytorch.gan_models.models import ode_gan from ecg_pytorch.gan_models.models import ode_gan_aaai from ecg_pytorch.dynamical_model import equations from ecg_pytorch.dynamical_model.ode_params import ODEParams import math import logging import pickle from ecg_pytorch.dynamical_model import typical_beat_params from ecg_pytorch.gan_models.models import vanila_gan from bokeh.plotting import figure, output_file, show, save from ecg_pytorch.data_reader import smooth_signal TYPICAL_ODE_N_PARAMS = [0.7, 0.25, -0.5 * math.pi, -7.0, 0.1, -15.0 * math.pi / 180.0, 30.0, 0.1, 0.0 * math.pi / 180.0, -3.0, 0.1, 15.0 * math.pi / 180.0, 0.2, 0.4, 160.0 * math.pi / 180.0] # custom weights initialization called on netG and netD def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: print(classname) nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0) def generate_typical_N_ode_params(b_size, device): noise_param = torch.Tensor(np.random.normal(0, 0.1, (b_size, 15))).to(device) params = 0.1 * noise_param + torch.Tensor(TYPICAL_ODE_N_PARAMS).to(device) return params def generate_typical_S_ode_params(b_size, device): noise_param = torch.Tensor(np.random.normal(0, 0.1, (b_size, 15))).to(device) params = 0.1 * noise_param + torch.Tensor(typical_beat_params.TYPICAL_ODE_S_PARAMS).to(device) return params def generate_typical_F_ode_params(b_size, device): noise_param = torch.Tensor(np.random.normal(0, 0.1, (b_size, 15))).to(device) params = 0.1 * noise_param + torch.Tensor(typical_beat_params.TYPICAL_ODE_F_PARAMS).to(device) return params def generate_typical_V_ode_params(b_size, device): noise_param = torch.Tensor(np.random.normal(0, 0.1, (b_size, 15))).to(device) params = 0.1 * noise_param + torch.Tensor(typical_beat_params.TYPICAL_ODE_V_PARAMS).to(device) return params def ode_loss(hb_batch, ode_params, device, beat_type): """ :param hb_batch: :return: """ # print(hb_batch[:, 0]) # # device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") delta_t = ode_params.h # params_one = [1.2, 0.25, -60.0 * math.pi / 180.0, -5.0, 0.1, -15.0 * math.pi / 180.0, # 30.0, 0.1, 0.0 * math.pi / 180.0, -7.5, 0.1, 15.0 * math.pi / 180.0, 0.75, 0.4, # 90.0 * math.pi / 180.0] # params_one = [0.7, 0.25, -0.5 * math.pi, -7.0, 0.1, -15.0 * math.pi / 180.0, # 30.0, 0.1, 0.0 * math.pi / 180.0, -3.0, 0.1, 15.0 * math.pi / 180.0, 0.2, 0.4, # 160.0 * math.pi / 180.0] batch_size = hb_batch.size()[0] # params_batch = np.array([params_one for _ in range(batch_size)]).reshape((batch_size, 15)) # params_batch = torch.Tensor(params_batch) if beat_type == "N": params_batch = generate_typical_N_ode_params(batch_size, device) elif beat_type == "S": params_batch = generate_typical_S_ode_params(batch_size, device) elif beat_type == 'F': params_batch = generate_typical_F_ode_params(batch_size, device) elif beat_type == 'V': params_batch = generate_typical_V_ode_params(batch_size, device) else: raise NotImplementedError() logging.debug("params batch shape: {}".format(params_batch.size())) x_t = torch.tensor(-0.417750770388669).to(device) y_t = torch.tensor(-0.9085616622823985).to(device) t = torch.tensor(0.0).to(device) f_ode_z_signal = None delta_hb_signal = None for i in range(215): # if i == 0: # init_z = -0.004551233843726818 # init_z =torch.Tensor(np.array([init_z for _ in range(batch_size)])).to(device) # delta_hb = (hb_batch[:, i + 1] - init_z) / delta_t # else: delta_hb = (hb_batch[:, i + 1] - hb_batch[:, i]) / delta_t delta_hb = delta_hb.view(-1, 1) z_t = hb_batch[:, i].view(-1, 1) f_ode_x = equations.d_x_d_t(y_t, x_t, t, ode_params.rrpc, ode_params.h) f_ode_y = equations.d_y_d_t(y_t, x_t, t, ode_params.rrpc, ode_params.h) f_ode_z = equations.d_z_d_t(x_t, y_t, z_t, t, params_batch, ode_params) logging.debug("f ode z shape {}".format(f_ode_z.shape)) # Nx1 logging.debug("f ode x shape {}".format(f_ode_x.shape)) logging.debug("f ode y shape {}".format(f_ode_y.shape)) y_t = y_t + delta_t * f_ode_y x_t = x_t + delta_t * f_ode_x t += 1 / 360 if f_ode_z_signal is None: f_ode_z_signal = f_ode_z delta_hb_signal = delta_hb else: f_ode_z_signal = torch.cat((f_ode_z_signal, f_ode_z), 1) delta_hb_signal = torch.cat((delta_hb_signal, delta_hb), 1) logging.debug("f signal shape: {}".format(f_ode_z_signal.shape)) logging.debug("delta hb signal shape: {}".format(delta_hb_signal.shape)) return delta_hb_signal, f_ode_z_signal def test_ode_loss(): with open('/Users/tomer.golany/PycharmProjects/ecg_pytorch/ecg_pytorch/dynamical_model/ode_normal_sample.pkl', 'rb') as handle: good_sample = pickle.load(handle) good_sample = np.array(good_sample).reshape((1, 216)) good_sample = torch.Tensor(good_sample) ode_params = ODEParams('cpu') delta_hb_signal, f_ode_z_signal = ode_loss(good_sample, ode_params) print(delta_hb_signal - f_ode_z_signal) mse_loss = nn.MSELoss() loss = mse_loss(delta_hb_signal, f_ode_z_signal) print("LOSS: ", loss) def euler_loss(hb_batch, params_batch, x_batch, y_batch, ode_params): """ :param hb_batch: Nx216 :param params_batch: Nx15 :return: """ logging.debug('hb batch shape: {}'.format(hb_batch.shape)) logging.debug('params batch shape: {}'.format(params_batch.shape)) logging.debug('x batch shape: {}'.format(x_batch.shape)) logging.debug('y batch shape: {}'.format(y_batch.shape)) delta_t = ode_params.h t = torch.tensor(0.0) f_ode_z_signal = None f_ode_x_signal = None f_ode_y_signal = None delta_hb_signal = None delta_x_signal = None delta_y_signal = None for i in range(215): delta_hb = (hb_batch[:, i + 1] - hb_batch[:, i]) / delta_t delta_y = (y_batch[:, i + 1] - y_batch[:, i]) / delta_t delta_x = (x_batch[:, i + 1] - x_batch[:, i]) / delta_t delta_hb = delta_hb.view(-1, 1) delta_x = delta_x.view(-1, 1) delta_y = delta_y.view(-1, 1) logging.debug("Delta heart-beat shape: {}".format(delta_hb.shape)) y_t = y_batch[:, i].view(-1, 1) x_t = x_batch[:, i].view(-1, 1) z_t = hb_batch[:, i].view(-1, 1) f_ode_x = equations.d_x_d_t(y_t, x_t, t, ode_params.rrpc, ode_params.h) f_ode_y = equations.d_y_d_t(y_t, x_t, t, ode_params.rrpc, ode_params.h) f_ode_z = equations.d_z_d_t(x_t, y_t, z_t, t, params_batch, ode_params) t += 1 / 512 logging.debug("f ode z shape {}".format(f_ode_z.shape)) # Nx1 logging.debug("f ode x shape {}".format(f_ode_x.shape)) logging.debug("f ode y shape {}".format(f_ode_y.shape)) if f_ode_z_signal is None: f_ode_z_signal = f_ode_z f_ode_x_signal = f_ode_x f_ode_y_signal = f_ode_y delta_hb_signal = delta_hb delta_x_signal = delta_x delta_y_signal = delta_y else: f_ode_z_signal = torch.cat((f_ode_z_signal, f_ode_z), 1) f_ode_x_signal = torch.cat((f_ode_x_signal, f_ode_x), 1) f_ode_y_signal = torch.cat((f_ode_y_signal, f_ode_y), 1) delta_hb_signal = torch.cat((delta_hb_signal, delta_hb), 1) delta_x_signal = torch.cat((delta_x_signal, delta_x), 1) delta_y_signal = torch.cat((delta_y_signal, delta_y), 1) logging.debug("f signal shape: {}".format(f_ode_z_signal.shape)) logging.debug("delta hb signal shape: {}".format(delta_hb_signal.shape)) return delta_hb_signal, f_ode_z_signal, f_ode_x_signal, f_ode_y_signal, delta_x_signal, delta_y_signal def train(batch_size, num_train_steps, model_dir, beat_type): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") ode_params = ODEParams(device) # # Support for tensorboard: # writer = SummaryWriter(model_dir) # # 1. create the ECG dataset: # composed = transforms.Compose([ecg_dataset_pytorch.Scale(), ecg_dataset_pytorch.ToTensor()]) dataset = ecg_dataset_pytorch.EcgHearBeatsDataset(transform=composed, beat_type=beat_type, lstm_setting=False) dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=1) print("Size of real dataset is {}".format(len(dataset))) # # 2. Create the models: # netG = ode_gan_aaai.DCGenerator(0).to(device) # netD = ode_gan_aaai.DCDiscriminator(0).to(device) # netD.apply(weights_init) # netG.apply(weights_init) netG = vanila_gan.VGenerator(0).to(device) netD = vanila_gan.VDiscriminator(0).to(device) # # Define loss functions: # cross_entropy_loss = nn.BCELoss() mse_loss = nn.MSELoss() # # Optimizers: # lr = 0.0002 beta1 = 0.5 writer.add_scalar('Learning_Rate', lr) optimizer_d = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999)) optimizer_g = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999)) # # Noise for validation: # val_noise = torch.Tensor(np.random.uniform(0, 1, (4, 100))).to(device) # val_noise = torch.Tensor(np.random.normal(0, 1, (4, 100))).to(device) # # Training loop" # epoch = 0 iters = 0 while True: num_of_beats_seen = 0 if iters == num_train_steps: break for i, data in enumerate(dataloader): if iters == num_train_steps: break netD.zero_grad() # # Discriminator from real beats: # ecg_batch = data['cardiac_cycle'].float().to(device) b_size = ecg_batch.shape[0] num_of_beats_seen += ecg_batch.shape[0] output = netD(ecg_batch) labels = torch.full((b_size,), 1, device=device) ce_loss_d_real = cross_entropy_loss(output, labels) writer.add_scalar('Discriminator/cross_entropy_on_real_batch', ce_loss_d_real.item(), global_step=iters) writer.add_scalars('Merged/losses', {'d_cross_entropy_on_real_batch': ce_loss_d_real.item()}, global_step=iters) ce_loss_d_real.backward() mean_d_real_output = output.mean().item() # # Discriminator from fake beats: # noise_input = torch.Tensor(np.random.uniform(0, 1, (b_size, 100))).to(device) # noise_input = torch.Tensor(np.random.normal(0, 1, (b_size, 100))).to(device) output_g_fake = netG(noise_input) output = netD(output_g_fake.detach()).to(device) labels.fill_(0) ce_loss_d_fake = cross_entropy_loss(output, labels) writer.add_scalar('Discriminator/cross_entropy_on_fake_batch', ce_loss_d_fake.item(), iters) writer.add_scalars('Merged/losses', {'d_cross_entropy_on_fake_batch': ce_loss_d_fake.item()}, global_step=iters) ce_loss_d_fake.backward() mean_d_fake_output = output.mean().item() total_loss_d = ce_loss_d_fake + ce_loss_d_real writer.add_scalar(tag='Discriminator/total_loss', scalar_value=total_loss_d.item(), global_step=iters) optimizer_d.step() netG.zero_grad() labels.fill_(1) output = netD(output_g_fake) # # Add euler loss: # delta_hb_signal, f_ode_z_signal = ode_loss(output_g_fake, ode_params, device, beat_type) mse_loss_euler = mse_loss(delta_hb_signal, f_ode_z_signal) logging.info("MSE ODE loss: {}".format(mse_loss_euler.item())) ce_loss_g_fake = cross_entropy_loss(output, labels) total_g_loss = mse_loss_euler + ce_loss_g_fake # total_g_loss = mse_loss_euler total_g_loss.backward() writer.add_scalar(tag='Generator/mse_ode', scalar_value=mse_loss_euler.item(), global_step=iters) writer.add_scalar(tag='Generator/cross_entropy_on_fake_batch', scalar_value=ce_loss_g_fake.item(), global_step=iters) writer.add_scalars('Merged/losses', {'g_cross_entropy_on_fake_batch': ce_loss_g_fake.item()}, global_step=iters) mean_d_fake_output_2 = output.mean().item() optimizer_g.step() if iters % 50 == 0: print("{}/{}: Epoch #{}: Iteration #{}: Mean D(real_hb_batch) = {}, mean D(G(z)) = {}." .format(num_of_beats_seen, len(dataset), epoch, iters, mean_d_real_output, mean_d_fake_output), end=" ") print("mean D(G(z)) = {} After backprop of D".format(mean_d_fake_output_2)) print("Loss D from real beats = {}. Loss D from Fake beats = {}. Total Loss D = {}". format(ce_loss_d_real, ce_loss_d_fake, total_loss_d), end=" ") print("Loss G = {}".format(ce_loss_g_fake)) # # Norma of gradients: # gNormGrad = get_gradient_norm_l2(netG) dNormGrad = get_gradient_norm_l2(netD) writer.add_scalar('Generator/gradients_norm', gNormGrad, iters) writer.add_scalar('Discriminator/gradients_norm', dNormGrad, iters) print( "Generator Norm of gradients = {}. Discriminator Norm of gradients = {}.".format(gNormGrad, dNormGrad)) if iters % 25 == 0: with torch.no_grad(): with torch.no_grad(): output_g = netG(val_noise) fig = plt.figure() plt.title("Fake beats from Generator. iteration {}".format(i)) for p in range(4): plt.subplot(2, 2, p + 1) plt.plot(output_g[p].cpu().detach().numpy(), label="fake beat") plt.plot(ecg_batch[p].cpu().detach().numpy(), label="real beat") plt.legend() writer.add_figure('Generator/output_example', fig, iters) plt.close() # # Add bokeh plot: # p = figure(x_axis_label='Sample number (360 Hz)', y_axis_label='Voltage[mV]') time = np.arange(0, 216) fake_beat = output_g[0].cpu().detach().numpy() w = 'hanning' smoothed_beat = smooth_signal.smooth(fake_beat, 10, w) p.line(time, smoothed_beat, line_width=2, line_color="blue") output_file("N_{}_ODE.html".format(iters)) save(p) if iters % 50 == 0: torch.save({ 'epoch': epoch, 'generator_state_dict': netG.state_dict(), }, model_dir + '/checkpoint_epoch_{}_iters_{}'.format(epoch, iters)) iters += 1 epoch += 1 writer.close() def get_gradient_norm_l2(model): total_norm = 0 for name, p in model.named_parameters(): if p.requires_grad and 'ode_params_generator' not in name: # print(name) param_norm = p.grad.data.norm(2) total_norm += param_norm.item() ** 2 total_norm = total_norm ** (1. / 2) # for p in model.parameters(): # # param_norm = p.grad.data.norm(2) # total_norm += param_norm.item() ** 2 # total_norm = total_norm ** (1. / 2) return total_norm if __name__ == "__main__": logging.basicConfig(level=logging.INFO) model_dir = 'tensorboard/ecg_vanila_ode_gan_S_beat/' beat_type = 'S' train(150, 5000, model_dir, beat_type) <file_sep>/ecg_pytorch/classifiers/utils.py import pickle def load_and_print_pickle_contents(pickle_path): with open(pickle_path, 'rb') as handle: b = pickle.load(handle) # print(b) return b if __name__ == "__main__": pickle_path = "/home/tomer/tomer/ecg_pytorch/ecg_pytorch/classifiers/pickles_results/" \ "S_ODE_GAN_lstm_different_ckps_500.pkl" d = load_and_print_pickle_contents(pickle_path) for chk in d: print("{}: mean: {}, max: {}".format(chk, d[chk]['MEAN'], d[chk]['MAX'])) <file_sep>/ecg_pytorch/dynamical_model/utils.py import numpy as np from scipy.stats import norm def rrprocess(n, f1=0.1, f2=0.25, c1=0.01, c2=0.01, lfhfratio=0.5, hrmean=60, hrstd=1, sf=512): """ GENERATE RR PROCESS :param flo: :param fhi: :param flostd: :param fhistd: :param lfhfratio: :param hrmean: :param hrstd: :param sf: :param n: :return: """ # Step 1: Calculate the power spectrum: sig2 = 1.0 sig1 = lfhfratio # Convert freq to rad/sec # f1 = 2.0 * math.pi * f1 # f2 = 2.0 * math.pi * f2 # c1 = 2.0 * math.pi * c1 # c2 = 2.0 * math.pi * c2 df = sf / float(n) # f = np.array([2.0 * math.pi * df * i for i in range(n)]) #f = np.linspace(0, 2.0 * math.pi, 512) f = np.linspace(0, 0.5, n) # Calaculate Power Spectrum S(f) # S_F = sig1 * norm.pdf(x=f, loc=f1, scale=c1) + sig2 * norm.pdf(x=f, loc=f2, scale=c2) # x_axis = np.linspace(0, 2.0, n) # plt.figure() # plt.plot(x_axis, S_F) # plt.xlabel("freq") # plt.ylabel("Power") # plt.title("Power spectrum") # plt.show() # Step 2: Create the RR-interval time series: # amplitudes = np.sqrt(S_F) amplitudes = np.linspace(0, 1, n) # phases = np.random.normal(loc=0, scale=1, size=len(S_F)) * 2 * np.pi phases = np.linspace(0, 1, n) * 2 * np.pi complex_series = [complex(amplitudes[i] * np.cos(phases[i]), amplitudes[i] * np.sin(phases[i])) for i in range(len(phases))] import cmath # print(cmath.polar(complex_series[0])) T = np.fft.ifft(complex_series, n) T = T.real rrmean = 60.0 / hrmean rrstd = 60.0 * hrstd / (hrmean * hrmean) std = np.std(T) ratio = rrstd / std T = ratio * T T = T + rrmean return T def generate_omega_function(f1, f2, c1, c2): """ :return: """ cardiac_cycle_len = 216 rr = rrprocess(cardiac_cycle_len,f1, f2, c1, c2, lfhfratio=0.5, hrmean=60, hrstd=1, sf=512) return rr def scale_signal(signal, min_val=-0.4, max_val=1.2): """ :param min: :param max: :return: """ # Scale signal to lie between -0.4 and 1.2 mV : zmin = min(signal) zmax = max(signal) zrange = zmax - zmin scaled = [(z - zmin) * max_val / zrange - min_val for z in signal] return scaled def smooth(x, window_len=11, window='flat'): """smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the begining and end part of the output signal. input: x: the input signal window_len: the dimension of the smoothing window; should be an odd integer window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman' flat window will produce a moving average smoothing. output: the smoothed signal example: t=linspace(-2,2,0.1) x=sin(t)+randn(len(t))*0.1 y=smooth(x) see also: numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve scipy.signal.lfilter TODO: the window parameter could be the window itself if an array instead of a string NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y. """ if x.ndim != 1: raise ValueError("smooth only accepts 1 dimension arrays.") if x.size < window_len: raise ValueError("Input vector needs to be bigger than window size.") if window_len < 3: return x if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise ValueError("Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'") s = np.r_[x[window_len - 1:0:-1], x, x[-2:-window_len - 1:-1]] # print(len(s)) if window == 'flat': # moving average w = np.ones(window_len, 'd') else: w = eval('np.' + window + '(window_len)') y = np.convolve(w / w.sum(), s, mode='valid') # return y return y[(int(window_len/2)-1):-(int(window_len/2) + 1)] if __name__ == "__main__": f1 = 0.1 f2 = 0.25 c1 = 0.01 c2 = 0.01 generate_omega_function(f1, f2, c1, c2) <file_sep>/ecg_pytorch/classifiers/metrics_test.py from bokeh.plotting import figure, output_file, show, ColumnDataSource if __name__ == "__main__": output_file("toolbar.html") fpr = [1, 2, 3, 4, 5] source = ColumnDataSource(data=dict( fpr=[1, 2, 3, 4, 5], tpr=[2, 4, 6, 4, 2], tnr = [1 - x for x in fpr], probs = [0.5, 0.4, 0.2, 0.1, 0.6], )) TOOLTIPS = [ ("(spe.(tnr),se.(tpr))", "(@tnr, $y)"), ("threshold", "@probs"), ] p = figure(plot_width=400, plot_height=400, tooltips=TOOLTIPS, title="Mouse over the dots") p.line('fpr', 'tpr', source=source) show(p)<file_sep>/ecg_pytorch/gan_models/models/old_ode_combined.py import torch.nn as nn from ecg_pytorch.dynamical_model.Euler.euler import Euler import torch import numpy as np import torch.nn.functional as F class Generator(nn.Module): def __init__(self, ngpu, device): super(Generator, self).__init__() self.ngpu = ngpu self.euler = Euler(device).to(device) self.fc1 = nn.Linear(50, 25) self.bn1 = nn.BatchNorm1d(num_features=25) self.fc2 = nn.Linear(25, 15) # self.conv1 = nn.Conv1d(in_channels=1, out_channels=1, ) def forward(self, noise_input, v0): x = F.leaky_relu(self.bn1(self.fc1(noise_input)), inplace=True) x = F.sigmoid(self.fc2(x)) x = 0.1 * x + torch.Tensor([1.2, 0.25, - (1 / 3) * np.pi, -5.0, 0.1, - (1 / 12) * np.pi, 20, 0.1, 0.0, -7.5, 0.1, (1 / 12) * np.pi, 0.3, 0.4, (1 / 2) * np.pi]) # input_params = x # input_params[:, 0] = input_params[:, 0] * 0.1 + 1.2 # input_params[:, 3] = input_params[:, 3] * 0.1 - 5.0 # input_params[:, 6] = input_params[:, 6] * 0.1 + 20 # input_params[:, 9] = input_params[:, 9] * 0.1 - 7.5 # input_params[:, 12] = input_params[:, 12] * 0.2 + 0.3 # # input_params[:, 1] = input_params[:, 1] * 0.1 + 0.25 # input_params[:, 4] = input_params[:, 4] * 0.1 + 0.1 # input_params[:, 7] = input_params[:, 7] * 0.1 + 0.1 # input_params[:, 10] = input_params[:, 10] * 0.1 + 0.1 # input_params[:, 13] = input_params[:, 13] * 0.1 + 0.4 # # input_params[:, 2] = input_params[:, 2] * 0.1 - (1 / 3) * np.pi # input_params[:, 5] = input_params[:, 5] * 0.1 - (1 / 12) * np.pi # input_params[:, 8] = input_params[:, 8] * 0.1 # input_params[:, 11] = input_params[:, 11] * 0.1 + (1 / 12) * np.pi # input_params[:, 14] = input_params[:, 14] * 0.1 + (1 / 2) * np.pi # input_params = input_params.float() z_t = self.euler(x.float(), v0) # output shape: NX216 # Try to add learnable noise layer: # z_t = z_t.view(-1, 1, 216) # z_t = return z_t def scale_signal(ecg_signal, min_val=-0.01563, max_val=0.042557): """ :param min: :param max: :return: """ res = [] for beat in ecg_signal: # Scale signal to lie between -0.4 and 1.2 mV : zmin = min(beat) zmax = max(beat) zrange = zmax - zmin scaled = [(z - zmin) * max_val / zrange + min_val for z in beat] scaled = torch.stack(scaled) res.append(scaled) res = torch.stack(res) return res # class DeltaGenerator(nn.Module): # def __init__(self, ngpu, device): # super(DeltaGenerator, self).__init__() # self.ngpu = ngpu # # self.fc1_z_delta = nn.Linear(in_features=50, out_features=1024) # self.bn1 = nn.BatchNorm1d(num_features=1024) # self.fc2_z_delta = nn.Linear(in_features=1024, out_features=54 * 128) # self.bn2 = nn.BatchNorm1d(num_features=54 * 128) # self.conv1_z_delta = nn.ConvTranspose1d(in_channels=128, out_channels=64, kernel_size=4, stride=2, padding=1) # self.bn3 = nn.BatchNorm1d(64) # self.conv2_z_delta = nn.ConvTranspose1d(in_channels=64, out_channels=1, kernel_size=4, stride=2, padding=1) # # def forward(self, x): # x = F.elu(self.bn1(self.fc1_z_delta(x))) # x = F.elu(self.bn2(self.fc2_z_delta(x))) # x = x.view(-1, 128, 54) # x = F.relu(self.bn3(self.conv1_z_delta(x))) # x = (self.conv2_z_delta(x)) # return x.view(-1, 216) class DeltaGenerator(nn.Module): def __init__(self, ngpu): super(DeltaGenerator, self).__init__() self.ngpu = ngpu ngf = 64 self.main = nn.Sequential( # shape in = [N, 50, 1] nn.ConvTranspose1d(50, ngf * 32, 4, 1, 0, bias=False), nn.BatchNorm1d(ngf * 32), nn.ReLU(True), # shape in = [N, 64*4, 4] nn.ConvTranspose1d(ngf * 32, ngf * 16, 4, 1, 0, bias=False), nn.BatchNorm1d(ngf * 16), nn.ReLU(True), # shape in = [N, 64*2, 7] nn.ConvTranspose1d(ngf * 16, ngf * 8, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf * 8), nn.ReLU(True), nn.ConvTranspose1d(ngf * 8, ngf * 4, 3, 2, 1, bias=False), nn.BatchNorm1d(ngf * 4), nn.ReLU(True), nn.ConvTranspose1d(ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf * 2), nn.ReLU(True), nn.ConvTranspose1d(ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm1d(ngf), nn.ReLU(True), nn.ConvTranspose1d(ngf, 1, 4, 2, 1, bias=False), ) def forward(self, input): input = input.view(-1, 50, 1) x = self.main(input) x = x.view(-1, 216) x = scale_signal(x) return x class CombinedGenerator(nn.Module): def __init__(self, ngpu, device): super(CombinedGenerator, self).__init__() self.ngpu = ngpu self.ode_generator = Generator(ngpu, device) self.z_delta_generator = DeltaGenerator(ngpu) def forward(self, x, v0): z = self.ode_generator(x, v0) z_delta = self.z_delta_generator(x) total = z + z_delta return total def test_generator(): netG = Generator(0, "cpu") noise_input = torch.Tensor(np.random.normal(0, 1, (2, 50))) print("Noise shape: {}".format(noise_input.size())) out = netG(noise_input) print(out.shape) print(list(netG.parameters())) if __name__ == "__main__": test_generator()<file_sep>/ecg_pytorch/data_reader/dataset_builder.py """Function that support building dataset for ECG heartbeats.""" import torchvision.transforms as transforms from ecg_pytorch.data_reader.ecg_dataset_pytorch import ToTensor, EcgHearBeatsDataset, EcgHearBeatsDatasetTest import torch import logging from enum import Enum from ecg_pytorch.gan_models.models import dcgan from ecg_pytorch.gan_models.models import vanila_gan from ecg_pytorch.gan_models.models import ode_gan_aaai class GanType(Enum): DCGAN = 0 ODE_GAN = 1 SIMULATOR = 2 VANILA_GAN = 3 VANILA_GAN_ODE = 4 NOISE = 5 def build(train_config): """Build PyTorch train and test data-loaders. :param train_config: :return: """ add_from_gan = train_config.add_data_from_gan batch_size = train_config.batch_size composed = transforms.Compose([ToTensor()]) if train_config.train_one_vs_all: dataset = EcgHearBeatsDataset(transform=composed, beat_type=train_config.generator_details.beat_type, one_vs_all=True, lstm_setting=False) testset = EcgHearBeatsDatasetTest(transform=composed, beat_type=train_config.generator_details.beat_type, one_vs_all=True, lstm_setting=False) init_auc_scores = [0, 0] else: init_auc_scores = [0, 0, 0, 0] dataset = EcgHearBeatsDataset(transform=composed, lstm_setting=False) testset = EcgHearBeatsDatasetTest(transform=composed, lstm_setting=False) testdataloader = torch.utils.data.DataLoader(testset, batch_size=300, shuffle=True, num_workers=1) # # Check if to add data from GAN: # if add_from_gan: num_examples_to_add = train_config.generator_details.num_examples_to_add generator_checkpoint_path = train_config.generator_details.checkpoint_path generator_beat_type = train_config.generator_details.beat_type gan_type = train_config.generator_details.gan_type logging.info("Adding {} samples of type {} from GAN {}".format(num_examples_to_add, generator_beat_type, gan_type)) logging.info("Size of training data before additional data from GAN: {}".format(len(dataset))) logging.info("#N: {}\t #S: {}\t #V: {}\t #F: {}\t".format(dataset.len_beat('N'), dataset.len_beat('S'), dataset.len_beat('V'), dataset.len_beat('F'))) if num_examples_to_add > 0: if gan_type == GanType.DCGAN: gNet = dcgan.DCGenerator(0) dataset.add_beats_from_generator(gNet, num_examples_to_add, generator_checkpoint_path, generator_beat_type) elif gan_type == GanType.ODE_GAN: gNet = ode_gan_aaai.DCGenerator(0) dataset.add_beats_from_generator(gNet, num_examples_to_add, generator_checkpoint_path, generator_beat_type) elif gan_type == GanType.SIMULATOR: dataset.add_beats_from_simulator(num_examples_to_add, generator_beat_type) elif gan_type == GanType.VANILA_GAN: gNet = vanila_gan.VGenerator(0) dataset.add_beats_from_generator(gNet, num_examples_to_add, generator_checkpoint_path, generator_beat_type) elif gan_type == GanType.VANILA_GAN_ODE: gNet = vanila_gan.VGenerator(0) dataset.add_beats_from_generator(gNet, num_examples_to_add, generator_checkpoint_path, generator_beat_type) elif gan_type == GanType.NOISE: dataset.add_noise(num_examples_to_add, generator_beat_type) else: raise ValueError("Unknown gan type {}".format(gan_type)) logging.info("Size of training data after additional data from GAN: {}".format(len(dataset))) logging.info("#N: {}\t #S: {}\t #V: {}\t #F: {}\t".format(dataset.len_beat('N'), dataset.len_beat('S'), dataset.len_beat('V'), dataset.len_beat('F'))) else: logging.info("No data is added. Train set size: ") logging.info("#N: {}\t #S: {}\t #V: {}\t #F: {}\t".format(dataset.len_beat('N'), dataset.len_beat('S'), dataset.len_beat('V'), dataset.len_beat('F'))) logging.info("test set size: ") logging.info("#N: {}\t #S: {}\t #V: {}\t #F: {}\t".format(testset.len_beat('N'), testset.len_beat('S'), testset.len_beat('V'), testset.len_beat('F'))) if train_config.weighted_sampling: weights_for_balance = dataset.make_weights_for_balanced_classes() weights_for_balance = torch.DoubleTensor(weights_for_balance) sampler = torch.utils.data.sampler.WeightedRandomSampler( weights=weights_for_balance, num_samples=len(weights_for_balance), replacement=True) train_data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=1, sampler=sampler) else: train_data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=1, shuffle=True) return train_data_loader, testdataloader, init_auc_scores<file_sep>/ecg_pytorch/gan_models/models/ode_gan_aaai.py import torch.nn as nn class DCGenerator(nn.Module): def __init__(self, ngpu): super(DCGenerator, self).__init__() self.ngpu = ngpu ngf = 64 self.main = nn.Sequential( # shape in = [N, 50, 1] nn.ConvTranspose1d(100, ngf * 32, 4, 1, 0, bias=True), nn.BatchNorm1d(ngf * 32), nn.ReLU(True), # shape in = [N, 64*4, 4] nn.ConvTranspose1d(ngf * 32, ngf * 16, 4, 1, 0, bias=True), nn.BatchNorm1d(ngf * 16), nn.ReLU(True), # shape in = [N, 64*2, 7] nn.ConvTranspose1d(ngf * 16, ngf * 8, 4, 2, 1, bias=True), nn.BatchNorm1d(ngf * 8), nn.ReLU(True), nn.ConvTranspose1d(ngf * 8, ngf * 4, 3, 2, 1, bias=True), nn.BatchNorm1d(ngf * 4), nn.ReLU(True), nn.ConvTranspose1d(ngf * 4, ngf * 2, 4, 2, 1, bias=True), nn.BatchNorm1d(ngf * 2), nn.ReLU(True), nn.ConvTranspose1d(ngf * 2, ngf, 4, 2, 1, bias=True), nn.BatchNorm1d(ngf), nn.ReLU(True), nn.ConvTranspose1d(ngf, 1, 4, 2, 1, bias=True), ) def forward(self, x): x = x.view(-1, 100, 1) x = self.main(x) x = x.view(-1, 216) return x class DCDiscriminator(nn.Module): def __init__(self, ngpu): super(DCDiscriminator, self).__init__() self.ngpu = ngpu ndf = 64 self.main = nn.Sequential( # input is (nc) x 64 x 64 nn.Conv1d(in_channels=1, out_channels=ndf, kernel_size=4, stride=2, padding=1, bias=False), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf) x 32 x 32 nn.Conv1d(ndf, ndf * 2, 4, 2, 1, bias=False), nn.BatchNorm1d(ndf * 2), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*2) x 16 x 16 nn.Conv1d(ndf * 2, ndf * 4, 4, 2, 1, bias=False), nn.BatchNorm1d(ndf * 4), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*4) x 8 x 8 nn.Conv1d(ndf * 4, ndf * 8, 4, 2, 1, bias=False), nn.BatchNorm1d(ndf * 8), nn.LeakyReLU(0.2, inplace=True), nn.Conv1d(ndf * 8, ndf * 16, 4, 2, 1, bias=False), nn.BatchNorm1d(ndf * 16), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*8) x 4 x 4 nn.Conv1d(ndf * 16, 1, 5, 2, 0, bias=False), nn.Sigmoid() ) def forward(self, x): x = x.view(-1, 1, 216) return self.main(x) <file_sep>/ecg_pytorch/classifiers/inference/run_inference.py import torch import cv2 from matplotlib import pyplot as plt from ecg_pytorch.data_reader import patient from ecg_pytorch.classifiers.models import fully_connected from ecg_pytorch.classifiers.models import cnn import logging import numpy as np import tqdm from ecg_pytorch.classifiers.inference import checkpoint_paths from ecg_pytorch.classifiers.models import deep_residual_conv import pandas as pd CLASS_TO_IND = {'N': 0, 'S': 1, 'V': 2, 'F': 3, 'Q': 4} IND_TO_CLASS = {0: 'N', 1: 'S', 2: 'V', 3: 'F', 4: 'Q'} N_COLOR = (255, 128, 0) S_COLOR = (51, 255, 510) V_COLOR = (0, 0, 255) F_COLOR = (255, 51, 255) Q_COLOR = (255, 0, 0) CLASS_TO_COLOR = {'N': N_COLOR, 'S': S_COLOR, 'V': V_COLOR, 'F': F_COLOR, 'Q': Q_COLOR} train_set = [101, 106, 108, 109, 112, 114, 115, 116, 118, 119, 122, 124, 201, 203, 205, 207, 208, 209, 215, 220, 223, 230] # DS1 train_set = [str(x) for x in train_set] test_set = [100, 103, 105, 111, 113, 117, 121, 123, 200, 202, 210, 212, 213, 214, 219, 221, 222, 228, 231, 232, 233, 234] # DS2 test_set = [str(x) for x in test_set] def eval_model(model, model_chk, patient_number): p_data = patient.beats_from_patient(patient_number) checkpoint = torch.load(model_chk, map_location='cpu') model.load_state_dict(checkpoint['net']) model.eval() fourcc = cv2.VideoWriter_fourcc('P', 'N', 'G', ' ') out = cv2.VideoWriter('test/patient_{}_inference_fc.avi'.format(patient_number), fourcc, 4, (640, 480)) softmax = torch.nn.Softmax() with torch.no_grad(): for i, beat_dict in enumerate(tqdm.tqdm(p_data)): beat = torch.Tensor(beat_dict['cardiac_cycle']) prediction = model(beat) prediction = softmax(prediction) pred_class_ind = torch.argmax(prediction).item() pred_class = IND_TO_CLASS[pred_class_ind] prediction = prediction.numpy() true_class = beat_dict['beat_type'] logging.info("predicted class: {}\t\t\t gt class: {}".format(pred_class, true_class)) logging.info("Scores:\t N: {}\t\t\t S: {}\t\t\t V: {}\t\t\t F: {}\t\t\t Q: {}".format(prediction[0], prediction[1], prediction[2], prediction[3], prediction[4])) plt.figure() plt.plot(beat_dict['cardiac_cycle']) plt.xlabel('Sample # (360 HZ)') plt.ylabel('Voltage') plt.savefig('temp.png') img = cv2.imread('temp.png', cv2.IMREAD_UNCHANGED) font = cv2.FONT_HERSHEY_SIMPLEX pt_print = "Patient: {}".format(patient_number) true_class_print = "Ground truth beat: {}".format(true_class) prdicted_beat_print = "Prediction: {}".format(pred_class) scores_print = "Scores: N: {:.2f} S: {:.2f} V: {:.2f} F: {:.2f} Q: {:.2f}".format(prediction[0], prediction[1], prediction[2], prediction[3], prediction[4]) beat_num_print = "Beat #{}".format(i) truce_class_color = CLASS_TO_COLOR[true_class] pred_class_color = CLASS_TO_COLOR[pred_class] cv2.putText(img, pt_print, (300, 30), font, 0.5, (0, 0, 0), 1, cv2.LINE_AA) cv2.putText(img, true_class_print, (10, 30), font, 0.5, truce_class_color, 1, cv2.LINE_AA) cv2.putText(img, prdicted_beat_print, (500, 30), font, 0.5, pred_class_color, 1, cv2.LINE_AA) cv2.putText(img, scores_print, (84, 70), font, 0.32, (0, 0, 255), 1, cv2.LINE_AA) cv2.putText(img, beat_num_print, (10, 450), font, 0.5, (0, 0, 0), 1, cv2.LINE_AA) out.write(img) plt.close() plt.clf() out.release() class ECGInferenceOneVsAll(object): def __init__(self, beat_type, model, model_chk, patient_number): """Initialize a new ECGInferenceOneVsAll object. :param beat_type: The the of beat which is classified. :param model: The network object without the loaded weights. :param model_chk: path to checkpoint file with weight values. :param patient_number: string - number of patient from the mit-bih dataset. """ self.beat_type = beat_type self.model = model self.model_chk = model_chk self.patient_number = patient_number def predict(self): """Returns probability predictions from an ECG signal of a patient.""" logging.info("Inference model {} Vs. all".format(self.beat_type)) p = patient.Patient(self.patient_number) heartbeats = p.heartbeats checkpoint = torch.load(self.model_chk, map_location='cpu') self.model.load_state_dict(checkpoint['net']) self.model.eval() softmax = torch.nn.Softmax() predictions = [] ground_truths_one_hot = [] ground_truths_class_str = [] classes_ind = [] predicted_classes_str = [] cardiac_cycles = [] with torch.no_grad(): for i, beat_dict in enumerate(tqdm.tqdm(heartbeats)): # logging.info("beat # {}".format(beat_dict['beat_ind'])) beat = torch.Tensor(beat_dict['cardiac_cycle']) cardiac_cycles.append(beat.numpy()) model_output = self.model(beat) output_probability = softmax(model_output) predicted_class_ind = torch.argmax(output_probability).item() if predicted_class_ind == 1: predicted_class_str = 'Other' else: predicted_class_str = self.beat_type output_probability = output_probability.numpy() # logging.info("prediction: {}\t ground truth: {}".format(prediction, beat_dict['aami_label_str'])) predictions.append([output_probability[0][0], output_probability[0][1]]) classes_ind.append(predicted_class_ind) predicted_classes_str.append(predicted_class_str) if beat_dict['aami_label_str'] == self.beat_type: ground_truths_one_hot.append([1, 0]) ground_truths_class_str.append("{}".format(self.beat_type)) else: ground_truths_one_hot.append([0, 1]) ground_truths_class_str.append("Other") return ground_truths_one_hot, predictions, classes_ind, predicted_classes_str, cardiac_cycles, \ ground_truths_class_str def inference_summary_df(self): ground_truths, predictions, classes_ind, predicted_classes_str, cardiac_cycles, ground_truths_class_str = \ self.predict() df = pd.DataFrame(list(zip(ground_truths, predictions, classes_ind, predicted_classes_str, ground_truths_class_str)), columns=['Ground Truth', 'Predictions', 'predicted class index', 'predicted class str', 'ground truth class str']) return df def inference_one_vs_all(beat_type, model, model_chk, patient_number): """Returns probability predictions from an ECG signal of a patient. :param beat_type: The the of beat which is classified. :param model: The network object without the loaded weights. :param model_chk: path to checkpoint file with weight values. :param patient_number: string - number of patient from the mit-bih dataset. :return: """ logging.info("Inference model {} Vs. all".format(beat_type)) p = patient.Patient(patient_number) heartbeats = p.heartbeats checkpoint = torch.load(model_chk, map_location='cpu') model.load_state_dict(checkpoint['net']) model.eval() softmax = torch.nn.Softmax() predictions = [] ground_truths = [] with torch.no_grad(): for i, beat_dict in enumerate(tqdm.tqdm(heartbeats)): # logging.info("beat # {}".format(beat_dict['beat_ind'])) beat = torch.Tensor(beat_dict['cardiac_cycle']) prediction = model(beat) prediction = softmax(prediction) prediction = prediction.numpy() # logging.info("prediction: {}\t ground truth: {}".format(prediction, beat_dict['aami_label_str'])) predictions.append([prediction[0][0], prediction[0][1]]) if beat_dict['aami_label_str'] == beat_type: ground_truths.append([1, 0]) else: ground_truths.append([0, 1]) return predictions, ground_truths def predictions_ground_truths_data_frame(beat_type, model, model_chk, patient_number): """Returns pandas dataframe of probability predictions from an ECG signal of a patient. :param beat_type: The the of beat which is classified. :param model: The network object without the loaded weights. :param model_chk: path to checkpoint file with weight values. :param patient_number: string - number of patient from the mit-bih dataset. :return: """ predictions, ground_truths = inference_one_vs_all(beat_type, model, model_chk, patient_number) df = pd.DataFrame(list(zip(predictions, ground_truths)), columns=['Predictions', 'Ground Truth']) return df if __name__ == "__main__": logging.basicConfig(level=logging.INFO) # ff = fully_connected.FF() # model_chk = checkpoint_paths.FF_CHECKPOINT_PATH # eval_model(ff, model_chk, patient_number='117') model_chk = '/Users/tomer.golany/PycharmProjects/ecg_pytorch/ecg_pytorch/classifiers/tensorboard/s_resnet_raw_v2/vgan_1000/checkpoint_epoch_iters_2685' net = deep_residual_conv.Net(2) p = '100' # preds, gts = inference_one_vs_all('S', net, model_chk, p) # preds = np.array(preds) # gts = np.array(gts) # print(preds.shape) # print(gts.shape) # pred_gts_df = predictions_ground_truths_data_frame('S', net, model_chk, p) # print(pred_gts_df) ecg_inference = ECGInferenceOneVsAll('S', net, model_chk, p) print(ecg_inference.inference_summary_df())<file_sep>/ecg_pytorch/classifiers/inference/checkpoint_paths.py # # Fully connected # FF_CHECKPOINT_PATH = '/Users/tomer.golany/PycharmProjects/ecg_pytorch/ecg_pytorch/classifiers/tensorboard/fc_with_chk/checkpoint_epoch_iters_4024'
ca0439a8863bc6da35019fb042b5d61076b3a4c3
[ "Markdown", "Python" ]
48
Python
tomerGolany/ecg_pytorch
c6e481149a45ab9c944eeb6b4fc940fbe5bb6dbb
06bd7010cc5f1dc5ef8bf2cf9d767569fe38a004
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Media; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; using WMPLib; namespace MuzikCalar { public partial class Form1 : Form { public Form1() { InitializeComponent(); } XmlDocument doc = new XmlDocument(); int totalMusic = 0; int count = 0; int index; private void Form1_Load(object sender, EventArgs e) { GetRadio(); } /// <summary> /// XML den radyoları ve MMS adreslerini çeken method. /// </summary> void GetRadio() { //doc.Load("C:\\Users\\tugba\\Desktop\\radiodb.xml"); doc.Load(Application.StartupPath + "\\" + "radiodb.xml"); XmlElement root = doc.DocumentElement; XmlNodeList kayitlar = root.SelectNodes("/data/row"); foreach (XmlNode secilen in kayitlar) { ListViewItem lv = new ListViewItem(); lv.Text = secilen.Attributes["url"].InnerText; lv.SubItems.Add(secilen.Attributes["name"].InnerText); listView1.Items.Add(lv); } } void ListenRadio(string url) { axWindowsMediaPlayer1.URL = url; } private void listView1_SelectedIndexChanged(object sender, EventArgs e) { if (listView1.SelectedItems.Count > 0) { ListenRadio(listView1.SelectedItems[0].Text.ToString()); } } private void button2_Click(object sender, EventArgs e) { openFileDialog1.Filter = "Media File(*.mpg,*.dat,*.avi,*.wmv,*.wav,*.mp3)|*.wav;*.mp3;*.mpg;*.dat;*.avi;*.wmv"; //seçeceğimiz dosyalar arasında filtreleme yapar. //openFileDialog1.InitialDirectory = Application.StartupPath; //Debug klasöründen başlanılmasını sağlıyor. openFileDialog1.Title = "Dosya Seç"; openFileDialog1.RestoreDirectory = true;//En son açılan dizi gözata basıldığı zaman tekrar açılır. //openFileDialog1.ShowDialog(); openFileDialog1.CheckFileExists = false; if (openFileDialog1.ShowDialog().ToString() == "OK") { //çoklu seçim için string[] safefilenames = openFileDialog1.SafeFileNames; string[] filenames = openFileDialog1.FileNames; openFileDialog1.CheckFileExists = true; openFileDialog1.CheckPathExists = true; count = lstbilgisayar.Items.Count; //listviewdaki kolonlari sayiyoruz. for (int i = 0; i < filenames.Length; i++) { totalMusic++; lstbilgisayar.Items.Add(totalMusic.ToString()); lstbilgisayar.Items[i].SubItems.Add(safefilenames[i]); lstbilgisayar.Items[i].SubItems.Add(filenames[i]); } for (int i = 0; i < openFileDialog1.SafeFileNames.Length; i++) { lstbilgisayar.Items[count].SubItems.Add(openFileDialog1.SafeFileNames[i].ToString()); } lstbilgisayar.Items[count].SubItems.Add(openFileDialog1.FileName.ToString()); openFileDialog1.FileName = ""; } } private void lstbilgisayar_SelectedIndexChanged(object sender, EventArgs e) { try { if (lstbilgisayar.SelectedItems.Count > 0) { index = lstbilgisayar.SelectedItems[0].Index; RadyoCal(lstbilgisayar.Items[index].SubItems[2].Text); textBox1.Text ="Oynatılıyor: "+ " " + lstbilgisayar.Items[index].SubItems[1].Text; } } catch (Exception ex) { lstbilgisayar.SelectedItems[0].Remove(); //MessageBox.Show(ex.ToString()); } } private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e) { if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsStopped) { WMPLib.IWMPPlaylist playlist = axWindowsMediaPlayer1.playlistCollection.newPlaylist("myplaylist"); WMPLib.IWMPMedia media; for (int i = 0; i < lstbilgisayar.Items.Count; i++) { media = axWindowsMediaPlayer1.newMedia(lstbilgisayar.Items[i].SubItems[2].Text); playlist.appendItem(media); } axWindowsMediaPlayer1.currentPlaylist = playlist; axWindowsMediaPlayer1.settings.autoStart = true; axWindowsMediaPlayer1.Ctlcontrols.next(); axWindowsMediaPlayer1.Ctlcontrols.play(); } } } }
f5f02d427f1b46d3eadf60867b1063aafceb3580
[ "C#" ]
1
C#
devtgb/MuzikCalar
a55676d19d210e7bfd4bdd733b2868b868026bf6
97a77de874af6e2a5d5e507243ccabce811927d0
refs/heads/master
<repo_name>agentmishra/letsencrypt-cpanel-dnsonly<file_sep>/README.md # letsencrypt-cpanel-dnsonly [Please see the website](https://dnsonly.letsencrypt-for-cpanel.com). <file_sep>/website/Makefile .PHONY: all deploy all: deploy deploy: aws --profile=fleetssl-site --region=ap-southeast-2 s3 cp index.html s3://dnsonly.letsencrypt-for-cpanel.com/index.html aws --profile=fleetssl-site --region=ap-southeast-2 cloudfront create-invalidation --distribution-id E2X1H7N04P4UVF --paths "/index.html" "/" <file_sep>/certificate-hook.sh #!/usr/bin/env bash # This file is managed by the letsencrypt-cpanel-dnsonly package. Do not modify it, as your changes will be overwritten during upgrades. set -euf -o pipefail EVENT_NAME="$1" [ "$EVENT_NAME" = "live-updated" ] || exit 42 # Credit: https://stackoverflow.com/a/10660730/1327984 rawurlencode() { local string="${1}" local strlen=${#string} local encoded="" local pos c o for (( pos=0 ; pos<strlen ; pos++ )); do c=${string:$pos:1} case "$c" in [-_.~a-zA-Z0-9] ) o="${c}" ;; * ) printf -v o '%%%02x' "'$c" esac encoded+="${o}" done echo "${encoded}" # You can either set a return variable (FASTER) } ACME_PREFIX=/var/lib/acme/live/$(hostname) CRT=$(rawurlencode "$(cat ${ACME_PREFIX}/cert)") KEY=$(rawurlencode "$(cat ${ACME_PREFIX}/privkey)") CHAIN=$(rawurlencode "$(cat ${ACME_PREFIX}/chain)") /usr/sbin/whmapi1 install_service_ssl_certificate service=cpanel crt="${CRT}" key="${KEY}" cabundle="${CHAIN}" && /sbin/service cpanel restart (/usr/sbin/whmapi1 install_service_ssl_certificate service=dovecot crt="${CRT}" key="${KEY}" cabundle="${CHAIN}" && /sbin/service dovecot restart) || true (/usr/sbin/whmapi1 install_service_ssl_certificate service=exim crt="${CRT}" key="${KEY}" cabundle="${CHAIN}" && /sbin/service exim restart) || true <file_sep>/Makefile ACMETOOL_VER?=0.0.61 VER?=0.1.0 .PHONY: clean package all publish all: package package: clean acmetool @rm -rf fpm; mkdir fpm; cp certificate-hook.sh pre-install.sh post-install.sh acmetool responses.yml fpm/ chmod 0644 fpm/responses.yml chmod +x fpm/acmetool fpm/*.sh dos2unix fpm/*.sh fpm/responses.yml fpm -a amd64 -s dir -t rpm -n letsencrypt-cpanel-dnsonly -v $(VER) -C ./fpm/ --before-install fpm/pre-install.sh --after-install fpm/post-install.sh --prefix /usr/local/letsencrypt-cpanel-dnsonly --rpm-os Linux --url https://dnsonly.letsencrypt-for-cpanel.com -d bind-utils --conflicts acmetool --conflicts acmetool-nocgo @rm -rf fpm acmetool: rm -rf scratch; mkdir scratch; wget -O scratch/acmetool.tar.gz https://github.com/hlandau/acme/releases/download/v$(ACMETOOL_VER)/acmetool-v$(ACMETOOL_VER)-linux_amd64.tar.gz tar -C scratch/ --strip-components=1 -zxf scratch/acmetool.tar.gz mv scratch/bin/acmetool . rm -rf scratch publish: rsync -vhz --progress *.rpm <EMAIL>:/home/web/repo ssh <EMAIL> "createrepo --update /home/web/repo" clean: rm -rf *.rpm <file_sep>/post-install.sh #!/usr/bin/env bash set -euf -o pipefail DNSONLY_PREFIX=/usr/local/letsencrypt-cpanel-dnsonly # Hook goes in libexec if it exists, otherwise lib HOOK_PREFIX=/usr/lib/acme/hooks if [ -d "/usr/libexec" ]; then HOOK_PREFIX=/usr/libexec/acme/hooks fi mkdir -p ${HOOK_PREFIX} cp ${DNSONLY_PREFIX}/certificate-hook.sh ${HOOK_PREFIX}/ echo "!!! Please wait, configuring acmetool !!!" ${DNSONLY_PREFIX}/acmetool quickstart --response-file=${DNSONLY_PREFIX}/responses.yml echo "!!! Please wait, trying to issue certificate now !!!" ${DNSONLY_PREFIX}/acmetool want $(hostname) echo "Done." <file_sep>/pre-install.sh #!/usr/bin/env bash if [ ! -f "/usr/sbin/whmapi1" ]; then echo "Cannot find cPanel installed (whmapi1 command missing). FAILED."; exit 1; fi host $(hostname) if [ $? -ne 0 ]; then echo "Hostname '$(hostname)' doesn't seem to resolve, at least according to this server. The server hostname must be a FQDN and resolve on the internet before this package may be installed. Please see https://documentation.cpanel.net/display/ALD/Change+Hostname ." exit 1; fi
385e9d19c599041a2ef17661ca52f15529d9eb3b
[ "Markdown", "Makefile", "Shell" ]
6
Markdown
agentmishra/letsencrypt-cpanel-dnsonly
6b88aed24f3a66aa738fdbc4840aa286d7de3f6b
8384c43de70a88fcf18b4bd3c501e8945139873b
refs/heads/main
<file_sep>import Find from "./components/Find"; import "./styles/output.css" function App() { return ( <div className="App"> <Find /> </div> ); } export default App; <file_sep>import React, { useState } from "react"; import axios from "axios"; function Find() { const [persons, setPersons] = useState([]); const handleFind = async () => { await axios .get("https://randomuser.me/api") .then((res) => { console.log(res); setPersons([...persons, res.data.results[0]]); }) .catch((err) => console.log(err)); }; return ( <div className="md:min-w-screen md:min-h-screen bg-blue-300"> <h1 className="relative text-3xl mb-3 font-bold text-center"> Find International Friend </h1> <div className="flex justify-center items-center md:min-h-screen md:min-w-screen px-3"> <div className="grid grid-cols-5 gap-2"> {persons.map((person, idx) => { return ( <div key={idx} className="md:flex md:flex-col border-4 border-black w-full h-full md:p-5" > <img className="relative w-full" src={person.picture.large} alt="..." /> <span className="relative md:flex md:justify-center md:items-center my-2"> Phone: {person.cell} </span> <span className="relative md:flex md:justify-center md:items-center my-2"> Name: {person.name.first} </span> <span className="relative md:flex md:justify-center md:items-center my-2"> Country: {person.location.country} </span> </div> ); })} </div> </div> <div className="md:flex md:justify-center md:items-center"> <button className="md:bg-red-400 md:rounded-lg md:px-5 md:py-2 md:m-3" onClick={handleFind} > Find </button> <button className="md:bg-red-400 md:rounded-lg md:px-5 md:py-2 md:m-3" onClick={() => setPersons([])} > Reset </button> </div> </div> ); } export default Find;
6a0f9e2f1bd50a8b7456f3e8c4d5f348ac27304e
[ "JavaScript" ]
2
JavaScript
Dmaul0906/findFriend
ff2ca4c1ca8c4c3e64dfac0bc395f7754ae041d3
1531026b8a20333220b26e5a129c6df30189b430
refs/heads/master
<repo_name>ColaStar/blogs<file_sep>/REARDME.md ## linux、mc启动项目 npm start ## windows启动项目 npm start:w ## 打包文件 npm run build ## 本地运行 npm run dev <file_sep>/static.sh cd static npm start
e51116caaade7b95a6a7a5676d0ace1e8ef96938
[ "Markdown", "Shell" ]
2
Markdown
ColaStar/blogs
28718e4e9c1efa17e7f71c32c2712cac5f65075d
493f795914787ec7a9995ff76cdd001983555066
refs/heads/master
<repo_name>corbettbain/maven_ynjp_api<file_sep>/src/main/face/com/face/service/FaceVisa.java package com.face.service; import com.face.config.Constants; import com.face.util.ToolUtils; import com.jishi.entity.ReturnInfo; import net.sf.json.JSONObject; import org.apache.commons.codec.Charsets; import org.apache.http.HttpEntity; import org.apache.http.client.entity.EntityBuilder; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MIME; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.util.HashMap; import java.util.Map; public class FaceVisa { private static String PHOTO_DIR; // TODO 填上你的appid和appkey private static final String appid = "21244644"; private static final String appkey = "<KEY>"; /** * 人脸上传 * * * */ public static ReturnInfo upFacePhoto(String personid,String dir,String img) throws Exception { ReturnInfo re = new ReturnInfo(); String body = test2_2_03(personid,dir,img); JSONObject obj= JSONObject.fromObject(body); //{"faceid":73030} String faceid=null; if(body.indexOf("faceid")>0) faceid = obj.getString("faceid"); if( faceid==null || faceid.length()<1 ) { re.setFlag(-1); re.setMessage("人脸上传失败"); return re; } re.setFlag(1); re.setMessage(faceid); return re; } /** * 2.07 人员人脸比对 * @param personid 人员ID(由2.1接口返回) * @param img 人脸照片 * @throws Exception */ public static String test2_2_07(String personid, String img) throws Exception { String re = ""; Map<String, String> params = new HashMap<String, String>(); params.put("client_id", appid); params.put("timestamp", ToolUtils.getTimestamp()); params.put("personid", personid); params.put("sign", ToolUtils.sign(appkey, params)); byte[] data = ToolUtils.getFileData(PHOTO_DIR, img); StringBuilder builder = new StringBuilder(Constants.HOST); builder.append(Constants.A207).append("?"); for (Map.Entry<String, String> entry : params.entrySet()) { builder.append(entry.getKey()).append('=').append(entry.getValue()).append('&'); } CloseableHttpClient client = HttpClients.createDefault(); HttpUriRequest request = RequestBuilder.post(builder.toString()) .setEntity(EntityBuilder.create().setBinary(data).build()) .build(); request.setHeader(MIME.CONTENT_TYPE, "image/jpeg"); CloseableHttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity); //System.out.println(body); re = body; } else { //System.out.println(statusCode); re = String.valueOf(statusCode); } response.close(); client.close(); return re; } /** * 2.07 人员人脸比对 * @param personid 人员ID(由2.1接口返回) * @param img 人脸照片 * @throws Exception */ public static String test2_2_07(String personid, byte[] img) throws Exception { String re = ""; Map<String, String> params = new HashMap<String, String>(); params.put("client_id", appid); params.put("timestamp", ToolUtils.getTimestamp()); params.put("personid", personid); params.put("sign", ToolUtils.sign(appkey, params)); byte[] data = img; System.err.println(img.length); StringBuilder builder = new StringBuilder(Constants.HOST); builder.append(Constants.A207).append("?"); for (Map.Entry<String, String> entry : params.entrySet()) { builder.append(entry.getKey()).append('=').append(entry.getValue()).append('&'); } CloseableHttpClient client = HttpClients.createDefault(); HttpUriRequest request = RequestBuilder.post(builder.toString()) .setEntity(EntityBuilder.create().setBinary(data).build()) .build(); request.setHeader(MIME.CONTENT_TYPE, "image/jpeg"); CloseableHttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity); //System.out.println(body); re = body; } else { //System.out.println(statusCode); re = String.valueOf(statusCode); } response.close(); client.close(); return re; } /** * 2.03 添加人脸照片 * @param personid 人员ID(由2.1接口返回) * @param dir 人脸姿态(0-未知,1-正脸,2-朝上,3-朝下,4-朝左,5-朝右;默认为0) * @param img 人脸照片 * @throws Exception */ public static String test2_2_03(String personid, String dir, String img) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("client_id", appid); params.put("timestamp", ToolUtils.getTimestamp()); params.put("personid", personid); params.put("dir", dir); params.put("sign", ToolUtils.sign(appkey, params)); byte[] data = ToolUtils.getFileData(PHOTO_DIR, img); StringBuilder builder = new StringBuilder(Constants.HOST); builder.append(Constants.A203).append("?"); for (Map.Entry<String, String> entry : params.entrySet()) { builder.append(entry.getKey()).append('=').append(entry.getValue()).append('&'); } CloseableHttpClient client = HttpClients.createDefault(); HttpUriRequest request = RequestBuilder.post(builder.toString()) .setEntity(EntityBuilder.create().setBinary(data).build()) .build(); request.setHeader(MIME.CONTENT_TYPE, "image/jpeg"); CloseableHttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); String body = ""; if (statusCode == 200) { HttpEntity entity = response.getEntity(); body = EntityUtils.toString(entity); //System.out.println(body); } else { //System.out.println(statusCode); body = String.valueOf(statusCode); } response.close(); client.close(); return body; } /** * 2.17 基础人脸比对二 * @param img1 人脸照片1 * @param img2 人脸照片2 * @throws Exception */ public static String test2_2_17(byte[] img1, byte[] img2) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("client_id", appid); params.put("timestamp", ToolUtils.getTimestamp()); params.put("sign", ToolUtils.sign(appkey, params)); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Map.Entry<String, String> entry : params.entrySet()) { builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.MULTIPART_FORM_DATA); } // 添加图片数据 byte[] image_1 = img1; byte[] image_2 = img2; builder.addBinaryBody("image_1", image_1, ContentType.create("image/jpeg"), "image_1"); builder.addBinaryBody("image_2", image_2, ContentType.create("image/jpeg"), "image_2"); HttpEntity requestEntity = builder.build(); HttpPost request = new HttpPost(Constants.HOST + Constants.A217); request.setEntity(requestEntity); CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(request); String body = ""; int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); body = EntityUtils.toString(entity, "utf-8"); } else { body = "人脸服务器异常"; } response.close(); client.close(); return body; } /** * 2.01 添加人员记录 */ public static String getPersonId() throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("client_id", appid); params.put("timestamp", ToolUtils.getTimestamp()); params.put("sign", ToolUtils.sign(appkey, params)); RequestBuilder builder = RequestBuilder.post(Constants.HOST + Constants.A201); for (Map.Entry<String, String> entry : params.entrySet()) { builder.addParameter(entry.getKey(), entry.getValue()); } builder.setCharset(Charsets.UTF_8); HttpUriRequest request = builder.build(); CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity, "utf-8"); response.close(); client.close(); return body; } else { response.close(); client.close(); return statusCode+""; } } } <file_sep>/src/main/java/com/jishi/service/impl/PushPayment.java package com.jishi.service.impl; import java.io.IOException; import java.util.Map; import com.corbett.enums.RequestMethod; import com.corbett.utils.http.HttpClient; import com.jiaquwork.util.DataCenterAPI; import com.jishi.dao.PushdataPaymentDao; import com.jishi.entity.datacenter.Payment; import com.jishi.service.AbstractPushData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component("PushPayment") public class PushPayment extends AbstractPushData { @Autowired private PushdataPaymentDao pushdataPaymentDao; @Override protected String getData(Map<String, Object> object) throws IOException { return HttpClient.getUrlData(DataCenterAPI.API_SEND_PAYMENT, object, RequestMethod.PUT, HttpClient.getRequestHeader()); } @Override protected void insert(Object object) { if(object instanceof Payment) pushdataPaymentDao.insert(object); } } <file_sep>/src/main/java/com/jishi/entity/Coach.java package com.jishi.entity; public class Coach { private String coachnum; private String name; private String inscode; public String getCoachnum() { return coachnum; } public void setCoachnum(String coachnum) { this.coachnum = coachnum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getInscode() { return inscode; } public void setInscode(String inscode) { this.inscode = inscode; } } <file_sep>/src/main/java/com/jishi/service/impl/Mine_coachService.java package com.jishi.service.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jishi.dao.DaoSupport; import com.jishi.entity.Coach_account; import com.jishi.entity.Coach_order; @Service(value="Mine_coachService") @Transactional(rollbackFor=Exception.class) public class Mine_coachService { @Resource(name = "daoSupport") private DaoSupport dao; public List<Coach_order> getCoachPay(Coach_order coach_order) throws Exception { return ( List<Coach_order>)dao.findForList("Mine_coachMapper.getCoachPay", coach_order); } public int getCoachInfo(Coach_order coach_order) throws Exception { return (Integer)dao.findForObject("Mine_coachMapper.getCoachInfo", coach_order); } public int getPayPage(Coach_order coach_order) throws Exception { return (Integer)dao.findForObject("Mine_coachMapper.getPayPage", coach_order); } public Map getCoachAmount(Coach_order coach_order) throws Exception { return (Map)dao.findForObject("Mine_coachMapper.getCoachAmount", coach_order); } public Coach_account getUserInfo(Coach_order coach_order) throws Exception { return (Coach_account)dao.findForObject("Mine_coachMapper.getUserInfo", coach_order); } public int setUserInfo(Coach_account coach_account) throws Exception { return (Integer)dao.update("Mine_coachMapper.setUserInfo", coach_account); } public int checkPassword(Map parameter) throws Exception { return (Integer)dao.findForObject("Mine_coachMapper.checkPassword", parameter); } public int updatePassword(Map parameter) throws Exception { return (Integer)dao.update("Mine_coachMapper.updatePassword", parameter); } public Map getServicePay(Map parameter) throws Exception { return (Map)dao.findForObject("Mine_coachMapper.getServicePay", parameter); } public Map checkCoachAmount(Map parameter) throws Exception { return (Map)dao.findForObject("Mine_coachMapper.checkCoachAmount", parameter); } public int addCoachTakeMoney(Map parameter) throws Exception { return (Integer)dao.save("Mine_coachMapper.addCoachTakeMoney", parameter); } public int changeOrderStatus(Map parameter) throws Exception { return (Integer)dao.update("Mine_coachMapper.changeOrderStatus", parameter); } public int addPayRecord(Map parameter) throws Exception { return (Integer)dao.save("Mine_coachMapper.addPayRecord", parameter); } public int updateCoachAmount(Map parameter) throws Exception { return (Integer)dao.update("Mine_coachMapper.updateCoachAmount", parameter); } } <file_sep>/src/main/java/com/jishi/service/impl/PushCoachStatusImpl.java package com.jishi.service.impl; import com.corbett.entity.ReturnMessage; import com.corbett.utils.spring.SpringContextUtil; import com.jishi.dao.PushdataCoachStatusDao; import com.jishi.entity.datacenter.CoachStatus; import com.jishi.entity.datacenter.view.CoachStatusview; import com.jishi.enums.PushDataType; import com.jishi.service.AbstractPushDatasService; import com.jishi.service.PushData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * Created by IntelliJ IDEA. * User: corbettbain * Date: 2017/7/7 * Time: 17:00 */ @Service("PushCoachStatusImpl") public class PushCoachStatusImpl extends AbstractPushDatasService{ @Autowired private PushdataCoachStatusDao pushdataCoachStatusDao; @Override protected List<?> select() { return pushdataCoachStatusDao.selectAll(); } @Override protected void delete(Integer integer) { pushdataCoachStatusDao.delete(integer); } @Override protected PushDataType getPushDataType() { return PushDataType.PushCoachStatus; } } <file_sep>/src/main/java/com/jishi/controller/LateplanControlle.java package com.jishi.controller; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.jishi.dao.DaoSupport; import com.jishi.entity.CoachInfo; import com.jishi.entity.Editlateplan; import com.jishi.entity.StulateplanInfo; import com.jishi.entity.lateplanInfo; import com.jishi.entity.view.ViewSelectstu; import com.jishi.entity.view.ViewStulate; import com.jishi.entity.view.Viewhaslatestu; import com.jishi.entity.view.Viewlateplan; import com.jishi.service.CoachLoginService; import com.jishi.service.LateplanService; import com.jishi.service.PushData; import com.jishi.service.RegionService; import com.jishi.service.TrainService; import com.jishi.until.ReturnMessage; import com.jishi.until.ReturnMessageList; import com.jishi.until.ReturnMessagePage; import com.jishi.until.ReturnMessage_entity; import com.jishi.until.ReturnlateplanInfo; import com.jishi.until.Tools; @Controller @RequestMapping(value = "/lateplan") public class LateplanControlle { @Resource(name = "CoachLoginService") CoachLoginService coachLoginService; @Resource(name = "LateplanService") LateplanService lateplanService; @Resource(name = "TrainService") TrainService trainService; // 我的排班 @RequestMapping(value = "/my_schedule ", method = RequestMethod.GET) @ResponseBody public ReturnMessageList<Viewlateplan> my_schedule(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "date", required = true) String date, @RequestParam(value = "token", required = true) String token) throws Exception { // Date d = DateUtil.fomatDate(date); ReturnMessageList<Viewlateplan> RM = new ReturnMessageList<Viewlateplan>(); ReturnMessage_entity<CoachInfo> RMcheck = coachLoginService.checktoken(token); if (RMcheck.getFlag() != 1) { RM.setFlag(RMcheck.getFlag()); RM.setMessage(RMcheck.getMessage()); return RM; } CoachInfo coachInfo = RMcheck.getData(); try { coachInfo.setDate(date); List<Viewlateplan> list = lateplanService.getlateplanlst(coachInfo); RM.setFlag(1); RM.setMessage("成功"); RM.setData(list); return RM; } catch (Exception e) { RM.setFlag(-1); RM.setMessage("服务器正在维护"); return RM; } } // 发布新课程 @RequestMapping(value = "/new_curriculum", method = RequestMethod.POST) @ResponseBody public ReturnMessage Edit(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, Editlateplan lateplan) throws Exception { ReturnMessage RM = new ReturnMessage(); try { ReturnMessage_entity<CoachInfo> RMcheck = coachLoginService.checktoken(token); if (RMcheck.getFlag() != 1) { RM.setFlag(RMcheck.getFlag()); RM.setMessage(RMcheck.getMessage()); return RM; } CoachInfo coachInfo = RMcheck.getData(); return lateplanService.new_curriculum(lateplan, coachInfo); } catch (Exception e) { System.err.println(e.getMessage()); RM.setFlag(-1); RM.setMessage("服务器正在维护"); return RM; } } // 课程详情 @RequestMapping(value = "/course_details ", method = RequestMethod.GET) @ResponseBody public ReturnlateplanInfo latepalanInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "plannum", required = true) String plannum, @RequestParam(value = "part", required = true) int part, @RequestParam(value = "token", required = true) String token) throws Exception { // Date d = DateUtil.fomatDate(date); ReturnlateplanInfo RM = new ReturnlateplanInfo(); ReturnMessage_entity<CoachInfo> RMcheck = coachLoginService.checktoken(token); if (RMcheck.getFlag() != 1) { RM.setFlag(RMcheck.getFlag()); RM.setMessage(RMcheck.getMessage()); return RM; } CoachInfo coachInfo = RMcheck.getData(); lateplanInfo check = lateplanService.getlateplanInfo(plannum); if (!check.getCoachnum().equals(coachInfo.getCoachNum())) { RM.setFlag(-1); RM.setMessage("没有操作权限"); return RM; } try { lateplanInfo info = new lateplanInfo(); info.setPlannum(plannum); info.setCoachnum(coachInfo.getCoachNum()); List<ViewStulate> list = new ArrayList<ViewStulate>(); if (part == 21) { list = lateplanService.getstulatebysubject2(info); } if (part == 31) { list = lateplanService.getstulatebysubject3(info); } RM.setFlag(1); RM.setMessage("成功"); RM.sethaveapplynumber(check.getHaveapplynumber()); RM.setData(list); return RM; } catch (Exception e) { System.err.println(e.getMessage()); RM.setFlag(-1); RM.setMessage("服务器正在维护"); return RM; } } // 选择学员 @RequestMapping(value = "/select_stu", method = RequestMethod.GET) @ResponseBody public ReturnMessagePage<ViewSelectstu> selectstu(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "plannum", required = true) String plannum, @RequestParam(value = "part", required = true) int part, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "page", required = true) int page, String name) throws Exception { // Date d = DateUtil.fomatDate(date); ReturnMessagePage<ViewSelectstu> RM = new ReturnMessagePage<ViewSelectstu>(); ReturnMessage_entity<CoachInfo> RMcheck = coachLoginService.checktoken(token); if (RMcheck.getFlag() != 1) { RM.setFlag(RMcheck.getFlag()); RM.setMessage(RMcheck.getMessage()); return RM; } CoachInfo coachInfo = RMcheck.getData(); try { lateplanInfo info = new lateplanInfo(); info.setPlannum(plannum); info.setCoachnum(coachInfo.getCoachNum()); info.setName(name); // 如果中文乱码转码 if (Tools.isMessyCode(info.getName())) { info.setName(Tools.strutf(info.getName())); } int start = (page - 1) * 10; info.setPagestart(start); info.setPagesize(10); List<ViewSelectstu> list = new ArrayList<ViewSelectstu>(); int totalPage = 0; if (part == 21) { totalPage = lateplanService.getcoachsubject2stucount(info); if (totalPage != 0) { list = lateplanService.getcoachsubject2stu(info); } } if (part == 31) { totalPage = lateplanService.getcoachsubject2stucount(info); if (totalPage != 0) { list = lateplanService.getcoachsubject3stu(info); } } RM.setFlag(1); RM.setTotalpage(totalPage); RM.setMessage("获取成功"); RM.setData(list); return RM; } catch (Exception e) { System.err.println(e.getMessage()); RM.setFlag(-1); RM.setMessage("服务器正在维护"); return RM; } } @Resource(name = "daoSupport") private DaoSupport dao; @Resource(name = "PushDataImpl") private PushData pushData; // 取消课程 @RequestMapping(value = "/cancel_course ", method = RequestMethod.POST) @ResponseBody public ReturnMessage canellate(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "plannum", required = true) String plannum) throws Exception { // Date d = DateUtil.fomatDate(date); ReturnMessage RM = new ReturnMessage(); ReturnMessage_entity<CoachInfo> RMcheck = coachLoginService.checktoken(token); if (RMcheck.getFlag() != 1) { RM.setFlag(RMcheck.getFlag()); RM.setMessage(RMcheck.getMessage()); return RM; } CoachInfo coachInfo = RMcheck.getData(); lateplanInfo check = lateplanService.getlateplanInfo(plannum); if (check.getHaveapplynumber() > 0) { RM.setFlag(-1); RM.setMessage("当前时段已有人预约,不可取消"); return RM; } if (!check.getCoachnum().equals(coachInfo.getCoachNum())) { RM.setFlag(-1); RM.setMessage("没有操作权限"); return RM; } try { int n = lateplanService.deletelateplan(plannum); if (n > 0) { // @SuppressWarnings("unchecked") // List<lateplanInfo> lateplanInfos = (List<lateplanInfo>) dao // .findForList("lateplanMapper.getLateplanIscount", // coachInfo.getCoachNum()); // for (lateplanInfo lateplanInfo : lateplanInfos) { // String inst_code = lateplanInfo.getInscode(); // String coach_num = lateplanInfo.getCoachnum(); // // CoachStatusview coachStatus = new CoachStatusview(inst_code, // coach_num, 1, lateplanInfo.getStartdate(), // null); // // com.corbett.entity.ReturnMessage returnMessage = // pushData.push(PushDataType.PushCoachStatus, // ObjectMap.transBean2Map(coachStatus)); // if (returnMessage.getFlag() != 1) { // throw new CorbettException("上报教练可预约状态失败"); // } // } RM.setFlag(1); RM.setMessage("课程取消成功"); } else { RM.setFlag(-1); RM.setMessage("课程取消失败"); } return RM; } catch (Exception e) { System.err.println(e.getMessage()); RM.setFlag(-1); RM.setMessage("服务器正在维护"); return RM; } } // 接受预约 @RequestMapping(value = "/accept_appointment ", method = RequestMethod.POST) @ResponseBody public ReturnMessage accept(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "simunum", required = true) String simunum) throws Exception { // Date d = DateUtil.fomatDate(date); ReturnMessage RM = new ReturnMessage(); ReturnMessage_entity<CoachInfo> RMcheck = coachLoginService.checktoken(token); if (RMcheck.getFlag() != 1) { RM.setFlag(RMcheck.getFlag()); RM.setMessage(RMcheck.getMessage()); return RM; } CoachInfo coachInfo = RMcheck.getData(); StulateplanInfo info = lateplanService.getstulateplanInfo(simunum); if (info.getStatus() == 1) { RM.setFlag(-1); RM.setMessage("已生效订单,请勿重复提交"); return RM; } // lateplanInfo check = // lateplanService.getlateplanInfo(info.getPlannum()); // if(check.getHaveapplynumber() >=check.getCanapplynumber()) // { // RM.setFlag(-1); // RM.setMessage("当前时段预约人数已满"); // return RM; // } try { info.setSimuNum(simunum); info.setStatus(1); info.setCoachnum(coachInfo.getCoachNum()); int n = lateplanService.updatestudentsimulate(info); if (n > 0) { RM.setFlag(1); RM.setMessage("接受成功"); } else { RM.setFlag(-1); RM.setMessage("接受失败"); } return RM; } catch (Exception e) { System.err.println(e.getMessage()); RM.setFlag(-1); RM.setMessage("服务器正在维护"); return RM; } } // 取消预约 @RequestMapping(value = "/cancel_reservation ", method = RequestMethod.POST) @ResponseBody public ReturnMessage canelstulate(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "simunum", required = true) String simunum) throws Exception { // Date d = DateUtil.fomatDate(date); ReturnMessage RM = new ReturnMessage(); ReturnMessage_entity<CoachInfo> RMcheck = coachLoginService.checktoken(token); if (RMcheck.getFlag() != 1) { RM.setFlag(RMcheck.getFlag()); RM.setMessage(RMcheck.getMessage()); return RM; } CoachInfo coachInfo = RMcheck.getData(); int cek = lateplanService.checkIspractice(simunum); if (cek > 0) { RM.setFlag(-1); RM.setMessage("预约订单已经使用,不可取消"); return RM; } StulateplanInfo check = lateplanService.getstulateplanInfo(simunum); if (check.getStatus() == -1) { RM.setFlag(-1); RM.setMessage("已失效订单,请勿重复提交"); return RM; } try { StulateplanInfo info = new StulateplanInfo(); info.setSimuNum(simunum); info.setCancelperson(1); info.setStatus(-1); info.setCoachnum(coachInfo.getCoachNum()); return lateplanService.cancel_reservation(coachInfo.getCoachNum(), check.getPlannum(), info); } catch (Exception e) { System.err.println(e.getMessage()); RM.setFlag(-1); RM.setMessage("服务器正在维护"); return RM; } } @RequestMapping(value = "/Invite_stu", method = RequestMethod.POST) @ResponseBody public ReturnMessage invitation(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "stunum", required = true) String stunum, @RequestParam(value = "plannum", required = true) String plannum) throws Exception { // Date d = DateUtil.fomatDate(date); ReturnMessage RM = new ReturnMessage(); ReturnMessage_entity<CoachInfo> RMcheck = coachLoginService.checktoken(token); if (RMcheck.getFlag() != 1) { RM.setFlag(RMcheck.getFlag()); RM.setMessage(RMcheck.getMessage()); return RM; } CoachInfo coachInfo = RMcheck.getData(); String[] stunumary = stunum.split(","); lateplanInfo check = lateplanService.getlateplanInfo(plannum); if (check.getHaveapplynumber() + stunumary.length > check.getCanapplynumber()) { RM.setFlag(-1); RM.setMessage("当前邀请人数超过最大预约限度,当前最多还可邀请" + (check.getCanapplynumber() - check.getHaveapplynumber()) + "人"); return RM; } if (!check.getCoachnum().equals(coachInfo.getCoachNum())) { RM.setFlag(-1); RM.setMessage("没有操作权限"); return RM; } if (check.getStatus() == 0) { RM.setFlag(-1); RM.setMessage("该订单暂未发布不可操作"); return RM; } try { return lateplanService.Invite_stu(check, stunumary, coachInfo.getCoachNum()); } catch (Exception e) { System.err.println(e.getMessage()); RM.setFlag(-1); RM.setMessage("服务器正在维护"); return RM; } } // @RequestMapping(value = "/haslatelst", method = RequestMethod.GET) @ResponseBody public ReturnMessagePage<Viewhaslatestu> selectstu(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "page", required = true) int page) throws Exception { // Date d = DateUtil.fomatDate(date); ReturnMessagePage<Viewhaslatestu> RM = new ReturnMessagePage<Viewhaslatestu>(); ReturnMessage_entity<CoachInfo> RMcheck = coachLoginService.checktoken(token); if (RMcheck.getFlag() != 1) { RM.setFlag(RMcheck.getFlag()); RM.setMessage(RMcheck.getMessage()); return RM; } CoachInfo coachInfo = RMcheck.getData(); try { lateplanInfo info = new lateplanInfo(); int start = (page - 1) * 10; info.setPagestart(start); info.setCoachnum(coachInfo.getCoachNum()); info.setPagesize(10); List<Viewhaslatestu> list = new ArrayList<Viewhaslatestu>(); int totalPage = lateplanService.gethaslatestuCount(coachInfo.getCoachNum()); if (totalPage != 0) { list = lateplanService.gethaslatestu(info); } RM.setFlag(1); RM.setTotalpage(totalPage); RM.setMessage("获取成功"); RM.setData(list); return RM; } catch (Exception e) { System.err.println(e.getMessage()); RM.setFlag(-1); RM.setMessage("服务器正在维护"); return RM; } } @Resource(name = "RegionServiceImpl") private RegionService regionService; @RequestMapping(value = "getRegion", method = RequestMethod.GET) @ResponseBody public ReturnMessage getRegion(@RequestParam(value = "token", required = true) String token) { ReturnMessage returnMessage = new ReturnMessage(); try { ReturnMessage_entity<CoachInfo> RMcheck = coachLoginService.checktoken(token); if (RMcheck.getFlag() != 1) { returnMessage.setFlag(RMcheck.getFlag()); returnMessage.setMessage(RMcheck.getMessage()); return returnMessage; } CoachInfo coachInfo = RMcheck.getData(); returnMessage.setData(regionService.getRegion(coachInfo.getInsCode())); returnMessage.setFlag(1); returnMessage.setMessage("success"); return returnMessage; } catch (Exception e) { returnMessage.setFlag(-1); returnMessage.setMessage("服务器正在升级"); return returnMessage; } } } <file_sep>/src/main/java/com/jishi/entity/SubjectHour.java package com.jishi.entity; import java.sql.Timestamp; public class SubjectHour { private int id;//自增编号 private String Inscode;//培训机构编号 private String Perdritype;//培训车型 private int Subject;//科目 private float SubjectHours;//目标学时 private float HourPrice;//小时单价 private float DisposablePrice;//一次性价格 private Timestamp CreateDate;//创建时间 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getInscode() { return Inscode; } public void setInscode(String inscode) { Inscode = inscode; } public String getPerdritype() { return Perdritype; } public void setPerdritype(String perdritype) { Perdritype = perdritype; } public int getSubject() { return Subject; } public void setSubject(int subject) { Subject = subject; } public float getSubjectHours() { return SubjectHours; } public void setSubjectHours(float subjectHours) { SubjectHours = subjectHours; } public float getHourPrice() { return HourPrice; } public void setHourPrice(float hourPrice) { HourPrice = hourPrice; } public float getDisposablePrice() { return DisposablePrice; } public void setDisposablePrice(float disposablePrice) { DisposablePrice = disposablePrice; } public Timestamp getCreateDate() { return CreateDate; } public void setCreateDate(Timestamp createDate) { CreateDate = createDate; } } <file_sep>/src/main/java/com/jishi/dao/zstu/UserInFoChange.java package com.jishi.dao.zstu; /** * 用户信息更新插入删除公共接口 * @author 周宁 - 2017年4月12日 - 下午5:31:33 项目:ynjp_api 包名:com.jishi.service.zstu * */ public interface UserInFoChange { /** * 根据用户实体插入操作 * @param object 教练- ;学员-StudentInfo 或者 登入信息 stidentlogin * @return * @throws Exception */ boolean insertUserInFo(Object object) throws Exception; /** * 根据用户编号删除信息 * @param number * @return */ boolean deleteUserInFoByNumber(String number) throws Exception; /** * 根据用户IC卡号删除信息 * @param number * @return */ boolean deleteUserInFoByIcCard(String icCard) throws Exception; /** * 根据用户身份证号删除信息 * @param number * @return */ boolean deleteUserInFoByidCard(String idCard) throws Exception; /** * 根据用户手机号删除信息 * @param number * @return */ boolean deleteUserInFoByPhoneNumber(String phoneNumber) throws Exception; /** * 根据用户登入token删除信息 * @param number * @return */ boolean deleteUserInFoByToken(String token) throws Exception; } <file_sep>/src/main/java/com/jishi/controller/CommentController.java package com.jishi.controller; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.jishi.entity.CoachInfo; import com.jishi.entity.CommentInfo; import com.jishi.entity.StudentInfo; import com.jishi.service.ClassRecordService; import com.jishi.service.CommentService; import com.jishi.service.TrainService; import com.jishi.service.impl.UserService; import com.jishi.until.DateUtil; import com.jishi.until.ReturnMessage; import com.jishi.until.ReturnMessageList; import com.jishi.until.ReturnMessagePage; import com.jishi.until.ReturnMessage_entity; /* * 评语控制器 * */ @Controller @RequestMapping(value = "/comment") public class CommentController { @Resource(name = "CommentService") CommentService commentService; @Resource(name = "UserService") UserService userService; // 获取标签 @RequestMapping(value = "/getTips", method = RequestMethod.GET) @ResponseBody public ReturnMessageList<String> getTips(HttpServletRequest request, HttpServletResponse response) throws Exception { ReturnMessageList<String> R = new ReturnMessageList<String>(); try { List<String> data = commentService.getTips(); R.setFlag(1); R.setMessage("获取成功"); R.setData(data); return R; } catch (Exception e) { R.setFlag(-1); R.setMessage("服务器正在维护"); return R; } } // @RequestMapping(value = "/getComments", method = RequestMethod.GET) @ResponseBody public ReturnMessagePage<CommentInfo> getComments(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "page", required = true) int page, @RequestParam(value = "token", required = true) String token) { ReturnMessagePage<CommentInfo> Rm = new ReturnMessagePage<CommentInfo>(); try { ReturnMessage_entity<StudentInfo> R = trainService.checkOwn(token); if (R.getFlag() == -1) { Rm.setFlag(-3); Rm.setMessage(R.getMessage()); return Rm; } int start = (page - 1) * 10; CommentInfo cm = new CommentInfo(); cm.setStuNum(R.getData().getStunum()); cm.setPagestart((page - 1) * 10); cm.setPagesize(10); int totalpage = (int) commentService.getCommentsPage(cm); List<CommentInfo> data = commentService.getComments(cm); for (CommentInfo item : data) { item.setReservationdate(DateUtil.Reservation_fomatDate(item.getStarttime(), item.getEndtime())); } Rm.setFlag(1); Rm.setMessage("获取成功"); Rm.setPagesize(10); Rm.setTotalpage(totalpage); Rm.setData(data); return Rm; } catch (Exception e) { // TODO Auto-generated catch block Rm.setFlag(-1); Rm.setMessage("服务器正在维护"); return Rm; } } // 评价提交 @Resource(name = "TrainService") TrainService trainService; @Resource(name = "ClassRecordService") ClassRecordService ClassRecordService; @RequestMapping(value = "/addComment", method = RequestMethod.POST) @ResponseBody public ReturnMessage addComment(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "orderNum", required = true) String orderNum, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "teachLevelScore", required = true) float teachLevelScore, @RequestParam(value = "teachStaeScore", required = true) float teachStaeScore, @RequestParam(value = "carStateScore", required = true) float carStateScore, @RequestParam(value = "commentContext", required = true) String commentContext, @RequestParam(value = "commentContent", required = false) String commentContent, CommentInfo cm) { ReturnMessage Rm = new ReturnMessage(); try { ReturnMessage_entity<StudentInfo> R = trainService.checkOwn(token); if (R.getFlag() == -1) { Rm.setFlag(-3); Rm.setMessage(R.getMessage()); return Rm; } cm.setCommentDate(new Date()); List<CoachInfo> simucoach = ClassRecordService.getSimuCoachName(R.getData().getInscode()); CommentInfo result = commentService.checkOrderIsExist(cm); if (result == null) { Rm.setFlag(-1); Rm.setMessage("该订单已评论,请勿重复提交"); return Rm; } if (!result.getStuNum().equals(R.getData().getStunum())) { Rm.setFlag(-1); Rm.setMessage("没有操作权限"); return Rm; } if (result.getIsSimulate() != 0) for (CoachInfo item : simucoach) { if (item.getCoachNum().equals(result.getCoachNum())) { result.setName(item.getName()); } } cm.setDuration(result.getDuration()); cm.setSubject(result.getSubject()); cm.setEndDate(DateUtil.fomatDate(result.getEndDate())); cm.setName(result.getName()); cm.setStuNum(result.getStuNum()); cm.setCoachNum(result.getCoachNum()); cm.setInscode(result.getInscode()); Rm = commentService.addComment(cm); return Rm; } catch (Exception e) { // TODO Auto-generated catch block Rm.setFlag(-1); Rm.setMessage("服务器正在维护"); return Rm; } } @RequestMapping(value = "/updateComment", method = RequestMethod.POST) @ResponseBody public ReturnMessage updateComment(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "orderNum", required = true) String orderNum, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "teachLevelScore", required = true) float teachLevelScore, @RequestParam(value = "teachStaeScore", required = true) float teachStaeScore, @RequestParam(value = "carStateScore", required = true) float carStateScore, @RequestParam(value = "commentContext", required = true) String commentContext, @RequestParam(value = "commentContent", required = false) String commentContent, CommentInfo cm) { ReturnMessage Rm = new ReturnMessage(); try { ReturnMessage_entity<StudentInfo> R = trainService.checkOwn(token); if (R.getFlag() == -1) { Rm.setFlag(-3); Rm.setMessage(R.getMessage()); return Rm; } cm.setCommentDate(new Date()); cm.setIscomment(1); CommentInfo result = commentService.checkOrderIsExist(cm); if (result == null) { Rm.setFlag(-1); Rm.setMessage("该订单不是可修改状态"); return Rm; } if (!result.getStuNum().equals(R.getData().getStunum())) { Rm.setFlag(-1); Rm.setMessage("没有操作权限"); return Rm; } cm.setName(result.getName()); cm.setStuNum(result.getStuNum()); cm.setCoachNum(result.getCoachNum()); cm.setInscode(result.getInscode()); Rm = commentService.updateComment(cm); return Rm; } catch (Exception e) { System.err.println(e.getMessage()); Rm.setFlag(-1); Rm.setMessage("服务器正在维护"); return Rm; } } } <file_sep>/src/main/java/com/jishi/entity/SchoolFS.java package com.jishi.entity; /** * Created by hasee on 2017/7/8. */ public class SchoolFS { private String inscode; private Double fs; public String getInscode() { return inscode; } public void setInscode(String inscode) { this.inscode = inscode; } public Double getFs() { return fs; } public void setFs(Double fs) { this.fs = fs; } } <file_sep>/src/main/java/com/jishi/service/impl/PushCarStatus.java package com.jishi.service.impl; import java.io.IOException; import java.util.Map; import com.corbett.enums.RequestMethod; import com.corbett.utils.http.HttpClient; import com.jiaquwork.util.DataCenterAPI; import com.jishi.service.AbstractPushData; public class PushCarStatus extends AbstractPushData { @Override protected String getData(Map<String, Object> object) throws IOException { return HttpClient.getUrlData(DataCenterAPI.API_SEND_TRAININGCAR, object, RequestMethod.PUT, HttpClient.getRequestHeader()); } @Override protected void insert(Object object) { // TODO Auto-generated method stub } } <file_sep>/src/main/java/com/jishi/entity/view/ViewJishiInfo.java package com.jishi.entity.view; /* * 签退后返回的学时数据 * ADD BY LXJ AT 2016/9/11 * */ public class ViewJishiInfo { private float minute; //分钟 private float duration; //学时 private float remainDuration; //余下学时 private float money; //费用 public float getMinute() { return minute; } public void setMinute(float minute) { this.minute = minute; } public float getDuration() { return duration; } public void setDuration(float duration) { this.duration = duration; } public float getRemainDuration() { return remainDuration; } public void setRemainDuration(float remainDuration) { this.remainDuration = remainDuration; } public float getMoney() { return money; } public void setMoney(float money) { this.money = money; } } <file_sep>/src/main/java/com/jishi/entity/SubjectRecordKey.java package com.jishi.entity; public class SubjectRecordKey { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column subject_record.inst_code * * @mbggenerated Wed May 24 15:35:17 CST 2017 */ private String instCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column subject_record.stu_num * * @mbggenerated Wed May 24 15:35:17 CST 2017 */ private String stuNum; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column subject_record.inst_code * * @return the value of subject_record.inst_code * * @mbggenerated Wed May 24 15:35:17 CST 2017 */ public String getInstCode() { return instCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column subject_record.inst_code * * @param instCode the value for subject_record.inst_code * * @mbggenerated Wed May 24 15:35:17 CST 2017 */ public void setInstCode(String instCode) { this.instCode = instCode; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column subject_record.stu_num * * @return the value of subject_record.stu_num * * @mbggenerated Wed May 24 15:35:17 CST 2017 */ public String getStuNum() { return stuNum; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column subject_record.stu_num * * @param stuNum the value for subject_record.stu_num * * @mbggenerated Wed May 24 15:35:17 CST 2017 */ public void setStuNum(String stuNum) { this.stuNum = stuNum; } }<file_sep>/src/main/java/com/jishi/until/datacenter/RequestStuParam.java package com.jishi.until.datacenter; public class RequestStuParam { public static final String idcard = "idcard"; public static final String iccard = "iccard"; public static final String phone = "phone"; } <file_sep>/src/main/java/com/jishi/entity/TrainOrder_Pay.java package com.jishi.entity; import java.sql.Timestamp; public class TrainOrder_Pay { private String OrderNum; private int StuOrCoach; private Timestamp PayDate; private int PayStyle; private String PaySerialNum; private float Money; private String PayAccount; private String IncomeAccount; public String getOrderNum() { return OrderNum; } public void setOrderNum(String orderNum) { OrderNum = orderNum; } public int getStuOrCoach() { return StuOrCoach; } public void setStuOrCoach(int stuOrCoach) { StuOrCoach = stuOrCoach; } public Timestamp getPayDate() { return PayDate; } public void setPayDate(Timestamp payDate) { PayDate = payDate; } public int getPayStyle() { return PayStyle; } public void setPayStyle(int payStyle) { PayStyle = payStyle; } public String getPaySerialNum() { return PaySerialNum; } public void setPaySerialNum(String paySerialNum) { PaySerialNum = paySerialNum; } public float getMoney() { return Money; } public void setMoney(float money) { Money = money; } public String getPayAccount() { return PayAccount; } public void setPayAccount(String payAccount) { PayAccount = payAccount; } public String getIncomeAccount() { return IncomeAccount; } public void setIncomeAccount(String incomeAccount) { IncomeAccount = incomeAccount; } } <file_sep>/src/main/java/com/jishi/entity/SimuCoach.java package com.jishi.entity; public class SimuCoach { } <file_sep>/src/main/java/com/jishi/service/PushData.java package com.jishi.service; import com.corbett.entity.ReturnMessage; import com.jishi.enums.PushDataType; public interface PushData { ReturnMessage push(PushDataType pushDataType, Object object,boolean isSave) throws Exception; } <file_sep>/src/main/java/com/jishi/entity/JsProsecutedComplaintsPhoto.java package com.jishi.entity; public class JsProsecutedComplaintsPhoto { /** * This field was generated by MyBatis Generator. This field corresponds to the database column js_prosecuted_complaints_photo.id * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ private Integer prosecutedComplaintsPhotoId; /** * This field was generated by MyBatis Generator. This field corresponds to the database column js_prosecuted_complaints_photo.prosecuted_complaints_id * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ private Integer prosecutedComplaintsId; /** * This field was generated by MyBatis Generator. This field corresponds to the database column js_prosecuted_complaints_photo.complaints_id * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ private Integer complaintsId; /** * This field was generated by MyBatis Generator. This field corresponds to the database column js_prosecuted_complaints_photo.photo_path * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ private String photoPath; /** * This method was generated by MyBatis Generator. This method returns the value of the database column js_prosecuted_complaints_photo.id * @return the value of js_prosecuted_complaints_photo.id * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ public Integer getProsecutedComplaintsPhotoId() { return prosecutedComplaintsPhotoId; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column js_prosecuted_complaints_photo.id * @param prosecutedComplaintsPhotoId the value for js_prosecuted_complaints_photo.id * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ public void setProsecutedComplaintsPhotoId(Integer prosecutedComplaintsPhotoId) { this.prosecutedComplaintsPhotoId = prosecutedComplaintsPhotoId; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column js_prosecuted_complaints_photo.prosecuted_complaints_id * @return the value of js_prosecuted_complaints_photo.prosecuted_complaints_id * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ public Integer getProsecutedComplaintsId() { return prosecutedComplaintsId; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column js_prosecuted_complaints_photo.prosecuted_complaints_id * @param prosecutedComplaintsId the value for js_prosecuted_complaints_photo.prosecuted_complaints_id * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ public void setProsecutedComplaintsId(Integer prosecutedComplaintsId) { this.prosecutedComplaintsId = prosecutedComplaintsId; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column js_prosecuted_complaints_photo.complaints_id * @return the value of js_prosecuted_complaints_photo.complaints_id * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ public Integer getComplaintsId() { return complaintsId; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column js_prosecuted_complaints_photo.complaints_id * @param complaintsId the value for js_prosecuted_complaints_photo.complaints_id * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ public void setComplaintsId(Integer complaintsId) { this.complaintsId = complaintsId; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column js_prosecuted_complaints_photo.photo_path * @return the value of js_prosecuted_complaints_photo.photo_path * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ public String getPhotoPath() { return photoPath; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column js_prosecuted_complaints_photo.photo_path * @param photoPath the value for js_prosecuted_complaints_photo.photo_path * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ public void setPhotoPath(String photoPath) { this.photoPath = photoPath; } }<file_sep>/src/main/java/com/jishi/dao/zstu/StuInFoManagement.java package com.jishi.dao.zstu; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.jishi.dao.DaoSupport; import com.jishi.entity.StudentInfo; import com.jishi.entity.studentlogin; /** * 学员查询 判断 更新 插入 删除 管理类 * @author 周宁 - 2017年4月12日 - 下午5:47:26 项目:ynjp_api 包名:com.jishi.service.impl * */ @Service public class StuInFoManagement implements StuInFo ,StuInFoChange{ private static final String RETURN_TYPE_STUINFO = "RETURN_TYPE_STUINFO"; private static final String RETURN_TYPE_STULOGININFO = "RETURN_TYPE_STULOGININFO"; private static final String RETURN_TYPE_STUINFO_COUNT = "RETURN_TYPE_STUINFO_COUNT"; private static final String RETURN_TYPE_STULOGININFO_COUNT = "RETURN_TYPE_STULOGININFO_COUNT"; @Resource(name = "daoSupport") private DaoSupport dao; @Override public Object getUserInFoByNumber(String number) throws Exception { StudentInfo studentInfo = new StudentInfo(); studentInfo.setStunum(number); return getStuObjectByInFo(studentInfo); } @Override public Object getUserInFoByToken(String token) throws Exception { studentlogin studentlogin = new studentlogin(); studentlogin.setToken(token); return getStuObjectByLogin(studentlogin); } @Override public Object getUserInFoByIC(String iCCard) throws Exception { StudentInfo studentInfo = new StudentInfo(); studentInfo.setIcCard(iCCard); return getStuObjectByInFo(studentInfo); } @Override public Object getUserInFoByIdCard(String idCard) throws Exception { StudentInfo studentInfo = new StudentInfo(); studentInfo.setIcCard(idCard); return getStuObjectByInFo(studentInfo); } @Override public Object getUserInFoByPhoneNumber(String phoneNumber) throws Exception { StudentInfo studentInfo = getStuInFoNew(); studentInfo.setPhone(phoneNumber); return getStuObjectByInFo(studentInfo); } @Override public boolean isPhoneNumber(String phoneNumber) throws Exception { StudentInfo studentInfo = getStuInFoNew(); studentInfo.setPhone(phoneNumber); return getBoolean(getStuCountObjectByInFo(studentInfo)); } @Override public boolean isIcCard(String icCard) throws Exception { StudentInfo studentInfo = getStuInFoNew(); studentInfo.setIcCard(icCard); return getBoolean(getStuCountObjectByInFo(studentInfo)); } @Override public boolean isIdCard(String idCard) throws Exception { StudentInfo studentInfo = getStuInFoNew(); studentInfo.setIdcard(idCard); return getBoolean(getStuCountObjectByInFo(studentInfo)); } @Override public boolean isToken(String token) throws Exception { studentlogin studentlogin = getStuLoginInFoNew(); studentlogin.setToken(token); return getBoolean(getStuCountObjectByLogin(studentlogin)); } @Override public boolean isNumber(String number) throws Exception { StudentInfo studentInfo = getStuInFoNew(); studentInfo.setStunum(number); return getBoolean(getStuCountObjectByInFo(studentInfo)); } @Override public boolean isNumberForLogin(String number) throws Exception { studentlogin studentlogin = getStuLoginInFoNew(); studentlogin.setStunum(number); return getBoolean(getStuLoginCountObjectByLohin(studentlogin)); } @Override public boolean isTokenForLogin(String token) throws Exception { studentlogin studentlogin = getStuLoginInFoNew(); studentlogin.setToken(token); return getBoolean(getStuLoginCountObjectByLohin(studentlogin)); } @Override public boolean isPhoneNumberForLogin(String phoneNumber) throws Exception { StudentInfo studentInfo = getStuInFoNew(); studentInfo.setPhone(phoneNumber); return getBoolean(getStuCountObjectByInFo(studentInfo)); } @Override public boolean insertUserInFo(Object object) throws Exception { return getBoolean(insertObject(object)); } @Override public boolean deleteUserInFoByNumber(String number) { // TODO Auto-generated method stub return true; } @Override public boolean deleteUserInFoByIcCard(String icCard) { // TODO Auto-generated method stub return true; } @Override public boolean deleteUserInFoByidCard(String idCard) { // TODO Auto-generated method stub return true; } @Override public boolean deleteUserInFoByPhoneNumber(String phoneNumber) { // TODO Auto-generated method stub return true; } @Override public boolean deleteUserInFoByToken(String token) { // TODO Auto-generated method stub return true; } @Override public boolean updateUserInFoByObject(StudentInfo studentInfo) throws Exception { return getBoolean(updateObject(studentInfo)); } @Override public boolean updateUserLoginInFoByObject(studentlogin studentlogin) throws Exception { return getBoolean(updateObject(studentlogin)); } @Override public StudentInfo getUserInFoByObject(StudentInfo studentInfo) throws Exception { return (StudentInfo) getStuObjectByInFo(studentInfo); } @Override public StudentInfo getUserInFoByObject(studentlogin studentlogin) throws Exception { return (StudentInfo) getStuObjectByLogin(studentlogin); } @Override public studentlogin getUserLoginInFoByObject(studentlogin studentlogin) throws Exception { return (studentlogin) getStuLoginObjectByLogin(studentlogin); } @Override public studentlogin getUserLoginInFoByObject(StudentInfo studentInfo) throws Exception { return (studentlogin) getStuLoginObjectByInFo(studentInfo); } @Override public boolean isStuInfo(StudentInfo studentInfo) throws Exception { return getBoolean(getStuCountObjectByInFo(studentInfo)); } @Override public boolean isStuInfo(studentlogin studentlogin) throws Exception { // TODO Auto-generated method stub return getBoolean(getStuCountObjectByLogin(studentlogin)); } @Override public boolean isStuLoginInFo(StudentInfo studentInfo) throws Exception { return getBoolean(getStuLoginCountObjectByInFo(studentInfo)); } @Override public boolean isStuLoginInFo(studentlogin studentlogin) throws Exception { return getBoolean(getStuLoginCountObjectByLohin(studentlogin)); } private Object getStuObject(Object object,String returnType) throws Exception{ switch (returnType) { case RETURN_TYPE_STUINFO: if (object != null) { if (object instanceof StudentInfo) { return dao.findForObject("StudentInfMapper.selectStuInFo", (StudentInfo)object); } if (object instanceof studentlogin) { return dao.findForObject("StudentInfMapper.selectStuInFoByLogin", (studentlogin)object); } }else { throw new NullPointerException("object null"); } case RETURN_TYPE_STULOGININFO: if (object != null) { if (object instanceof studentlogin) { return dao.findForObject("StudentInfMapper.selectStuLoginInFo", (studentlogin)object); } if (object instanceof StudentInfo) { return dao.findForObject("StudentInfMapper.selectStuLoginInFoByInFo", (StudentInfo)object); } }else { throw new NullPointerException("object null"); } case RETURN_TYPE_STUINFO_COUNT: if (object != null) { if (object instanceof StudentInfo) { return dao.findForObject("StudentInfMapper.selectStuInFoCount", (StudentInfo)object); } if (object instanceof studentlogin) { return dao.findForObject("StudentInfMapper.selectStuInFoCountByLogin", (studentlogin)object); } }else { throw new NullPointerException("object null"); } case RETURN_TYPE_STULOGININFO_COUNT: if (object != null) { if (object instanceof StudentInfo) { return dao.findForObject("StudentInfMapper.selectStuLoginInFoCountByInFo", (StudentInfo)object); } if (object instanceof studentlogin) { return dao.findForObject("StudentInfMapper.selectStuLoginInFoCount", (studentlogin)object); } }else { throw new NullPointerException("object null"); } default: break; } return returnType; } private StudentInfo getStuInFoNew(){ return new StudentInfo(); } private studentlogin getStuLoginInFoNew(){ return new studentlogin(); } private boolean getBoolean(Object object){ if ((Integer)object > 0) { return true; }else { return false; } } private Object getStuObjectByInFo(StudentInfo studentInfo) throws Exception{ return getStuObject(studentInfo, RETURN_TYPE_STUINFO); } private Object getStuCountObjectByInFo(StudentInfo studentInfo) throws Exception{ return getStuObject(studentInfo, RETURN_TYPE_STUINFO_COUNT); } private Object getStuObjectByLogin(studentlogin studentlogin) throws Exception{ return getStuObject(studentlogin, RETURN_TYPE_STUINFO); } private Object getStuCountObjectByLogin(studentlogin studentlogin) throws Exception{ return getStuObject(studentlogin, RETURN_TYPE_STUINFO_COUNT); } private Object getStuLoginObjectByInFo(StudentInfo studentInfo) throws Exception{ return getStuObject(studentInfo, RETURN_TYPE_STULOGININFO); } private Object getStuLoginCountObjectByInFo(StudentInfo studentInfo) throws Exception{ return getStuObject(studentInfo, RETURN_TYPE_STULOGININFO_COUNT); } private Object getStuLoginObjectByLogin(studentlogin studentlogin) throws Exception{ return getStuObject(studentlogin, RETURN_TYPE_STULOGININFO); } private Object getStuLoginCountObjectByLohin(studentlogin studentlogin) throws Exception{ return getStuObject(studentlogin, RETURN_TYPE_STULOGININFO_COUNT); } /** * 更新插入删除等操作 * @throws Exception */ private Object insertObject(Object object) throws Exception{ if (object instanceof StudentInfo) { return dao.save("StudentInfMapper.insertSelective", (StudentInfo)object); }else if (object instanceof studentlogin) { return dao.save("StudentInfMapper.insertLoginInFo", (studentlogin)object); }else { throw new NullPointerException("object 异常"); } } private Object updateObject(Object object) throws Exception{ if (object instanceof StudentInfo) { return dao.update("StudentInfMapper.updateJsStudent", (StudentInfo)object); }else if (object instanceof studentlogin) { return dao.update("StudentInfMapper.updateJsStudentLohinInFo", (studentlogin)object); }else { throw new NullPointerException("object 异常"); } } private Object deleteObject(Object object) throws Exception{ if (object instanceof StudentInfo) { return dao.delete("", (StudentInfo)object); }else if (object instanceof studentlogin) { return dao.delete("", (studentlogin)object); }else { throw new NullPointerException("object 异常"); } } } <file_sep>/src/main/java/com/jishi/service/impl/UserActivationStuImpl.java package com.jishi.service.impl; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSONObject; import com.corbett.enums.RequestMethod; import com.corbett.utils.http.HttpClient; import com.jiaquwork.entity.datacenter.Student; import com.jiaquwork.util.DataCenterAPI; import com.jiaquwork.util.datacenter.ResponseParam; import com.jishi.dao.zstu.StuInFoManagement; import com.jishi.entity.StudentInfo; import com.jishi.entity.studentlogin; import com.jishi.enums.UserLoginType; import com.jishi.until.NumberUtil; @Service("stuActivation") public class UserActivationStuImpl extends UserActivationAbstract { @Autowired private StuInFoManagement stuInFoManagement; @Override protected int updateUserBasicData(Object object, String phoneNumber, Double lot, Double lat) throws Exception { StudentInfo studentInfo = new StudentInfo(); studentInfo.setPhone(phoneNumber); studentInfo.setStatus(ACTIVATION_STATUS); if (lot != null) { studentInfo.setLongitude(lot); } if (lat != null) { studentInfo.setLatitude(lat); } studentInfo.setIsOnlyOne("true"); boolean flag = stuInFoManagement.updateUserInFoByObject(studentInfo); if (flag) { return 1; } return 0; } @Override protected boolean chenkIcAndIdCardFromJQ(String ic, String idCard) throws Exception { StudentInfo studentInfo = new StudentInfo(); studentInfo.setIcCard(ic); studentInfo.setIdcard(idCard); return stuInFoManagement.isStuInfo(studentInfo); } @Override protected boolean checkPhone(String phoneNumber, Integer status) throws Exception { StudentInfo studentInfo = new StudentInfo(); studentInfo.setPhone(phoneNumber); studentInfo.setStatus(status); return stuInFoManagement.isStuInfo(studentInfo); } @Override protected boolean checkIC(String ic, Integer status) throws Exception { StudentInfo studentInfo = new StudentInfo(); studentInfo.setIcCard(ic); studentInfo.setStatus(status); return stuInFoManagement.isStuInfo(studentInfo); } @Override protected Object getUserBasicDate(String ic, String idCard, String phoneNumber) throws Exception { // StudentInfo studentInfo = new StudentInfo(); // studentInfo.setPhone(phoneNumber); // studentInfo.setIdcard(idCard); // studentInfo.setIcCard(ic); /** * 从数据中心获取 */ String data = HttpClient.getUrlDataWithKeyValue(DataCenterAPI.API_GET_STU_ONE, HttpClient.getMapParam("idcard", idCard, "iccard", ic, "phone", phoneNumber), RequestMethod.GET, HttpClient.getRequestHeader()); JSONObject jsonObject = JSONObject.parseObject(data); Student student = null; if (jsonObject.getString(ResponseParam.status).equals("200")) { student = JSONObject.toJavaObject(JSONObject.parseObject(jsonObject.getString("data")), Student.class); } return new StudentInfo(student); } @Override protected Integer insertUserBasicData(Object object, String phoneNumber, Double lot, Double lat) throws Exception { StudentInfo studentInfo = getStudentInFo(object); boolean flag = false; studentInfo.setPhone(phoneNumber); if (lot != null) { studentInfo.setLongitude(lot); } if (lat != null) { studentInfo.setLatitude(lat); } flag = stuInFoManagement.insertUserInFo(studentInfo); if (flag) { return 1; } return 0; } @Override protected Map<String, Object> updatePassword(Object object, String phoneNumber, String password) throws Exception { studentlogin studentlogin = new studentlogin(); StudentInfo studentInfo = getStudentInFo(object); studentlogin.setStunum(studentInfo.getStunum()); studentlogin.setPassword(<PASSWORD>); studentlogin.setToken(NumberUtil.getToken()); studentlogin.setLoginDate(Timestamp.valueOf(LocalDateTime.now())); studentlogin.setIsOnlyOne("true"); boolean flag = stuInFoManagement.updateUserLoginInFoByObject(studentlogin); Map<String, Object> map = new HashMap<>(); ; Integer count = 0; if (flag) { count = 1; map.put(FLAG, count); map.put(TOKEN, studentlogin.getToken()); map.put(STU_NUMBER, studentlogin.getStunum()); map.put(INST_CODE, studentInfo.getInscode()); } else { map.put(FLAG, -1); } return map; } @Override protected boolean checkPhoneAndIc(String ic, String phoneNumber, int status) throws Exception { StudentInfo studentInfo = new StudentInfo(); studentInfo.setIcCard(ic); studentInfo.setPhone(phoneNumber); studentInfo.setStatus(status); return stuInFoManagement.isStuInfo(studentInfo); } @Override protected boolean checkLoginInFo(String phoneNumber) throws Exception { studentlogin studentlogin = new studentlogin(); studentlogin.setUserid(phoneNumber); return stuInFoManagement.isStuLoginInFo(studentlogin); } @Override protected Map<String, Object> insertLoginInFo(Object object, String phoneNumber, String password) throws Exception { StudentInfo studentInfo = getStudentInFo(object); studentInfo.setPhone(phoneNumber); studentInfo.setPassword(<PASSWORD>); studentlogin studentlogin = new studentlogin(); studentlogin.setUserid(phoneNumber); studentlogin.setStunum(studentInfo.getStunum()); studentlogin.setPassword(<PASSWORD>); studentlogin.setToken(NumberUtil.getToken()); studentlogin.setLoginDate(Timestamp.valueOf(LocalDateTime.now())); studentlogin.setIsVisiter(UserLoginType.ACVIATION_USER.getLoginType()); boolean flag = stuInFoManagement.insertUserInFo(studentlogin); Map<String, Object> map = new HashMap<>(); int count = 0; if (flag) { count = 1; } map.put(FLAG, count); map.put(TOKEN, studentlogin.getToken()); map.put(STU_NUMBER, studentlogin.getStunum()); map.put(INST_CODE, studentInfo.getInscode()); return map; } @Override protected boolean checkCode(String phoneNumber, String code) throws Exception { // TODO Auto-generated method stub return false; } @Override protected Map<String, Object> updateLoginInFo(Object object, String phoneNumber, String password) throws Exception { StudentInfo studentInfo = getStudentInFo(object); studentInfo.setPhone(phoneNumber); studentInfo.setPassword(<PASSWORD>); studentlogin studentlogin = new studentlogin(); studentlogin.setUserid(phoneNumber); studentlogin.setStunum(studentInfo.getStunum()); studentlogin.setPassword(<PASSWORD>); studentlogin.setToken(NumberUtil.getToken()); studentlogin.setLoginDate(Timestamp.valueOf(LocalDateTime.now())); studentlogin.setIsVisiter(UserLoginType.ACVIATION_USER.getLoginType()); studentlogin.setIsOnlyOne("true"); boolean flag = stuInFoManagement.updateUserLoginInFoByObject(studentlogin); Map<String, Object> map = new HashMap<>(); int count = 0; if (flag) { count = 1; } map.put(FLAG, count); map.put(TOKEN, studentlogin.getToken()); map.put(STU_NUMBER, studentlogin.getStunum()); map.put(INST_CODE, studentInfo.getInscode()); return map; } private StudentInfo getStudentInFo(Object object) { return (StudentInfo) object; } } <file_sep>/src/main/java/com/jishi/dao/PublicDao.java package com.jishi.dao; import java.util.List; /** * Created by IntelliJ IDEA. * User: corbettbain * Date: 2017/7/5 * Time: 16:27 */ public interface PublicDao { int insert(Object object); int delete(Object object); int update(Object object); List<?> select(Object o); int selectAllCount(Object o); } <file_sep>/src/main/java/com/jishi/entity/view/ViewTrainIndexTopInfo.java package com.jishi.entity.view; public class ViewTrainIndexTopInfo { private float subject2_fulfil ; private float subject2_unfulfil ; private float subject3_fulfil ; private float subject3_unfulfil ; public float getSubject2_fulfil() { return (float)(Math.round(subject2_fulfil*10))/10; } public void setSubject2_fulfil(float subject2_fulfil) { this.subject2_fulfil = subject2_fulfil; } public float getSubject2_unfulfil() { return (float)(Math.round(subject2_unfulfil*10))/10; } public void setSubject2_unfulfil(float subject2_unfulfil) { this.subject2_unfulfil = subject2_unfulfil; } public float getSubject3_fulfil() { return (float)(Math.round(subject3_fulfil*10))/10; } public void setSubject3_fulfil(float subject3_fulfil) { this.subject3_fulfil = subject3_fulfil; } public float getSubject3_unfulfil() { return (float)(Math.round(subject3_unfulfil*10))/10; } public void setSubject3_unfulfil(float subject3_unfulfil) { this.subject3_unfulfil = subject3_unfulfil; } } <file_sep>/src/main/java/com/jishi/service/impl/h5_ServiceImpl.java package com.jishi.service.impl; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.JSONObject; import com.jishi.dao.DaoSupport; import com.jishi.entity.ClassRecordInfo; import com.jishi.entity.CoachInfo; import com.jishi.entity.StudentHousInfo; import com.jishi.entity.SubjectHoursVeiw; import com.jishi.entity.view.View_hour_record; import com.jishi.entity.view.View_nearby_coach; import com.jishi.entity.view.View_nearby_school; import com.jishi.service.h5_Service; @Service("h5Service") @Transactional(rollbackFor = Exception.class) public class h5_ServiceImpl implements h5_Service { private static final String weburl = "http://192.168.127.12:8080/jishi_image/manage/student/"; @Resource(name = "daoSupport") private DaoSupport dao; @SuppressWarnings("unchecked") @Override public List<View_nearby_coach> get_nearby_coachlist(Map<String, Object> map) throws Exception { // TODO Auto-generated method stub return (List<View_nearby_coach>) dao.findForList("CoachMapper.getnearby_coachlist", map); } @Override public int get_nearby_coach_count(Map<String, Object> map) throws Exception { // TODO Auto-generated method stub return (int) dao.findForObject("CoachMapper.getnearby_coach_count", map); } @SuppressWarnings("unchecked") @Override public List<View_nearby_school> get_nearby_school_list(Map<String, Object> map) throws Exception { // TODO Auto-generated method stub return (List<View_nearby_school>) dao.findForList("SchoolJoinMapper.get_nearby_schoollist", map); } @Override public int get_nearby_school_count(Map<String, Object> map) throws Exception { // TODO Auto-generated method stub return (int) dao.findForObject("SchoolJoinMapper.get_nearby_school_count", map); } @Override public View_nearby_coach get_nearby_coach_details(CoachInfo coachInfo) throws Exception { // TODO Auto-generated method stub return (View_nearby_coach) dao.findForObject("CoachMapper.get_coach_details", coachInfo); } @Override public View_nearby_school get_nearby_school_details(CoachInfo coachInfo) throws Exception { // TODO Auto-generated method stub return (View_nearby_school) dao.findForObject("SchoolJoinMapper.get_school_details", coachInfo); } @SuppressWarnings("unchecked") @Override public List<View_nearby_coach> get_school_coachlist(CoachInfo coachInfo) throws Exception { // TODO Auto-generated method stub return (List<View_nearby_coach>) dao.findForList("SchoolJoinMapper.get_school_coachlist", coachInfo); } @SuppressWarnings("unchecked") @Override public Map<String, Object> get_hour_record(ClassRecordInfo record) throws Exception { // TODO Auto-generated method stub StudentHousInfo studentHousInfo = (StudentHousInfo) dao.findForObject("StudentHousMapper.getStudentHousInfo", record.getStuNum()); Map<String, Object> map = new HashMap<String, Object>(); switch (record.getSubjCode()) { case "1": map.put("AreadyStudy", studentHousInfo.getSubject1_fulfil()); map.put("RemainingTime", studentHousInfo.getSubject1_exam()); map.put("Subject", "1"); float minute = (studentHousInfo.getSubject1_exam() - studentHousInfo.getSubject1_fulfil()) < 0 ? 0 : (studentHousInfo.getSubject1_exam() - studentHousInfo.getSubject1_fulfil()); map.put("score_defualt", minute); break; case "2": map.put("AreadyStudy", studentHousInfo.getSubject2_fulfil()); map.put("RemainingTime", studentHousInfo.getSubject2_exam()); map.put("Subject", "2"); float minute1 = (studentHousInfo.getSubject2_exam() - studentHousInfo.getSubject2_fulfil()) < 0 ? 0 : (studentHousInfo.getSubject2_exam() - studentHousInfo.getSubject2_fulfil()); map.put("score_defualt", minute1); break; case "3": map.put("AreadyStudy", studentHousInfo.getSubject3_fulfil()); map.put("RemainingTime", studentHousInfo.getSubject3_exam()); map.put("Subject", "3"); float minute2 = (studentHousInfo.getSubject3_exam() - studentHousInfo.getSubject3_fulfil()) < 0 ? 0 : (studentHousInfo.getSubject3_exam() - studentHousInfo.getSubject3_fulfil()); map.put("score_defualt", minute2); break; case "4": map.put("AreadyStudy", studentHousInfo.getSubject4_fulfil()); map.put("RemainingTime", studentHousInfo.getSubject4_exam()); map.put("Subject", "4"); float minute3 = (studentHousInfo.getSubject4_exam() - studentHousInfo.getSubject4_fulfil()) < 0 ? 0 : (studentHousInfo.getSubject4_exam() - studentHousInfo.getSubject4_fulfil()); map.put("score_defualt", minute3); break; default: break; } List<View_hour_record> list = (List<View_hour_record>) dao .findForList("ClassRecordMapper.getClassRecordInfobystunum", record); for (View_hour_record item : list) { SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd"); item.setDate(format.format(item.getStarttime())); SimpleDateFormat slot = new SimpleDateFormat("HH:mm"); item.setTime_slot(slot.format(item.getStarttime()) + "-" + slot.format(item.getEndtime())); } Map<String, Object> reMap = new HashMap<String, Object>(); reMap.put("hourInfo", map); reMap.put("hourRecord", list); return reMap; } @Override public Object getSubjectHors(String phone, String idCard) throws Exception { JSONObject jObject = new JSONObject(); SubjectHoursVeiw subjectHoursVeiw = new SubjectHoursVeiw(); Map<String, Object> map = new HashMap<>(); map.put("phone", phone); map.put("idCard", idCard); subjectHoursVeiw = (SubjectHoursVeiw) dao.findForObject("StudentInfMapper.selectStudentSubjectHours", map); if (subjectHoursVeiw == null) { jObject.put("flag", 0); return jObject; } subjectHoursVeiw.setPhotoPath(weburl + subjectHoursVeiw.getPhotoPath()); JSONObject jsonObject2 = new JSONObject(); jsonObject2.put("AreadyStudy", subjectHoursVeiw.getAreadyStudy1()); jsonObject2.put("RemainingTime", subjectHoursVeiw.getRemainingTime1()); jsonObject2.put("Subject", subjectHoursVeiw.getSubject1()); jsonObject2.put("score_defualt", subjectHoursVeiw.getScore1_defualt()); JSONObject jsonObject3 = new JSONObject(); jsonObject3.put("AreadyStudy", subjectHoursVeiw.getAreadyStudy2()); jsonObject3.put("RemainingTime", subjectHoursVeiw.getRemainingTime2()); jsonObject3.put("Subject", subjectHoursVeiw.getSubject2()); jsonObject3.put("score_defualt", subjectHoursVeiw.getScore2_defualt()); JSONObject jsonObject4 = new JSONObject(); jsonObject4.put("AreadyStudy", subjectHoursVeiw.getAreadyStudy3()); jsonObject4.put("RemainingTime", subjectHoursVeiw.getRemainingTime3()); jsonObject4.put("Subject", subjectHoursVeiw.getSubject3()); jsonObject4.put("score_defualt", subjectHoursVeiw.getScore3_defualt()); JSONObject jsonObject5 = new JSONObject(); jsonObject5.put("AreadyStudy", subjectHoursVeiw.getAreadyStudy4()); jsonObject5.put("RemainingTime", subjectHoursVeiw.getRemainingTime4()); jsonObject5.put("Subject", subjectHoursVeiw.getSubject4()); jsonObject5.put("score_defualt", subjectHoursVeiw.getScore4_defualt()); List<JSONObject> jsonObject = new ArrayList<>(); jsonObject.add(jsonObject2); jsonObject.add(jsonObject3); jsonObject.add(jsonObject4); jsonObject.add(jsonObject5); jObject.put("flag", 1); jObject.put("data", jsonObject); jObject.put("name", subjectHoursVeiw.getName()); jObject.put("photoPath", subjectHoursVeiw.getPhotoPath()); jObject.put("phone", subjectHoursVeiw.getPhone()); jObject.put("stuNum", subjectHoursVeiw.getStuNum()); return jObject; } @Override public List<View_nearby_coach> getCoachlist(Map<String, Object> map) throws Exception { return (List<View_nearby_coach>) dao.findForList("CoachMapper.getCoachlist", map); } @Override public int getCoachCount(Map<String, Object> map) throws Exception { return (int) dao.findForObject("CoachMapper.getCoachlistCount",map); } @Override public List<View_nearby_school> getSchoollist(Map<String, Object> map) throws Exception { return (List<View_nearby_school>) dao.findForList("SchoolJoinMapper.getSchoollist", map); } @Override public int getSchoolCount(Map<String, Object> map) throws Exception { return (int) dao.findForObject("SchoolJoinMapper.getCchoolCount", map); } } <file_sep>/src/main/java/com/jishi/entity/FormInfo.java package com.jishi.entity; import org.springframework.web.multipart.MultipartFile; public class FormInfo { private MultipartFile studentPhoto; public MultipartFile getStudentPhoto() { return studentPhoto; } public void setStudentPhoto(MultipartFile studentPhoto) { this.studentPhoto = studentPhoto; } } <file_sep>/src/main/java/com/jishi/entity/view/ViewStulate.java package com.jishi.entity.view; public class ViewStulate { private String stunum; private String name; private int status; private float totalhous; private float simuhous; private String icon; private String simunum; private int ispractice; public String getStunum() { return stunum; } public void setStunum(String stunum) { this.stunum = stunum; } public int getIspractice() { return ispractice; } public void setIspractice(int ispractice) { this.ispractice = ispractice; } public String getSimunum() { return simunum; } public void setSimunum(String simunum) { this.simunum = simunum; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public float getTotalhous() { return (float) (Math.round(totalhous * 10)) / 10; } public void setTotalhous(float totalhous) { this.totalhous = totalhous; } public float getSimuhous() { return (float) (Math.round(simuhous * 10)) / 10; } public void setSimuhous(float simuhous) { this.simuhous = simuhous; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } } <file_sep>/src/main/java/com/jishi/service/impl/UserService.java package com.jishi.service.impl; import java.util.Date; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jishi.dao.DaoSupport; import com.jishi.entity.LoginResult; import com.jishi.entity.PhotoInfo; import com.jishi.entity.ReturnInfo; import com.jishi.entity.Sms; import com.jishi.entity.StudentAccount; import com.jishi.entity.StudentInfo; @Service(value="UserService") @Transactional(rollbackFor=Exception.class) public class UserService { @Resource(name = "daoSupport") private DaoSupport dao; /** * 鐧诲綍鏂规硶 * @param student * @return * @throws Exception */ public LoginResult getStudentByPhone(StudentAccount student) throws Exception { return (LoginResult)dao.findForObject("LoginMapper.getStudentByPhone", student); } /** * 妫�娴媗ogin琛ㄨ处鍙峰瓨涓嶅瓨鍦� * @param student * @return * @throws Exception */ public int checkStudentAccountByPhoneNew(StudentAccount student) throws Exception { return (Integer)dao.findForObject("LoginMapper.checkStudentAccountByPhoneNew", student); } public int checkStudentAccountByToken(StudentAccount student) throws Exception { return (Integer)dao.findForObject("LoginMapper.checkStudentAccountByToken", student); } /** * 妫�娴媠tudent琛ㄨ处鍙峰瓨涓嶅瓨鍦� * @param student * @return * @throws Exception */ public StudentAccount checkStudentAccountByPhoneOld(StudentAccount student) throws Exception { return (StudentAccount)dao.findForObject("LoginMapper.checkStudentAccountByPhoneOld", student); } /** * 鎶婄煭淇″啓鍒版暟鎹簱 * @param sms * @return * @throws Exception */ public int recordSms(Sms sms) throws Exception { return (Integer)dao.save("LoginMapper.recordSms", sms); } /** * 妫�娴嬫墜鏈哄彿鐭俊瀛樹笉瀛樺湪 * @param sms * @return * @throws Exception */ public int checkSms(Sms sms) throws Exception { return (Integer)dao.findForObject("LoginMapper.checkSms", sms); } /** * 娉ㄥ唽瀛﹀憳鐢ㄦ埛 * @param student * @return * @throws Exception */ public int addUser(StudentAccount student) throws Exception { return (Integer)dao.save("LoginMapper.addUser", student); } /** * 鎶婄煭淇$姸鎬佹敼1浣滃簾 * @param sms * @return * @throws Exception */ public int updateSmsUsed(Sms sms) throws Exception { return (Integer)dao.update("LoginMapper.updateSmsUsed", sms); } /** * 淇敼瀛﹀憳瀵嗙爜 * @param student * @return * @throws Exception */ public int updateUserPassword(StudentAccount student) throws Exception { return (Integer)dao.update("LoginMapper.updateUserPassword", student); } /** * 检测是否备案 * @param student * @return * @throws Exception */ public int checkStudentIsRecord(StudentAccount student) throws Exception { return (Integer)dao.findForObject("LoginMapper.checkStudentIsRecord", student); } /** * 根据TOKEN获取学员相关信息,并检测学员状态 * */ public ReturnInfo getStuInfoByToken(String token) throws Exception { ReturnInfo re = new ReturnInfo(); StudentInfo studentInfo = (StudentInfo)dao.findForObject("StudentInfMapper.getStudentInfoBytoken", token); if( studentInfo==null ) { re.setFlag(-1); re.setMessage("token不存在"); return re; } if( studentInfo.getStatus()!=2 ) { re.setFlag(-1); re.setMessage("学员未备案"); return re; } re.setFlag(1); re.setStudentInfo(studentInfo); return re; } /** * 学员添加人脸 * * */ public ReturnInfo addPhoto(String faceId,String stuNum,String photoUrl) throws Exception { ReturnInfo re = new ReturnInfo(); PhotoInfo photoInfo = new PhotoInfo(); photoInfo.setApplyobject(stuNum); photoInfo.setCreatedate(new Date()); photoInfo.setFaceId(faceId); photoInfo.setIsapply(0); photoInfo.setPhotoobject(1); photoInfo.setPhotoName("学员头像"); photoInfo.setPhotoUrl(photoUrl); dao.save("PhotoMapper.insertPhoto", photoInfo); re.setFlag(1); return re; } /** * 学员添加人脸 * * */ public int checkPhoto(String stuNum) throws Exception { return (int)dao.findForObject("PhotoMapper.checkPhoto", stuNum); } public String getInscodeName(String inscode) throws Exception { return (String)dao.findForObject("LoginMapper.getInscodeName", inscode); } public int addRegistrationID(Map paramter) throws Exception { return (Integer)dao.update("LoginMapper.addRegistrationID", paramter); } } <file_sep>/src/main/java/com/jishi/until/ResultList.java package com.jishi.until; import com.corbett.entity.ReturnMessage; /** * Created by hasee on 2017/7/8. */ public class ResultList extends ReturnMessage{ private Integer page; public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } } <file_sep>/src/main/java/com/jishi/controller/SchoolPayController.java package com.jishi.controller; import java.sql.Timestamp; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.jishi.entity.InscodeAccount; import com.jishi.entity.SchoolpayHandle; import com.jishi.entity.StudentInfo; import com.jishi.entity.TrainOrder; import com.jishi.service.PayService; import com.jishi.service.SchoolPayService; import com.jishi.service.TrainService; import com.jishi.until.ReturnList; import com.jishi.until.ReturnMessage; import com.jishi.until.ReturnMessage_entity; @Controller @RequestMapping(value = "/schoolpay") public class SchoolPayController { @Resource(name = "SchoolPayService") SchoolPayService schoolPayService; @RequestMapping(value = "/getaccount", method = RequestMethod.GET) @ResponseBody public ReturnList<InscodeAccount> InscodeAccountlst(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "inscode", required = true) String inscode) throws Exception { // Date d = DateUtil.fomatDate(date); ReturnList<InscodeAccount> RM = new ReturnList<InscodeAccount>(); try { List<InscodeAccount> list = schoolPayService.getInscodeAccountList(inscode); for (InscodeAccount item : list) { if (item.getAccounttype() == 1) { // item.setPhotoPath("http://192.168.1.56:8080/Img/up/account/"+item.getPhotoPath()); item.setPhotoPath("http://api.jiaqu365.com/jishi_image/manage/account/" + item.getPhotoPath()); } } RM.setFlag(1); RM.setMessage("成功"); RM.setData(list); return RM; } catch (Exception e) { // TODO: handle exception System.err.println(e.getMessage()); RM.setFlag(-1); RM.setMessage("服务器异常"); return RM; } } @Resource(name = "TrainService") TrainService trainService; @Resource(name = "PayService") PayService payService; @RequestMapping(value = "/save", method = RequestMethod.POST) @ResponseBody public ReturnMessage Edit(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "paytype", required = true) String paytype, @RequestParam(value = "number", required = true) String number, @RequestParam(value = "ordernum", required = true) String ordernum) throws Exception { ReturnMessage RM = new ReturnMessage(); try { ReturnMessage_entity<StudentInfo> R = trainService.checkOwn(token); if (R.getFlag() == -1) { RM.setFlag(-3); RM.setMessage(R.getMessage()); return RM; } TrainOrder order = trainService.getTrainOrderDetailsbyOrderNum(ordernum); ReturnMessage Ro = payService.CheckOrder(order); if (Ro.getFlag() == -1) { RM.setFlag(-1); RM.setMessage(Ro.getMessage()); return RM; } SchoolpayHandle handle = new SchoolpayHandle(); handle.setNumber(number); handle.setOrderNum(ordernum); handle.setPayStyle(paytype); Timestamp Createdate = new Timestamp(new Date().getTime()); handle.setCreateDate(Createdate); int n = schoolPayService.updateorderIspay(ordernum); int m = schoolPayService.insertschoolpayhandle(handle); RM.setFlag(1); RM.setMessage("操作成功"); return RM; } catch (Exception e) { // TODO: handle exception System.err.println(e.getMessage()); RM.setFlag(-1); RM.setMessage("服务器异常"); return RM; } } } <file_sep>/src/main/java/com/jishi/service/impl/SchoolPayServiceImpl.java package com.jishi.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jishi.dao.DaoSupport; import com.jishi.entity.InscodeAccount; import com.jishi.entity.SchoolpayHandle; import com.jishi.entity.TrainOrder; import com.jishi.service.SchoolPayService; import com.jishi.until.ReturnMessage; @Service(value="SchoolPayService") @Transactional(rollbackFor=Exception.class) public class SchoolPayServiceImpl implements SchoolPayService { @Resource(name = "daoSupport") private DaoSupport dao; public List<InscodeAccount> getInscodeAccountList(String Inscode) throws Exception { return (List<InscodeAccount>)dao.findForList("SchoolPayMapper.getInscodeAccountList", Inscode); } public int insertschoolpayhandle(SchoolpayHandle Handle) throws Exception { return (int)dao.save("SchoolPayMapper.insertschoolpayhandle", Handle); } public int updateorderIspay(String OrderNum) throws Exception { return (int)dao.save("SchoolPayMapper.updateorderIspay", OrderNum); } } <file_sep>/src/main/java/com/jishi/entity/StuFocusCoach.java package com.jishi.entity; /** * Created by IntelliJ IDEA. * User: corbettbain * Date: 2017/7/5 * Time: 16:48 */ /** * 学员关注教练实体 */ public class StuFocusCoach { private String stuNum; private String coachNum; private String focusTime; private Integer isDelete; private String changeTime; public String getStuNum() { return stuNum; } public void setStuNum(String stuNum) { this.stuNum = stuNum; } public String getCoachNum() { return coachNum; } public void setCoachNum(String coachNum) { this.coachNum = coachNum; } public String getFocusTime() { return focusTime; } public void setFocusTime(String focusTime) { this.focusTime = focusTime; } public Integer getIsDelete() { return isDelete; } public void setIsDelete(Integer isDelete) { this.isDelete = isDelete; } public String getChangeTime() { return changeTime; } public void setChangeTime(String changeTime) { this.changeTime = changeTime; } } <file_sep>/src/main/java/com/jishi/service/TrainService.java package com.jishi.service; import java.util.List; import java.util.Map; import org.springframework.transaction.annotation.Transactional; import com.jishi.entity.ClassRecordInfo; import com.jishi.entity.StudentHousInfo; import com.jishi.entity.StudentInfo; import com.jishi.entity.SubjectHour; import com.jishi.entity.TrainOrder; import com.jishi.entity.lateplanInfo; import com.jishi.entity.view.ViewTrainDetails; import com.jishi.entity.view.ViewTrainHourPrice; import com.jishi.entity.view.ViewTrainIndexOrderInfo; import com.jishi.entity.view.ViewTrainRecordInfo; import com.jishi.entity.view.ViewTrainTimeDetails; import com.jishi.entity.view.View_Order_Pay_info; import com.jishi.until.ReturnMessage_entity; @Transactional(rollbackFor = Exception.class) public interface TrainService { /* * ��ҳѧԱѧʱ */ StudentHousInfo getStudenthours(String stunum) throws Exception; /* * ��Ŀ��ѧʱ */ float getSubjectToTalhours(SubjectHour subjectHour) throws Exception; /* * ��ҳ�����б� */ List<ViewTrainIndexOrderInfo> getTrainOrderList(String stunum) throws Exception; /* * �������� */ ViewTrainDetails getTrainOrderDetails(TrainOrder Order) throws Exception; /* * ѧ��ʱ������ */ List<ViewTrainTimeDetails> getTimeDetails(ClassRecordInfo crInfo) throws Exception; /* * ��Ŀ���� */ ViewTrainHourPrice getHourPrice(SubjectHour subjectHour) throws Exception; /* * ��ǰ��¼ѧԱ��� */ String getStuNum(String Token) throws Exception; /* * ��ǰ��¼ѧԱ��Ϣ */ StudentInfo getStudentInfo(String stunum) throws Exception; /* * ��ѵ��¼ */ List<ViewTrainRecordInfo> getTrainRecordList(TrainOrder Order) throws Exception; /* * ��ѵ��¼���� */ int getTrainRecordCount(TrainOrder order) throws Exception; List<ClassRecordInfo> getpageTimeDetails(Map M) throws Exception; // ���ݶ�����Ż�ȡ������Ϣ TrainOrder getTrainOrderDetailsbyOrderNum(String OrderNum) throws Exception; List<ViewTrainIndexOrderInfo> get_simulate_by_stunum(lateplanInfo info) throws Exception; ViewTrainIndexOrderInfo getsimucoachName(String CoachNum) throws Exception; ReturnMessage_entity<StudentInfo> checkOwn(String Token) throws Exception; ViewTrainIndexOrderInfo get_simulatedetails_by_simunum(lateplanInfo info) throws Exception; List<ViewTrainIndexOrderInfo> get_simulatelist_by_stunum(lateplanInfo info) throws Exception; int get_simulatelist_by_stunum_count(lateplanInfo info) throws Exception; View_Order_Pay_info get_Order_Pay_Details(TrainOrder order) throws Exception; } <file_sep>/src/main/java/com/jishi/until/datacenter/JsonUtil.java package com.jishi.until.datacenter; import java.io.IOException; import org.apache.poi.ss.formula.functions.T; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class JsonUtil { private static ObjectMapper objectMapper = new ObjectMapper(); public static T[] getT(String data,Class<T[]> classs) throws JsonParseException, JsonMappingException, IOException{ T[] ts = null; ts = (T[]) objectMapper.readValue(data, classs); return ts; } } <file_sep>/src/main/java/com/jishi/entity/view/View_nearby_coach.java package com.jishi.entity.view; public class View_nearby_coach { private String coachnum; private String name; private String teachpermitted; private String licnum; private String years; private String domicile_location; private double distance;// 距离 private String label; private String coachjj; private String inscodename; private String icon; private Double fs; public Double getFs() { return fs; } public void setFs(Double fs) { this.fs = fs; } public String getIcon() { return icon == null ? icon : "http://192.168.3.11:8080/jishi_image/manage/coach/" + icon; } public void setIcon(String icon) { this.icon = icon; } public String getInscodename() { return inscodename; } public void setInscodename(String inscodename) { this.inscodename = inscodename; } public String getCoachjj() { return coachjj; } public void setCoachjj(String coachjj) { this.coachjj = coachjj; } public String getCoachnum() { return coachnum; } public void setCoachnum(String coachnum) { this.coachnum = coachnum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTeachpermitted() { return teachpermitted; } public void setTeachpermitted(String teachpermitted) { this.teachpermitted = teachpermitted; } public String getLicnum() { return licnum; } public void setLicnum(String licnum) { this.licnum = licnum; } public String getYears() { if (years != null && years.length() == 18) { years = (Integer.parseInt(years.substring(8, 10)) / 10 * 10) == 0 ? "00后" : (Integer.parseInt(years.substring(8, 10)) / 10 * 10) + "后"; } return years; } public void setYears(String years) { this.years = years; } public String getDomicile_location() { return domicile_location; } public void setDomicile_location(String domicile_location) { this.domicile_location = domicile_location; } public double getDistance() { return distance; } public void setDistance(double distance) { this.distance = distance; } public String getLabel() { return label == null ? "包接送,不吸烟,普通话标准" : label; } public void setLabel(String label) { this.label = label; } } <file_sep>/src/main/java/com/jishi/entity/rt/UnpayOrder_rt.java package com.jishi.entity.rt; import java.util.Date; public class UnpayOrder_rt { private String ordernum; private String stunum; Date startDate; Date endDate; private float duration; private float money; private String coachnum; private String coachname; private String subject; private String stuname; private int issimulate; public String getCoachname() { return coachname; } public void setCoachname(String coachname) { this.coachname = coachname; } public int getIssimulate() { return issimulate; } public void setIssimulate(int issimulate) { this.issimulate = issimulate; } public String getOrdernum() { return ordernum; } public void setOrdernum(String ordernum) { this.ordernum = ordernum; } public String getStunum() { return stunum; } public void setStunum(String stunum) { this.stunum = stunum; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public float getDuration() { return duration; } public void setDuration(float duration) { this.duration = duration; } public float getMoney() { return money; } public void setMoney(float money) { this.money = money; } public String getCoachnum() { return coachnum; } public void setCoachnum(String coachnum) { this.coachnum = coachnum; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getStuname() { return stuname; } public void setStuname(String stuname) { this.stuname = stuname; } } <file_sep>/src/main/java/com/jishi/entity/CoachTeachInfo.java package com.jishi.entity; import java.util.Date; public class CoachTeachInfo { private String institutionCode; // 培训机构编号 private String coachNum; // 教练员编号 private int status; // 当前签到状态 private String loginNum; // 当前签到的编号 private int currentSubject; // 当前科目 private String studentNum; // 学员编号 private String studentLoginNum; // 学员签到编号 private Date studentLoginDate; // 学员签到时间 private String applyNum; // 预约编号 private int IsSimulate; // 模拟签到或实车签到 private Date CoachLoginDate; // 学员签到时间 public Date getCoachLoginDate() { return CoachLoginDate; } public void setCoachLoginDate(Date coachLoginDate) { CoachLoginDate = coachLoginDate; } public int getIsSimulate() { return IsSimulate; } public void setIsSimulate(int isSimulate) { IsSimulate = isSimulate; } public String getApplyNum() { return applyNum; } public void setApplyNum(String applyNum) { this.applyNum = applyNum; } public String getStudentNum() { return studentNum; } public void setStudentNum(String studentNum) { this.studentNum = studentNum; } public String getStudentLoginNum() { return studentLoginNum; } public void setStudentLoginNum(String studentLoginNum) { this.studentLoginNum = studentLoginNum; } public Date getStudentLoginDate() { return studentLoginDate; } public void setStudentLoginDate(Date studentLoginDate) { this.studentLoginDate = studentLoginDate; } public int getCurrentSubject() { return currentSubject; } public void setCurrentSubject(int currentSubject) { this.currentSubject = currentSubject; } public String getInstitutionCode() { return institutionCode; } public void setInstitutionCode(String institutionCode) { this.institutionCode = institutionCode; } public String getCoachNum() { return coachNum; } public void setCoachNum(String coachNum) { this.coachNum = coachNum; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getLoginNum() { return loginNum; } public void setLoginNum(String loginNum) { this.loginNum = loginNum; } } <file_sep>/src/main/java/com/jishi/entity/view/ViewTrainRecordInfo.java package com.jishi.entity.view; import java.text.SimpleDateFormat; import java.util.Date; public class ViewTrainRecordInfo { private String OrderNum ;//������� private String CoachNum;//������� private String CoachName;//�������� private Date StartDate;//��ʼʱ�� private Date EndDate;//����ʱ�� private int IsPay ;//�Ƿ��Ѹ��� private int IsComment;//�Ƿ������� private int IsLock;//��ǰ���� private int Subject;//��Ŀ private float Duration;//��ѧʱ private float Money;//�ܼ� public String getCoachNum() { return CoachNum; } public void setCoachNum(String coachNum) { CoachNum = coachNum; } public String getOrderNum() { return OrderNum; } public void setOrderNum(String orderNum) { OrderNum = orderNum; } public String getCoachName() { return CoachName; } public void setCoachName(String coachName) { CoachName = coachName; } public String getStartDate() { if(StartDate != null) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String date = format.format(StartDate); return date; } else { return null; } } public void setStartDate(Date startDate) { StartDate = startDate; } public String getEndDate() { if(EndDate != null) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String date = format.format(EndDate); return date; } else { return null; } } public void setEndDate(Date endDate) { EndDate = endDate; } public int getIsPay() { return IsPay; } public void setIsPay(int isPay) { IsPay = isPay; } public int getIsComment() { return IsComment; } public void setIsComment(int isComment) { IsComment = isComment; } public int getIsLock() { return IsLock; } public void setIsLock(int isLock) { IsLock = isLock; } public int getSubject() { return Subject; } public void setSubject(int subject) { Subject = subject; } public float getDuration() { return (float)(Math.round(Duration*10))/10; } public void setDuration(float duration) { Duration = duration; } public float getMoney() { return Money; } public void setMoney(float money) { Money = money; } } <file_sep>/src/main/face/com/face/util/Md5Utils.java package com.face.util; import java.security.MessageDigest; public class Md5Utils { public static String md5(String str) { byte[] bytes = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); bytes = messageDigest.digest(); } catch (Exception e) { return ""; } return hex_encode(bytes); } private static String hex_encode(byte bytes[]) { final char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; StringBuilder builder = new StringBuilder(bytes.length * 2); for (byte b : bytes) { builder.append(hex[(b >> 4) & 0x0F]); builder.append(hex[b & 0x0F]); } return builder.toString(); } }<file_sep>/src/main/java/com/jishi/entity/datacenter/view/PublicPushDataView.java package com.jishi.entity.datacenter.view; /** * Created by IntelliJ IDEA. * User: corbettbain * Date: 2017/7/7 * Time: 18:12 */ public class PublicPushDataView { private Integer push_id; public Integer getPush_id() { return push_id; } public void setPush_id(Integer push_id) { this.push_id = push_id; } } <file_sep>/src/main/java/com/jishi/controller/ztec/UsersController.java package com.jishi.controller.ztec; import java.io.PrintWriter; import java.sql.Timestamp; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.corbett.exception.CorbettException; import com.jishi.entity.CoachInfo; import com.jishi.entity.CoachLogin; import com.jishi.entity.Coach_account; import com.jishi.entity.Coach_order; import com.jishi.entity.Sms; import com.jishi.entity.studentlogin; import com.jishi.entity.view.CoachLoginView; import com.jishi.enums.ResponseCodeEnum; import com.jishi.enums.UserType; import com.jishi.service.CoachLoginService; import com.jishi.service.Search; import com.jishi.service.UsersService; import com.jishi.service.impl.Mine_coachService; import com.jishi.service.impl.UserService; import com.jishi.until.NumberUtil; import com.jishi.until.ReturnMessage; import com.jishi.until.ReturnMessage_entity; import com.jishi.until.ReturnTool; @Controller @RequestMapping("/coach") public class UsersController { @Resource(name = "Mine_coachService") Mine_coachService mine_coachService; @Autowired private CoachLoginService coachLoginService; @Resource(name = "UserService") UserService userService; @Resource(name = "coachUsersService") UsersService usersService; @RequestMapping(value = "/updatePassword", method = RequestMethod.POST) @ResponseBody public ReturnMessage updatePassword(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "password", required = true) String newPassword, @RequestParam(value = "phone", required = true) String phone, @RequestParam(value = "code", required = true) String code) throws Exception { ReturnMessage returnMessage = new ReturnMessage(); try { returnMessage = coachLoginService.updatePassword(phone, code, UserType.COACH, newPassword); return returnMessage; } catch (Exception e) { // TODO: handle exception returnMessage.setFlag(ResponseCodeEnum.ERROR.getCode()); returnMessage.setMessage(ResponseCodeEnum.ERROR.getMessage()); return returnMessage; } } @RequestMapping(value = "/setUserInfo", method = RequestMethod.POST) @ResponseBody public void setUserInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "coachJJ", required = true) String coachJJ, @RequestParam(value = "coachnum", required = true) String coachnum, Coach_account coach_account) throws Exception { response.setContentType("text/json;charset=UTF-8"); PrintWriter out = response.getWriter(); try { ReturnMessage_entity<CoachInfo> rM = coachLoginService.checktoken(token); CoachInfo coachInfo = rM.getData(); if (rM.getFlag() == -3) { out.write(ReturnTool.getJsonMessageResult(rM.getFlag(), rM.getMessage())); return; } coach_account.setInscode(coachInfo.getInsCode()); mine_coachService.setUserInfo(coach_account); out.write(ReturnTool.getJsonMessageResult(1, "修改成功")); } catch (Exception e) { // TODO: handle exception out.write(ReturnTool.getJsonMessageResult(-1, "请求失败")); } } @RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public ReturnMessage_entity<CoachLoginView> tologin(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "phone", required = true) String phone, @RequestParam(value = "password", required = true) String password) throws Exception { ReturnMessage_entity<CoachLoginView> RM = new ReturnMessage_entity<CoachLoginView>(); response.setContentType("text/json;charset=UTF-8"); try { CoachLogin coachLogin = new CoachLogin(); coachLogin.setPassWord(<PASSWORD>); coachLogin.setPhone(phone); CoachLoginView coachLoginView = coachLoginService.login(coachLogin); if (coachLoginView != null) { coachLogin.setToken(NumberUtil.getToken()); Timestamp loginDate = new Timestamp(new Date().getTime()); coachLogin.setLoginDate(loginDate); if (coachLoginService.updateloginphone(coachLogin) > 0) { coachLoginView.setToken(coachLogin.getToken()); RM.setFlag(ResponseCodeEnum.SUCCESS.getCode()); RM.setMessage(ResponseCodeEnum.SUCCESS.getMessage()); RM.setData(coachLoginView); } } else { RM.setFlag(-1); RM.setMessage("用户名或密码错误"); } return RM; } catch (Exception e) { // TODO: handle exception RM.setFlag(ResponseCodeEnum.ERROR.getCode()); RM.setMessage(ResponseCodeEnum.ERROR.getMessage()); return RM; } } @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET) @ResponseBody public void getUserInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "coachnum", required = true) String coachnum, Coach_order coach_order) throws Exception { response.setContentType("text/json;charset=UTF-8"); PrintWriter out = response.getWriter(); try { ReturnMessage_entity<CoachInfo> rM = coachLoginService.checktoken(token); CoachInfo coachInfo = rM.getData(); if (rM.getFlag() == -3) { out.write(ReturnTool.getJsonMessageResult(rM.getFlag(), rM.getMessage())); return; } coach_order.setInscode(coachInfo.getInsCode()); Coach_account coach_account = mine_coachService.getUserInfo(coach_order); out.write(ReturnTool.getJsonObjectResult(ResponseCodeEnum.SUCCESS.getCode(), ResponseCodeEnum.SUCCESS.getMessage(), coach_account)); } catch (Exception e) { out.write(ReturnTool.getJsonMessageResult(ResponseCodeEnum.ERROR.getCode(), ResponseCodeEnum.ERROR.getMessage())); } } @RequestMapping(value = "/updatePwd", method = RequestMethod.POST) @ResponseBody public ReturnMessage updatePwd(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "phone", required = true) String phone, @RequestParam(value = "password", required = true) String password, @RequestParam(value = "code", required = true) int code) throws Exception { ReturnMessage RM = new ReturnMessage(); // 检测验证码 Sms sms = new Sms(); sms.setTel(phone); sms.setCode(code); sms.setCheckdate(new Date()); try { int n = userService.checkSms(sms); if (n == 0) { RM.setFlag(ResponseCodeEnum.CODE_ERROR.getCode()); RM.setMessage(ResponseCodeEnum.CODE_ERROR.getMessage()); return RM; } CoachLogin checkphone = coachLoginService.checkphone(phone); if (checkphone == null) { RM.setFlag(ResponseCodeEnum.USER_NOT_FOUND_ERROR.getCode()); RM.setMessage(ResponseCodeEnum.USER_NOT_FOUND_ERROR.getMessage()); return RM; } CoachLogin coachLogin = new CoachLogin(); coachLogin.setCoachNum(checkphone.getCoachNum()); coachLogin.setPassWord(<PASSWORD>); coachLogin.setPhone(phone); coachLogin.setToken(NumberUtil.getToken()); int m = 0; // 新增 if (coachLoginService.checkloginphone(phone) == 0) { m = coachLoginService.insertloginphone(coachLogin); } else { m = coachLoginService.updateloginphone(coachLogin); } if (m > 0) { userService.updateSmsUsed(sms); RM.setFlag(ResponseCodeEnum.SUCCESS.getCode()); RM.setMessage(ResponseCodeEnum.SUCCESS.getMessage()); } else { RM.setFlag(ResponseCodeEnum.UPDATE_ERROR.getCode()); RM.setMessage(ResponseCodeEnum.UPDATE_ERROR.getMessage()); } return RM; } catch (Exception e) { RM.setFlag(ResponseCodeEnum.ERROR.getCode()); RM.setMessage(ResponseCodeEnum.ERROR.getMessage()); return RM; } } @RequestMapping(value = "/registered", method = RequestMethod.POST) @ResponseBody public ReturnMessage registered(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "code", required = true) String code, @RequestParam(value = "password", required = true) String password, @RequestParam(value = "phoneNumber", required = true) String phoneNumber) throws Exception { ReturnMessage returnMessage = new ReturnMessage(); try { returnMessage = usersService.registered(phoneNumber, code, UserType.COACH, password); if (returnMessage.getFlag() == 2) { CoachLogin coachLogin = (CoachLogin) returnMessage.getData(); coachLogin.setPassWord(<PASSWORD>); int m = coachLoginService.updateloginphone(coachLogin); if (m > 0) { Map<String, Object> map = new HashMap<String, Object>(); map.put("isVisiter", coachLogin.getIsVisiter()); map.put("coachNum", coachLogin.getCoachNum()); map.put("token", coachLogin.getToken()); returnMessage.setFlag(1); returnMessage.setMessage("登入成功"); returnMessage.setData(map); return returnMessage; } } return returnMessage; } catch (Exception e) { returnMessage.setFlag(ResponseCodeEnum.ERROR.getCode()); returnMessage.setMessage(ResponseCodeEnum.ERROR.getMessage()); return returnMessage; } } @Resource(name = "SearchImpl") private Search search; @RequestMapping(value = "search", method = RequestMethod.GET) @ResponseBody public ReturnMessage getInfo(HttpServletRequest request,@RequestParam(value = "type", required = true) int type, @RequestParam(value = "name", required = true) String name, @RequestParam(value = "token", required = true) String token) { ReturnMessage returnMessage = new ReturnMessage(); try { studentlogin studentlogin = (studentlogin) request.getSession().getAttribute("user"); returnMessage = search.search(type, name); return returnMessage; } catch (CorbettException e) { e.printStackTrace(); returnMessage = new ReturnMessage(); returnMessage.setFlag(-1); returnMessage.setMessage(e.getMessage()); return returnMessage; }catch (Exception e) { e.printStackTrace(); returnMessage = new ReturnMessage(); returnMessage.setFlag(-1); returnMessage.setMessage("服务器正在升级"); return returnMessage; } } } <file_sep>/src/main/java/com/jishi/service/impl/UserActivationCoachImpl.java package com.jishi.service.impl; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.jishi.dao.DAO; import com.jishi.entity.CoachInfo; import com.jishi.entity.CoachLogin; import com.jishi.entity.Sms; import com.jishi.enums.UserLoginType; import com.jishi.until.NumberUtil; /** * 教练激活业务 * * @author 周宁 * */ @Service("coachActivation") public class UserActivationCoachImpl extends UserActivationAbstract { @Resource(name = "daoSupport") private DAO dao; @Override protected boolean checkPhone(String phoneNumber,Integer status) throws Exception { int count = (int) dao.findForObject("CoachMapper.checkPhoneNumber", phoneNumber); if (count > 0) { return true; } return false; } @Override protected boolean checkIC(String ic,Integer status) { try { int count = (int) dao.findForObject("CoachMapper.checkIcCard", ic); if (count > 0) { return true; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } @Override protected Object getUserBasicDate(String ic, String idCard,String phoneNumber) throws Exception { CoachInfo coachInfo = new CoachInfo(); coachInfo.setIcCard(ic); coachInfo.setIdCard(idCard); Object object = dao.findForObject("CoachMapper.getCoachInfoForParams", coachInfo); return object; } @Override protected Integer insertUserBasicData(Object object, String phoneNumber,Double lot,Double lat) throws Exception { CoachInfo coachInfo = (CoachInfo) object; coachInfo.setMobile(phoneNumber); coachInfo.setStatus(ACTIVATION_STATUS); coachInfo.setLongitude(lot); coachInfo.setLatitude(lat); return (int) dao.save("CoachMapper.insertCoachInFo", coachInfo); } @Override protected Map<String, Object> updatePassword(Object object, String phoneNumber, String password) throws Exception { CoachLogin coachLogin = new CoachLogin(); coachLogin.setPhone(phoneNumber); coachLogin.setPassWord(password); int count = (int) dao.update("CoachMapper.updateloginphone", coachLogin); Map<String, Object> map = null; if (count > 0) { map = updateLoginInFo(object, phoneNumber, password); } else { map = new HashMap<>(); map.put(FLAG, -1); } return map; } @Override protected boolean checkPhoneAndIc(String ic, String phoneNumber, int status) { CoachInfo coachInfo = new CoachInfo(); coachInfo.setMobile(phoneNumber); coachInfo.setIcCard(ic); coachInfo.setStatus(status); try { int count = (int) dao.findForObject("CoachMapper.checkPhoneAndIc", coachInfo); if (count > 0) { return true; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } @Override protected boolean checkLoginInFo(String phoneNumber) { try { int count = (int) dao.findForObject("CoachMapper.checkloginphone", phoneNumber); if (count > 0) { return true; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } @Override protected boolean checkCode(String phoneNumber, String code) throws Exception { Sms sms = new Sms(); sms.setTel(phoneNumber); sms.setCode(Integer.valueOf(code)); sms.setCheckdate(new Date()); Integer count = (Integer) dao.findForObject("LoginMapper.checkSms", sms); if (count > 0) { return true; } return false; } @Override protected Map<String, Object> insertLoginInFo(Object object, String phoneNumber, String password) throws Exception { CoachInfo coachInfo = (CoachInfo) object; String coachNum = coachInfo.getCoachNum(); CoachLogin coachLogin = new CoachLogin(); coachLogin.setCoachNum(coachNum); coachLogin.setPhone(phoneNumber); coachLogin.setPassWord(<PASSWORD>); coachLogin.setToken(NumberUtil.getToken()); coachLogin.setLoginDate(Timestamp.valueOf(LocalDateTime.now())); coachLogin.setIsVisiter(UserLoginType.ACVIATION_USER.getLoginType()); int count = (int) dao.save("CoachMapper.insertloginphone", coachLogin); Map<String, Object> map = new HashMap<>(); map.put(FLAG, count); map.put(TOKEN, coachLogin.getToken()); map.put(USER_NUMBER, coachNum); return map; } @Override protected Map<String, Object> updateLoginInFo(Object object, String phoneNumber, String password) throws Exception { CoachInfo coachInfo = (CoachInfo) object; String coachNum = coachInfo.getCoachNum(); CoachLogin coachLogin = new CoachLogin(); coachLogin.setCoachNum(coachNum); coachLogin.setPhone(phoneNumber); coachLogin.setPassWord(<PASSWORD>); coachLogin.setToken(NumberUtil.getToken()); coachLogin.setLoginDate(Timestamp.valueOf(LocalDateTime.now())); coachLogin.setIsVisiter(UserLoginType.ACVIATION_USER.getLoginType()); int count = (int) dao.update("CoachMapper.updateloginphone", coachLogin); Map<String, Object> map = new HashMap<>(); map.put(FLAG, count); map.put(TOKEN, coachLogin.getToken()); map.put(USER_NUMBER, coachNum); return map; } @Override protected int updateUserBasicData(Object object, String phoneNumber,Double lot,Double lat) throws Exception { CoachInfo coachInfo = (CoachInfo) object; coachInfo.setMobile(phoneNumber); coachInfo.setStatus(ACTIVATION_STATUS); coachInfo.setLongitude(lot); coachInfo.setLatitude(lat); return (int) dao.update("CoachMapper.updateCoachInFo", coachInfo); } @Override protected boolean chenkIcAndIdCardFromJQ(String ic, String idCard) throws Exception { CoachInfo coachInfo = new CoachInfo(); coachInfo.setIcCard(ic); coachInfo.setIdCard(idCard); if (dao.findForObject("CoachMapper.getCoachInfoForParams", coachInfo) == null) { return false; } else { return true; } } } <file_sep>/src/main/java/com/jishi/service/order/GetOrder.java package com.jishi.service.order; import com.jishi.until.Page; public interface GetOrder { /** * 为支付订单 * @param number 用户编号 * @param page 分页信息 * @return * @throws Exception */ Object getUnpaid(String number, Page page) throws Exception; /** * 获取已支付订单 * @param number * @param page * @return * @throws Exception */ Object getPaid(String number,Page page) throws Exception; } <file_sep>/src/main/java/com/jishi/service/SimuclassService.java package com.jishi.service; import java.util.List; import com.jishi.entity.rt.SimuclassDetail_rt; import com.jishi.entity.view.View_IsCourse_bycoachnum; import com.jishi.entity.view.View_UnPayOrder; import com.jishi.entity.view.View_stu_coach; import com.jishi.until.ReturnMessage; public interface SimuclassService { View_stu_coach getCoach_by_stunum(String stunum) throws Exception; List<SimuclassDetail_rt> getSimuclassDetailByDate(SimuclassDetail_rt date) throws Exception; List<View_IsCourse_bycoachnum> get_Simuclass_ByDate(SimuclassDetail_rt date) throws Exception; View_UnPayOrder checkOrderOrIsPay(String stunum) throws Exception; String check_stu_date_hours(SimuclassDetail_rt date) throws Exception; ReturnMessage add_student_simulate(String[] plannum_arr, String stunum) throws Exception; } <file_sep>/src/main/java/com/jishi/entity/CoachInfo.java package com.jishi.entity; import java.util.Date; /* * 鏁欑粌鍛樺疄浣� * ADD BY LXJ AT 2016/9/6 * */ public class CoachInfo { private String coachNum; // 鏁欑粌缂栧彿 private String insCode; // 鍩硅鏈烘瀯缂栧彿 private String name; // 濮撳悕 private String sex; // 鎬у埆 private String idCard; // 韬唤璇佸彿 private String mobile; // 鎵嬫満鍙风爜 private String address; // 鑱旂郴鍦板潃 private int photo; // 鐓х墖鏂囦欢ID private int fingerPrint; // 鎸囩汗鍥剧墖ID private String drilicence; // 椹鹃┒璇佸彿 private String fstdrilicDate; // 椹鹃┒璇佸垵棰嗘棩鏈� private String occupationNo; // 鑱屼笟璧勬牸璇佸彿 private String occupationLevel; // 鑱屼笟璧勬牸绛夌骇 private String driPermitted; // 鍑嗛┚杞﹀瀷 private String teachPermitted; // 鍑嗘暀杞﹀瀷 private String employStatus; // 渚涜亴鐘舵�� private Date hireDate; // 鍏ヨ亴鏃堕棿 private Date leaveDate; // 绂昏亴鏃堕棿 private Date createDate; // 鏂板鏃堕棿 private Date recordDate; // 澶囨鏃堕棿 private int status; // 鐘舵�� private String carNum; // 鏁欑粌杞︾紪鍙� private String icCard;// IC卡号 private String photoPath; private String coachJJ; private float CoachAmount; private float InscodeAmount; private String date; private double distance;// 距离 private Double longitude; private Double latitude; public double getDistance() { return distance; } public void setDistance(double distance) { this.distance = distance; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public String getPhotoPath() { return photoPath; } public void setPhotoPath(String photoPath) { this.photoPath = photoPath; } public String getCoachJJ() { return coachJJ; } public void setCoachJJ(String coachJJ) { this.coachJJ = coachJJ; } public String getIcCard() { return icCard; } public void setIcCard(String icCard) { this.icCard = icCard; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public float getCoachAmount() { return CoachAmount; } public void setCoachAmount(float coachAmount) { CoachAmount = coachAmount; } public float getInscodeAmount() { return InscodeAmount; } public void setInscodeAmount(float inscodeAmount) { InscodeAmount = inscodeAmount; } public String getCarNum() { return carNum; } public void setCarNum(String carNum) { this.carNum = carNum; } public String getCoachNum() { return coachNum; } public void setCoachNum(String coachNum) { this.coachNum = coachNum; } public String getInsCode() { return insCode; } public void setInsCode(String insCode) { this.insCode = insCode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getPhoto() { return photo; } public void setPhoto(int photo) { this.photo = photo; } public int getFingerPrint() { return fingerPrint; } public void setFingerPrint(int fingerPrint) { this.fingerPrint = fingerPrint; } public String getDrilicence() { return drilicence; } public void setDrilicence(String drilicence) { this.drilicence = drilicence; } public String getFstdrilicDate() { return fstdrilicDate; } public void setFstdrilicDate(String fstdrilicDate) { this.fstdrilicDate = fstdrilicDate; } public String getOccupationNo() { return occupationNo; } public void setOccupationNo(String occupationNo) { this.occupationNo = occupationNo; } public String getOccupationLevel() { return occupationLevel; } public void setOccupationLevel(String occupationLevel) { this.occupationLevel = occupationLevel; } public String getDriPermitted() { return driPermitted; } public void setDriPermitted(String driPermitted) { this.driPermitted = driPermitted; } public String getTeachPermitted() { return teachPermitted; } public void setTeachPermitted(String teachPermitted) { this.teachPermitted = teachPermitted; } public String getEmployStatus() { return employStatus; } public void setEmployStatus(String employStatus) { this.employStatus = employStatus; } public Date getHireDate() { return hireDate; } public void setHireDate(Date hireDate) { this.hireDate = hireDate; } public Date getLeaveDate() { return leaveDate; } public void setLeaveDate(Date leaveDate) { this.leaveDate = leaveDate; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getRecordDate() { return recordDate; } public void setRecordDate(Date recordDate) { this.recordDate = recordDate; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } } <file_sep>/src/main/java/com/jishi/entity/view/ViewTrainTimeDetails.java package com.jishi.entity.view; import java.text.SimpleDateFormat; import java.util.Date; public class ViewTrainTimeDetails { private Date Starttime;//��ʼʱ�� private Date Endtime;//����ʱ�� private float Duration;//ѧʱ public float getDuration() { return (float)(Math.round(Duration*10))/10; } public void setDuration(float duration) { Duration = duration; } public String getStarttime() { if(Starttime != null) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String date = format.format(Starttime); return date; } else { return null; } } public void setStarttime(Date starttime) { Starttime = starttime; } public String getEndtime() { if(Endtime != null) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String date = format.format(Endtime); return date; } else { return null; } } public void setEndtime(Date endtime) { Endtime = endtime; } } <file_sep>/src/main/java/com/jishi/entity/datacenter/view/CoachStatusview.java package com.jishi.entity.datacenter.view; /** * 上报教练员可预约状态 * @author 周宁 2017年5月25日 上午10:20:17 * */ public class CoachStatusview extends PublicPushDataView{ private String inst_code; private String coach_num; private Integer employ_status; private String date; private String lic_num; public String getInst_code() { return inst_code; } public void setInst_code(String inst_code) { this.inst_code = inst_code; } public String getCoach_num() { return coach_num; } public void setCoach_num(String coach_num) { this.coach_num = coach_num; } public Integer getEmploy_status() { return employ_status; } public void setEmploy_status(Integer employ_status) { this.employ_status = employ_status; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getLic_num() { return lic_num; } public void setLic_num(String lic_num) { this.lic_num = lic_num; } public CoachStatusview(String inst_code, String coach_num, Integer employ_status, String date, String lic_num) { super(); this.inst_code = inst_code; this.coach_num = coach_num; this.employ_status = employ_status; this.date = date; this.lic_num = lic_num; } public CoachStatusview() { // TODO Auto-generated constructor stub } @Override public String toString() { return "CoachStatusview{" + "inst_code='" + inst_code + '\'' + ", coach_num='" + coach_num + '\'' + ", employ_status=" + employ_status + ", date='" + date + '\'' + ", lic_num='" + lic_num + '\'' + '}'; } } <file_sep>/src/main/java/com/jishi/service/impl/PushPaymentImpl.java package com.jishi.service.impl; import com.jishi.dao.PushdataPaymentDao; import com.jishi.enums.PushDataType; import com.jishi.service.AbstractPushDatasService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by IntelliJ IDEA. * User: corbettbain * Date: 2017/7/7 * Time: 17:34 */ @Service("PushPaymentImpl") public class PushPaymentImpl extends AbstractPushDatasService{ @Autowired private PushdataPaymentDao pushdataPaymentDao; @Override protected List<?> select() { return pushdataPaymentDao.selectAll(); } @Override protected PushDataType getPushDataType() { return PushDataType.PushPayment; } @Override protected void delete(Integer integer) { pushdataPaymentDao.delete(integer); } } <file_sep>/src/main/java/com/jishi/dao/PushdataEvalustionDao.java package com.jishi.dao; import java.util.List; /** * Created by IntelliJ IDEA. * User: corbettbain * Date: 2017/7/7 * Time: 14:40 */ public interface PushdataEvalustionDao extends PublicDao { List<?> selectAll(); } <file_sep>/src/main/java/com/jishi/dao/PushdataPaymentDao.java package com.jishi.dao; import com.jishi.dao.PublicDao; import java.util.List; /** * Created by IntelliJ IDEA. * User: corbettbain * Date: 2017/7/7 * Time: 14:22 */ public interface PushdataPaymentDao extends PublicDao { List<?> selectAll(); } <file_sep>/src/main/java/com/jishi/entity/view/ViewStuInFo.java package com.jishi.entity.view; import com.jishi.entity.StudentInfo; public class ViewStuInFo extends StudentInfo{ } <file_sep>/src/main/java/com/jishi/service/SchoolSynchronize.java package com.jishi.service; public interface SchoolSynchronize{ /** * 同步驾校 * @param inst_code 驾校编号 * @return * @throws Exception */ boolean schoolSynchronization() throws Exception; /** * 同步驾校 * @param inst_code 驾校编号 * @return * @throws Exception */ boolean schoolSynchronization(String inst_code) throws Exception; } <file_sep>/src/main/java/com/jishi/service/impl/PushComplaintImpl.java package com.jishi.service.impl; import com.jishi.dao.JsPushdataComplaintsMapper; import com.jishi.enums.PushDataType; import com.jishi.service.AbstractPushDatasService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by IntelliJ IDEA. * User: corbettbain * Date: 2017/7/7 * Time: 17:32 */ @Service("PushComplaintImpl") public class PushComplaintImpl extends AbstractPushDatasService { @Autowired private JsPushdataComplaintsMapper jsPushdataComplaintsMapper; @Override protected List<?> select() { return jsPushdataComplaintsMapper.selectAll(); } @Override protected void delete(Integer integer) { jsPushdataComplaintsMapper.delete(integer); } @Override protected PushDataType getPushDataType() { return PushDataType.PushComplaint; } } <file_sep>/src/main/java/com/jishi/enums/SubjectType.java package com.jishi.enums; import com.corbett.exception.CorbettException; public enum SubjectType { SUBJECT1(1,11,"科目一"),SUBJECT2(2,21,"科目二"),SUBJECT3(3,31,"科目三"); private Integer subjectCode1; private Integer subjectCode2; private String subjectCode3; private SubjectType(Integer subjectCode1,Integer subjectCode2,String subjectCode3) { setSubjectCode1(subjectCode1); setSubjectCode2(subjectCode2); setSubjectCode3(subjectCode3); } public Integer getSubjectCode1() { return subjectCode1; } public void setSubjectCode1(Integer subjectCode1) { this.subjectCode1 = subjectCode1; } public Integer getSubjectCode2() { return subjectCode2; } public void setSubjectCode2(Integer subjectCode2) { this.subjectCode2 = subjectCode2; } public String getSubjectCode3() { return subjectCode3; } public void setSubjectCode3(String subjectCode3) { this.subjectCode3 = subjectCode3; } public static SubjectType geSubjectType(Integer subjectCode2) throws CorbettException{ for (SubjectType iterable_element : SubjectType.values()) { if (iterable_element.getSubjectCode2()==subjectCode2) { return iterable_element; } if(iterable_element.getSubjectCode1() == subjectCode2){ return iterable_element; } } throw new CorbettException("没有对应的枚举类型"); } } <file_sep>/src/main/java/com/jishi/entity/Student_PayRecord.java package com.jishi.entity; import java.sql.Timestamp; public class Student_PayRecord { private String StuNum; private float Money; private String Remark; private float Amount; private Timestamp CreateDate; private int Pagestart;//��ǰ���� private int pagesize;//��ǰ���� private String OrderNum; public String getOrderNum() { return OrderNum; } public void setOrderNum(String orderNum) { OrderNum = orderNum; } public int getPagestart() { return Pagestart; } public void setPagestart(int pagestart) { Pagestart = pagestart; } public int getPagesize() { return pagesize; } public void setPagesize(int pagesize) { this.pagesize = pagesize; } public String getStuNum() { return StuNum; } public void setStuNum(String stuNum) { StuNum = stuNum; } public float getMoney() { return Money; } public void setMoney(float money) { Money = money; } public String getRemark() { return Remark; } public void setRemark(String remark) { Remark = remark; } public float getAmount() { return Amount; } public void setAmount(float amount) { Amount = amount; } public Timestamp getCreateDate() { return CreateDate; } public void setCreateDate(Timestamp createDate) { CreateDate = createDate; } } <file_sep>/src/main/java/com/jishi/entity/StudentInfo.java package com.jishi.entity; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.jiaquwork.entity.datacenter.Student; import com.jishi.entity.datacenter.StudentForPersion; /* * 瀛﹀憳瀹炰綋琛� * ADD BY LXJ AT 2016/09/07 * */ public class StudentInfo extends studentlogin{ private String Stunum; private String inscode; //鍩硅鏈烘瀯缂栧彿 private String idcard ; //璇佷欢鍙� private String cardtype; //璇佷欢绫诲瀷 private String nationality; //鍥界睄 private String sex; //鎬у埆 private String name; //瀛﹀憳濮撳悕 private String address; //鑱旂郴鍦板潃 private String phone; //鎵嬫満鍙风爜 private String photo; //鐓х墖鏂囦欢ID private String fingerprint; //鎸囩汗鍥剧墖ID private String busitype; //涓氬姟绫诲瀷 private String drilicnum; //椹鹃┒璇佸彿 private Date fstdrilicDate; //椹鹃┒璇佸垵棰嗘棩鏈� private String perdritype; //鍘熷噯椹捐溅鍨� private String traintype; //鍩硅杞﹀瀷 private Date applyDate; //鎶ュ悕鏃堕棿 private Date createDate; //鏂板鏃堕棿 private Date recordDate; //澶囨鏃堕棿 private int status; //鐘舵�� private String password;//瀵嗙爜 private String PhotoUrl;//瀵嗙爜 private int subject; private int personId; //人脸 private float amount; private String photoPath; private double longitude; private double latitude; private String icCard; public int getSubject() { return subject; } public void setSubject(int subject) { this.subject = subject; } public String getPhotoUrl() { return PhotoUrl; } public void setPhotoUrl(String photoUrl) { PhotoUrl = photoUrl; } public int getPersonId() { return personId; } public void setPersonId(int personId) { this.personId = personId; } public String getStunum() { return Stunum; } public void setStunum(String stunum) { Stunum = stunum; } public String getRecordDate() { if (recordDate !=null) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = format.format(recordDate); return date; } else { return null; } } public void setRecordDate(Date recordDate) { this.recordDate = recordDate; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFstdrilicDate() { if (fstdrilicDate !=null) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = format.format(fstdrilicDate); return date; } else { return null; } } public void setFstdrilicDate(Date fstdrilicDate) { this.fstdrilicDate = fstdrilicDate; } public String getApplyDate() { if (applyDate !=null) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = format.format(applyDate); return date; } else { return null; } } public void setApplyDate(Date applyDate) { this.applyDate = applyDate; } public String getCreateDate() { if (createDate !=null) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = format.format(createDate); return date; } else { return null; } } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getRecorddate() { if (recordDate !=null) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = format.format(recordDate); return date; } else { return null; } } public void setRecorddate(Date recorddate) { this.recordDate = recorddate; } public String getInscode() { return inscode; } public void setInscode(String inscode) { this.inscode = inscode; } public String getIdcard() { return idcard; } public void setIdcard(String idcard) { this.idcard = idcard; } public String getCardtype() { return cardtype; } public void setCardtype(String cardtype) { this.cardtype = cardtype; } public String getNationality() { return nationality; } public void setNationality(String nationality) { this.nationality = nationality; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public String getFingerprint() { return fingerprint; } public void setFingerprint(String fingerprint) { this.fingerprint = fingerprint; } public String getBusitype() { return busitype; } public void setBusitype(String busitype) { this.busitype = busitype; } public String getDrilicnum() { return drilicnum; } public void setDrilicnum(String drilicnum) { this.drilicnum = drilicnum; } public String getPerdritype() { return perdritype; } public void setPerdritype(String perdritype) { this.perdritype = perdritype; } public String getTraintype() { return traintype; } public void setTraintype(String traintype) { this.traintype = traintype; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public float getAmount() { return amount; } public void setAmount(float amount) { this.amount = amount; } public String getPhotoPath() { return photoPath; } public void setPhotoPath(String photoPath) { this.photoPath = photoPath; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public String getIcCard() { return icCard; } public void setIcCard(String icCard) { this.icCard = icCard; } public StudentInfo(String stunum, String inscode, String idcard, String cardtype, String nationality, String sex, String name, String address, String phone, String photo, String fingerprint, String busitype, String drilicnum, Date fstdrilicDate, String perdritype, String traintype, Date applyDate, Date createDate, Date recordDate, int status, String password, String photoUrl, int subject, int personId, float amount, String photoPath, double longitude, double latitude, String icCard) { super(); Stunum = stunum; this.inscode = inscode; this.idcard = idcard; this.cardtype = cardtype; this.nationality = nationality; this.sex = sex; this.name = name; this.address = address; this.phone = phone; this.photo = photo; this.fingerprint = fingerprint; this.busitype = busitype; this.drilicnum = drilicnum; this.fstdrilicDate = fstdrilicDate; this.perdritype = perdritype; this.traintype = traintype; this.applyDate = applyDate; this.createDate = createDate; this.recordDate = recordDate; this.status = status; this.password = <PASSWORD>; PhotoUrl = photoUrl; this.subject = subject; this.personId = personId; this.amount = amount; this.photoPath = photoPath; this.longitude = longitude; this.latitude = latitude; this.icCard = icCard; } @Override public String toString() { return "StudentInfo [Stunum=" + Stunum + ", inscode=" + inscode + ", idcard=" + idcard + ", cardtype=" + cardtype + ", nationality=" + nationality + ", sex=" + sex + ", name=" + name + ", address=" + address + ", phone=" + phone + ", photo=" + photo + ", fingerprint=" + fingerprint + ", busitype=" + busitype + ", drilicnum=" + drilicnum + ", fstdrilicDate=" + fstdrilicDate + ", perdritype=" + perdritype + ", traintype=" + traintype + ", applyDate=" + applyDate + ", createDate=" + createDate + ", recordDate=" + recordDate + ", status=" + status + ", password=" + <PASSWORD> + ", PhotoUrl=" + PhotoUrl + ", subject=" + subject + ", personId=" + personId + ", amount=" + amount + ", photoPath=" + photoPath + ", longitude=" + longitude + ", latitude=" + latitude + ", icCard=" + icCard + "]"; } public StudentInfo() { // TODO Auto-generated constructor stub } public StudentInfo(StudentForPersion studentForPersion) throws ParseException{ SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟 String dstr=studentForPersion.getApplydate(); java.util.Date date=sdf.parse(dstr); this.Stunum = studentForPersion.getStu_num(); this.cardtype = studentForPersion.getCardtype(); this.applyDate = date; this.photoPath = studentForPersion.getPhoto(); this.name = studentForPersion.getName(); this.sex = studentForPersion.getSex().toString(); this.inscode = studentForPersion.getInst_code(); this.idcard = studentForPersion.getIdcard(); this.nationality = studentForPersion.getNationality(); this.traintype = studentForPersion.getTra_type(); } public StudentInfo(Student studentForPersion) throws ParseException{ SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟 String dstr=studentForPersion.getApplydate(); java.util.Date date=sdf.parse(dstr); this.Stunum = studentForPersion.getStu_num(); this.cardtype = studentForPersion.getCardtype(); this.applyDate = date; this.photoPath = studentForPersion.getPhoto(); this.name = studentForPersion.getName(); this.sex = studentForPersion.getSex().toString(); this.inscode = studentForPersion.getInst_code(); this.idcard = studentForPersion.getIdcard(); this.nationality = studentForPersion.getNationality(); this.traintype = studentForPersion.getTra_type(); } } <file_sep>/src/main/java/com/jishi/entity/StagePhotoInfo.java package com.jishi.entity; import java.util.Date; public class StagePhotoInfo { private String photoId; private String photoUrl; private int photoType; private String recNum; private Date createdate; private int successId; private String remark; private String inscode; private int isSimulate; public int getIsSimulate() { return isSimulate; } public void setIsSimulate(int isSimulate) { this.isSimulate = isSimulate; } public String getInscode() { return inscode; } public void setInscode(String inscode) { this.inscode = inscode; } public String getPhotoId() { return photoId; } public void setPhotoId(String photoId) { this.photoId = photoId; } public String getPhotoUrl() { return photoUrl; } public void setPhotoUrl(String photoUrl) { this.photoUrl = photoUrl; } public int getPhotoType() { return photoType; } public void setPhotoType(int photoType) { this.photoType = photoType; } public String getRecNum() { return recNum; } public void setRecNum(String recNum) { this.recNum = recNum; } public Date getCreatedate() { return createdate; } public void setCreatedate(Date createdate) { this.createdate = createdate; } public int getSuccessId() { return successId; } public void setSuccessId(int successId) { this.successId = successId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } } <file_sep>/src/main/java/com/jishi/entity/InscodeAccount.java package com.jishi.entity; public class InscodeAccount { private int Accounttype; private String TypeName; private String AccountNum; private String AccountName; private String PhotoPath; public int getAccounttype() { return Accounttype; } public void setAccounttype(int accounttype) { Accounttype = accounttype; } public String getTypeName() { return TypeName; } public void setTypeName(String typeName) { TypeName = typeName; } public String getAccountNum() { return AccountNum; } public void setAccountNum(String accountNum) { AccountNum = accountNum; } public String getAccountName() { return AccountName; } public void setAccountName(String accountName) { AccountName = accountName; } public String getPhotoPath() { return PhotoPath; } public void setPhotoPath(String photoPath) { PhotoPath = photoPath; } } <file_sep>/src/main/java/com/jishi/entity/view/ViewContrastResult.java package com.jishi.entity.view; public class ViewContrastResult { private int result; private String confidence; public int getResult() { return result; } public void setResult(int result) { this.result = result; } public String getConfidence() { return confidence; } public void setConfidence(String confidence) { this.confidence = confidence; } } <file_sep>/src/main/java/com/jishi/until/ReturnTool.java package com.jishi.until; import java.util.HashMap; import net.sf.json.JSONObject; public class ReturnTool { public static String getJsonObjectResult(int flag,String message,Object object) { HashMap msg=new HashMap(); msg.put("flag", flag); msg.put("message", message); msg.put("data", object); JSONObject jsonArray = JSONObject.fromObject(msg); return jsonArray.toString(); } public static String getJsonMessageResult(int flag,String message) { HashMap msg=new HashMap(); msg.put("flag", flag); msg.put("message", message); JSONObject jsonArray = JSONObject.fromObject(msg); return jsonArray.toString(); } public static String getJsonObjectResult(int flag,String message,Object object,Object object2,String name) { HashMap msg=new HashMap(); msg.put("flag", flag); msg.put("message", message); msg.put("data", object); msg.put(name, object2); JSONObject jsonArray = JSONObject.fromObject(msg); return jsonArray.toString(); } } <file_sep>/src/main/java/com/jishi/entity/StudentHousInfo.java package com.jishi.entity; import java.util.Date; /* * 瀛﹀憳瀛︽椂琛� * ADD BY LXJ AT 2016/09/07 * */ public class StudentHousInfo { private String stuNum; // 瀛﹀憳缂栧彿 private String subject1_coachid; // 绉戠洰涓�鏁欑粌 private String subject2_coachid; // 绉戠洰浜屾暀缁� private String subject3_coachid; // 绉戠洰涓夋暀缁� private String subject4_coachid; // 绉戠洰鍥涙暀缁� private String subject1_coachname; // 绉戠洰涓�鏁欑粌鍚嶇О private String subject2_coachname; // 绉戠洰涓�鏁欑粌鍚嶇О private String subject3_coachname; // 绉戠洰涓�鏁欑粌鍚嶇О private String subject4_coachname; // 绉戠洰涓�鏁欑粌鍚嶇О private float subject1_fulfil; // 绉戠洰涓�瀹屾垚瀛︽椂 private float subject2_fulfil; // 绉戠洰浜屽畬鎴愬鏃� private float subject3_fulfil; // 绉戠洰涓夊畬鎴愬鏃� private float subject4_fulfil; // 绉戠洰鍥涘畬鎴愬鏃� private float subject1_valid; // 绉戠洰涓�鏈夋晥瀛︽椂 private float subject2_valid; // 绉戠洰浜屾湁鏁堝鏃� private float subject3_valid; // 绉戠洰涓夋湁鏁堝鏃� private float subject4_valid; // 绉戠洰鍥涙湁鏁堝鏃� private float subject1_exam; // 绉戠洰涓�鑰冩牳瀛︽椂 private float subject2_exam; // 绉戠洰浜岃�冩牳瀛︽椂 private float subject3_exam; // 绉戠洰涓夎�冩牳瀛︽椂 private float subject4_exam; // 绉戠洰鍥涜�冩牳瀛︽椂 private int current_subject; // 姝e湪缁冧範绉戠洰 private int isPractice; // 鏄惁缁冧範 private String coachLoginNum; // 鏁欑粌绛惧埌缂栧彿 private String studentLoginNum; // 瀛﹀憳绛惧埌缂栧彿 private String Inscode; // 培训机构编号 private String Perdritype; // 培训车型 private String Token; private Date studentLoginDate; // 学员签到时间 private float simusubject2_fulfil; // 科目二模拟学时 private float simusubject3_fulfil; // 科目三模拟学时 private float duration; // 添加的学时数量 public float getSimusubject2_fulfil() { return simusubject2_fulfil; } public void setSimusubject2_fulfil(float simusubject2_fulfil) { this.simusubject2_fulfil = simusubject2_fulfil; } public float getSimusubject3_fulfil() { return simusubject3_fulfil; } public void setSimusubject3_fulfil(float simusubject3_fulfil) { this.simusubject3_fulfil = simusubject3_fulfil; } public float getDuration() { return duration; } public void setDuration(float duration) { this.duration = duration; } public Date getStudentLoginDate() { return studentLoginDate; } public void setStudentLoginDate(Date studentLoginDate) { this.studentLoginDate = studentLoginDate; } public String getToken() { return Token; } public void setToken(String token) { Token = token; } public String getInscode() { return Inscode; } public void setInscode(String inscode) { Inscode = inscode; } public String getPerdritype() { return Perdritype; } public void setPerdritype(String perdritype) { Perdritype = perdritype; } public String getCoachLoginNum() { return coachLoginNum; } public void setCoachLoginNum(String coachLoginNUm) { this.coachLoginNum = coachLoginNUm; } public String getStudentLoginNum() { return studentLoginNum; } public void setStudentLoginNum(String studentLoginNum) { this.studentLoginNum = studentLoginNum; } public float getSubject1_fulfil() { return subject1_fulfil; } public void setSubject1_fulfil(float subject1_fulfil) { this.subject1_fulfil = subject1_fulfil; } public float getSubject2_fulfil() { return subject2_fulfil; } public void setSubject2_fulfil(float subject2_fulfil) { this.subject2_fulfil = subject2_fulfil; } public float getSubject3_fulfil() { return subject3_fulfil; } public void setSubject3_fulfil(float subject3_fulfil) { this.subject3_fulfil = subject3_fulfil; } public float getSubject4_fulfil() { return subject4_fulfil; } public void setSubject4_fulfil(float subject4_fulfil) { this.subject4_fulfil = subject4_fulfil; } public float getSubject1_valid() { return subject1_valid; } public void setSubject1_valid(float subject1_valid) { this.subject1_valid = subject1_valid; } public float getSubject2_valid() { return subject2_valid; } public void setSubject2_valid(float subject2_valid) { this.subject2_valid = subject2_valid; } public float getSubject3_valid() { return subject3_valid; } public void setSubject3_valid(float subject3_valid) { this.subject3_valid = subject3_valid; } public float getSubject4_valid() { return subject4_valid; } public void setSubject4_valid(float subject4_valid) { this.subject4_valid = subject4_valid; } public float getSubject1_exam() { return subject1_exam; } public void setSubject1_exam(float subject1_exam) { this.subject1_exam = subject1_exam; } public float getSubject2_exam() { return subject2_exam; } public void setSubject2_exam(float subject2_exam) { this.subject2_exam = subject2_exam; } public float getSubject3_exam() { return subject3_exam; } public void setSubject3_exam(float subject3_exam) { this.subject3_exam = subject3_exam; } public float getSubject4_exam() { return subject4_exam; } public void setSubject4_exam(float subject4_exam) { this.subject4_exam = subject4_exam; } public String getStuNum() { return stuNum; } public void setStuNum(String stuNum) { this.stuNum = stuNum; } public String getSubject1_coachid() { return subject1_coachid; } public void setSubject1_coachid(String subject1_coachid) { this.subject1_coachid = subject1_coachid; } public String getSubject2_coachid() { return subject2_coachid; } public void setSubject2_coachid(String subject2_coachid) { this.subject2_coachid = subject2_coachid; } public String getSubject3_coachid() { return subject3_coachid; } public void setSubject3_coachid(String subject3_coachid) { this.subject3_coachid = subject3_coachid; } public String getSubject4_coachid() { return subject4_coachid; } public void setSubject4_coachid(String subject4_coachid) { this.subject4_coachid = subject4_coachid; } public String getSubject1_coachname() { return subject1_coachname; } public void setSubject1_coachname(String subject1_coachname) { this.subject1_coachname = subject1_coachname; } public String getSubject2_coachname() { return subject2_coachname; } public void setSubject2_coachname(String subject2_coachname) { this.subject2_coachname = subject2_coachname; } public String getSubject3_coachname() { return subject3_coachname; } public void setSubject3_coachname(String subject3_coachname) { this.subject3_coachname = subject3_coachname; } public String getSubject4_coachname() { return subject4_coachname; } public void setSubject4_coachname(String subject4_coachname) { this.subject4_coachname = subject4_coachname; } public int getCurrent_subject() { return current_subject; } public void setCurrent_subject(int current_subject) { this.current_subject = current_subject; } public int getIsPractice() { return isPractice; } public void setIsPractice(int isPractice) { this.isPractice = isPractice; } } <file_sep>/src/main/java/com/jishi/controller/h5/H5Controller.java package com.jishi.controller.h5; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.map.util.JSONPObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONObject; import com.corbett.exception.CorbettException; import com.jishi.entity.ClassRecordInfo; import com.jishi.entity.CoachInfo; import com.jishi.entity.PredictionApply; import com.jishi.entity.StudentEvaluation; import com.jishi.entity.view.View_nearby_coach; import com.jishi.entity.view.View_nearby_school; import com.jishi.service.PredictionApplyService; import com.jishi.service.StuComment; import com.jishi.service.h5_Service; import com.jishi.until.Range; import com.jishi.until.ReturnMessage; import com.jishi.until.ReturnMessage_entity; @Controller @RequestMapping(value = "/h5") public class H5Controller { @Resource(name = "h5Service") h5_Service h5service; @RequestMapping(value = "/nearby_coach", method = RequestMethod.GET) @ResponseBody public Object nearby_coach(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "longitude", required = true) double longitude, @RequestParam(value = "latitude", required = true) double latitude, String callback) { List<View_nearby_coach> list = new ArrayList<View_nearby_coach>(); try { Range range = new Range(); Map<String, Object> map = range.Range_lat_Lng(longitude, latitude); list = h5service.get_nearby_coachlist(map); JSONPObject jsonpObject = new JSONPObject(callback, list); return jsonpObject; } catch (Exception e) { // TODO Auto-generated catch block JSONPObject err = new JSONPObject(callback, list); return err; } } @RequestMapping(value = "/nearby_school", method = RequestMethod.GET) @ResponseBody public Object nearby_school(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "longitude", required = true) double longitude, @RequestParam(value = "latitude", required = true) double latitude, String callback) { List<View_nearby_school> list = new ArrayList<View_nearby_school>(); try { Range range = new Range(); Map<String, Object> map = range.Range_lat_Lng(longitude, latitude); list = h5service.get_nearby_school_list(map); JSONPObject jsonpObject = new JSONPObject(callback, list); return jsonpObject; } catch (Exception e) { JSONPObject err = new JSONPObject(callback, list); return err; } } @RequestMapping(value = "/school_details", method = RequestMethod.GET) @ResponseBody public Object school_details(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "inscode", required = true) String inscode, Double longitude, Double latitude, String callback) { View_nearby_school model = new View_nearby_school(); try { if (longitude == null) { longitude = 100.276001; } if (latitude == null) { latitude = 25.611137; } CoachInfo coachInfo = new CoachInfo(); coachInfo.setInsCode(inscode); coachInfo.setLongitude(longitude); coachInfo.setLatitude(latitude); model = h5service.get_nearby_school_details(coachInfo); JSONPObject jsonpObject = new JSONPObject(callback, model); return jsonpObject; } catch (Exception e) { JSONPObject err = new JSONPObject(callback, model); return err; } } @RequestMapping(value = "/coach_details", method = RequestMethod.GET) @ResponseBody public Object coach_details(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "coachnum", required = true) String coachnum, Double longitude, Double latitude, String callback) { ReturnMessage_entity<View_nearby_coach> R = new ReturnMessage_entity<View_nearby_coach>(); View_nearby_coach model = new View_nearby_coach(); try { if (longitude == null) { longitude = 100.276001; } if (latitude == null) { latitude = 25.611137; } CoachInfo coachInfo = new CoachInfo(); coachInfo.setCoachNum(coachnum); coachInfo.setLongitude(longitude); coachInfo.setLatitude(latitude); model = h5service.get_nearby_coach_details(coachInfo); JSONPObject jsonpObject = new JSONPObject(callback, model); return jsonpObject; } catch (Exception e) { System.err.println(e.getMessage()); JSONPObject err = new JSONPObject(callback, model); return err; } } @RequestMapping(value = "/school_coach", method = RequestMethod.GET) @ResponseBody public Object school_coach(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "inscode", required = true) String inscode, Double longitude, Double latitude, String callback) { List<View_nearby_coach> list = new ArrayList<View_nearby_coach>(); try { if (longitude == null) { longitude = 100.276001; } if (latitude == null) { latitude = 25.611137; } CoachInfo coachInfo = new CoachInfo(); coachInfo.setInsCode(inscode); coachInfo.setLongitude(longitude); coachInfo.setLatitude(latitude); list = h5service.get_school_coachlist(coachInfo); JSONPObject jsonpObject = new JSONPObject(callback, list); return jsonpObject; } catch (Exception e) { JSONPObject err = new JSONPObject(callback, list); return err; } } @RequestMapping(value = "/hour_record", method = RequestMethod.GET) @ResponseBody public Object hour_record(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "stunum", required = true) String stunum, @RequestParam(value = "part", required = true) int part, String callback) { Map<String, Object> list = new HashMap<String, Object>(); try { ClassRecordInfo record = new ClassRecordInfo(); record.setStuNum(stunum); record.setSubjCode(part + ""); list = h5service.get_hour_record(record); JSONPObject jsonpObject = new JSONPObject(callback, list); return jsonpObject; } catch (Exception e) { System.err.println(e.getMessage()); JSONPObject err = new JSONPObject(callback, list); return err; } } @RequestMapping(value = "/getSubjectHours", method = RequestMethod.GET) @ResponseBody public Object getSubjectHours(@RequestParam(value = "phone", required = true) String phone, @RequestParam(value = "idCard", required = true) String idCard, String callback) { ReturnMessage returnMessage = new ReturnMessage(); try { JSONObject jsonObject = (JSONObject) h5service.getSubjectHors(phone, idCard); JSONPObject jsonpObject = new JSONPObject(callback, jsonObject); return jsonpObject; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); JSONPObject err = new JSONPObject(callback, returnMessage); return err; } } @Resource(name = "StuCommentImpl") private StuComment stuComment; @RequestMapping("getInsEvaluation") @ResponseBody public ReturnMessage getStuToIns(@RequestParam(value = "num",required = true) String num, @RequestParam(value = "page",required = true) Integer page, @RequestParam(value = "pageSize",required = true) Integer pageSize){ ReturnMessage returnMessage = new ReturnMessage(); StudentEvaluation studentEvaluation = new StudentEvaluation(); studentEvaluation.setPagesize(pageSize); studentEvaluation.setPagestart(page); studentEvaluation.setObjectNum(num); try { returnMessage = stuComment.getStuToInsEvaluation(studentEvaluation); returnMessage.setFlag(1); returnMessage.setMessage("success"); return returnMessage; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } @RequestMapping("getCoachEvaluation") @ResponseBody public ReturnMessage getStuToCoach(@RequestParam(value = "num",required = true) String num, @RequestParam(value = "page",required = true) Integer page, @RequestParam(value = "pageSize",required = true) Integer pageSize){ ReturnMessage returnMessage = new ReturnMessage(); StudentEvaluation studentEvaluation = new StudentEvaluation(); studentEvaluation.setPagesize(pageSize); studentEvaluation.setPagestart(page); studentEvaluation.setObjectNum(num); try { returnMessage = stuComment.getStuToCoachEvaluation(studentEvaluation); returnMessage.setFlag(1); returnMessage.setMessage("success"); return returnMessage; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } @Autowired private PredictionApplyService predictionApplyService; @RequestMapping("insertPredictionApply") @ResponseBody public ReturnMessage insertPredictionApply(PredictionApply predictionApply,ReturnMessage returnMessage){ try { predictionApplyService.insert(predictionApply); returnMessage.setFlag(1); returnMessage.setMessage("预报名成功"); return returnMessage; } catch (CorbettException e) { e.printStackTrace(); returnMessage.setFlag(-1); returnMessage.setMessage(e.getMessage()); return returnMessage; }catch (Exception e) { e.printStackTrace(); returnMessage.setFlag(-1); returnMessage.setMessage("服务器正在升级,请稍候再试"); return returnMessage; } } } <file_sep>/src/main/java/com/jishi/controller/Mime_coachController.java package com.jishi.controller; import java.io.PrintWriter; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.jishi.entity.CoachInfo; import com.jishi.entity.Coach_account; import com.jishi.entity.Coach_order; import com.jishi.service.CoachLoginService; import com.jishi.service.impl.Mine_coachService; import com.jishi.until.ReturnMessage_entity; import com.jishi.until.ReturnTool; @Controller @RequestMapping(value = "/coach") public class Mime_coachController { @Resource(name = "Mine_coachService") Mine_coachService mine_coachService; @Autowired private CoachLoginService coachLoginService; @RequestMapping(value = "/getCoachInfo", method = RequestMethod.GET) @ResponseBody public void getCoachInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "coachnum", required = true) String coachnum, Coach_order coach_order) throws Exception { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { ReturnMessage_entity<CoachInfo> rM = coachLoginService.checktoken(token); CoachInfo coachInfo = rM.getData(); if (rM.getFlag() == -3) { out.write(ReturnTool.getJsonMessageResult(-3, rM.getMessage())); return; } coach_order.setInscode(coachInfo.getInsCode()); int orderCount = mine_coachService.getCoachInfo(coach_order); Map result = mine_coachService.getCoachAmount(coach_order); result.put("orderCount", orderCount); out.write(ReturnTool.getJsonObjectResult(1, "请求成功", result)); } catch (Exception e) { // TODO: handle exception out.write(ReturnTool.getJsonMessageResult(-1, "请求失败")); } } @RequestMapping(value = "/getUserInfo-1", method = RequestMethod.GET) @ResponseBody public void getUserInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "coachnum", required = true) String coachnum, Coach_order coach_order) throws Exception { response.setContentType("text/json;charset=UTF-8"); PrintWriter out = response.getWriter(); try { ReturnMessage_entity<CoachInfo> rM = coachLoginService.checktoken(token); CoachInfo coachInfo = rM.getData(); if (rM.getFlag() == -3) { out.write(ReturnTool.getJsonMessageResult(-1, "用户数据出错")); return; } coach_order.setInscode(coachInfo.getInsCode()); Coach_account coach_account = mine_coachService.getUserInfo(coach_order); out.write(ReturnTool.getJsonObjectResult(1, "请求成功", coach_account)); } catch (Exception e) { // TODO: handle exception out.write(ReturnTool.getJsonMessageResult(-1, "请求失败")); } } @RequestMapping(value = "/setUserInfo-1", method = RequestMethod.POST) @ResponseBody public void setUserInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "coachJJ", required = true) String coachJJ, @RequestParam(value = "coachnum", required = true) String coachnum, Coach_account coach_account) throws Exception { response.setContentType("text/json;charset=UTF-8"); PrintWriter out = response.getWriter(); try { ReturnMessage_entity<CoachInfo> rM = coachLoginService.checktoken(token); CoachInfo coachInfo = rM.getData(); if (rM.getFlag() == -3) { out.write(ReturnTool.getJsonMessageResult(-1, "用户数据出错")); return; } coach_account.setInscode(coachInfo.getInsCode()); int result = mine_coachService.setUserInfo(coach_account); out.write(ReturnTool.getJsonMessageResult(1, "修改成功")); } catch (Exception e) { // TODO: handle exception out.write(ReturnTool.getJsonMessageResult(-1, "请求失败")); } } @RequestMapping(value = "/updatePWD", method = RequestMethod.POST) @ResponseBody public void updatePassword(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "oldPassword", required = true) String oldPassword, @RequestParam(value = "newPassword", required = true) String newPassword, Coach_account coach_account) throws Exception { response.setContentType("text/json;charset=UTF-8"); PrintWriter out = response.getWriter(); try { ReturnMessage_entity<CoachInfo> rM = coachLoginService.checktoken(token); CoachInfo coachInfo = rM.getData(); if (rM.getFlag() == -3) { out.write(ReturnTool.getJsonMessageResult(-1, "用户数据出错")); return; } coach_account.setInscode(coachInfo.getInsCode()); Map<String, String> accMap = new HashMap<String, String>(); accMap.put("password", <PASSWORD>); accMap.put("coachnum", coachInfo.getCoachNum()); accMap.put("newPassword", <PASSWORD>); if (mine_coachService.checkPassword(accMap) == 1) { if (mine_coachService.updatePassword(accMap) == 1) { out.write(ReturnTool.getJsonMessageResult(1, "修改成功")); } } else { out.write(ReturnTool.getJsonMessageResult(-1, "原密码错误")); } } catch (Exception e) { // TODO: handle exception out.write(ReturnTool.getJsonMessageResult(-1, "请求失败")); } } @RequestMapping(value = "/surePay", method = RequestMethod.POST) @ResponseBody public void surePay(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "coachnum", required = true) String coachnum, @RequestParam(value = "ordernum", required = true) String ordernum, Coach_account coach_account) throws Exception { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { ReturnMessage_entity<CoachInfo> rM = coachLoginService.checktoken(token); CoachInfo coachInfo = rM.getData(); if (rM.getFlag() == -3) { out.write(ReturnTool.getJsonMessageResult(-1, "用户数据出错")); return; } coach_account.setInscode(coachInfo.getInsCode()); Map param = new HashMap(); param.put("ordernum", ordernum); param.put("coachnum", coachnum); // 获取服务费 Map serviceMoneyMap = mine_coachService.getServicePay(param); // 获取教练余额 Map coachAmountMap = mine_coachService.checkCoachAmount(param); float serviceMoney = (Float) serviceMoneyMap.get("serviceMoney"); float coachAmount = (Float) coachAmountMap.get("coachAmount"); float schoolAmount = (Float) coachAmountMap.get("schoolAmount"); String stunum = (String) serviceMoneyMap.get("stunum"); float money = (Float) serviceMoneyMap.get("money"); if (serviceMoney <= coachAmount) { Map coachTakeMap = new HashMap(); coachTakeMap.put("stunum", stunum); coachTakeMap.put("coachnum", coachnum); coachTakeMap.put("inscode", coachInfo.getInsCode()); coachTakeMap.put("money", -money); coachTakeMap.put("remark", "教练线下收取"); coachTakeMap.put("coachAmount", coachAmount - money); coachTakeMap.put("inscodeAmount", schoolAmount - money); coachTakeMap.put("createdate", new Date()); coachTakeMap.put("ordernum", ordernum); // 添加教练收支表的支出(提现) if (mine_coachService.addCoachTakeMoney(coachTakeMap) == 1) { Map coachAddMap = new HashMap(); coachAddMap.put("stunum", stunum); coachAddMap.put("coachnum", coachnum); coachAddMap.put("inscode", coachInfo.getInsCode()); coachAddMap.put("money", money - serviceMoney); coachAddMap.put("remark", "教练收取学费"); coachAddMap.put("coachAmount", coachAmount - serviceMoney); coachAddMap.put("inscodeAmount", schoolAmount - serviceMoney); coachAddMap.put("createdate", new Date()); coachAddMap.put("ordernum", ordernum); if (mine_coachService.addCoachTakeMoney(coachAddMap) == 1) { if (mine_coachService.changeOrderStatus(param) == 1) { Map payRecordMap = new HashMap(); payRecordMap.put("ordernum", ordernum); payRecordMap.put("stuOrCoach", 2); payRecordMap.put("paydate", new Date()); payRecordMap.put("payStyle", 3); payRecordMap.put("paySerialnum", ""); payRecordMap.put("money", money); payRecordMap.put("payAccount", ""); payRecordMap.put("incomeAccount", ""); if (mine_coachService.addPayRecord(payRecordMap) == 1) { Map newAmount = new HashMap(); newAmount.put("newAmount", coachAmount - serviceMoney); newAmount.put("coachnum", coachnum); if (mine_coachService.updateCoachAmount(newAmount) == 1) { out.write(ReturnTool.getJsonMessageResult(1, "支付成功")); } ; } ; } } } } else { out.write(ReturnTool.getJsonMessageResult(-1, "余额不足")); } } catch (Exception e) { // TODO: handle exception out.write(ReturnTool.getJsonMessageResult(-1, "请求失败")); } } } <file_sep>/src/main/java/com/jishi/service/StuFocusService.java package com.jishi.service; import com.corbett.exception.CorbettException; import com.jishi.entity.StuFocusCoach; import com.jishi.entity.StuFocusSchool; import com.jishi.entity.view.View_nearby_coach; import com.jishi.entity.view.View_nearby_school; import java.util.List; import java.util.Map; /** * Created by hasee on 2017/7/8. */ public interface StuFocusService { List<View_nearby_coach> getFocusCoachList(Map<String,Object> map); int getFocusCoachListCount(Map<String,Object> map); List<View_nearby_school> getFocusInscodeList(Map<String,Object> map); int getFocusInscodeListCount(Map<String,Object> map); void insert(StuFocusCoach stuFocusCoach) throws CorbettException; void insert(StuFocusSchool stuFocusSchool) throws CorbettException; } <file_sep>/src/main/java/com/jishi/entity/Institution.java package com.jishi.entity; import java.util.Date; import com.jiaquwork.entity.datacenter.School; /** * 培训结构 * */ public class Institution { private String inscode; private String district; private String name; private String shortname; private String licnum; private String licetime; private String business; private String creditcode; private String address; private String postcode; private String legal; private String contact; private String phone; private String busiscope; private String busistatus; private String level; private String coachnumber; private String grasupvnum; private String safmngnum; private String tracarnum; private String classroom; private String thclassroom; private String praticefield; private Date createdate; private Date recorddate; private String status; private String province; private String city; private String recorddateStart; private String recorddateEnd; public String getRecorddateStart() { return recorddateStart; } public void setRecorddateStart(String recorddateStart) { this.recorddateStart = recorddateStart; } public String getRecorddateEnd() { return recorddateEnd; } public void setRecorddateEnd(String recorddateEnd) { this.recorddateEnd = recorddateEnd; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } private int pagestart; //分页起始 private int pagesize; public int getPagestart() { return pagestart; } public void setPagestart(int pagestart) { this.pagestart = pagestart; } public int getPagesize() { return pagesize; } public void setPagesize(int pagesize) { this.pagesize = pagesize; } public String getInscode() { return inscode; } public void setInscode(String inscode) { this.inscode = inscode; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getShortname() { return shortname; } public void setShortname(String shortname) { this.shortname = shortname; } public String getLicnum() { return licnum; } public void setLicnum(String licnum) { this.licnum = licnum; } public String getLicetime() { return licetime; } public void setLicetime(String licetime) { this.licetime = licetime; } public String getBusiness() { return business; } public void setBusiness(String business) { this.business = business; } public String getCreditcode() { return creditcode; } public void setCreditcode(String creditcode) { this.creditcode = creditcode; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPostcode() { return postcode; } public void setPostcode(String postcode) { this.postcode = postcode; } public String getLegal() { return legal; } public void setLegal(String legal) { this.legal = legal; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getBusiscope() { return busiscope; } public void setBusiscope(String busiscope) { this.busiscope = busiscope; } public String getBusistatus() { return busistatus; } public void setBusistatus(String busistatus) { this.busistatus = busistatus; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getCoachnumber() { return coachnumber; } public void setCoachnumber(String coachnumber) { this.coachnumber = coachnumber; } public String getGrasupvnum() { return grasupvnum; } public void setGrasupvnum(String grasupvnum) { this.grasupvnum = grasupvnum; } public String getSafmngnum() { return safmngnum; } public void setSafmngnum(String safmngnum) { this.safmngnum = safmngnum; } public String getTracarnum() { return tracarnum; } public void setTracarnum(String tracarnum) { this.tracarnum = tracarnum; } public String getClassroom() { return classroom; } public void setClassroom(String classroom) { this.classroom = classroom; } public String getThclassroom() { return thclassroom; } public void setThclassroom(String thclassroom) { this.thclassroom = thclassroom; } public String getPraticefield() { return praticefield; } public void setPraticefield(String praticefield) { this.praticefield = praticefield; } public Date getCreatedate() { return createdate; } public void setCreatedate(Date createdate) { this.createdate = createdate; } public Date getRecorddate() { return recorddate; } public void setRecorddate(Date recorddate) { this.recorddate = recorddate; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Institution() { // TODO Auto-generated constructor stub } public Institution(School school) { this.shortname = school.getShortname(); this.inscode = school.getInst_code(); this.tracarnum = school.getTra_car_num(); this.name = school.getName(); this.phone = school.getPhone(); this.address = school.getAddress(); } } <file_sep>/src/main/java/com/jishi/entity/view/ViewCoachStudent.java package com.jishi.entity.view; public class ViewCoachStudent { private String stunum; private String name; private String Phone; private int number; private String icon; public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getStunum() { return stunum; } public void setStunum(String stunum) { this.stunum = stunum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return Phone; } public void setPhone(String phone) { Phone = phone; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } } <file_sep>/src/main/java/com/jishi/entity/datacenter/CarSchedule.java package com.jishi.entity.datacenter; /** * 上报车辆预约排班信息 * @author 周宁 2017年5月25日 上午10:20:37 * */ public class CarSchedule { private String inst_code; private String car_num; /** * 1可约 */ private Integer car_status; private String date; public String getInst_code() { return inst_code; } public void setInst_code(String inst_code) { this.inst_code = inst_code; } public String getCar_num() { return car_num; } public void setCar_num(String car_num) { this.car_num = car_num; } public Integer getCar_status() { return car_status; } public void setCar_status(Integer car_status) { this.car_status = car_status; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public CarSchedule(String inst_code, String car_num, Integer car_status, String date) { super(); this.inst_code = inst_code; this.car_num = car_num; this.car_status = car_status; this.date = date; } public CarSchedule() { // TODO Auto-generated constructor stub } } <file_sep>/src/main/java/com/jishi/dao/JsStuComplaintsMapper.java package com.jishi.dao; import com.jishi.entity.JsStuComplaints; import com.jishi.entity.JsStuComplaintsExample; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; public interface JsStuComplaintsMapper { /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_complaints * @mbggenerated Thu Apr 20 09:39:29 CST 2017 */ int countByExample(JsStuComplaintsExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_complaints * @mbggenerated Thu Apr 20 09:39:29 CST 2017 */ int deleteByExample(JsStuComplaintsExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_complaints * @mbggenerated Thu Apr 20 09:39:29 CST 2017 */ int deleteByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_complaints * @mbggenerated Thu Apr 20 09:39:29 CST 2017 */ int insert(JsStuComplaints record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_complaints * @mbggenerated Thu Apr 20 09:39:29 CST 2017 */ int insertSelective(JsStuComplaints record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_complaints * @mbggenerated Thu Apr 20 09:39:29 CST 2017 */ List<JsStuComplaints> selectByExample(JsStuComplaintsExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_complaints * @mbggenerated Thu Apr 20 09:39:29 CST 2017 */ JsStuComplaints selectByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_complaints * @mbggenerated Thu Apr 20 09:39:29 CST 2017 */ int updateByExampleSelective(@Param("record") JsStuComplaints record, @Param("example") JsStuComplaintsExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_complaints * @mbggenerated Thu Apr 20 09:39:29 CST 2017 */ int updateByExample(@Param("record") JsStuComplaints record, @Param("example") JsStuComplaintsExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_complaints * @mbggenerated Thu Apr 20 09:39:29 CST 2017 */ int updateByPrimaryKeySelective(JsStuComplaints record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_complaints * @mbggenerated Thu Apr 20 09:39:29 CST 2017 */ int updateByPrimaryKey(JsStuComplaints record); }<file_sep>/src/main/java/com/jishi/service/UsersService.java package com.jishi.service; import com.jishi.enums.UserType; import com.jishi.until.ReturnMessage; public interface UsersService { static final String IS_VISITER = "isVisiter"; static final String TOKEN = "token"; /** * 修改密码 * @param phone * @param newPassword * @param code * @return */ ReturnMessage updatePassword(String phone,String newPassword,String code ); /** * 修改简介 * @param object * @return * @throws Exception */ int setUserInfo(Object object) throws Exception; /** * 获取用户信息 * @param object * @return * @throws Exception */ Object getUserInfo(Object object) throws Exception; /** * 注册 * @param phoneNumber * @param code * @param password * @return * @throws Exception */ ReturnMessage registered(String phoneNumber,String code,UserType userType, String password) throws Exception; } <file_sep>/src/main/resources/config.properties photoRealUrl=D://Program Files//apache-tomcat//apache-tomcat-7.0.67//webapps//img// photoViewUrl=http://localhost:8081/img/<file_sep>/src/main/java/com/jishi/enums/UserType.java package com.jishi.enums; public enum UserType { COACH("getCoachOrder"),STU(""); private String getOrderBeanName; private UserType(String getOrderBeanName) { setGetOrderBeanName(getOrderBeanName); } public String getGetOrderBeanName() { return getOrderBeanName; } public void setGetOrderBeanName(String getOrderBeanName) { this.getOrderBeanName = getOrderBeanName; } } <file_sep>/src/main/java/com/jishi/service/impl/PushStuBespeak.java package com.jishi.service.impl; import java.io.IOException; import java.util.Map; import com.jishi.dao.PushdataStuSpeakDao; import com.jishi.entity.datacenter.StuBespeak; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.corbett.enums.RequestMethod; import com.corbett.utils.http.HttpClient; import com.jiaquwork.util.DataCenterAPI; import com.jishi.service.AbstractPushData; @Service("PushStuBespeak") public class PushStuBespeak extends AbstractPushData { @Autowired private PushdataStuSpeakDao pushdataStuSpeakDao; @Override protected String getData(Map<String, Object> object) throws IOException { return HttpClient.getUrlData(DataCenterAPI.API_SEND_BESPEAK, object, RequestMethod.PUT, HttpClient.getRequestHeader()); } @Override protected void insert(Object object) { if(object instanceof StuBespeak){ pushdataStuSpeakDao.insert(object); } } } <file_sep>/src/main/java/com/jishi/service/impl/TestAdvice.java package com.jishi.service.impl; import java.util.Date; import javax.annotation.Resource; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import com.jishi.entity.Sms; @Order(1) @Component @Aspect public class TestAdvice { @Resource(name="UserService") UserService userService; @Around("execution(* com.jishi.service.impl.CoachLoginServiceImpl.insertloginphones(..))") public Object tLog(ProceedingJoinPoint pjp) throws Throwable{ System.out.println("kaishi抛异常"); Sms sms=new Sms(); sms.setTel("18957700301"); sms.setCode(Integer.valueOf(5656)); sms.setCheckdate(new Date()); userService.updateSmsUsed(sms); // throw new NullPointerException("nimabi"); return pjp.proceed(); } } <file_sep>/src/main/java/com/jishi/entity/rece/ReceFaceInfo.java package com.jishi.entity.rece; import org.springframework.web.multipart.MultipartFile; public class ReceFaceInfo { private MultipartFile studentPhoto; //学员照片 private String token; public MultipartFile getStudentPhoto() { return studentPhoto; } public void setStudentPhoto(MultipartFile studentPhoto) { this.studentPhoto = studentPhoto; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } } <file_sep>/src/main/java/com/jishi/entity/Editlateplan.java package com.jishi.entity; public class Editlateplan { private String date; private int subjecthours; private String starttime; private String endtime; private float price; private int part; private int confirmapplystyle; private int days; private int canapplynumber; private int seq; public int getSeq() { return seq; } public void setSeq(int seq) { this.seq = seq; } public int getCanapplynumber() { return canapplynumber; } public void setCanapplynumber(int canapplynumber) { this.canapplynumber = canapplynumber; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public int getSubjecthours() { return subjecthours; } public void setSubjecthours(int subjecthours) { this.subjecthours = subjecthours; } public String getStarttime() { return starttime; } public void setStarttime(String starttime) { this.starttime = starttime; } public String getEndtime() { return endtime; } public void setEndtime(String endtime) { this.endtime = endtime; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public int getPart() { return part; } public void setPart(int part) { this.part = part; } public int getConfirmapplystyle() { return confirmapplystyle; } public void setConfirmapplystyle(int confirmapplystyle) { this.confirmapplystyle = confirmapplystyle; } public int getDays() { return days; } public void setDays(int day) { this.days = day; } } <file_sep>/src/main/java/com/jishi/controller/UserController.java package com.jishi.controller; import java.io.PrintWriter; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.face.service.FaceVisa; import com.jishi.entity.CoachLogin; import com.jishi.entity.LoginResult; import com.jishi.entity.ReturnInfo; import com.jishi.entity.Sms; import com.jishi.entity.StudentAccount; import com.jishi.entity.rece.ReceFaceInfo; import com.jishi.service.CoachLoginService; import com.jishi.service.impl.UserService; import com.jishi.until.DateUtil; import com.jishi.until.GetSmsTool; import com.jishi.until.NumberUtil; import com.jishi.until.ReturnTool; import com.jishi.until.UploadUtil; @Controller @RequestMapping(value="/user") public class UserController { @Resource(name="UserService") UserService userService; /*PrintWriter out = response.getWriter();*/ /* * 上传人脸照片 * ADD BY LXJ AT 2016/09/20 * .... * */ @RequestMapping(value="/send_face") @ResponseBody public ReturnInfo sendFace(ReceFaceInfo form) throws Exception { ReturnInfo reMsg = new ReturnInfo(); if( form.getToken()==null || form.getToken().length()<1 ) { reMsg.setFlag(-1); reMsg.setMessage("token为空"); return reMsg; } if( form.getStudentPhoto()==null ) { reMsg.setFlag(-1); reMsg.setMessage("图片未上传"); return reMsg; } reMsg = UploadUtil.UpStudentPhoto(form.getStudentPhoto()); //上传照片 if( reMsg.getFlag()!=1 ) return reMsg; String pathFile = String.valueOf(reMsg.getMessage()); reMsg = userService.getStuInfoByToken(form.getToken()); //根据学员TOKEN获取相应信息 if( reMsg.getFlag()!=1 ) return reMsg; String stuNum = reMsg.getStudentInfo().getStunum(); int n =userService.checkPhoto(stuNum); if( n > 4) { reMsg.setFlag(-1); reMsg.setMessage("人脸照片不能超过5张"); return reMsg; } reMsg = FaceVisa.upFacePhoto(String.valueOf(reMsg.getStudentInfo().getPersonId()), "1", pathFile); //人脸上传 if( reMsg.getFlag()!=1 ) return reMsg; String photoUrl = pathFile.substring(pathFile.lastIndexOf("/")+1); reMsg = userService.addPhoto(String.valueOf(reMsg.getMessage()), stuNum, photoUrl); //添加本地库 if( reMsg.getFlag()!=1 ) return reMsg; reMsg.setFlag(1); reMsg.setMessage("上传成功"); return reMsg; } //登录defaultValue这个是默认值 @RequestMapping(value = "/login",method =RequestMethod.POST) public void toLogin(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="phone", required=true) String phone, @RequestParam(value="password", required=true) String password, @RequestParam(value="registrationID", required=true) String registrationID )throws Exception { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); StudentAccount student=new StudentAccount(); student.setUserid(phone); student.setPassword(<PASSWORD>); try { LoginResult resultInfo=userService.getStudentByPhone(student); if (resultInfo!=null) { if (userService.checkStudentIsRecord(student)==2) { Map paramter = new HashMap(); paramter.put("registrationID",registrationID); paramter.put("userid",phone); userService.addRegistrationID(paramter); String nameString=userService.getInscodeName(resultInfo.getInscode()); resultInfo.setName(nameString); out.write(ReturnTool.getJsonObjectResult(1, "登录成功",resultInfo)); } else { out.write(ReturnTool.getJsonMessageResult(0, "该学员未备案")); } } else { out.write(ReturnTool.getJsonMessageResult(-1, "用户名或者密码错误")); } } catch (Exception e) { out.write(ReturnTool.getJsonMessageResult(-2, "服务器异常")); } } @Autowired private CoachLoginService coachLoginService; @RequestMapping(value = "/getSms-1",method =RequestMethod.POST) public void getSms(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="phone", required=true) String phone) throws Exception { response.setContentType("text/html;charset=UTF-8"); //发送验证码 PrintWriter out = response.getWriter(); StudentAccount student =new StudentAccount(); student.setUserid(phone); StudentAccount result = userService.checkStudentAccountByPhoneOld(student); CoachLogin checkphone = coachLoginService.checkphone(phone); if (result==null && checkphone == null) { out.write(ReturnTool.getJsonMessageResult(-2, "该账号不存在")); return; } int code= (int) (Math.random()*9000+1000); if ( GetSmsTool.sendSms("你的验证码是"+code+",有效时间15分钟",phone).equals("0")) { Sms sms=new Sms(); sms.setCode(code); sms.setTel(phone); Date date = new Date(); sms.setCreatedate(new Date()); sms.setInvaliddate(DateUtil.fomatDate(DateUtil.getAfterminutime("15"))); if(userService.recordSms(sms)==1) { out.write(ReturnTool.getJsonMessageResult(1, "发送成功")); } else { out.write(ReturnTool.getJsonMessageResult(0, "发送失败")); } } else { out.write(ReturnTool.getJsonMessageResult(-1, "短信异常")); } } //注册 @RequestMapping(value = "/update",method =RequestMethod.POST) public void toRegister(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="phone", required=true) String phone,@RequestParam(value="password", required=true) String password,@RequestParam(value="code", required=true) int code) throws Exception { //检测验证码 response.setContentType("text/html;charset=UTF-8"); Sms sms=new Sms(); sms.setTel(phone); sms.setCode(code); sms.setCheckdate(new Date()); PrintWriter out = response.getWriter(); try { int n = userService.checkSms(sms); if (userService.checkSms(sms)>0) { StudentAccount student =new StudentAccount(); student.setUserid(phone); student.setPassword(<PASSWORD>); StudentAccount result = userService.checkStudentAccountByPhoneOld(student); if (result!=null) { if (userService.checkStudentAccountByPhoneNew(student)>0) { //这里是修改密码 userService.updateUserPassword(student); userService.updateSmsUsed(sms); } else { //这里是创建账号 student.setStunum(result.getStunum()); student.setToken(NumberUtil.getToken()); student.setStunum(result.getStunum()); userService.addUser(student); userService.updateSmsUsed(sms); } out.write(ReturnTool.getJsonMessageResult(1, "修改成功")); } else { out.write(ReturnTool.getJsonMessageResult(-1, "用户不存在")); } } else { out.write(ReturnTool.getJsonMessageResult(0, "验证码错误")); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } } <file_sep>/src/main/java/com/jishi/entity/rt/Simuclass_rt.java package com.jishi.entity.rt; public class Simuclass_rt { private String startdDate; int isExist; public String getStartdDate() { return startdDate; } public void setStartdDate(String startdDate) { this.startdDate = startdDate; } public int getIsExist() { return isExist; } public void setIsExist(int isExist) { this.isExist = isExist; } } <file_sep>/src/main/java/com/jishi/entity/view/ViewTrainHourPrice.java package com.jishi.entity.view; public class ViewTrainHourPrice { private float HourPrice; public float getHourPrice() { return HourPrice; } public void setHourPrice(float hourPrice) { HourPrice = hourPrice; } } <file_sep>/src/main/java/com/jishi/entity/ReturnInfo.java package com.jishi.entity; /* * 返回实体 * ADD BY LXJ AT 2016/9/6 * */ public class ReturnInfo { private int flag; //返回编号 private Object message; //返回信息 //private Object coachInfo; //教练相关信息 //private Object jishiInfo; //计时相关信息 private StudentInfo studentInfo; public StudentInfo getStudentInfo() { return studentInfo; } public void setStudentInfo(StudentInfo studentInfo) { this.studentInfo = studentInfo; } // public Object getCoachInfo() { // return coachInfo; // } // public void setCoachInfo(Object coachInfo) { // this.coachInfo = coachInfo; // } // public Object getJishiInfo() { // return jishiInfo; // } // public void setJishiInfo(Object jishiInfo) { // this.jishiInfo = jishiInfo; // } public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } public Object getMessage() { return message; } public void setMessage(Object message) { this.message = message; } } <file_sep>/src/main/java/com/jishi/dao/JsProsecutedComplaintsPhotoMapper.java package com.jishi.dao; import com.jishi.entity.JsProsecutedComplaintsPhoto; import com.jishi.entity.JsProsecutedComplaintsPhotoExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface JsProsecutedComplaintsPhotoMapper { /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_prosecuted_complaints_photo * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ int countByExample(JsProsecutedComplaintsPhotoExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_prosecuted_complaints_photo * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ int deleteByExample(JsProsecutedComplaintsPhotoExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_prosecuted_complaints_photo * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ int deleteByPrimaryKey(Integer prosecutedComplaintsPhotoId); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_prosecuted_complaints_photo * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ int insert(JsProsecutedComplaintsPhoto record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_prosecuted_complaints_photo * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ int insertSelective(JsProsecutedComplaintsPhoto record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_prosecuted_complaints_photo * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ List<JsProsecutedComplaintsPhoto> selectByExample(JsProsecutedComplaintsPhotoExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_prosecuted_complaints_photo * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ JsProsecutedComplaintsPhoto selectByPrimaryKey(Integer prosecutedComplaintsPhotoId); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_prosecuted_complaints_photo * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ int updateByExampleSelective(@Param("record") JsProsecutedComplaintsPhoto record, @Param("example") JsProsecutedComplaintsPhotoExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_prosecuted_complaints_photo * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ int updateByExample(@Param("record") JsProsecutedComplaintsPhoto record, @Param("example") JsProsecutedComplaintsPhotoExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_prosecuted_complaints_photo * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ int updateByPrimaryKeySelective(JsProsecutedComplaintsPhoto record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_prosecuted_complaints_photo * @mbggenerated Thu Apr 20 10:45:50 CST 2017 */ int updateByPrimaryKey(JsProsecutedComplaintsPhoto record); }<file_sep>/src/main/java/com/jishi/entity/datacenter/Complaint.java package com.jishi.entity.datacenter; /** * 上报学员投诉信息 * @author 周宁 2017年5月25日 上午10:21:16 * */ public class Complaint { private Integer id; private Integer sub_id; private String call_url; private String inst_code; private String stu_num; private String name; private Integer sex; private String c_date; private String c_type; private String obj_num; private String obj_name; private String content; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getSub_id() { return sub_id; } public void setSub_id(Integer sub_id) { this.sub_id = sub_id; } public String getCall_url() { return call_url; } public void setCall_url(String call_url) { this.call_url = call_url; } public String getInst_code() { return inst_code; } public void setInst_code(String inst_code) { this.inst_code = inst_code; } public String getStu_num() { return stu_num; } public void setStu_num(String stu_num) { this.stu_num = stu_num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public String getC_date() { return c_date.substring(0, 10); } public void setC_date(String c_date) { this.c_date = c_date; } public String getC_type() { return c_type; } public void setC_type(String c_type) { this.c_type = c_type; } public String getObj_num() { return obj_num; } public void setObj_num(String obj_num) { this.obj_num = obj_num; } public String getObj_name() { return obj_name; } public void setObj_name(String obj_name) { this.obj_name = obj_name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Complaint(Integer id, Integer sub_id, String call_url, String inst_code, String stu_num, String name, Integer sex, String c_date, String c_type, String obj_num, String obj_name, String content) { super(); this.id = id; this.sub_id = sub_id; this.call_url = call_url; this.inst_code = inst_code; this.stu_num = stu_num; this.name = name; this.sex = sex; this.c_date = c_date; this.c_type = c_type; this.obj_num = obj_num; this.obj_name = obj_name; this.content = content; } public Complaint() { // TODO Auto-generated constructor stub } @Override public String toString() { return "ComplaintView{" + "id=" + id + ", sub_id=" + sub_id + ", call_url='" + call_url + '\'' + ", inst_code='" + inst_code + '\'' + ", stu_num='" + stu_num + '\'' + ", name='" + name + '\'' + ", sex=" + sex + ", c_date='" + c_date + '\'' + ", c_type='" + c_type + '\'' + ", obj_num='" + obj_num + '\'' + ", obj_name='" + obj_name + '\'' + ", content='" + content + '\'' + '}'; } } <file_sep>/src/main/java/com/jishi/entity/CoachLogin.java package com.jishi.entity; import java.sql.Timestamp; public class CoachLogin { private int Id; private String CoachNum; private String Phone; private String PassWord; private String Token; private Timestamp LoginDate; private String registrationID; private int isVisiter;//是否是游客 public int getIsVisiter() { return isVisiter; } public void setIsVisiter(int isVisiter) { this.isVisiter = isVisiter; } public String getRegistrationID() { return registrationID; } public void setRegistrationID(String registrationID) { this.registrationID = registrationID; } public int getId() { return Id; } public void setId(int id) { Id = id; } public String getCoachNum() { return CoachNum; } public void setCoachNum(String coachNum) { CoachNum = coachNum; } public String getPhone() { return Phone; } public void setPhone(String phone) { Phone = phone; } public String getPassWord() { return PassWord; } public void setPassWord(String passWord) { PassWord = passWord; } public String getToken() { return Token; } public void setToken(String token) { Token = token; } public Timestamp getLoginDate() { return LoginDate; } public void setLoginDate(Timestamp loginDate) { LoginDate = loginDate; } } <file_sep>/src/main/java/com/jishi/entity/lateplanInfo.java package com.jishi.entity; import java.sql.Timestamp; public class lateplanInfo { private String plannum; private String inscode; private String itemnum; private int part; private String startdate; private String enddate; private String starttime; private String endtime; private String seqnum; private String coachnum; private String name; private int confirmapplystyle; private int status; private int subjecthours; private int canapplynumber; private Timestamp createdate; private int haveapplynumber; private int pricetype; private float price; private String address; private int Pagestart;// ��ǰ���� private int pagesize;// ��ǰ���� private int IsSimulate; private String stunum; private String simunum; private String moblie; public String getMoblie() { return moblie; } public void setMoblie(String moblie) { this.moblie = moblie; } private int seq; public int getSeq() { return seq; } public void setSeq(int seq) { this.seq = seq; } public String getSimunum() { return simunum; } public void setSimunum(String simunum) { this.simunum = simunum; } public String getStunum() { return stunum; } public void setStunum(String stunum) { this.stunum = stunum; } /** * add 2017.3.22 by zn * * @return */ private int isPractice; private int ispay; public int getIspay() { return ispay; } public void setIspay(int ispay) { this.ispay = ispay; } public int getIsPractice() { return isPractice; } public void setIsPractice(int isPractice) { this.isPractice = isPractice; } public int getIsSimulate() { return IsSimulate; } public void setIsSimulate(int isSimulate) { IsSimulate = isSimulate; } public int getPagestart() { return Pagestart; } public void setPagestart(int pagestart) { Pagestart = pagestart; } public int getPagesize() { return pagesize; } public void setPagesize(int pagesize) { this.pagesize = pagesize; } public String getPlannum() { return plannum; } public void setPlannum(String plannum) { this.plannum = plannum; } public String getInscode() { return inscode; } public void setInscode(String inscode) { this.inscode = inscode; } public String getItemnum() { return itemnum; } public void setItemnum(String itemnum) { this.itemnum = itemnum; } public int getPart() { return part; } public void setPart(int part) { this.part = part; } public String getStartdate() { return startdate; } public void setStartdate(String startdate) { this.startdate = startdate; } public String getEnddate() { return enddate; } public void setEnddate(String enddate) { this.enddate = enddate; } public String getStarttime() { return starttime; } public void setStarttime(String starttime) { this.starttime = starttime; } public String getEndtime() { return endtime; } public void setEndtime(String endtime) { this.endtime = endtime; } public String getSeqnum() { return seqnum; } public void setSeqnum(String seqnum) { this.seqnum = seqnum; } public String getCoachnum() { return coachnum; } public void setCoachnum(String coachnum) { this.coachnum = coachnum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getConfirmapplystyle() { return confirmapplystyle; } public void setConfirmapplystyle(int confirmapplystyle) { this.confirmapplystyle = confirmapplystyle; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getSubjecthours() { return subjecthours; } public void setSubjecthours(int subjecthours) { this.subjecthours = subjecthours; } public int getCanapplynumber() { return canapplynumber; } public void setCanapplynumber(int canapplynumber) { this.canapplynumber = canapplynumber; } public Timestamp getCreatedate() { return createdate; } public void setCreatedate(Timestamp createdate) { this.createdate = createdate; } public int getHaveapplynumber() { return haveapplynumber; } public void setHaveapplynumber(int haveapplynumber) { this.haveapplynumber = haveapplynumber; } public int getPricetype() { return pricetype; } public void setPricetype(int pricetype) { this.pricetype = pricetype; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } <file_sep>/src/main/java/com/jishi/controller/SimuclassController.java package com.jishi.controller; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.jishi.entity.Simuclass; import com.jishi.entity.StudentInfo; import com.jishi.entity.StulateplanInfo; import com.jishi.entity.rt.SimuclassDetail_rt; import com.jishi.entity.view.View_IsCourse_bycoachnum; import com.jishi.entity.view.View_UnPayOrder; import com.jishi.entity.view.View_stu_coach; import com.jishi.service.LateplanService; import com.jishi.service.SimuclassService; import com.jishi.service.TrainService; import com.jishi.service.impl.UserService; import com.jishi.until.DateUtil; import com.jishi.until.ReturnMessage; import com.jishi.until.ReturnMessageList; import com.jishi.until.ReturnMessage_entity; @Controller @RequestMapping(value = "/simuclass") public class SimuclassController { @Resource(name = "SimuclassService") SimuclassService simuclassService; @Resource(name = "UserService") UserService userService; @Resource(name = "TrainService") TrainService trainService; @Resource(name = "LateplanService") LateplanService lateplanService; @RequestMapping(value = "/getCoach_by_stunum", method = RequestMethod.GET) @ResponseBody public ReturnMessage_entity<View_stu_coach> getCoaches(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "token", required = true) String token) throws Exception { ReturnMessage_entity<View_stu_coach> Rm = new ReturnMessage_entity<View_stu_coach>(); ReturnMessage_entity<StudentInfo> R = trainService.checkOwn(token); if (R.getFlag() == -1) { Rm.setFlag(-3); Rm.setMessage(R.getMessage()); return Rm; } try { View_stu_coach view_stu_coach = simuclassService.getCoach_by_stunum(R.getData().getStunum()); Rm.setFlag(1); Rm.setMessage("获取成功"); Rm.setData(view_stu_coach); return Rm; } catch (Exception e) { // TODO: handle exception Rm.setFlag(-1); Rm.setMessage("服务器正在维护"); return Rm; } } @RequestMapping(value = "/getSimuclassDetailByDate", method = RequestMethod.GET) @ResponseBody public ReturnMessageList<SimuclassDetail_rt> getSimuclassByDate(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "date", required = true) String date, @RequestParam(value = "token", required = true) String token, @RequestParam(value = "coachnum", required = true) String coachnum, @RequestParam(value = "part", required = true) int part) { ReturnMessageList<SimuclassDetail_rt> Rm = new ReturnMessageList<SimuclassDetail_rt>(); try { ReturnMessage_entity<StudentInfo> R = trainService.checkOwn(token); if (R.getFlag() == -1) { Rm.setFlag(-3); Rm.setMessage(R.getMessage()); return Rm; } SimuclassDetail_rt dateDetail_rt = new SimuclassDetail_rt(); dateDetail_rt.setStartDate(date); dateDetail_rt.setCoachNum(coachnum); dateDetail_rt.setPart(part); dateDetail_rt.setStuNum(R.getData().getStunum()); List<SimuclassDetail_rt> lst = simuclassService.getSimuclassDetailByDate(dateDetail_rt); for (SimuclassDetail_rt simuclassDetail_rt : lst) { if (simuclassDetail_rt.getIsReserved() > 0) { simuclassDetail_rt.setIsReserved(1); } } Rm.setData(lst); Rm.setFlag(1); Rm.setMessage("获取成功"); return Rm; } catch (Exception e) { // TODO Auto-generated catch block System.err.println(e.getMessage()); Rm.setFlag(-1); Rm.setMessage("服务器正在维护"); return Rm; } } @RequestMapping(value = "/getSimuclassByDate", method = RequestMethod.GET) @ResponseBody public ReturnMessageList<View_IsCourse_bycoachnum> getSimuclassDetailByDate(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "date", required = true) String date, @RequestParam(value = "coachnum", required = true) String coachnum, @RequestParam(value = "part", required = true) int part, @RequestParam(value = "token", required = true) String token) { ReturnMessageList<View_IsCourse_bycoachnum> Rm = new ReturnMessageList<View_IsCourse_bycoachnum>(); try { ReturnMessage_entity<StudentInfo> R = trainService.checkOwn(token); if (R.getFlag() == -1) { Rm.setFlag(-3); Rm.setMessage(R.getMessage()); return Rm; } SimuclassDetail_rt rt = new SimuclassDetail_rt(); // 取date后7天数据 String endate = DateUtil.getSpecifiedDayBefore(date, 6); rt.setStartTime(date); rt.setEndTime(endate); rt.setCoachNum(coachnum); rt.setPart(part); List<View_IsCourse_bycoachnum> data = simuclassService.get_Simuclass_ByDate(rt); List<View_IsCourse_bycoachnum> lst = new ArrayList<View_IsCourse_bycoachnum>(); for (int i = 0; i < 7; i++) { View_IsCourse_bycoachnum model = new View_IsCourse_bycoachnum(); model.setDate(DateUtil.getSpecifiedDayBefore(date, i)); model.setNumber(0); for (View_IsCourse_bycoachnum item : data) { if (model.getDate().equals(item.getDate())) { model.setNumber(item.getNumber()); continue; } } lst.add(model); } Rm.setFlag(1); Rm.setMessage("获取成功"); Rm.setData(lst); return Rm; } catch (Exception e) { // TODO Auto-generated catch block System.err.println(e.getMessage()); Rm.setFlag(-1); Rm.setMessage("服务器正在维护"); return Rm; } } @RequestMapping(value = "/Reservation_course ", method = RequestMethod.POST) @ResponseBody public ReturnMessage_entity<View_UnPayOrder> sureSimuclass(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "plannum", required = true) String plannum, @RequestParam(value = "coachNum", required = true) String coachNum, @RequestParam(value = "token", required = true) String token, Simuclass simuclass) { ReturnMessage_entity<View_UnPayOrder> Rm = new ReturnMessage_entity<View_UnPayOrder>(); try { ReturnMessage_entity<StudentInfo> R = trainService.checkOwn(token); if (R.getFlag() == -1) { Rm.setFlag(-3); Rm.setMessage(R.getMessage()); return Rm; } View_UnPayOrder model = simuclassService.checkOrderOrIsPay(R.getData().getStunum()); if (model != null && model.getIsLock() == 1) { Rm.setFlag(3); Rm.setMessage("当前有记录正在练习中"); return Rm; } if (model != null && model.getIsPay() == 0) { Rm.setFlag(5); Rm.setMessage("有未支付订单"); Rm.setData(model); return Rm; } String[] plannum_arr = plannum.split(","); SimuclassDetail_rt dateDetail_rt = new SimuclassDetail_rt(); dateDetail_rt.setStuNum(R.getData().getStunum()); dateDetail_rt.setPlanNum(plannum_arr[0]); String hours = simuclassService.check_stu_date_hours(dateDetail_rt); if (hours != null && Integer.parseInt(hours) >= 4) { Rm.setFlag(-1); Rm.setMessage("当前日期已约满4学时"); Rm.setData(model); return Rm; } ReturnMessage r = simuclassService.add_student_simulate(plannum_arr, R.getData().getStunum()); if (r.getFlag() != 1) { Rm.setFlag(-1); Rm.setMessage(r.getMessage()); return Rm; } Rm.setFlag(1); Rm.setMessage("预约成功"); return Rm; } catch (Exception e) { // TODO Auto-generated catch block System.err.println(e.getMessage()); Rm.setFlag(-1); Rm.setMessage("服务器正在维护"); return Rm; } } @RequestMapping(value = "/cancelReserved", method = RequestMethod.POST) @ResponseBody public ReturnMessage cancelReserved(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "simunum", required = true) String simunum, @RequestParam(value = "reason", required = true) String reason, @RequestParam(value = "token", required = true) String token) throws Exception { ReturnMessage RM = new ReturnMessage(); ReturnMessage_entity<StudentInfo> R = trainService.checkOwn(token); if (R.getFlag() == -1) { RM.setFlag(-3); RM.setMessage(R.getMessage()); return RM; } int cek = lateplanService.checkIspractice(simunum); if (cek > 0) { RM.setFlag(-1); RM.setMessage("预约订单已经使用,不可取消"); return RM; } StulateplanInfo check = lateplanService.getstulateplanInfo(simunum); if (check.getStatus() == -1) { RM.setFlag(-1); RM.setMessage("已失效订单,请勿重复提交"); return RM; } if (!R.getData().getStunum().equals(check.getStuNum())) { RM.setFlag(-1); RM.setMessage("没有操作权限"); return RM; } try { StulateplanInfo info = new StulateplanInfo(); info.setSimuNum(simunum); info.setCancelperson(2); info.setStatus(-1); info.setCancelreason(reason); return lateplanService.cancel_reservation(check.getCoachnum(), check.getPlannum(), info); } catch (Exception e) { // TODO: handle exception System.err.println(e.getMessage()); RM.setFlag(-1); RM.setMessage("服务器正在维护"); return RM; } } } <file_sep>/src/main/java/com/jishi/entity/view/View_stu_coach.java package com.jishi.entity.view; public class View_stu_coach { private String subject2_coachid; private String subject3_coachid; private String subject2_coachname; private String subject3_coachname; public String getSubject2_coachid() { return subject2_coachid; } public void setSubject2_coachid(String subject2_coachid) { this.subject2_coachid = subject2_coachid; } public String getSubject3_coachid() { return subject3_coachid; } public void setSubject3_coachid(String subject3_coachid) { this.subject3_coachid = subject3_coachid; } public String getSubject2_coachname() { return subject2_coachname; } public void setSubject2_coachname(String subject2_coachname) { this.subject2_coachname = subject2_coachname; } public String getSubject3_coachname() { return subject3_coachname; } public void setSubject3_coachname(String subject3_coachname) { this.subject3_coachname = subject3_coachname; } } <file_sep>/src/main/java/com/jishi/entity/view/ViewStu_PayRecordInfo.java package com.jishi.entity.view; import java.sql.Timestamp; import java.text.SimpleDateFormat; public class ViewStu_PayRecordInfo { private float Money; private String Remark; private Timestamp CreateDate; public float getMoney() { return Money; } public void setMoney(float money) { Money = money; } public String getRemark() { return Remark; } public void setRemark(String remark) { Remark = remark; } public String getCreateDate() { if(CreateDate != null) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String date = format.format(CreateDate); return date; } else { return null; } } public void setCreateDate(Timestamp createDate) { CreateDate = createDate; } } <file_sep>/src/main/java/com/jishi/entity/SchoolJoin.java package com.jishi.entity; import java.util.Date; public class SchoolJoin { private String name; private String tel; private String source; private String schoolname; private Date createDate; public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getSchoolname() { return schoolname; } public void setSchoolname(String schoolname) { this.schoolname = schoolname; } } <file_sep>/src/main/java/com/jishi/dao/JsComplaintsPhotoMapper.java package com.jishi.dao; import com.jishi.entity.JsComplaintsPhoto; import com.jishi.entity.JsComplaintsPhotoExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface JsComplaintsPhotoMapper { /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_complaints_photo * @mbggenerated Thu Apr 20 10:44:40 CST 2017 */ int countByExample(JsComplaintsPhotoExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_complaints_photo * @mbggenerated Thu Apr 20 10:44:40 CST 2017 */ int deleteByExample(JsComplaintsPhotoExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_complaints_photo * @mbggenerated Thu Apr 20 10:44:40 CST 2017 */ int deleteByPrimaryKey(Integer complaintsPhotoId); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_complaints_photo * @mbggenerated Thu Apr 20 10:44:40 CST 2017 */ int insert(JsComplaintsPhoto record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_complaints_photo * @mbggenerated Thu Apr 20 10:44:40 CST 2017 */ int insertSelective(JsComplaintsPhoto record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_complaints_photo * @mbggenerated Thu Apr 20 10:44:40 CST 2017 */ List<JsComplaintsPhoto> selectByExample(JsComplaintsPhotoExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_complaints_photo * @mbggenerated Thu Apr 20 10:44:40 CST 2017 */ JsComplaintsPhoto selectByPrimaryKey(Integer complaintsPhotoId); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_complaints_photo * @mbggenerated Thu Apr 20 10:44:40 CST 2017 */ int updateByExampleSelective(@Param("record") JsComplaintsPhoto record, @Param("example") JsComplaintsPhotoExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_complaints_photo * @mbggenerated Thu Apr 20 10:44:40 CST 2017 */ int updateByExample(@Param("record") JsComplaintsPhoto record, @Param("example") JsComplaintsPhotoExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_complaints_photo * @mbggenerated Thu Apr 20 10:44:40 CST 2017 */ int updateByPrimaryKeySelective(JsComplaintsPhoto record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_complaints_photo * @mbggenerated Thu Apr 20 10:44:40 CST 2017 */ int updateByPrimaryKey(JsComplaintsPhoto record); }<file_sep>/src/main/face/com/face/config/Constants.java package com.face.config; public class Constants { // 工程根目录 public static final String ROOT_DIR = System.getProperty("user.dir"); // 接口前缀 public static final String HOST = "http://open.facevisa.com"; // 接口 public static final String A201 = "/v2/person/new"; public static final String A203 = "/v2/person/add_face"; public static final String A207 = "/v2/person/match"; public static final String A215 = "/v2/base/prepare_target"; public static final String A216 = "/v2/base/target_match"; public static final String A217 = "/v2/base/match"; public static final String A218 = "/v2/base/ocr"; public static final String A219 = "/v2/base/ocr_both"; public static final String A220 = "/v2/base/id_auth_with_img"; // ContentType public static final String TYPE1 = "application/octet-stream"; public static final String TYPE2 = "image/jpeg"; public static final String TYPE3 = "image/png"; } <file_sep>/src/main/java/com/jishi/controller/datacenter/DataPushController.java package com.jishi.controller.datacenter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONObject; import com.corbett.enums.RequestMethod; import com.corbett.utils.http.HttpClient; import com.corbett.utils.map.ObjectMap; import com.jiaquwork.service.datacenter.DataPush; import com.jiaquwork.util.DataCenterAPI; import com.jiaquwork.util.datacenter.RequestCarReservationStatusParam; import com.jiaquwork.util.datacenter.RequestCoachrReservationStatusParam; import com.jiaquwork.util.datacenter.ResponseParam; import com.jishi.entity.datacenter.CoachSchedule; import com.jishi.entity.datacenter.Complaint; import com.jishi.entity.datacenter.Evaluation; import com.jishi.entity.datacenter.Payment; import com.jishi.entity.datacenter.PushRegion; import com.jishi.entity.datacenter.Setting; import com.jishi.entity.datacenter.StuBespeak; import com.jishi.until.ReturnMessage; import com.jishi.until.ReturnMessageTool; @Controller @RequestMapping("dataPush") public class DataPushController { @Autowired private DataPush dataPush; @RequestMapping(value = "/pushCoachStatus", method = org.springframework.web.bind.annotation.RequestMethod.PUT) @ResponseBody public ReturnMessage pushCoachrReservationStatus(@RequestParam(value = "inst_code") String inst_code, @RequestParam(value = "coach_num") String coach_num, @RequestParam(value = "employ_status") String employ_status, @RequestParam(value = "lic_num") String lic_num, @RequestParam(value = "date") String date) { try { String data = dataPush.dataPush(DataCenterAPI.API_SEND_COACH, RequestMethod.PUT, HttpClient.getMapParam(RequestCoachrReservationStatusParam.inst_code, inst_code, RequestCoachrReservationStatusParam.coach_num, coach_num, RequestCoachrReservationStatusParam.employ_status, employ_status, RequestCoachrReservationStatusParam.lic_num, lic_num, RequestCoachrReservationStatusParam.date, date), HttpClient.getRequestHeader()); JSONObject jsonObject = JSONObject.parseObject(data); if (jsonObject.getString(ResponseParam.status).equals("200")) { return ReturnMessageTool.getSuccess("上报成功"); } else { return ReturnMessageTool.getError(jsonObject.getString(ResponseParam.msg)); } } catch (Exception e) { return ReturnMessageTool.getError(); } } @RequestMapping(value = "/pushCarStatus", method = org.springframework.web.bind.annotation.RequestMethod.PUT) @ResponseBody public ReturnMessage pushCarReservationStatus(@RequestParam(value = "inst_code") String inst_code, @RequestParam(value = "car_num") String car_num, @RequestParam(value = "car_status") String car_status, @RequestParam(value = "date") String date) { try { String data = dataPush.dataPush(DataCenterAPI.API_SEND_TRAININGCAR, RequestMethod.PUT, HttpClient.getMapParam(RequestCarReservationStatusParam.inst_code, inst_code, RequestCarReservationStatusParam.car_num, car_num, RequestCarReservationStatusParam.car_status, car_status, RequestCarReservationStatusParam.date, date), HttpClient.getRequestHeader()); JSONObject jsonObject = JSONObject.parseObject(data); if (jsonObject.getString(ResponseParam.status).equals("200")) { return ReturnMessageTool.getSuccess("上报成功"); } else { return ReturnMessageTool.getError(jsonObject.getString(ResponseParam.msg)); } } catch (Exception e) { return ReturnMessageTool.getError(); } } @RequestMapping(value = "/pushRegion", method = org.springframework.web.bind.annotation.RequestMethod.PUT) @ResponseBody public ReturnMessage pushRegion(PushRegion pushRegion) { try { String data = dataPush.dataPush(DataCenterAPI.API_SEND_REGION, RequestMethod.PUT,ObjectMap.transBean2Map(pushRegion), HttpClient.getRequestHeader()); JSONObject jsonObject = JSONObject.parseObject(data); if (jsonObject.getString(ResponseParam.status).equals("200")) { return ReturnMessageTool.getSuccess("上报成功"); } else { return ReturnMessageTool.getError(jsonObject.getString(ResponseParam.msg)); } } catch (Exception e) { return ReturnMessageTool.getError(); } } @RequestMapping(value = "/pushCoachSchedule", method = org.springframework.web.bind.annotation.RequestMethod.PUT) @ResponseBody public ReturnMessage pushCoachSchedule(CoachSchedule coachSchedule) { try { String data = dataPush.dataPush(DataCenterAPI.API_SEND_SCHEDULE, RequestMethod.PUT,ObjectMap.transBean2Map(coachSchedule), HttpClient.getRequestHeader()); JSONObject jsonObject = JSONObject.parseObject(data); if (jsonObject.getString(ResponseParam.status).equals("200")) { return ReturnMessageTool.getSuccess("上报成功"); } else { return ReturnMessageTool.getError(jsonObject.getString(ResponseParam.msg)); } } catch (Exception e) { return ReturnMessageTool.getError(); } } @RequestMapping(value = "/pushStuBespeak", method = org.springframework.web.bind.annotation.RequestMethod.PUT) @ResponseBody public ReturnMessage pushStuBespeak(StuBespeak StuBespeak) { try { String data = dataPush.dataPush(DataCenterAPI.API_SEND_BESPEAK, RequestMethod.PUT,ObjectMap.transBean2Map(StuBespeak), HttpClient.getRequestHeader()); JSONObject jsonObject = JSONObject.parseObject(data); if (jsonObject.getString(ResponseParam.status).equals("200")) { return ReturnMessageTool.getSuccess("上报成功"); } else { return ReturnMessageTool.getError(jsonObject.getString(ResponseParam.msg)); } } catch (Exception e) { return ReturnMessageTool.getError(); } } @RequestMapping(value = "/pushPayment", method = org.springframework.web.bind.annotation.RequestMethod.PUT) @ResponseBody public ReturnMessage pushPayment(Payment payment) { try { String data = dataPush.dataPush(DataCenterAPI.API_SEND_PAYMENT, RequestMethod.PUT,ObjectMap.transBean2Map(payment), HttpClient.getRequestHeader()); JSONObject jsonObject = JSONObject.parseObject(data); if (jsonObject.getString(ResponseParam.status).equals("200")) { return ReturnMessageTool.getSuccess("上报成功"); } else { return ReturnMessageTool.getError(jsonObject.getString(ResponseParam.msg)); } } catch (Exception e) { return ReturnMessageTool.getError(); } } @RequestMapping(value = "/pushEvaluation", method = org.springframework.web.bind.annotation.RequestMethod.PUT) @ResponseBody public ReturnMessage pushEvaluation(Evaluation evaluation) { try { String data = dataPush.dataPush(DataCenterAPI.API_SEND_EVALUATION, RequestMethod.PUT,ObjectMap.transBean2Map(evaluation), HttpClient.getRequestHeader()); JSONObject jsonObject = JSONObject.parseObject(data); if (jsonObject.getString(ResponseParam.status).equals("200")) { return ReturnMessageTool.getSuccess("上报成功"); } else { return ReturnMessageTool.getError(jsonObject.getString(ResponseParam.msg)); } } catch (Exception e) { return ReturnMessageTool.getError(); } } @RequestMapping(value = "/pushComplaint", method = org.springframework.web.bind.annotation.RequestMethod.PUT) @ResponseBody public ReturnMessage pushComplaint(Complaint complaint) { try { String data = dataPush.dataPush(DataCenterAPI.API_SEND_COMPLAINT, RequestMethod.PUT,ObjectMap.transBean2Map(complaint), HttpClient.getRequestHeader()); JSONObject jsonObject = JSONObject.parseObject(data); if (jsonObject.getString(ResponseParam.status).equals("200")) { return ReturnMessageTool.getSuccess("上报成功"); } else { return ReturnMessageTool.getError(jsonObject.getString(ResponseParam.msg)); } } catch (Exception e) { return ReturnMessageTool.getError(); } } @RequestMapping(value = "/pushSeting", method = org.springframework.web.bind.annotation.RequestMethod.PUT) @ResponseBody public ReturnMessage pushSeting(Setting setting) { try { String data = dataPush.dataPush(DataCenterAPI.API_SEND_COMPLAINT, RequestMethod.PUT,ObjectMap.transBean2Map(setting), HttpClient.getRequestHeader()); JSONObject jsonObject = JSONObject.parseObject(data); if (jsonObject.getString(ResponseParam.status).equals("200")) { return ReturnMessageTool.getSuccess("上报成功"); } else { return ReturnMessageTool.getError(jsonObject.getString(ResponseParam.msg)); } } catch (Exception e) { return ReturnMessageTool.getError(); } } } <file_sep>/src/main/java/com/jishi/controller/SchoolJoinController.java package com.jishi.controller; import java.io.PrintWriter; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.jishi.entity.FacePay_orderDetail; import com.jishi.entity.SchoolJoin; import com.jishi.service.impl.SchoolJoinService; import com.jishi.until.DateUtil; import com.jishi.until.NumberUtil; import com.jishi.until.ReturnMessage; import com.jishi.until.ReturnTool; import com.jishi.until.Trantool; import net.sf.json.JSONObject; @Controller @RequestMapping(value = "/apply") public class SchoolJoinController extends BaseController { @Resource(name = "SchoolJoinService") SchoolJoinService schoolJoinService; @RequestMapping(value = "/schoolmobile") public ModelAndView schoolmobile() throws Exception { ModelAndView mv = this.getModelAndView(); try { mv.setViewName("/school/schoolh5"); } catch (Exception e) { mv.setViewName("/err.jsp"); } return mv; } @RequestMapping(value = "/schoolpc") public ModelAndView schoolpc() throws Exception { ModelAndView mv = this.getModelAndView(); try { mv.setViewName("/school/schoolpc"); } catch (Exception e) { mv.setViewName("/err.jsp"); } return mv; } /** * 驾校 * * @param request * @param response * @throws Exception */ @RequestMapping(value = "/addSchool") public void toSchoolh5(HttpServletRequest request, HttpServletResponse response) throws Exception { PrintWriter out = response.getWriter(); response.setContentType("text/html;charset=UTF-8"); String name = request.getParameter("name"); String tel = request.getParameter("phone"); SchoolJoin schooljoin = new SchoolJoin(); schooljoin.setName(name); schooljoin.setTel(tel); schooljoin.setCreateDate(new Date()); schooljoin.setSource("mobile"); schooljoin.setSchoolname(request.getParameter("school")); if (schoolJoinService.checkTelIsExist(tel) > 0) { out.write(ReturnTool.getJsonMessageResult(-1, "该手机号已存在")); return; } ; try { if (schoolJoinService.addSchoolUser(schooljoin) == 1) { /* * SMS_Queue sq = new SMS_Queue(); sq.setTell(tel); * sq.setCreateDate(new Date()); sq.setContext("尊敬的"+name * +"恭喜您成功报名学车,并获得500元学车优惠券,稍后我们会有专业的学车顾问联系您,告诉您学车相关事宜,请注意接听您的手机!!或者您也可以拨打我们电话0571-28092588;官网www.jiaqu365.com" * ); fService.addSMS_Queue(sq); */ HashMap msg = new HashMap(); msg.put("flag", "1"); msg.put("message", "报名成功"); JSONObject jsonArray = JSONObject.fromObject(msg); out.write(jsonArray.toString()); } else { } } catch (Exception e) { HashMap msg = new HashMap(); msg.put("flag", "-1"); msg.put("message", "报名失败,你的手机已经报过名"); JSONObject jsonArray = JSONObject.fromObject(msg); out.write(jsonArray.toString()); } } @RequestMapping(value = "/addSchoolpc", method = RequestMethod.POST) public void toSchoolpc(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); String tel = request.getParameter("phone"); SchoolJoin schooljoin = new SchoolJoin(); schooljoin.setName(name); schooljoin.setTel(tel); schooljoin.setCreateDate(new Date()); schooljoin.setSource("pc"); schooljoin.setSchoolname(request.getParameter("school")); if (schoolJoinService.checkTelIsExist(tel) > 0) { out.write(ReturnTool.getJsonMessageResult(-1, "该手机号已存在")); return; } ; try { if (schoolJoinService.addSchoolUser(schooljoin) == 1) { /* * SMS_Queue sq = new SMS_Queue(); sq.setTell(tel); * sq.setCreateDate(new Date()); sq.setContext("尊敬的"+name * +"恭喜您成功报名学车,并获得500元学车优惠券,稍后我们会有专业的学车顾问联系您,告诉您学车相关事宜,请注意接听您的手机!!或者您也可以拨打我们电话0571-28092588;官网www.jiaqu365.com" * ); fService.addSMS_Queue(sq); */ HashMap msg = new HashMap(); msg.put("flag", "1"); msg.put("message", "报名成功"); JSONObject jsonArray = JSONObject.fromObject(msg); out.write(jsonArray.toString()); } else { } } catch (Exception e) { HashMap msg = new HashMap(); msg.put("flag", "-1"); msg.put("message", "报名失败,你的手机已经报过名"); JSONObject jsonArray = JSONObject.fromObject(msg); out.write(jsonArray.toString()); } } @RequestMapping("/facepay") public ModelAndView toFacepay() { ModelAndView mv = this.getModelAndView(); mv.setViewName("facepay/facepay"); return mv; } @RequestMapping(value = "/getOrder", method = RequestMethod.GET) @ResponseBody public ReturnMessage getOrder(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "ordernum", required = true) String ordernum, FacePay_orderDetail orderDetail) throws Exception { response.setContentType("text/html;charset=UTF-8"); ReturnMessage rm = new ReturnMessage(); Map param = new HashMap(); param.put("ordernum", ordernum); param.put("ispay", 0); // 跟据定单号获取定单星系 Map ret = schoolJoinService.checkOrderByOrdernum(param); param.put("inscode", ret.get("inscode")); if (ret == null) { rm.setFlag(-1); rm.setMessage("订单不存在"); return rm; } else { ret.put("expdate", new Date()); ret.put("status", "0"); ret.put("ordernum", ordernum); // 查询是否存在支付宝订单 Map stuorder = schoolJoinService.checkOrderIsUsed(ret); if (stuorder != null) { Main toolMain = new Main(); Map token = schoolJoinService.getAuth_token(param); FacePay_orderDetail newOrder = Trantool.getOrderDetail(ret); // 支付宝订单 newOrder.setOrdernum((String) stuorder.get("ordernum")); if (token != null) { newOrder.setAuth_token((String) token.get("token")); } Map<String, Object> ret2 = toolMain.test_trade_precreate(newOrder); if (ret2 != null) { String oldcode = (String) ret2.get("qr_code"); String newcode = oldcode + "?rand=" + NumberUtil.getRandomNum3(); ret2.put("qr_code", newcode); rm.setData(ret2); rm.setMessage("下单成功"); rm.setFlag(1); return rm; } else { rm.setFlag(-1); rm.setMessage("下单失败"); return rm; } } else { Main toolMain = new Main(); FacePay_orderDetail newOrder = Trantool.getOrderDetail(ret); ordernum = ordernum + NumberUtil.getZRandomNum4(); newOrder.setOrdernum(ordernum); Map token = schoolJoinService.getAuth_token(param); if (token != null) { newOrder.setAuth_token((String) token.get("token")); } Map<String, Object> ret2 = toolMain.test_trade_precreate(newOrder); if (ret2 != null) { Map pm = new HashMap(); pm.put("ordernum", ret2.get("out_trade_no")); pm.put("stunum", ret.get("stunum")); pm.put("expdate", DateUtil.getAfterminutime("1440")); schoolJoinService.addAliorder(pm); rm.setData(ret2); rm.setMessage("下单成功"); rm.setFlag(1); return rm; } else { rm.setFlag(-1); rm.setMessage("下单失败"); return rm; } } } } } <file_sep>/src/main/java/com/jishi/dao/JsStuProsecutedComplaintsMapper.java package com.jishi.dao; import com.jishi.entity.JsStuProsecutedComplaints; import com.jishi.entity.JsStuProsecutedComplaintsExample; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; public interface JsStuProsecutedComplaintsMapper { /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ int countByExample(JsStuProsecutedComplaintsExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ int deleteByExample(JsStuProsecutedComplaintsExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ int deleteByPrimaryKey(Integer stuPCId); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ int insert(JsStuProsecutedComplaints record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ int insertSelective(JsStuProsecutedComplaints record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ List<JsStuProsecutedComplaints> selectByExample(JsStuProsecutedComplaintsExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ JsStuProsecutedComplaints selectByPrimaryKey(Integer stuPCId); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ int updateByExampleSelective(@Param("record") JsStuProsecutedComplaints record, @Param("example") JsStuProsecutedComplaintsExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ int updateByExample(@Param("record") JsStuProsecutedComplaints record, @Param("example") JsStuProsecutedComplaintsExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ int updateByPrimaryKeySelective(JsStuProsecutedComplaints record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ int updateByPrimaryKey(JsStuProsecutedComplaints record); }<file_sep>/src/main/java/com/jishi/service/impl/UsersServiceImpl.java package com.jishi.service.impl; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.jishi.dao.DaoSupport; import com.jishi.entity.CoachLogin; import com.jishi.enums.UserLoginType; import com.jishi.enums.UserType; import com.jishi.service.UsersService; import com.jishi.until.NumberUtil; import com.jishi.until.ReturnMessage; import com.jishi.until.ReturnMessageTool; @Service("coachUsersService") public class UsersServiceImpl implements UsersService { @Resource(name = "daoSupport") private DaoSupport dao; @Override public ReturnMessage updatePassword(String phone, String newPassword, String code) { // TODO Auto-generated method stub return null; } @Override public int setUserInfo(Object object) throws Exception { // TODO Auto-generated method stub return 0; } @Override public Object getUserInfo(Object object) throws Exception { // TODO Auto-generated method stub return null; } @Override public ReturnMessage registered(String phoneNumber, String code,UserType userType, String password) throws Exception { CoachLogin coachLogin = new CoachLogin(); coachLogin.setPassWord(<PASSWORD>); coachLogin.setPhone(phoneNumber); coachLogin.setToken(NumberUtil.getToken()); coachLogin.setLoginDate(Timestamp.valueOf(LocalDateTime.now())); coachLogin.setIsVisiter(UserLoginType.IS_VISITER.getLoginType()); int count = (int)dao.save("CoachMapper.insertloginphone", coachLogin); Map<String, Object> map = new HashMap<>(); if (count > 0) { map.put(IS_VISITER, 1); map.put(TOKEN, coachLogin.getToken()); }else { throw new RuntimeException("插入登入信息失败"); } return ReturnMessageTool.getSuccess(map); } } <file_sep>/src/main/java/com/jishi/entity/view/ViewStudentForLoginInfo.java package com.jishi.entity.view; public class ViewStudentForLoginInfo { private String Stunum ; //学员编号 private String subject1_fulfil ; private String subject2_fulfil ; private String subject3_fulfil ; private String subject4_fulfil ; private String current_subject ; //正在学习科目 private String StudentLoginNum ; //学员签到编号 private String CoachLoginNum ; //教练签到编号 private String IsPractice ; //是否正在学习 private String Name ; //姓名 private String Idcard ; //证件号码 private String Cardtype ; //证件类型 private String Phone ; //学员电话 private String Photo ; //学员照片 private String Status; //学员状态 public String getStunum() { return Stunum; } public void setStunum(String stunum) { Stunum = stunum; } public String getSubject1_fulfil() { return subject1_fulfil; } public void setSubject1_fulfil(String subject1_fulfil) { this.subject1_fulfil = subject1_fulfil; } public String getSubject2_fulfil() { return subject2_fulfil; } public void setSubject2_fulfil(String subject2_fulfil) { this.subject2_fulfil = subject2_fulfil; } public String getSubject3_fulfil() { return subject3_fulfil; } public void setSubject3_fulfil(String subject3_fulfil) { this.subject3_fulfil = subject3_fulfil; } public String getSubject4_fulfil() { return subject4_fulfil; } public void setSubject4_fulfil(String subject4_fulfil) { this.subject4_fulfil = subject4_fulfil; } public String getCurrent_subject() { return current_subject; } public void setCurrent_subject(String current_subject) { this.current_subject = current_subject; } public String getStudentLoginNum() { return StudentLoginNum; } public void setStudentLoginNum(String studentLoginNum) { StudentLoginNum = studentLoginNum; } public String getCoachLoginNum() { return CoachLoginNum; } public void setCoachLoginNum(String coachLoginNum) { CoachLoginNum = coachLoginNum; } public String getIsPractice() { return IsPractice; } public void setIsPractice(String isPractice) { IsPractice = isPractice; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getIdcard() { return Idcard; } public void setIdcard(String idcard) { Idcard = idcard; } public String getCardtype() { return Cardtype; } public void setCardtype(String cardtype) { Cardtype = cardtype; } public String getPhone() { return Phone; } public void setPhone(String phone) { Phone = phone; } public String getPhoto() { return Photo; } public void setPhoto(String photo) { Photo = photo; } public String getStatus() { return Status; } public void setStatus(String status) { Status = status; } } <file_sep>/src/main/java/com/jishi/controller/SchoolAppController.java package com.jishi.controller; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.commons.CommonsMultipartFile; import com.jishi.entity.rt.UnpayOrder_rt; import com.jishi.entity.schoolapp.StuInfo; import org.springframework.web.multipart.MultipartFile; import com.jishi.service.impl.SchoolAppService; import com.jishi.until.DateUtil; import com.jishi.until.FileUpload; import com.jishi.until.NumberUtil; import com.jishi.until.ReturnMessage; import com.sun.jmx.snmp.Timestamp; import com.sun.org.apache.bcel.internal.generic.NEW; import com.jishi.until.ReturnMessage_entity; import com.jishi.until.Tools; import com.sun.org.apache.bcel.internal.generic.NEW; import net.sf.json.JSONObject; import com.face.service.FaceVisa; import com.jishi.entity.CommentInfo; import com.jishi.entity.StudentInfo; import com.jishi.entity.rece.*; import com.jishi.entity.view.ViewContrastResult; @Controller @RequestMapping(value="/schoolApp") public class SchoolAppController { @Resource(name="SchoolAppService") SchoolAppService schoolAppService; @RequestMapping(value = "/login",method =RequestMethod.POST) @ResponseBody public ReturnMessage toLogin(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="user", required=true) String user, @RequestParam(value="password", required=true) String password ) { response.setContentType("text/html;charset=UTF-8"); ReturnMessage rm= new ReturnMessage(); Map userParam =new HashMap(); userParam.put("user", user); userParam.put("password", <PASSWORD>); try { Map result = schoolAppService.checkUserAndPassword(userParam); if (result != null) { List<Map> limits = schoolAppService.getLimits(result); List<Integer> lst = new ArrayList<Integer>(); for (Map map : limits) { lst.add((Integer)map.get("mennum")); } result.put("limits", lst); rm.setFlag(1); rm.setMessage("登录成功"); rm.setData(result); return rm; } else { rm.setFlag(-1); rm.setMessage("账号或者密码错误"); return rm; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); rm.setFlag(-1); rm.setMessage("参数出错"); return rm; } } @RequestMapping(value = "/monthStudent",method =RequestMethod.GET) @ResponseBody public ReturnMessage toThisMonthStudentCount(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="inscode", required=true) String inscode ) { response.setContentType("text/html;charset=UTF-8"); ReturnMessage rm= new ReturnMessage(); String firstDay = DateUtil.getThisMonthFirstDay(); Map param = new HashMap(); param.put("inscode", inscode); param.put("startTime", firstDay); param.put("endTime",new Date()); try { Map result =new HashMap(); int studentCount = schoolAppService.getThisMonthNewStudentCount(param); result.put("count",studentCount); result.put("willCount",0); rm.setFlag(1); rm.setMessage("请求成功"); rm.setData(result); return rm; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); rm.setFlag(-1); rm.setMessage("参数错误"); return rm; } } @RequestMapping(value = "/stuInfo",method =RequestMethod.POST) @ResponseBody public ReturnMessage toCommitStudentInfo(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="inscode", required=true) String inscode, @RequestParam(value="img", required=true) CommonsMultipartFile img, @RequestParam(value="name", required=true) String name, @RequestParam(value="sex", required=true) int sex, @RequestParam(value="nationality", required=true) String nationality, @RequestParam(value="cardtype", required=true) int cardtype, @RequestParam(value="idcard", required=true) String idcard, @RequestParam(value="address", required=true) String address, @RequestParam(value="busitype", required=true) int busitype, @RequestParam(value="traintype", required=true) String traintype, @RequestParam(value="applydate", required=true) String applydate, @RequestParam(value="phone", required=true) String phone, StuInfo stuInfo ) { if (Tools.isMessyCode(stuInfo.getName())) { stuInfo.setName(Tools.strutf(stuInfo.getName())); } if (Tools.isMessyCode(stuInfo.getNationality())) { stuInfo.setNationality(Tools.strutf(stuInfo.getNationality())); } if (Tools.isMessyCode(stuInfo.getAddress())) { stuInfo.setAddress(Tools.strutf(stuInfo.getAddress())); } response.setContentType("text/html;charset=UTF-8"); ReturnMessage rm= new ReturnMessage(); String stunum =NumberUtil.getStudentCode(); stuInfo.setStunum(stunum); stuInfo.setStatus(0); stuInfo.setCreatedate(new Date()); String fileName =stunum; /*String path="/data/sites/up/manage";*/ String path="D:/pdf"; try { int res=schoolAppService.checkPhoneOrIdCardIsExited(phone,idcard); if (res==-1) { rm.setFlag(-1); rm.setMessage("手机号已经存在"); return rm; } if (res==-2) { rm.setFlag(-1); rm.setMessage("证件号已经存在"); return rm; } if (res==0) { int reusl=schoolAppService.updateNewStudent(stuInfo); if (reusl==1) { rm.setFlag(1); rm.setMessage("修改成功"); Map stuMap = new HashMap(); stuMap.put("stunum", schoolAppService.getstunum(stuInfo.getPhone())); rm.setData(stuMap); return rm; }; } JSONObject obj= JSONObject.fromObject(FaceVisa.getPersonId()); if(obj.containsKey("personid")) { int personid =(Integer)obj.get("personid"); StudentInfo stu =new StudentInfo(); stu.setStunum(stunum); stu.setInscode(inscode); stu.setPersonId(personid); stuInfo.setPersonid(personid); schoolAppService.UpStudentPhoto(img, stu); } if (schoolAppService.addNewStudent(stuInfo)==1) { Map stuMap = new HashMap(); stuMap.put("stunum", stunum); rm.setFlag(1); rm.setData(stuMap); rm.setMessage("添加成功"); return rm; } else { rm.setFlag(-1); rm.setMessage("参数错误"); return rm; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); rm.setFlag(-1); rm.setMessage("参数错误"); return rm; } } @RequestMapping(value = "/unpayOrder",method =RequestMethod.GET) @ResponseBody public ReturnMessage toGetUnpayOrder(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="inscode", required=true) String inscode, @RequestParam(value="page", required=true) int page, @RequestParam(value="stuname", required=false) String stuname ) { response.setContentType("text/html;charset=UTF-8"); ReturnMessage rm= new ReturnMessage(); if (Tools.isMessyCode(stuname)) { stuname = Tools.strutf(stuname); } Map param = new HashMap(); param.put("inscode", inscode); param.put("stuname", stuname); param.put("isPay", 0); if (stuname==null) { int start = (page -1)*10; param.put("pagestart", start); param.put("pagesize", 10); try { int pages=schoolAppService.getUnpayOrderPageNum(param)/10+1; List<UnpayOrder_rt> lst = schoolAppService.getUnpayOrder(param); List<Map> coachLst = schoolAppService.getAllCoachname(param); List<Map> simucoachLst = schoolAppService.getAllSimuCoachname(param); for (UnpayOrder_rt unpayOrder_rt : lst) { if (unpayOrder_rt.getIssimulate()==1) { for (Map map : simucoachLst) { if (unpayOrder_rt.getCoachnum().equals(map.get("coachnum"))) { unpayOrder_rt.setCoachname((String)map.get("coachname")); } } } else { for (Map map : coachLst) { if (unpayOrder_rt.getCoachnum().equals(map.get("coachnum"))) { unpayOrder_rt.setCoachname((String)map.get("coachname")); } } } } Map ret =new HashMap(); ret.put("pages", pages); ret.put("content", lst); rm.setFlag(1); rm.setMessage("请求成功"); rm.setData(ret); return rm; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); rm.setFlag(-1); rm.setMessage("参数错误"); return rm; } } else { try { List<UnpayOrder_rt> lst = schoolAppService.getUnpayOrderByName(param); List<Map> coachLst = schoolAppService.getAllCoachname(param); List<Map> simucoachLst = schoolAppService.getAllSimuCoachname(param); for (UnpayOrder_rt unpayOrder_rt : lst) { if (unpayOrder_rt.getIssimulate()==1) { for (Map map : simucoachLst) { if (unpayOrder_rt.getCoachnum().equals(map.get("coachnum"))) { unpayOrder_rt.setCoachname((String)map.get("coachname")); } } } else { for (Map map : coachLst) { if (unpayOrder_rt.getCoachnum().equals(map.get("coachnum"))) { unpayOrder_rt.setCoachname((String)map.get("coachname")); } } } } rm.setFlag(1); rm.setMessage("请求成功"); rm.setData(lst); return rm; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); rm.setFlag(-1); rm.setMessage("参数错误"); return rm; } } } @RequestMapping(value = "/face_contrast ",method =RequestMethod.POST) @ResponseBody public ReturnMessage_entity<ViewContrastResult> face_contrast(HttpServletRequest request,HttpServletResponse response,contrastInfo Info) { ReturnMessage_entity<ViewContrastResult> R = new ReturnMessage_entity<ViewContrastResult>(); ReturnMessage_entity<StudentInfo> check = schoolAppService.checkcontrastInfo(Info); if(check.getFlag() != 1) { R.setFlag(check.getFlag()); R.setMessage(check.getMessage()); return R; } try { String body = FaceVisa.test2_2_17(Info.getFixedPhoto().getBytes(), Info.getContrastPhoto().getBytes()); R = schoolAppService.contrastresult(body,Info.getContrastPhoto(),check.getData()); if(R.getFlag() !=1) return R; return R; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); R.setFlag(-1); R.setMessage("网络异常"); return R; } } @RequestMapping(value = "/siumpast ",method =RequestMethod.POST) @ResponseBody public ReturnMessage_entity<ViewContrastResult> siumpast(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="stunum", required=true) String stunum,@RequestParam(value="stuphoto", required=true) MultipartFile stuphoto) { ReturnMessage_entity<ViewContrastResult> R = new ReturnMessage_entity<ViewContrastResult>(); ReturnMessage_entity<StudentInfo> check = schoolAppService.checkstu(stunum); if(check.getFlag() != 1) { R.setFlag(check.getFlag()); R.setMessage(check.getMessage()); return R; } try { String body = FaceVisa.test2_2_07(check.getData().getPersonId()+"", stuphoto.getBytes()); R = schoolAppService.siumpast(body,stunum); //System.err.println(Rm.getMessage()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return R; } @RequestMapping(value = "/face_comment ",method =RequestMethod.POST) @ResponseBody public ReturnMessage_entity<ViewContrastResult> facecomment(HttpServletRequest request,HttpServletResponse response,CommentInfo cm,@RequestParam(value="stuphoto", required=true) MultipartFile stuphoto) { ReturnMessage_entity<ViewContrastResult> R = new ReturnMessage_entity<ViewContrastResult>(); //检测参数 ReturnMessage checkpams = schoolAppService.checkCommentInfo(cm); if (Tools.isMessyCode(cm.getCommentContent())) { cm.setCommentContent(Tools.strutf(cm.getCommentContent())); } if (Tools.isMessyCode(cm.getCommentContext())) { cm.setCommentContext(Tools.strutf(cm.getCommentContext())); } if(checkpams.getFlag() != 1) { R.setFlag(checkpams.getFlag()); R.setMessage(checkpams.getMessage()); return R; } //人脸验证并现金支付 R = schoolAppService.cash_pay(cm.getOrderNum(), stuphoto); if(R.getFlag() != 1) { return R; } //评价订单 ReturnMessage commentresult = schoolAppService.cash_comment(cm); if(commentresult.getFlag() != 1 ) { R.setFlag(commentresult.getFlag()); R.setMessage(commentresult.getMessage()); return R; } R.setFlag(1); R.setMessage("操作成功"); return R; } } <file_sep>/src/main/java/com/jishi/service/order/Order.java package com.jishi.service.order; import com.jishi.enums.UserType; import com.jishi.until.Page; public interface Order { /** * 获取未支付订单 * @param getOrderType 用户类型 * @param number 编号 * @param page 分野信息 * @return * @throws Exception */ Object getUnpaid(UserType getOrderType,String number,Page page) throws Exception; /** * 获取已支付订单 * @param getOrderType * @param number * @param page * @return * @throws Exception */ Object getPaid(UserType getOrderType,String number,Page page) throws Exception; /** * 获取订单详情 * @param orderNumber 订单比编号 * @return * @throws Exception */ Object getOrderInFo(String orderNumber) throws Exception; } <file_sep>/src/main/java/com/jishi/dao/SubjectRecordMapper.java package com.jishi.dao; import com.jishi.entity.SubjectRecord; import com.jishi.entity.SubjectRecordKey; public interface SubjectRecordMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table subject_record * * @mbggenerated Wed May 24 15:35:17 CST 2017 */ int deleteByPrimaryKey(SubjectRecordKey key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table subject_record * * @mbggenerated Wed May 24 15:35:17 CST 2017 */ int insert(SubjectRecord record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table subject_record * * @mbggenerated Wed May 24 15:35:17 CST 2017 */ int insertSelective(SubjectRecord record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table subject_record * * @mbggenerated Wed May 24 15:35:17 CST 2017 */ SubjectRecord selectByPrimaryKey(SubjectRecordKey key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table subject_record * * @mbggenerated Wed May 24 15:35:17 CST 2017 */ int updateByPrimaryKeySelective(SubjectRecord record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table subject_record * * @mbggenerated Wed May 24 15:35:17 CST 2017 */ int updateByPrimaryKey(SubjectRecord record); int selectCountByPrimaryKey(SubjectRecordKey key); }<file_sep>/src/main/java/com/jishi/service/activation/UserActivation.java package com.jishi.service.activation; import com.jishi.until.ReturnMessage; public interface UserActivation { static final String ACTIVATION_FAIL = "激活失败"; static final String ACTIVATION_SUCCESS = "激活成功,欢迎登入!"; static final String ACTIVATION_SUCCESS_ALREADY = "您已激活,密码设置成功"; static final String PHONE_ALREADY_ACTIVATION = "该手机号码已激活,请直接登录"; static final String IC_ALREADY_ACTIVATION = ACTIVATION_FAIL + ",该IC卡已激活"; static final String IC_NOT_FOUND = ACTIVATION_FAIL + ",ic卡号或者id卡号不正确"; static final String CODE_ERROR = "验证码不正确,请重新输入"; /** * 用户激活 * @param code 验证吗 * @param ic ic卡后 * @param idCard 身份证后六位 * @param phoneNumber 手机号 * @param lot 经度 * @param lat 纬度 * @return true or false * @throws Exception */ ReturnMessage userActivation(String phoneNumber,String code, String password,String ic,String idCard,Double lot,Double lat) throws Exception; } <file_sep>/src/main/java/com/jishi/service/impl/StuComplaintImpl.java package com.jishi.service.impl; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.corbett.utils.date.DateFormat; import com.corbett.utils.file.FileUitls; import com.jishi.dao.DaoSupport; import com.jishi.dao.JsComplaintsPhotoMapper; import com.jishi.dao.JsProsecutedComplaintsPhotoMapper; import com.jishi.dao.JsStuComplaintsMapper; import com.jishi.dao.JsStuProsecutedComplaintsMapper; import com.jishi.dao.zstu.StuInFoManagement; import com.jishi.entity.CoachInfo; import com.jishi.entity.Institution; import com.jishi.entity.JsComplaintsPhoto; import com.jishi.entity.JsComplaintsPhotoExample; import com.jishi.entity.JsProsecutedComplaintsPhoto; import com.jishi.entity.JsProsecutedComplaintsPhotoExample; import com.jishi.entity.JsStuComplaints; import com.jishi.entity.JsStuComplaintsExample; import com.jishi.entity.JsStuProsecutedComplaints; import com.jishi.entity.JsStuProsecutedComplaintsExample; import com.jishi.entity.StudentInfo; import com.jishi.entity.datacenter.Complaint; import com.jishi.entity.datacenter.PushDataInFo; import com.jishi.enums.PersonType; import com.jishi.enums.PushDataType; import com.jishi.exception.JiaQuException; import com.jishi.service.PushData; import com.jishi.service.impl.queue.SendMessageToDataCenter; import com.jishi.service.zstu.StuComplaint; import com.jishi.until.Tools; @Service public class StuComplaintImpl implements StuComplaint { private static final String Path = "/mnt/sites/up_img/manage/complaints/"; private static final String Path_local = "F:/"; private static final String call_url = ""; private static final String weburl = "http://172.16.58.3:8080/jishi_image/manage/complaints/"; private Logger logger = LoggerFactory.getLogger(StuComplaintImpl.class); @Autowired private JsStuComplaintsMapper jsStuComplaintsMapper; @Autowired private JsComplaintsPhotoMapper jsComplaintsPhotoMapper; @Autowired private JsStuProsecutedComplaintsMapper jsStuProsecutedComplaintsMapper; @Autowired private JsProsecutedComplaintsPhotoMapper jsProsecutedComplaintsPhotoMapper; @Resource(name = "PushDataImpl") private PushData pushData; @Autowired private StuInFoManagement stuInFoManagement; @Resource(name = "daoSupport") private DaoSupport dao; @Autowired private SendMessageToDataCenter sendMessageToDataCenter; @Override public List<JsStuComplaints> getComplaints(String stu_num, Integer page, Integer pageSize) throws Exception { List<JsStuComplaints> record = new ArrayList<>(); JsStuComplaints jsStuComplaint = new JsStuComplaints(); if (pageSize != null) { jsStuComplaint.setPagesize(pageSize); } jsStuComplaint.setPagestart(page); System.out.println("page:" + page); JsStuComplaintsExample example = new JsStuComplaintsExample(); example.setLimitClause("limit " + jsStuComplaint.getPagestart() + "," + jsStuComplaint.getPagesize()); System.out.println(example.getLimitClause()); example.setOrderByClause("complaints_time desc"); example.createCriteria().andStuNumEqualTo(stu_num).andIsRevokedEqualTo(0); record = jsStuComplaintsMapper.selectByExample(example);// 查询投诉 if (record.size() <= 0) { // throw new JiaQuException("GET FAIL"); return record; } for (JsStuComplaints jsStuComplaints : record) { /** * 将编号换成名称 */ CoachInfo coachInfo = null; if (PersonType.valueOf(jsStuComplaints.getComplaintsType()).equals(PersonType.coach)) { coachInfo = new CoachInfo(); coachInfo.setCoachNum(jsStuComplaints.getComplaintsObject()); coachInfo = (CoachInfo) dao.findForObject("CoachMapper.getCoachInfoForParams", coachInfo); jsStuComplaints.setComplaintsObject(coachInfo.getName()); } if (PersonType.valueOf(jsStuComplaints.getComplaintsType()).equals(PersonType.school)) { Institution institution = new Institution(); institution.setInscode(jsStuComplaints.getComplaintsObject()); institution = (Institution) dao.findForObject("InstitutionMapper.getInstitutionList", institution); jsStuComplaints.setComplaintsObject(institution.getName()); } /** * 查询投诉图片实体,并加上网络地址 */ JsComplaintsPhotoExample jsComplaintsPhotoExample = new JsComplaintsPhotoExample(); jsComplaintsPhotoExample.createCriteria().andComplaintsIdEqualTo(jsStuComplaints.getId()); List<JsComplaintsPhoto> jsComplaintsPhotos = jsComplaintsPhotoMapper .selectByExample(jsComplaintsPhotoExample); for (JsComplaintsPhoto jsComplaintsPhoto : jsComplaintsPhotos) { jsComplaintsPhoto.setPhotoPath( weburl + jsStuComplaints.getStuNum() + "/" + "0/" + jsComplaintsPhoto.getPhotoPath()); } /** * 设置到投诉实体中 */ jsStuComplaints.setJsComplaintsPhotos(jsComplaintsPhotos); /** * 判断是否有追诉,有则获取 */ if (jsStuComplaints.getIsProsecuted() == 1) { JsStuProsecutedComplaintsExample jsStuProsecutedComplaintsExample = new JsStuProsecutedComplaintsExample(); jsStuProsecutedComplaintsExample.createCriteria().andComplaintsIdEqualTo(jsStuComplaints.getId()); List<JsStuProsecutedComplaints> jsStuProsecutedComplaints = jsStuProsecutedComplaintsMapper .selectByExample(jsStuProsecutedComplaintsExample); for (JsStuProsecutedComplaints jsStuProsecutedComplaint : jsStuProsecutedComplaints) { JsProsecutedComplaintsPhotoExample jsProsecutedComplaintsPhotoExample = new JsProsecutedComplaintsPhotoExample(); jsProsecutedComplaintsPhotoExample.createCriteria() .andProsecutedComplaintsIdEqualTo(jsStuProsecutedComplaint.getStuPCId()); List<JsProsecutedComplaintsPhoto> jsProsecutedComplaintsPhotos = jsProsecutedComplaintsPhotoMapper .selectByExample(jsProsecutedComplaintsPhotoExample); for (JsProsecutedComplaintsPhoto jsProsecutedComplaintsPhoto : jsProsecutedComplaintsPhotos) { jsProsecutedComplaintsPhoto.setPhotoPath(weburl + jsStuComplaints.getStuNum() + "/" + jsStuComplaints.getIsProsecuted() + "/" + jsProsecutedComplaintsPhoto.getPhotoPath()); } jsStuProsecutedComplaint.setJsProsecutedComplaintsPhotos(jsProsecutedComplaintsPhotos); } jsStuComplaints.setJsStuProsecutedComplaints(jsStuProsecutedComplaints); } } return record; } @Override public JsStuComplaints getComplaint(String stu_num, Integer id) throws Exception { List<JsStuComplaints> record = new ArrayList<>(); JsStuComplaintsExample example = new JsStuComplaintsExample(); example.createCriteria().andIdEqualTo(id).andStuNumEqualTo(stu_num).andIsRevokedEqualTo(0); record = jsStuComplaintsMapper.selectByExample(example); if (record.size() <= 0) { throw new JiaQuException("GET FAIL"); } for (JsStuComplaints jsStuComplaints : record) { CoachInfo coachInfo = null; if (PersonType.valueOf(jsStuComplaints.getComplaintsType()).equals(PersonType.coach)) { coachInfo = new CoachInfo(); coachInfo.setCoachNum(jsStuComplaints.getComplaintsObject()); coachInfo = (CoachInfo) dao.findForObject("CoachMapper.getCoachInfoForParams", coachInfo); jsStuComplaints.setComplaintsObject(coachInfo.getName()); } if (PersonType.valueOf(jsStuComplaints.getComplaintsType()).equals(PersonType.school)) { Institution institution = new Institution(); institution.setInscode(jsStuComplaints.getComplaintsObject()); institution = (Institution) dao.findForObject("InstitutionMapper.getInstitutionList", institution); jsStuComplaints.setComplaintsObject(institution.getName()); } JsComplaintsPhotoExample jsComplaintsPhotoExample = new JsComplaintsPhotoExample(); jsComplaintsPhotoExample.createCriteria().andComplaintsIdEqualTo(jsStuComplaints.getId()); List<JsComplaintsPhoto> jsComplaintsPhotos = jsComplaintsPhotoMapper .selectByExample(jsComplaintsPhotoExample); for (JsComplaintsPhoto jsComplaintsPhoto : jsComplaintsPhotos) { jsComplaintsPhoto.setPhotoPath(weburl + jsStuComplaints.getStuNum() + "/" + jsStuComplaints.getIsProsecuted() + "/" + jsComplaintsPhoto.getPhotoPath()); } jsStuComplaints.setJsComplaintsPhotos(jsComplaintsPhotos); } return record.get(0); } @Override public boolean deleteComplaint(String stu_num, Integer id) throws JiaQuException { JsStuComplaints record = new JsStuComplaints(); record.setIsRevoked(1); JsStuComplaintsExample example = new JsStuComplaintsExample(); example.createCriteria().andIdEqualTo(id).andStuNumEqualTo(stu_num); int flag = jsStuComplaintsMapper.updateByExampleSelective(record, example); if (flag > 0) { return true; } else { throw new JiaQuException("Undo failed"); } } @Override public boolean insertComplaints(String complaints_type, String complaints_object, String complaints_content, Integer is_prosecuted, List<MultipartFile> files, String stuNum) throws Exception { logger.info("insertComplaints:开始插:complaints_type:" + complaints_type + " complaints_object:" + complaints_object + " complaints_content:" + complaints_content + " is_prosecuted:" + is_prosecuted + " stuNum:" + stuNum); // 如果中文乱码转码 if (Tools.isMessyCode(complaints_type)) { complaints_type = Tools.strutf(complaints_type); } if (Tools.isMessyCode(complaints_object)) { complaints_object = Tools.strutf(complaints_object); } if (Tools.isMessyCode(complaints_content)) { complaints_content = Tools.strutf(complaints_content); } if (Tools.isMessyCode(stuNum)) { stuNum = Tools.strutf(stuNum); } JsStuComplaints jsStuComplaints = new JsStuComplaints(); logger.info("insertComplaints:开始插" + jsStuComplaints); logger.info("insertComplaints:开始插" + complaints_content); jsStuComplaints.setComplaintsContent(complaints_content); logger.info("insertComplaints:开始插" + complaints_object); jsStuComplaints.setComplaintsObject(complaints_object); logger.info("insertComplaints:开始插" + stuNum); jsStuComplaints.setStuNum(stuNum); logger.info("insertComplaints:开始插" + complaints_type); jsStuComplaints.setComplaintsType(complaints_type); logger.info("insertComplaints:开始插" + is_prosecuted); jsStuComplaints.setIsProsecuted(is_prosecuted); logger.info("insertComplaints:开始插前" + jsStuComplaintsMapper); jsStuComplaints.setComplaintsTime(new Date()); int complaintsId = jsStuComplaintsMapper.insertSelective(jsStuComplaints); logger.info("insertComplaints:开始插后"); complaintsId = jsStuComplaints.getId(); logger.info("insertComplaints:插入编号:" + complaintsId); if (complaintsId == 1) { JsStuComplaintsExample example = new JsStuComplaintsExample(); example.createCriteria().andStuNumEqualTo(stuNum); List<JsStuComplaints> jComplaints = jsStuComplaintsMapper.selectByExample(example); complaintsId = jComplaints.get(jComplaints.size() - 1).getId(); } if (complaintsId > 0) { // 判断file数组不能为空并且长度大于0 // logger.info("insertComplaints:files: " + files + "," + // files.size()); if (files != null && files.size() > 0) { // 循环获取file数组中得文件 for (int i = 0; i < files.size(); i++) { MultipartFile file = files.get(i); // 保存文件 logger.info("insertComplaints:开始保存文件:"); String fileName = saveFile(file, stuNum, is_prosecuted); logger.info("insertComplaints:保存文件结束: 文件名:" + fileName); if (!"".equals(fileName)) { JsComplaintsPhoto record = new JsComplaintsPhoto(); record.setComplaintsId(complaintsId); record.setPhotoPath(fileName); int count = jsComplaintsPhotoMapper.insertSelective(record); if (count <= 0) { throw new JiaQuException("insert photo failed"); } } } } StudentInfo studentInfo = (StudentInfo) stuInFoManagement.getUserInFoByNumber(stuNum); Complaint complaint = new Complaint(complaintsId, null, call_url, studentInfo.getInscode(), stuNum, studentInfo.getName(), Integer.valueOf(studentInfo.getSex()), com.corbett.utils.date.DateFormat.date2Str(jsStuComplaints.getComplaintsTime()), complaints_type, complaints_object, null, complaints_content); PushDataInFo pushDataInFo = new PushDataInFo(PushDataType.PushComplaint, complaint); sendMessageToDataCenter.process(pushDataInFo); } else { throw new JiaQuException("insert failed"); } return true; } @Override public boolean insertProsecutedComplaints(Integer id, String complaints_content, Integer is_prosecuted, List<MultipartFile> files) throws Exception { // 如果中文乱码转码 if (Tools.isMessyCode(complaints_content)) { complaints_content = Tools.strutf(complaints_content); } // 修改被追诉 JsStuComplaints jsStuComplaints = new JsStuComplaints(); jsStuComplaints.setIsProsecuted(is_prosecuted); jsStuComplaints.setId(id); jsStuComplaintsMapper.updateByPrimaryKeySelective(jsStuComplaints); jsStuComplaints = jsStuComplaintsMapper.selectByPrimaryKey(id); // 开始插入追诉 JsStuProsecutedComplaints jsStuProsecutedComplaints = new JsStuProsecutedComplaints(); jsStuProsecutedComplaints.setComplaintsContent(complaints_content); jsStuProsecutedComplaints.setComplaintsTime(new Date()); jsStuProsecutedComplaints.setComplaintsId(id); Integer prosecutedComplaintsId = jsStuProsecutedComplaintsMapper.insertSelective(jsStuProsecutedComplaints); if (prosecutedComplaintsId > 0) { prosecutedComplaintsId = jsStuProsecutedComplaints.getStuPCId(); } else { throw new JiaQuException("投诉失败,请稍候投诉"); } if (prosecutedComplaintsId == 1) { JsStuProsecutedComplaintsExample jsStuProsecutedComplaintsExample = new JsStuProsecutedComplaintsExample(); jsStuProsecutedComplaintsExample.createCriteria().andComplaintsIdEqualTo(id); List<JsStuProsecutedComplaints> jsStuProsecutedComplaintsList = jsStuProsecutedComplaintsMapper .selectByExample(jsStuProsecutedComplaintsExample); prosecutedComplaintsId = jsStuProsecutedComplaintsList.get(jsStuProsecutedComplaintsList.size() - 1) .getStuPCId(); } if (prosecutedComplaintsId > 0) { // 判断file数组不能为空并且长度大于0 if (files != null && files.size() > 0) { // 循环获取file数组中得文件 for (int i = 0; i < files.size(); i++) { MultipartFile file = files.get(i); // 保存文件 String fileName = saveFile(file, jsStuComplaints.getStuNum(), is_prosecuted); if (!"".equals(fileName)) { JsProsecutedComplaintsPhoto jsProsecutedComplaintsPhoto = new JsProsecutedComplaintsPhoto(); jsProsecutedComplaintsPhoto.setComplaintsId(id); jsProsecutedComplaintsPhoto.setProsecutedComplaintsId(prosecutedComplaintsId); jsProsecutedComplaintsPhoto.setPhotoPath(fileName); Integer count = jsProsecutedComplaintsPhotoMapper.insertSelective(jsProsecutedComplaintsPhoto); if (count <= 0) { throw new JiaQuException("追诉图片上传失败"); } } } } /** * 添加上报信息 */ StudentInfo studentInfo = (StudentInfo) stuInFoManagement.getUserInFoByNumber(jsStuComplaints.getStuNum()); Complaint complaint = new Complaint(id, prosecutedComplaintsId, call_url, studentInfo.getInscode(), jsStuComplaints.getStuNum(), studentInfo.getName(), Integer.valueOf(studentInfo.getSex()), DateFormat.date2Str(jsStuComplaints.getComplaintsTime()), PersonType.valueOf(jsStuComplaints.getComplaintsType()).getValue(), jsStuComplaints.getComplaintsObject(), null, complaints_content); PushDataInFo pushDataInFo = new PushDataInFo(PushDataType.PushComplaint, complaint); sendMessageToDataCenter.process(pushDataInFo); } else { throw new JiaQuException("insert failed"); } return true; } /*** * 保存文件 * * @param file * @return * @throws IOException * @throws IllegalStateException */ private String saveFile(MultipartFile file, String stuNum, Integer is_prosecuted) throws IllegalStateException, IOException { // 判断文件是否为空 if (!file.isEmpty()) { try { logger.info("saveFile:文件不为空"); String fileName = file.getOriginalFilename(); String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); String OS = System.getProperty("os.name").toLowerCase(); String fileNames = String.valueOf(System.currentTimeMillis()) + "." + suffix; // 文件保存路径 logger.info("saveFile:OS:" + OS + " fileNames:" + fileNames); String path = Path + stuNum + "/" + String.valueOf(is_prosecuted); String filePath = path + "/" + fileNames; if (OS.indexOf("linux") < 0) { path = Path_local + "\\" + stuNum + "\\" + String.valueOf(is_prosecuted); filePath = path + "\\" + fileNames; } logger.info("saveFile:path" + path); // File file2 = new File(path); // if (!file2.exists() && !file2.isDirectory()) { // System.out.println("//不存在"); // file2.mkdir(); // } else { // System.out.println("//目录存在"); // } FileUitls.isExistDir(path); // 转存文件 file.transferTo(new File(filePath)); return fileNames; } catch (Exception e) { e.printStackTrace(); } } return ""; } @Override public Integer countComplaints(String stu_num, Integer isRevoked) { JsStuComplaintsExample example = new JsStuComplaintsExample(); example.createCriteria().andStuNumEqualTo(stu_num).andIsRevokedEqualTo(isRevoked); return jsStuComplaintsMapper.countByExample(example); } } <file_sep>/src/main/java/com/jishi/entity/rt/Coach_rt.java package com.jishi.entity.rt; public class Coach_rt { private String inscode; private String coachnum; private String name; private int sex; private String Teachpermitted; private String mobile; private String photo; private float averageScore; public String getInscode() { return inscode; } public void setInscode(String inscode) { this.inscode = inscode; } public float getAverageScore() { return averageScore; } public void setAverageScore(float averageScore) { this.averageScore = averageScore; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getCoachnum() { return coachnum; } public void setCoachnum(String coachnum) { this.coachnum = coachnum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getTeachpermitted() { return Teachpermitted; } public void setTeachpermitted(String teachpermitted) { Teachpermitted = teachpermitted; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } } <file_sep>/src/main/java/com/jishi/service/impl/SchoolAppService.java package com.jishi.service.impl; import java.util.HashMap; import java.util.List; import java.sql.Timestamp; import java.util.Date; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import com.face.service.FaceVisa; import com.jishi.dao.DaoSupport; import com.jishi.entity.CoachInfo; import com.jishi.entity.Coach_PayRecord; import com.jishi.entity.Coach_order; import com.jishi.entity.CommentInfo; import com.jishi.entity.rt.UnpayOrder_rt; import com.jishi.entity.schoolapp.StuInfo; import com.jishi.entity.ReturnInfo; import com.jishi.entity.StudentInfo; import com.jishi.entity.TrainOrder; import com.jishi.entity.TrainOrder_Pay; import com.jishi.entity.studentlogin; import com.jishi.entity.rece.contrastInfo; import com.jishi.entity.view.ViewContrastResult; import com.jishi.service.PayService; import com.jishi.service.PushData; import com.jishi.service.TrainService; import com.jishi.until.DateUtil; import com.jishi.until.DrawImage; import com.jishi.until.FileUpload; import com.jishi.until.NumberUtil; import com.jishi.until.ReturnMessage; import com.jishi.until.ReturnMessage_entity; import com.jishi.until.Tools; import net.sf.json.JSONObject; @Service(value="SchoolAppService") @Transactional(rollbackFor=Exception.class) public class SchoolAppService { @Resource(name = "daoSupport") private DaoSupport dao; @Resource(name = "PushDataImpl") private PushData pushData; @Resource(name="SchoolAppService") SchoolAppService schoolAppService; public Map checkUserAndPassword(Map map) throws Exception { return (Map)dao.findForObject("SchoolAppMapper.checkUserAndPassword", map); } public List<Map> getLimits(Map map) throws Exception { return (List<Map>)dao.findForList("SchoolAppMapper.getLimits", map); } public int getThisMonthNewStudentCount(Map map) throws Exception { return (Integer)dao.findForObject("SchoolAppMapper.getThisMonthNewStudentCount", map); } public int addNewStudent(StuInfo map) throws Exception { return (Integer)dao.save("SchoolAppMapper.addNewStudent", map); } public int updateNewStudent(StuInfo map) throws Exception { return (Integer)dao.update("SchoolAppMapper.updateNewStudent", map); } public int checkPhoneOrIdCardIsExited(String phone, String idcard) throws Exception { Map param = new HashMap(); param.put("phone", phone); param.put("idcard", idcard); Map phoneCount = (Map)dao.findForObject("SchoolAppMapper.checkPhoneIsExited", param); Map idcardCount = (Map)dao.findForObject("SchoolAppMapper.checkIdCardIsExited", param); Map ret =new HashMap(); if (idcardCount!=null) { String phonenum =(String)idcardCount.get("phone"); if (phone.equals(phonenum)) { return 0; } else { return -2; } } if (phoneCount!=null) { int status =(Integer)phoneCount.get("status"); if (status==0) { return 0; } else { return -1; } } else { return 1; } } public String getstunum(String phone) throws Exception { return (String)dao.findForObject("SchoolAppMapper.getstunum", phone); } public List<UnpayOrder_rt> getUnpayOrder(Map map) throws Exception { return (List<UnpayOrder_rt>)dao.findForList("SchoolAppMapper.getUnpayOrder", map); } public int getUnpayOrderPageNum(Map map) throws Exception { return (Integer)dao.findForObject("SchoolAppMapper.getUnpayOrderPageNum", map); } public List<Map> getAllCoachname(Map map) throws Exception { return (List<Map>)dao.findForList("SchoolAppMapper.getAllCoachname", map); } public List<Map> getAllSimuCoachname(Map map) throws Exception { return (List<Map>)dao.findForList("SchoolAppMapper.getAllSimuCoachname", map); } public List<UnpayOrder_rt> getUnpayOrderByName(Map map) throws Exception { return (List<UnpayOrder_rt>)dao.findForList("SchoolAppMapper.getUnpayOrderByName", map); } /** * 当面付回调接口 * @param map * @return * @throws Exception */ public void updateOrderStatus(Map parm,Map orderMap) throws Exception { dao.update("SchoolAppMapper.updateOrderStatus", parm); schoolAppService.addNewPayRecord(orderMap); schoolAppService.updateAliOrder(orderMap); Map ret = schoolAppService.getStuAccoutData(parm); if (ret!=null) { float amount =Float.parseFloat((String)orderMap.get("amount")); orderMap.put("stunum", ret.get("stunum")); orderMap.put("stuname", ret.get("stuname")); orderMap.put("coachname", ret.get("coachname")); orderMap.put("balance", (Float)ret.get("stubalance")); orderMap.put("inscode", ret.get("inscode")); orderMap.put("coachnum", ret.get("coachnum")); orderMap.put("remark", ""); orderMap.put("issimulate", ret.get("issimulate")); orderMap.put("coachBalance",(Float)ret.get("coachBalance")+amount); orderMap.put("schoolBalance",(Float)ret.get("schoolBalance")+amount); schoolAppService.addStuWalletRecord(orderMap); schoolAppService.addCoachWalletRecord(orderMap); if ((Integer)orderMap.get("issimulate")==0) { schoolAppService.updateCoachBalance(orderMap); } else { schoolAppService.updateSimuCoachBalance(orderMap); } schoolAppService.addSchoolWalletRecord(orderMap); //schoolAppService.updateSchoolBalance(orderMap); /** * 开始上报交易信息 */ } else { throw new RuntimeException(); } } public int addNewPayRecord(Map map) throws Exception { return (Integer)dao.save("SchoolAppMapper.addNewPayRecord", map); } public int updateAliOrder(Map map) throws Exception { return (Integer)dao.update("SchoolAppMapper.updateAliOrder", map); } public Map getStuAccoutData(Map map) throws Exception { Map ret = (Map)dao.findForObject("SchoolAppMapper.getStuAccoutData", map); if (ret!=null) { String coachnum =(String) ret.get("coachnum"); int issimulate =(Integer) ret.get("issimulate"); if (issimulate==0) { Map coachMap =new HashMap(); coachMap.put("coachnum", coachnum); Map coachname = (Map)dao.findForObject("SchoolAppMapper.getCoachNameByCoachnum", coachMap); if (coachname!=null) { String nameString =(String)coachname.get("coachname"); ret.put("coachname", nameString); ret.put("coachBalance", coachname.get("coachBalance")); } } else { Map coachMap =new HashMap(); coachMap.put("coachnum", coachnum); Map coachname = (Map)dao.findForObject("SchoolAppMapper.getSimuCoachNameByCoachnum", coachMap); if (coachname!=null) { String nameString =(String)coachname.get("coachname"); ret.put("coachname", nameString); ret.put("coachBalance", coachname.get("coachBalance")); } } } return ret; } public int addStuWalletRecord(Map map) throws Exception { return (Integer)dao.save("SchoolAppMapper.addStuWalletRecord", map); } public int addCoachWalletRecord(Map map) throws Exception { return (Integer)dao.save("SchoolAppMapper.addCoachWalletRecord", map); } public int addSchoolWalletRecord(Map map) throws Exception { return (Integer)dao.save("SchoolAppMapper.addSchoolWalletRecord", map); } public int updateCoachBalance(Map map) throws Exception { return (Integer)dao.update("SchoolAppMapper.updateCoachBalance", map); } public int updateSimuCoachBalance(Map map) throws Exception { return (Integer)dao.update("SchoolAppMapper.updateSimuCoachBalance", map); } public int updateSchoolBalance(Map map) throws Exception { return (Integer)dao.update("SchoolAppMapper.updateSchoolBalance", map); } public ReturnMessage_entity<StudentInfo> checkcontrastInfo(contrastInfo info) { ReturnMessage_entity<StudentInfo> R = new ReturnMessage_entity<StudentInfo>(); if(info.getFixedPhoto() == null) { R.setFlag(-1); R.setMessage("身份证照片为空"); return R; } if(info.getContrastPhoto() == null) { R.setFlag(-1); R.setMessage("对比照片为空"); return R; } if(info.getStunum() == null) { R.setFlag(-1); R.setMessage("未上传学员编号"); return R; } R = checkstu(info.getStunum()); return R; } public ReturnMessage_entity<StudentInfo> checkstu(String stunum ){ ReturnMessage_entity<StudentInfo> R = new ReturnMessage_entity<>(); StudentInfo stu = new StudentInfo(); try { stu = (StudentInfo)dao.findForObject("StudentInfMapper.getStudentInfo", stunum); } catch (Exception e) { // TODO Auto-generated catch block R.setFlag(-1); R.setMessage("网络异常"); return R; } if(stu == null) { R.setFlag(-1); R.setMessage("学员不存在"); return R; } if(stu.getStatus() != 0) { R.setFlag(-1); R.setMessage("学员已报名,不能操作"); return R; } R.setFlag(1); R.setData(stu); return R; } public ReturnMessage_entity<ViewContrastResult> contrastresult(String body,MultipartFile multipartFile,StudentInfo stu) { ReturnMessage_entity<ViewContrastResult> R = new ReturnMessage_entity<ViewContrastResult>(); JSONObject obj= JSONObject.fromObject(body); ViewContrastResult Result = new ViewContrastResult(); if(obj.containsKey("result")) Result.setResult(Integer.parseInt(obj.getString("result"))); if(obj.containsKey("confidence")) Result.setConfidence(obj.getString("confidence")); R.setData(Result); if(Result.getResult() < 2 ) { R.setFlag(-1); R.setMessage("图片对比失败"); } else { try { ReturnMessage photo = UpStudentPhoto(multipartFile,stu); if(photo.getFlag() != 1) { R.setFlag(photo.getFlag()); R.setMessage(photo.getMessage()); return R; } R.setFlag(1); R.setMessage("对比成功"); return R; } catch (Exception e) { // TODO Auto-generated catch block System.err.println(e.getMessage()); R.setFlag(-1); R.setMessage("网路异常"); return R; } } return R; } @Resource(name="UserService") UserService userService; /* * 上传学员照片 * */ public ReturnMessage UpStudentPhoto(MultipartFile multipartFile,StudentInfo stu) throws Exception { ReturnMessage R = new ReturnMessage(); String path = "/mnt/sites/up_img/manage/student/"; String filepath =path +stu.getInscode(); String name =stu.getStunum()+"_"+Tools.getRandNum18(); //上传原图至服务器 String PhotoUrl = stu.getInscode() +"/"+ FileUpload.fileUp(multipartFile,filepath,name); //生成缩略图 String smallpath = path +"small_" +PhotoUrl; DrawImage draw = new DrawImage(path+PhotoUrl,smallpath); draw.resizeByHeight(450); ReturnInfo faceR = FaceVisa.upFacePhoto(stu.getPersonId()+"", "1", path+PhotoUrl); if(faceR.getFlag() != 1) { R.setFlag(faceR.getFlag()); R.setMessage((String)faceR.getMessage()); return R; } ReturnInfo reMsg = userService.addPhoto(String.valueOf(faceR.getMessage()), stu.getStunum(), PhotoUrl); //添加本地库 R.setFlag(1); return R; } public ReturnMessage_entity<ViewContrastResult> siumpast(String body,String stunum) { ReturnMessage_entity<ViewContrastResult> R = new ReturnMessage_entity<ViewContrastResult>(); JSONObject obj= JSONObject.fromObject(body); ViewContrastResult Result = new ViewContrastResult(); if(obj.containsKey("result")) Result.setResult(Integer.parseInt(obj.getString("result"))); if(obj.containsKey("confidence")) Result.setConfidence(obj.getString("confidence")); R.setData(Result); if(Result.getResult() < 2 ) { R.setFlag(-1); R.setMessage("签到失败"); } else { StudentInfo stu = new StudentInfo(); try { stu = (StudentInfo)dao.findForObject("StudentInfMapper.getStudentInfo", stunum); if(stu.getStatus() == 0) { if((Integer)dao.findForObject("StudentInfMapper.checkstudenthous", stunum) == 0) { //生成学员学时信息和阶段培训信息 dao.save("StudentInfMapper.insertSubjectCoach", stu.getStunum()); } if((Integer)dao.findForObject("StudentInfMapper.checkstagetrainningtime", stunum) == 0) { for (int i = 1; i < 5; i++) { stu.setSubject(i); dao.save("StudentInfMapper.insertstagetrainningtime", stu); } } if((Integer)dao.findForObject("StudentInfMapper.checkstulogin", stunum) == 0) { studentlogin login = new studentlogin(); login.setPassword("<PASSWORD>"); login.setStunum(stu.getStunum()); login.setUserid(stu.getPhone()); login.setToken(NumberUtil.getToken()); dao.save("StudentInfMapper.addstudentlogin", login); } stu.setStatus(1); dao.save("StudentInfMapper.Updatstudent", stu); } } catch (Exception e) { // TODO Auto-generated catch block R.setFlag(-1); R.setMessage("网络异常"); System.err.println(e.getMessage()); return R; } R.setFlag(1); R.setMessage("签到成功"); } return R; } @Resource(name="TrainService") TrainService trainService; @Resource(name="PayService") PayService payService; public ReturnMessage_entity<ViewContrastResult> cash_pay(String OrderNum,MultipartFile stuphoto) { ReturnMessage_entity<ViewContrastResult> R = new ReturnMessage_entity<ViewContrastResult>(); try { TrainOrder order =(TrainOrder)dao.findForObject("TrainOrderMapper.getTrainOrderDetailsbyOrderNum", OrderNum); StudentInfo stu = (StudentInfo)dao.findForObject("StudentInfMapper.getStudentInfo", order.getStuNum()); String body = FaceVisa.test2_2_07(stu.getPersonId()+"", stuphoto.getBytes()); JSONObject obj= JSONObject.fromObject(body); ViewContrastResult Result = new ViewContrastResult(); if(obj.containsKey("result")) Result.setResult(Integer.parseInt(obj.getString("result"))); if(obj.containsKey("confidence")) Result.setConfidence(obj.getString("confidence")); R.setData(Result); if(Result.getResult() < 2 ) { R.setFlag(-1); R.setMessage("人脸验证失败"); return R; } else { ReturnMessage checkOrder = payService.CheckOrder(order); if(checkOrder.getFlag() != 1) { R.setFlag(checkOrder.getFlag()); R.setMessage(checkOrder.getMessage()); return R; } //改变订单表支付状态 payService.updateorderIspay(OrderNum); Timestamp timestamp = new Timestamp((new Date()).getTime()); //新增订单记录 TrainOrder_Pay order_Pay = new TrainOrder_Pay(); order_Pay.setOrderNum(OrderNum); order_Pay.setStuOrCoach(3); order_Pay.setPayDate(timestamp); order_Pay.setPayStyle(4); order_Pay.setMoney(order.getMoney()); order_Pay.setPaySerialNum(Tools.getRandNum18()); order_Pay.setPayAccount(order.getInscode()); order_Pay.setIncomeAccount(order.getInscode()); payService.insertorder_pay(order_Pay); //改变教练余额 CoachInfo coachInfo = payService.getCoachAmount(order); Coach_PayRecord coach_PayRecord = new Coach_PayRecord(); coach_PayRecord.setStuNum(order.getStuNum()); coach_PayRecord.setInscode(coachInfo.getInsCode()); coach_PayRecord.setCoachNum(coachInfo.getCoachNum()); coach_PayRecord.setMoney(order.getDurationMoney()); coach_PayRecord.setRemark("您收益了"+order.getDurationMoney()+"元,来自学员【"+order.getStuName()+"】的【"+Subjectstr(order.getSubject())+"】学习"); coach_PayRecord.setCreateDate(timestamp); coach_PayRecord.setCoachAmount(coachInfo.getCoachAmount()+order.getDurationMoney()); coach_PayRecord.setInscodeAmount(coachInfo.getInscodeAmount()); coach_PayRecord.setOrderNum(OrderNum); coach_PayRecord.setServicesMoney(order.getServiceMoney()); coach_PayRecord.setIsSimulate(order.getIsSimulate()); payService.insertCoach_PayRecord(coach_PayRecord); //更新教练余额 payService.updateCoachAmount(coach_PayRecord); //如果有服务费,新增驾校收支记录,改变驾校余额,新增服务费收取记录 if(coach_PayRecord.getServicesMoney() > 0) { Coach_PayRecord service_PayRecord =coach_PayRecord; service_PayRecord.setMoney(-order.getServiceMoney()); service_PayRecord.setRemark("您支出了"+order.getServiceMoney()+"元,用于驾校线下收取现金支付给平台的服务费"); coach_PayRecord.setCoachAmount(coachInfo.getCoachAmount()); coach_PayRecord.setInscodeAmount(coachInfo.getInscodeAmount()-order.getServiceMoney()); payService.insertservicemoneyrecord(coach_PayRecord); //更新驾校余额 payService.updateInscodeAmount(service_PayRecord); } } } catch (Exception e) { // TODO Auto-generated catch block R.setFlag(-1); R.setMessage("网络错误"); return R; } R.setFlag(1); R.setMessage("操作成功"); return R; } public String Subjectstr(int Subject) { String Subjectstr =""; switch (Subject) { case 1: Subjectstr = "科目一"; break; case 21: Subjectstr = "科目二实车"; break; case 22: Subjectstr = "科目二模拟"; break; case 31: Subjectstr ="科目三实车"; break; case 32: Subjectstr = "科目三模拟"; break; case 4: Subjectstr ="科目四"; break; default: break; } return Subjectstr; } public ReturnMessage checkCommentInfo(CommentInfo cm){ ReturnMessage R = new ReturnMessage(); if(cm.getOrderNum() == null) { R.setFlag(-1); R.setMessage("未上传订单编号"); return R; } if(cm.getCommentContent() == null) { R.setFlag(-1); R.setMessage("未上传评价内容"); return R; } if(cm.getCommentContext() == null) { R.setFlag(-1); R.setMessage("未上传评价内容"); return R; } if(cm.getTeachLevelScore() <= 0) { R.setFlag(-1); R.setMessage("请上传正确教学水平评分"); return R; } if(cm.getTeachStaeScore() <= 0) { R.setFlag(-1); R.setMessage("请上传正确教学状态评分"); return R; } if(cm.getCarStateScore() <= 0) { R.setFlag(-1); R.setMessage("请上传正确车辆状况评分"); return R; } R.setFlag(1); return R; } public ReturnMessage cash_comment(CommentInfo cm) { ReturnMessage r= new ReturnMessage(); try { TrainOrder order =(TrainOrder)dao.findForObject("TrainOrderMapper.getTrainOrderDetailsbyOrderNum", cm.getOrderNum()); if (order == null ) //找不到该订单或订单有误 { r.setFlag(-1); r.setMessage("不存在该订单号"); return r; } if (order.getIsPay() == 0) { r.setFlag(-1); r.setMessage("该订单未支付,不允许评论操作"); return r; } if (order.getIsComment() == 1) { r.setFlag(-1); r.setMessage("该订单已评论,请勿重复操作"); return r; } CoachInfo c = payService.getCoachAmount(order); cm.setCommentDate(new Date()); cm.setDuration(order.getDuration()); cm.setSubject(order.getSubject()); cm.setEndDate(order.getEndDate()); cm.setStuNum(order.getStuNum()); cm.setCoachNum(order.getCoachNum()); cm.setInscode(order.getInscode()); cm.setName(c.getName()); cm.setInscode(order.getInscode()); cm.setCoachNum(order.getCoachNum()); dao.save("CommentMapper.addComment",cm); dao.update("CommentMapper.changeOrderCommentStatus",cm); } catch (Exception e) { // TODO Auto-generated catch block r.setFlag(-1); r.setMessage("网络错误"); return r; } r.setFlag(1); r.setMessage("操作成功"); return r; } } <file_sep>/src/main/java/com/jishi/service/AdivceMethod.java package com.jishi.service; import java.lang.reflect.Method; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; @Component @Aspect public class AdivceMethod { @Before("execution(* com.jishi.service.impl.PersonImpl.*(..))") public String beforeEat(){ String ssString = "吃饭没洗手,不许吃饭"; System.out.println(ssString); return ssString; } // @AfterReturning(returning="rvt",pointcut="execution(* com.jishi.service.impl.PersonImpl.drink(..))") // public Object log(Object rvt) { // System.out.println("不要准吃饭"); // return rvt; // } @Around("execution(* com.jishi.service.impl.PersonImpl.drink(..))") // 匹配该工程下BabyPerson的eatLunch方法 public Object aroundEat(ProceedingJoinPoint pjp) throws Throwable { System.out .println("-------------------这里是环绕增强,吃晚饭前先玩一玩!-------------------"); MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); Method method = methodSignature.getMethod(); // System.out // .println("-------------------这里是环绕增强,晚饭吃完后要得睡觉了!-------------------"); // return retVal; boolean flg = false; if (flg) { Object retVal = pjp.proceed(); return retVal; } System.out.println("参数是:" + pjp.getArgs()[0]); return "bufuhe"; } } <file_sep>/src/main/java/com/jishi/until/http/HttpClient.java package com.jishi.until.http; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.jishi.enums.RequestMethod; public class HttpClient { /** * 是否使用缓存 */ public static Boolean UseCaches = false; /** * 连接超时时间 单位毫秒 */ public static Integer ConnectTimeout = 10000; /** * 读取超时间 单位毫秒 */ public static Integer ReadTimeout = 10000; /** * 设置此 httpurlconnection 实例是否应该自动执行 http 重定向(响应代码为 3xx 的请求) 默认值来自 * followredirects,其默认情况下为 true。 */ public static Boolean InstanceFollowRedirects = false; private static final String Content_Type = "Content-Type"; private static final String Content_Type_VALUE = "application/json"; /** * 访问连接获取数据 * * @param strUrl * 链接url * @param param * map型参数 ,注:中文参数有些情况需要用 URLEncoder.encode(param, * "utf-8");转换utf-8编码格式参数 * @param requestMethod * 访问类型 例如 get请求 或者 post 请求 可为 null * @param property * map 型的请求头信息 可为null * @return rs (String Data) * @throws IOException */ public static String getUrlData(String strUrl, Map<String, Object> param, RequestMethod requestMethod, Map<String, String> property) throws IOException { HttpURLConnection connection = null; BufferedReader read = null; String rs = null; InputStream in = null; DataOutputStream outputStream = null; try { if (requestMethod.getRequestMethod() == null || requestMethod.getRequestMethod().equals("GET")) { strUrl = strUrl + "?" + urlencode(param); } URL url = new URL(strUrl); connection = (HttpURLConnection) url.openConnection(); if (requestMethod.getRequestMethod() == null || requestMethod.getRequestMethod().equals("GET")) { connection.setRequestMethod("GET"); } else { connection.setRequestMethod("POST"); connection.setDoOutput(true); } // 设置请求头 if (property != null) { Iterator<Map.Entry<String, String>> iteratorMap = property.entrySet().iterator(); while (iteratorMap.hasNext()) { Map.Entry<java.lang.String, java.lang.String> entry = iteratorMap.next(); connection.setRequestProperty(entry.getKey(), entry.getValue()); } } if (UseCaches != null) { connection.setUseCaches(UseCaches); } if (ConnectTimeout != null) { connection.setConnectTimeout(ConnectTimeout); } if (ReadTimeout != null) { connection.setReadTimeout(ReadTimeout); } connection.setInstanceFollowRedirects(InstanceFollowRedirects); connection.connect(); if (param != null && requestMethod.getRequestMethod().equals("POST")) { try { outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(urlencode(param)); outputStream.flush(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } in = connection.getInputStream(); read = new BufferedReader(new InputStreamReader(in, "UTF-8")); String lists = null; StringBuffer sBuffer = new StringBuffer(); while ((lists = read.readLine()) != null) { sBuffer.append(lists); } rs = sBuffer.toString(); System.out.println(rs); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (read != null) { read.close(); } if (in != null) { in.close(); } if (outputStream != null) { outputStream.close(); } if (connection != null) { connection.disconnect(); } } return rs; } // 将map型转为请求参数型 @SuppressWarnings("rawtypes") public static String urlencode(Map<String, Object> param) { StringBuilder sb = new StringBuilder(); for (Map.Entry i : param.entrySet()) { try { sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return sb.toString(); } public static Map<String, String> getRequestHeader() { Map<String, String> map = new HashMap<>(); map.put(Content_Type, Content_Type_VALUE); return map; } public static Map<String, Object> getMapParam(Object... objects) { if (objects.length > 0) { Map<String, Object> map = new HashMap<>(); for (int i = 0; i < objects.length; i = i + 2) { map.put((String) objects[i], objects[i + 1]); } return map; } return null; } } <file_sep>/src/main/java/com/jishi/entity/BaseConfigInfo.java package com.jishi.entity; public class BaseConfigInfo { private String flag; private long flagValue; public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } public long getFlagValue() { return flagValue; } public void setFlagValue(long flagValue) { this.flagValue = flagValue; } } <file_sep>/src/main/java/com/jishi/entity/JsStuProsecutedComplaintsExample.java package com.jishi.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class JsStuProsecutedComplaintsExample { /** * This field was generated by MyBatis Generator. This field corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. This field corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. This field corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ public JsStuProsecutedComplaintsExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. This class corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andStuPCIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andStuPCIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andStuPCIdEqualTo(Integer value) { addCriterion("id =", value, "stuPCId"); return (Criteria) this; } public Criteria andStuPCIdNotEqualTo(Integer value) { addCriterion("id <>", value, "stuPCId"); return (Criteria) this; } public Criteria andStuPCIdGreaterThan(Integer value) { addCriterion("id >", value, "stuPCId"); return (Criteria) this; } public Criteria andStuPCIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "stuPCId"); return (Criteria) this; } public Criteria andStuPCIdLessThan(Integer value) { addCriterion("id <", value, "stuPCId"); return (Criteria) this; } public Criteria andStuPCIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "stuPCId"); return (Criteria) this; } public Criteria andStuPCIdIn(List<Integer> values) { addCriterion("id in", values, "stuPCId"); return (Criteria) this; } public Criteria andStuPCIdNotIn(List<Integer> values) { addCriterion("id not in", values, "stuPCId"); return (Criteria) this; } public Criteria andStuPCIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "stuPCId"); return (Criteria) this; } public Criteria andStuPCIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "stuPCId"); return (Criteria) this; } public Criteria andComplaintsIdIsNull() { addCriterion("complaints_id is null"); return (Criteria) this; } public Criteria andComplaintsIdIsNotNull() { addCriterion("complaints_id is not null"); return (Criteria) this; } public Criteria andComplaintsIdEqualTo(Integer value) { addCriterion("complaints_id =", value, "complaintsId"); return (Criteria) this; } public Criteria andComplaintsIdNotEqualTo(Integer value) { addCriterion("complaints_id <>", value, "complaintsId"); return (Criteria) this; } public Criteria andComplaintsIdGreaterThan(Integer value) { addCriterion("complaints_id >", value, "complaintsId"); return (Criteria) this; } public Criteria andComplaintsIdGreaterThanOrEqualTo(Integer value) { addCriterion("complaints_id >=", value, "complaintsId"); return (Criteria) this; } public Criteria andComplaintsIdLessThan(Integer value) { addCriterion("complaints_id <", value, "complaintsId"); return (Criteria) this; } public Criteria andComplaintsIdLessThanOrEqualTo(Integer value) { addCriterion("complaints_id <=", value, "complaintsId"); return (Criteria) this; } public Criteria andComplaintsIdIn(List<Integer> values) { addCriterion("complaints_id in", values, "complaintsId"); return (Criteria) this; } public Criteria andComplaintsIdNotIn(List<Integer> values) { addCriterion("complaints_id not in", values, "complaintsId"); return (Criteria) this; } public Criteria andComplaintsIdBetween(Integer value1, Integer value2) { addCriterion("complaints_id between", value1, value2, "complaintsId"); return (Criteria) this; } public Criteria andComplaintsIdNotBetween(Integer value1, Integer value2) { addCriterion("complaints_id not between", value1, value2, "complaintsId"); return (Criteria) this; } public Criteria andComplaintsContentIsNull() { addCriterion("complaints_content is null"); return (Criteria) this; } public Criteria andComplaintsContentIsNotNull() { addCriterion("complaints_content is not null"); return (Criteria) this; } public Criteria andComplaintsContentEqualTo(String value) { addCriterion("complaints_content =", value, "complaintsContent"); return (Criteria) this; } public Criteria andComplaintsContentNotEqualTo(String value) { addCriterion("complaints_content <>", value, "complaintsContent"); return (Criteria) this; } public Criteria andComplaintsContentGreaterThan(String value) { addCriterion("complaints_content >", value, "complaintsContent"); return (Criteria) this; } public Criteria andComplaintsContentGreaterThanOrEqualTo(String value) { addCriterion("complaints_content >=", value, "complaintsContent"); return (Criteria) this; } public Criteria andComplaintsContentLessThan(String value) { addCriterion("complaints_content <", value, "complaintsContent"); return (Criteria) this; } public Criteria andComplaintsContentLessThanOrEqualTo(String value) { addCriterion("complaints_content <=", value, "complaintsContent"); return (Criteria) this; } public Criteria andComplaintsContentLike(String value) { addCriterion("complaints_content like", value, "complaintsContent"); return (Criteria) this; } public Criteria andComplaintsContentNotLike(String value) { addCriterion("complaints_content not like", value, "complaintsContent"); return (Criteria) this; } public Criteria andComplaintsContentIn(List<String> values) { addCriterion("complaints_content in", values, "complaintsContent"); return (Criteria) this; } public Criteria andComplaintsContentNotIn(List<String> values) { addCriterion("complaints_content not in", values, "complaintsContent"); return (Criteria) this; } public Criteria andComplaintsContentBetween(String value1, String value2) { addCriterion("complaints_content between", value1, value2, "complaintsContent"); return (Criteria) this; } public Criteria andComplaintsContentNotBetween(String value1, String value2) { addCriterion("complaints_content not between", value1, value2, "complaintsContent"); return (Criteria) this; } public Criteria andComplaintsTimeIsNull() { addCriterion("complaints_time is null"); return (Criteria) this; } public Criteria andComplaintsTimeIsNotNull() { addCriterion("complaints_time is not null"); return (Criteria) this; } public Criteria andComplaintsTimeEqualTo(Date value) { addCriterion("complaints_time =", value, "complaintsTime"); return (Criteria) this; } public Criteria andComplaintsTimeNotEqualTo(Date value) { addCriterion("complaints_time <>", value, "complaintsTime"); return (Criteria) this; } public Criteria andComplaintsTimeGreaterThan(Date value) { addCriterion("complaints_time >", value, "complaintsTime"); return (Criteria) this; } public Criteria andComplaintsTimeGreaterThanOrEqualTo(Date value) { addCriterion("complaints_time >=", value, "complaintsTime"); return (Criteria) this; } public Criteria andComplaintsTimeLessThan(Date value) { addCriterion("complaints_time <", value, "complaintsTime"); return (Criteria) this; } public Criteria andComplaintsTimeLessThanOrEqualTo(Date value) { addCriterion("complaints_time <=", value, "complaintsTime"); return (Criteria) this; } public Criteria andComplaintsTimeIn(List<Date> values) { addCriterion("complaints_time in", values, "complaintsTime"); return (Criteria) this; } public Criteria andComplaintsTimeNotIn(List<Date> values) { addCriterion("complaints_time not in", values, "complaintsTime"); return (Criteria) this; } public Criteria andComplaintsTimeBetween(Date value1, Date value2) { addCriterion("complaints_time between", value1, value2, "complaintsTime"); return (Criteria) this; } public Criteria andComplaintsTimeNotBetween(Date value1, Date value2) { addCriterion("complaints_time not between", value1, value2, "complaintsTime"); return (Criteria) this; } public Criteria andIsRevokedIsNull() { addCriterion("is_revoked is null"); return (Criteria) this; } public Criteria andIsRevokedIsNotNull() { addCriterion("is_revoked is not null"); return (Criteria) this; } public Criteria andIsRevokedEqualTo(Integer value) { addCriterion("is_revoked =", value, "isRevoked"); return (Criteria) this; } public Criteria andIsRevokedNotEqualTo(Integer value) { addCriterion("is_revoked <>", value, "isRevoked"); return (Criteria) this; } public Criteria andIsRevokedGreaterThan(Integer value) { addCriterion("is_revoked >", value, "isRevoked"); return (Criteria) this; } public Criteria andIsRevokedGreaterThanOrEqualTo(Integer value) { addCriterion("is_revoked >=", value, "isRevoked"); return (Criteria) this; } public Criteria andIsRevokedLessThan(Integer value) { addCriterion("is_revoked <", value, "isRevoked"); return (Criteria) this; } public Criteria andIsRevokedLessThanOrEqualTo(Integer value) { addCriterion("is_revoked <=", value, "isRevoked"); return (Criteria) this; } public Criteria andIsRevokedIn(List<Integer> values) { addCriterion("is_revoked in", values, "isRevoked"); return (Criteria) this; } public Criteria andIsRevokedNotIn(List<Integer> values) { addCriterion("is_revoked not in", values, "isRevoked"); return (Criteria) this; } public Criteria andIsRevokedBetween(Integer value1, Integer value2) { addCriterion("is_revoked between", value1, value2, "isRevoked"); return (Criteria) this; } public Criteria andIsRevokedNotBetween(Integer value1, Integer value2) { addCriterion("is_revoked not between", value1, value2, "isRevoked"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. This class corresponds to the database table js_stu_prosecuted_complaints * @mbggenerated Thu Apr 20 11:18:27 CST 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table js_stu_prosecuted_complaints * * @mbggenerated do_not_delete_during_merge Thu Apr 20 10:01:48 CST 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } }<file_sep>/src/main/java/com/jishi/service/ClassRecordService.java package com.jishi.service; import java.util.List; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import com.jishi.entity.ClassRecordInfo; import com.jishi.entity.CoachInfo; import com.jishi.entity.view.ViewClassRecordDeatil; import com.jishi.entity.view.ViewClassRecordInfo; import com.jishi.entity.view.ViewCoachStudent; import com.jishi.entity.view.ViewHistoryRecord; import com.jishi.entity.view.ViewStuClassRecord; import com.jishi.entity.view.ViewsubjectInfo; import com.jishi.until.ReturnMessage; @Transactional(rollbackFor = Exception.class) public interface ClassRecordService { List<ViewClassRecordInfo> getClassRecordlst(ClassRecordInfo ClassRecordInfo) throws Exception; int getClassRecordCount(ClassRecordInfo ClassRecordInfo) throws Exception; ViewClassRecordDeatil getClassRecordInfo(ClassRecordInfo ClassRecordInfo) throws Exception; List<ViewsubjectInfo> getsubjectInfo(int subject) throws Exception; List<ViewHistoryRecord> getstuHistoryRecordlst(ClassRecordInfo classRecordInfo) throws Exception; int getstuHistoryRecordCount(ClassRecordInfo classRecordInfo) throws Exception; int updateRecord(ClassRecordInfo ClassRecordInfo) throws Exception; List<ViewCoachStudent> getstudentbycoachNumlst(ClassRecordInfo classRecordInfo) throws Exception; int getstudentbycoachNumcount(ClassRecordInfo classRecordInfo) throws Exception; List<CoachInfo> getSimuCoachName(String Inscode) throws Exception; List<ViewStuClassRecord> getstuclassRecordlst(ClassRecordInfo classRecordInfo) throws Exception; int getstuclassRecordCount(ClassRecordInfo classRecordInfo) throws Exception; ReturnMessage start_train(String coachnum, String simunum, String stunum, int isface, MultipartFile studentPhoto) throws Exception; ReturnMessage end_train(String coachnum, String simunum, String stunum, int isface, MultipartFile studentPhoto) throws Exception; } <file_sep>/src/main/java/com/jishi/controller/zstu/LearnCarController.java package com.jishi.controller.zstu; import com.corbett.entity.ReturnMessage; import com.corbett.utils.map.ObjectMap; import com.jishi.controller.BaseController; import com.jishi.dao.DaoSupport; import com.jishi.entity.CoachInfo; import com.jishi.entity.SchoolFS; import com.jishi.entity.SearchParam; import com.jishi.entity.view.View_nearby_coach; import com.jishi.entity.view.View_nearby_school; import com.jishi.service.h5_Service; import com.jishi.until.Range; import com.jishi.until.ResultList; import com.jishi.until.ReturnMessage_entity; import org.codehaus.jackson.map.util.JSONPObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; /** * Created by hasee on 2017/7/8. */ @Controller @RequestMapping("info") public class LearnCarController extends BaseController { @Resource(name = "h5Service") h5_Service h5service; @Resource(name = "daoSupport") private DaoSupport dao; @RequestMapping("schoollist") @ResponseBody public ResultList getSchoolList(SearchParam searchParam) { List<View_nearby_school> list = new ArrayList<View_nearby_school>(); Map<String, Object> map = null; ResultList returnMessage = new ResultList(); try { int page = Integer.valueOf(searchParam.getPage()); if (searchParam.getLongitude() != null) { Range range = new Range(); map= range.Range_lat_Lng(searchParam.getLongitude(), searchParam.getLatitude()); searchParam.setDistance("true"); searchParam.setMaxLat((Double) map.get("maxLat")); searchParam.setMaxLng((Double) map.get("maxLng")); searchParam.setMinLat((Double) map.get("minLat")); searchParam.setMinLng((Double) map.get("minLng")); // searchParam.setPage("limit " + (Integer.valueOf(searchParam.getPage())-1)*10 + ",10"); map = ObjectMap.transBean2Map(searchParam); }else { // searchParam.setPage("limit " + (Integer.valueOf(searchParam.getPage())-1)*10 + ",10"); searchParam.setPage(null); map = ObjectMap.transBean2Map(searchParam); } list = h5service.getSchoollist(map); List<SchoolFS> schoolFSs = (List<SchoolFS>) dao.findForList("SchoolJoinMapper.getfswithschool",null); for (View_nearby_school view_nearby_school:list) { for (SchoolFS schoolFS:schoolFSs){ if (view_nearby_school.getInscode().equals(schoolFS.getInscode())){ view_nearby_school.setFs(schoolFS.getFs()); } } } Collections.sort(list,new Comparator<View_nearby_school>(){ public int compare(View_nearby_school arg0, View_nearby_school arg1) { if (arg0.getFs() != null && arg1.getFs() != null){ if (arg0.getFs()>arg1.getFs()){ return -1; }else { return 1; } }else { return -1; } } }); /** * 分页 */ returnMessage.setPage(list.size()); int count = (int) Math.ceil(list.size()/10); if (page == count){ list = list.subList((page - 1) * 10, list.size()); }else { list = list.subList((page - 1) * 10, page * 10); } returnMessage.setFlag(1); returnMessage.setMessage("success"); returnMessage.setData(list); return returnMessage; } catch (Exception e) { e.printStackTrace(); returnMessage.setFlag(-1); returnMessage.setMessage(e.getMessage()); return returnMessage; } } @RequestMapping("coachlist") @ResponseBody public ResultList coachlist(SearchParam searchParam){ List<View_nearby_coach> list = new ArrayList<View_nearby_coach>(); Map<String, Object> map = null; ResultList returnMessage = new ResultList(); try { if (searchParam.getLongitude() != null) { Range range = new Range(); map= range.Range_lat_Lng(searchParam.getLongitude(), searchParam.getLatitude()); searchParam.setDistance("true"); searchParam.setMaxLat((Double) map.get("maxLat")); searchParam.setMaxLng((Double) map.get("maxLng")); searchParam.setMinLat((Double) map.get("minLat")); searchParam.setMinLng((Double) map.get("minLng")); // searchParam.setPage("limit " + (Integer.valueOf(searchParam.getPage())-1)*10 + ",10"); searchParam.setPage(null); map = ObjectMap.transBean2Map(searchParam); }else { // searchParam.setPage("limit " + (Integer.valueOf(searchParam.getPage())-1)*10 + ",10"); searchParam.setPage(null); map = ObjectMap.transBean2Map(searchParam); } returnMessage.setPage(h5service.getCoachCount(map)); list = h5service.getCoachlist(map); returnMessage.setFlag(1); returnMessage.setMessage("success"); returnMessage.setData(list); return returnMessage; }catch (Exception e){ e.printStackTrace(); returnMessage.setFlag(-1); returnMessage.setMessage(e.getMessage()); return returnMessage; } } @RequestMapping(value = "/school_details", method = RequestMethod.GET) @ResponseBody public Object school_details(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "inscode", required = true) String inscode, Double longitude, Double latitude) { View_nearby_school model = new View_nearby_school(); ReturnMessage returnMessage = new ResultList(); try { if (longitude == null) { longitude = 100.276001; } if (latitude == null) { latitude = 25.611137; } CoachInfo coachInfo = new CoachInfo(); coachInfo.setInsCode(inscode); coachInfo.setLongitude(longitude); coachInfo.setLatitude(latitude); model = h5service.get_nearby_school_details(coachInfo); returnMessage.setData(model); returnMessage.setFlag(1); returnMessage.setMessage("success"); return returnMessage; } catch (Exception e) { returnMessage.setFlag(-1); returnMessage.setMessage(e.getMessage()); return returnMessage; } } @RequestMapping(value = "/coach_details", method = RequestMethod.GET) @ResponseBody public Object coach_details(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "coachnum", required = true) String coachnum, Double longitude, Double latitude) { View_nearby_coach model = new View_nearby_coach(); ReturnMessage returnMessage = new ReturnMessage(); try { if (longitude == null) { longitude = 100.276001; } if (latitude == null) { latitude = 25.611137; } CoachInfo coachInfo = new CoachInfo(); coachInfo.setCoachNum(coachnum); coachInfo.setLongitude(longitude); coachInfo.setLatitude(latitude); model = h5service.get_nearby_coach_details(coachInfo); returnMessage.setData(model); returnMessage.setFlag(1); returnMessage.setMessage("success"); return returnMessage; } catch (Exception e) { returnMessage.setFlag(-1); returnMessage.setMessage("success"); return returnMessage; } } @RequestMapping(value = "/school_coach", method = RequestMethod.GET) @ResponseBody public Object school_coach(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "inscode", required = true) String inscode, Double longitude, Double latitude) { List<View_nearby_coach> list = new ArrayList<View_nearby_coach>(); ReturnMessage returnMessage = new ReturnMessage(); try { if (longitude == null) { longitude = 100.276001; } if (latitude == null) { latitude = 25.611137; } CoachInfo coachInfo = new CoachInfo(); coachInfo.setInsCode(inscode); coachInfo.setLongitude(longitude); coachInfo.setLatitude(latitude); list = h5service.get_school_coachlist(coachInfo); returnMessage.setData(list); returnMessage.setFlag(1); returnMessage.setMessage("success"); return returnMessage; } catch (Exception e) { returnMessage.setFlag(-1); returnMessage.setMessage(e.getMessage()); return returnMessage; } } } <file_sep>/src/main/java/com/jishi/entity/datacenter/PublicInFoForPerson.java package com.jishi.entity.datacenter; public class PublicInFoForPerson { private String photo; private String name; private Integer sex; private String inst_code; private String idcard; private String nationality; private String phone; private Integer id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public String getInst_code() { return inst_code; } public void setInst_code(String inst_code) { this.inst_code = inst_code; } public String getIdcard() { return idcard; } public void setIdcard(String idcard) { this.idcard = idcard; } public String getNationality() { return nationality; } public void setNationality(String nationality) { this.nationality = nationality; } @Override public String toString() { return "PublicInFoForPerson [photo=" + photo + ", name=" + name + ", sex=" + sex + ", inst_code=" + inst_code + ", idcard=" + idcard + ", nationality=" + nationality + "]"; } public PublicInFoForPerson(String photo, String name, Integer sex, String inst_code, String idcard, String nationality) { super(); this.photo = photo; this.name = name; this.sex = sex; this.inst_code = inst_code; this.idcard = idcard; this.nationality = nationality; } public PublicInFoForPerson() { // TODO Auto-generated constructor stub } } <file_sep>/src/main/java/com/jishi/entity/datacenter/PublicInFoForSchool.java package com.jishi.entity.datacenter; public class PublicInFoForSchool { private String idcard; private String iccard; private String mobile; private String address; private String photo; private String name; private Integer sex; private String inst_code; public String getIccard() { return iccard; } public void setIccard(String iccard) { this.iccard = iccard; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getIdcard() { return idcard; } public void setIdcard(String idcard) { this.idcard = idcard; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public String getInst_code() { return inst_code; } public void setInst_code(String inst_code) { this.inst_code = inst_code; } public PublicInFoForSchool() { // TODO Auto-generated constructor stub } @Override public String toString() { return "PublicInFoForSchool [idcard=" + idcard + ", iccard=" + iccard + ", mobile=" + mobile + ", address=" + address + ", photo=" + photo + ", name=" + name + ", sex=" + sex + ", inst_code=" + inst_code + "]"; } public PublicInFoForSchool(String idcard, String iccard, String mobile, String address, String photo, String name, Integer sex, String inst_code) { super(); this.idcard = idcard; this.iccard = iccard; this.mobile = mobile; this.address = address; this.photo = photo; this.name = name; this.sex = sex; this.inst_code = inst_code; } } <file_sep>/src/main/java/com/jishi/until/datacenter/ResponseParam.java package com.jishi.until.datacenter; public class ResponseParam { public static final String msg = "msg"; public static final String total = "total"; public static final String data = "data"; public static final String success = "success"; public static final String status = "status"; } <file_sep>/src/main/java/com/jishi/enums/PushDataType.java package com.jishi.enums; public enum PushDataType { PushCoachStatus("PushCoachStatus",""),PushCarStatus("PushCarStatus",""),PushCoachSchedule("PushCoachSchedule","") ,PushComplaint("PushComplaint",""),PushEvaluation("PushEvaluation",""),PushPayment("PushPayment",""),PushRegion("PushRegion","") ,PushSeting("PushSeting",""),PushStuBespeak("PushStuBespeak",""); private String beanName;//正常流程上报时需要用到的bean的名字 private String pushFailDataBeanName;//正常流程上报时失败后从数据库取数据中上报时所需bean的名字 private PushDataType(String beanNname,String pushFailDataBeanName) { setBeanName(beanNname); setPushFailDataBeanName(pushFailDataBeanName); } public String getBeanName() { return beanName; } public void setBeanName(String beanName) { this.beanName = beanName; } public String getPushFailDataBeanName() { return pushFailDataBeanName; } public void setPushFailDataBeanName(String pushFailDataBeanName) { this.pushFailDataBeanName = pushFailDataBeanName; } } <file_sep>/src/main/java/com/jishi/service/impl/PushStuBespeakImpl.java package com.jishi.service.impl; import com.jishi.dao.PushdataStuSpeakDao; import com.jishi.enums.PushDataType; import com.jishi.service.AbstractPushDatasService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by IntelliJ IDEA. * User: corbettbain * Date: 2017/7/7 * Time: 17:34 */ @Service("PushStuBespeakImpl") public class PushStuBespeakImpl extends AbstractPushDatasService{ @Autowired private PushdataStuSpeakDao pushdataStuSpeakDao; @Override protected List<?> select() { return pushdataStuSpeakDao.selectAll(); } @Override protected PushDataType getPushDataType() { return PushDataType.PushStuBespeak; } @Override protected void delete(Integer integer) { pushdataStuSpeakDao.delete(integer); } } <file_sep>/src/main/java/com/jishi/entity/datacenter/view/EvaluationView.java package com.jishi.entity.datacenter.view; /** * 上报学员评价信息 * @author 周宁 2017年5月25日 上午10:22:01 * */ public class EvaluationView extends PublicPushDataView{ private String stu_num; private String inst_code; private String evl_object; private String obj_num; private String obj_name; private String date; private String overall; private String evl_srvmanner; private String evl_content; public String getStu_num() { return stu_num; } public void setStu_num(String stu_num) { this.stu_num = stu_num; } public String getInst_code() { return inst_code; } public void setInst_code(String inst_code) { this.inst_code = inst_code; } public String getEvl_object() { return evl_object; } public void setEvl_object(String evl_object) { this.evl_object = evl_object; } public String getObj_num() { return obj_num; } public void setObj_num(String obj_num) { this.obj_num = obj_num; } public String getObj_name() { return obj_name; } public void setObj_name(String obj_name) { this.obj_name = obj_name; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getOverall() { return overall; } public void setOverall(String overall) { this.overall = overall; } public String getEvl_srvmanner() { return evl_srvmanner; } public void setEvl_srvmanner(String evl_srvmanner) { this.evl_srvmanner = evl_srvmanner; } public String getEvl_content() { return evl_content; } public void setEvl_content(String evl_content) { this.evl_content = evl_content; } public EvaluationView(String stu_num, String inst_code, String evl_object, String obj_num, String obj_name, String date, String overall, String evl_srvmanner, String evl_content) { super(); this.stu_num = stu_num; this.inst_code = inst_code; this.evl_object = evl_object; this.obj_num = obj_num; this.obj_name = obj_name; this.date = date; this.overall = overall; this.evl_srvmanner = evl_srvmanner; this.evl_content = evl_content; } public EvaluationView() { } @Override public String toString() { return "EvaluationView{" + "stu_num='" + stu_num + '\'' + ", inst_code='" + inst_code + '\'' + ", evl_object='" + evl_object + '\'' + ", obj_num='" + obj_num + '\'' + ", obj_name='" + obj_name + '\'' + ", date='" + date + '\'' + ", overall='" + overall + '\'' + ", evl_srvmanner='" + evl_srvmanner + '\'' + ", evl_content='" + evl_content + '\'' + '}'; } } <file_sep>/src/main/java/com/jishi/enums/ResponseCodeEnum.java package com.jishi.enums; public enum ResponseCodeEnum { SUCCESS(1,"success"),ERROR(-1,"服务器正在维护中"),GET_ERROR(-1,"获取失败"),UPDATE_ERROR(-1,"修改失败") ,CODE_ERROR(-1,"验证码错误"),USER_NOT_FOUND_ERROR(-1,"用户不存在"),CODE_SEND_ERROR(-1,"验证码发送异常") , CODE_SEND_FAIL(-1,"验证码发送失败"),USER_REGISTERED_ERROR(2,"该手机号已经注册"); private Integer code; private String message; private ResponseCodeEnum(Integer code,String message) { setCode(code); setMessage(message); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } <file_sep>/src/main/java/com/jishi/controller/WeiXinPayController.java package com.jishi.controller; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.PrintWriter; import java.nio.charset.Charset; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.SortedMap; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.JDOMException; import org.oms.app.model.MdlTemplate; import org.oms.app.service.WXOrderQuery; import org.oms.app.service.WXPay; import org.oms.app.service.WXPrepay; import org.oms.app.util.XMLUtil; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.jishi.entity.StudentInfo; import com.jishi.entity.Student_PayRecord; import com.jishi.entity.TrainOrder; import com.jishi.entity.TrainOrder_Pay; import com.jishi.service.PayService; import com.jishi.service.TrainService; import com.jishi.until.NumberUtil; import com.jishi.until.ReturnMessage; import com.jishi.until.ReturnMessage_entity; import com.jishi.until.ReturnTool; import com.tenpay.AccessTokenRequestHandler; import com.tenpay.util.ConstantUtil; import net.sf.json.JSONObject; import util.ResponsePage; @Controller @RequestMapping("/weixinpay") public class WeiXinPayController extends ResponsePage { @Resource(name = "TrainService") TrainService trainService; @RequestMapping(value = "/wxpay", method = RequestMethod.GET) public void doWeinXinRequest(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "Token", required = true) String Token, @RequestParam(value = "OrderNum", required = true) String OrderNum) throws Exception { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // 检验学员 ReturnMessage_entity<StudentInfo> R = trainService.checkOwn(Token); if (R.getFlag() == -1) { out.write(ReturnTool.getJsonObjectResult(-3, R.getMessage(), null)); } TrainOrder order = null; try { order = trainService.getTrainOrderDetailsbyOrderNum(OrderNum); } catch (Exception e) { // TODO: handle exception order = null; return; } ReturnMessage Ro = payService.CheckOrder(order); if (Ro.getFlag() == -1) { out.write(ReturnTool.getJsonMessageResult(-1, Ro.getMessage())); return; } String spbill_create_ip = request.getRemoteAddr(); WXPrepay prePay = new WXPrepay(); prePay.setAppid(ConstantUtil.APP_ID); prePay.setBody(Subjectstr(order.getSubject()) + "学习"); prePay.setPartnerKey(ConstantUtil.PARTNER_KEY); prePay.setMch_id(ConstantUtil.PARTNER); String notify_url = ConstantUtil.notify_url; if (ConstantUtil.istest) { notify_url = ConstantUtil.notify_urltest; } prePay.setNotify_url(notify_url); prePay.setOut_trade_no(OrderNum + "a" + NumberUtil.getRandomNum3()); prePay.setSpbill_create_ip("127.0.0.1"); prePay.setTotal_fee(Math.round(order.getMoney() * 100) + ""); prePay.setTrade_type("APP"); // 获取预支付订单号 String prepayid = prePay.submitXmlGetPrepayId(); String string = ""; if (prepayid != null && prepayid.length() > 10) { // 生成微信支付参数,此处拼接为完整的JSON格式,符合支付调起传入格式 SortedMap<Object, Object> jsParam = WXPay.createPackageValue(ConstantUtil.APP_ID, ConstantUtil.PARTNER_KEY, prepayid); System.out.println("jsParam=" + jsParam); // 此处可以添加订单的处理逻辑 string = ReturnTool.getJsonObjectResult(1, "成功", jsParam); } out.write(string); } // 此处为微信支付配置的域名 String base_url = "http://wxpay.omsapp.cn"; /** * 通知调用方法 */ @Resource(name = "PayService") PayService payService; @RequestMapping(value = "/WeiXinCallBack") public void notice(HttpServletRequest request, HttpServletResponse response) throws Exception { PrintWriter out = response.getWriter(); InputStream inStream = request.getInputStream(); ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); String result = new String(outSteam.toByteArray(), "utf-8"); Map<String, String> map = null; map = XMLUtil.doXMLParse(result); // 此处获取accessToken String accessToken = AccessTokenRequestHandler.getAccessToken(); // 此处调用订单查询接口验证是否交易成功 boolean isSucc = reqOrderquery(map, accessToken); // 支付成功,商户处理后同步返回给微信参数 if (!isSucc) { // 支付失败 System.out.println("支付失败"); } else { System.out.println("===============付款成功=============="); // ------------------------------ // 处理业务开始 // ------------------------------ // 此处处理订单状态,结合自己的订单数据完成订单状态的更新 // ------------------------------ // 处理业务完毕 // ------------------------------ // 改变订单表支付状态 String out_trade_no = map.get("out_trade_no").split("a")[0]; TrainOrder order = null; try { order = trainService.getTrainOrderDetailsbyOrderNum(out_trade_no); ReturnMessage Ro = payService.CheckOrder(order); if (Ro.getFlag() == -1) { out.write(ReturnTool.getJsonMessageResult(-1, Ro.getMessage())); out.print("fail");// 请不要修改或删除; return; } if ((Float.parseFloat(map.get("total_fee")) / 100) != order.getMoney()) { return; } // payService.updateorderIspay(out_trade_no); // 支付时间 String gmt_payment = map.get("time_end"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); Date date = simpleDateFormat.parse(gmt_payment); Timestamp timestamp = new Timestamp(date.getTime()); // 新增订单支付记录 TrainOrder_Pay order_Pay = new TrainOrder_Pay(); order_Pay.setOrderNum(out_trade_no); order_Pay.setStuOrCoach(1); // 交易付款时间 order_Pay.setPayDate(timestamp); order_Pay.setPayStyle(2); order_Pay.setMoney(Float.parseFloat(map.get("total_fee")) / 100); order_Pay.setPaySerialNum(map.get("transaction_id")); // 支付账户(买家支付宝账号) /* String device_info = map.get("device_info"); */ order_Pay.setPayAccount(""); // 收入账户(卖家支付宝账号) String mch_id = map.get("mch_id"); order_Pay.setIncomeAccount(mch_id); // payService.inserterr("卖家支付宝账号"+seller_email); // payService.insertorder_pay(order_Pay); // 新增学员支付记录 Student_PayRecord student_PayRecord = new Student_PayRecord(); student_PayRecord.setStuNum(order.getStuNum()); student_PayRecord.setMoney(0 - (Float.parseFloat(map.get("total_fee")) / 100)); student_PayRecord.setAmount(order.getAmount()); student_PayRecord.setCreateDate(timestamp); String Remark = "您支出了" + Float.parseFloat(map.get("total_fee")) / 100 + "元,用于【" + Subjectstr(order.getSubject()) + "】学习"; student_PayRecord.setRemark(Remark); student_PayRecord.setOrderNum(out_trade_no); payService.insertpay(order, out_trade_no, order_Pay, student_PayRecord); String noticeStr = setXML("SUCCESS", ""); out.print(new ByteArrayInputStream(noticeStr.getBytes(Charset.forName("UTF-8")))); } catch (Exception e) { // TODO: handle exception return; } } } public static String setXML(String return_code, String return_msg) { return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>"; } /** * 请求订单查询接口 * * @param map * @param accessToken * @return */ public static boolean reqOrderquery(Map<String, String> map, String accessToken) { WXOrderQuery orderQuery = new WXOrderQuery(); orderQuery.setAppid(map.get("appid")); orderQuery.setMch_id(map.get("mch_id")); orderQuery.setTransaction_id(map.get("transaction_id")); orderQuery.setOut_trade_no(map.get("out_trade_no")); orderQuery.setNonce_str(map.get("nonce_str")); // 此处需要密钥PartnerKey,此处直接写死,自己的业务需要从持久化中获取此密钥,否则会报签名错误 orderQuery.setPartnerKey(ConstantUtil.PARTNER_KEY); Map<String, String> orderMap = orderQuery.reqOrderquery(); // 此处添加支付成功后,支付金额和实际订单金额是否等价,防止钓鱼 if (orderMap.get("return_code") != null && orderMap.get("return_code").equalsIgnoreCase("SUCCESS")) { if (orderMap.get("trade_state") != null && orderMap.get("trade_state").equalsIgnoreCase("SUCCESS")) { String total_fee = map.get("total_fee"); String order_total_fee = map.get("total_fee"); if (Integer.parseInt(order_total_fee) >= Integer.parseInt(total_fee)) { return true; } } } return false; } /** * 支付成功后发送支付成功的模版消息 * * @param accessToken * @param openid * @param orderid * @return */ public boolean sendTemplateMsg(String accessToken, String openid, String orderid) { MdlTemplate tempMsg = new MdlTemplate(); tempMsg.addItem("remark", "欢迎再次购买!", "#4169E1"); tempMsg.addItem("expDate", "2015年12月24日", "#4169E1"); tempMsg.addItem("number", "1份", "#4169E1"); tempMsg.addItem("name", "赞助费", "#4169E1"); tempMsg.addItem("productType", "商品名", "#4169E1"); tempMsg.setTemplate_id("5ODqfQRJl-dpMf8s-S9TNDeQo4DATDJZDhUvr1gOAcU"); tempMsg.setTopcolor("#7CFC00"); tempMsg.setTouser(openid); // 此处构造支付订单详情页面地址,此处demo不做详细处理,实际项目中需要处理 tempMsg.setUrl(base_url + "/order?orderid=" + orderid); JSONObject obj = JSONObject.fromObject(tempMsg); System.out.println("obj=" + obj); // 此处调用发送模版消息的API /* * JSONObject jo = WeixinUtil.sendTemplate(accessToken, tempMsg); * System.out.println("jo===" + jo); if (jo != null && * jo.getInt("errcode") == 0) { return true; } * System.out.println("========发送模版消息失败========="); */ return false; } public String Subjectstr(int Subject) { String Subjectstr = ""; switch (Subject) { case 1: Subjectstr = "科目一"; break; case 21: Subjectstr = "科目二实车"; break; case 22: Subjectstr = "科目二模拟"; break; case 31: Subjectstr = "科目三实车"; break; case 32: Subjectstr = "科目三模拟"; break; case 4: Subjectstr = "科目四"; break; default: break; } return Subjectstr; } }
c1faca293cec4e986b27892e0c54b0ae3c04d899
[ "Java", "INI" ]
113
Java
corbettbain/maven_ynjp_api
fc76468cafeed5bee2c7e2987db3212e9122fb1c
fa9dfc4234a73cbd52925bdb1fef2939eead3f0f
refs/heads/main
<file_sep>package ejercicio01; import java.util.InputMismatchException; import java.util.Scanner; public class APP { public static void main(String[] args) { AdivinaNumero a = new AdivinaNumero(); boolean fi = false; int cnt = 0, num; // Este bucle es el que contara los intentos que hemos necesitado i nos ira // pidiendo numeros. while (fi == false) { num = pedirNumero("Inserte un numero:"); if (num != 0) fi = a.comparar(num); cnt++; System.out.println("\n"); } System.out.println("Has tardado " + cnt + " En adivinar el numero."); } // Este metodo es el encargado de pedir el numero al usuario y de lanzar la // excepcion en caso de que el valor no sea valido. public static int pedirNumero(String text) { Scanner s = new Scanner(System.in); int num = 0; System.out.println(text); try { num = s.nextInt(); } catch (InputMismatchException e) { System.out.println("Valor introducido no válido, has de introducir un numero."); return 0; } return num; } } <file_sep># UD10 Repositorio creado para los ejercicios de la UD10 <file_sep>package ejercicio01; import java.util.Random; public class AdivinaNumero { private int num; // Solo con este constructor nos vale. public AdivinaNumero() { Random r = new Random(); num = r.nextInt((501 - 1) + 1) + 1; } // Este metodo realizara las comprovaciones del numero public boolean comparar(int num) { if (this.num == num) return true; if (this.num < num) { System.out.println("El número a adivinar es menor."); } else if (this.num > num) { System.out.println("El número a adivinar es mayor."); } return false; } // Get del numero public int getNum() { return num; } } <file_sep>package APP; import exepciones.MiExcepcion; public class APP { public static void main(String[] args) { try { System.out.println("Mensaje mostrado por pantalla."); throw new MiExcepcion(111); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println("Programa terminado."); } }
67411c505ba819b5e379fda30ee39f270a93082b
[ "Markdown", "Java" ]
4
Java
dimobo/UD10
4657e9afaecae7f8c85b4861c7a43a9fffaf17c2
8834502115dfbc83998af28f87bf215f30c8a2f6
refs/heads/master
<repo_name>fehimecapar/proje2<file_sep>/HastaneOtomasyonu/HastaneOtomasyonu/src/hastaneotomasyonu/HastaneOtomasyonu.java package hastaneotomasyonu; import java.util.ArrayList; import java.util.Scanner; public class HastaneOtomasyonu { public static void main(String[] args) { Doktorlar d=new Doktorlar(); Hastalar h=new Hastalar(); TıbbiBirimler t=new TıbbiBirimler(); RandevularH randevu1=new RandevularH(); Laboratuvar lab=new Laboratuvar(); System.out.println("q-ÇIKIŞ"); System.out.println("hastanenin tıbbi birimleri"); Scanner s=new Scanner(System.in); t.birimler(); System.out.println("pazar günleri acil birim hariç diğer tıbbi birimlerimiz hizmet vermemektedir"); while(true){ System.out.println("lütfen bir tane tıbbi birim seçiniz:"); String secim=s.nextLine(); if(secim.equals("q")) { System.out.println("sistemden çıkış yapılıyor..."); break; } else if(secim.equals("1")) { d.acil_doktorları(); System.out.println("lütfen acil doktoru secimi yapınız:(1-5 arası)"); String secim2=s.nextLine(); s.nextLine(); if(secim2.equals("1")) { System.out.println("doktorun tatil günü pazartesi"); d.hasta_arttır(); } else if(secim2.equals("2")) { System.out.println("doktorun tatil günü salı "); d.hasta_arttır(); } else if(secim2.equals("3")) { System.out.println("doktorun tatil günü çarşamba"); d.hasta_arttır(); } else if(secim2.equals("4")) { System.out.println("doktorun tatil günü perşembe"); d.hasta_arttır(); } else{ System.out.println("doktorun tatil günü cuma"); d.hasta_arttır(); } } else if(secim.equals("2")) { d.bashekim(); } else if(secim.equals("3")) { d.beslenme_diyet(); System.out.println("lütfen diyetisyen secimi yapınız:(1-2 arası)"); String secim2=s.nextLine(); s.nextLine(); if(secim2.equals("1")) { System.out.println("doktorun tatil günü cumartesi"); d.hasta_arttır(); } else{ System.out.println("doktorun tatil günü cuma"); d.hasta_arttır(); } } else if(secim.equals("4")) { d.cocuk_cerrahi(); System.out.println("hastanemizde sadece 1 tane cocuk allerjisi bölümü doktoru vardır." + "doktorun tatil günü perşembe" + "doktordan randevu almak istiyor musunuz:(e/h)"); String secim2=s.nextLine(); s.nextLine(); if(secim2.equals("e")) { d.hasta_arttır(); } s.nextLine(); } else if(secim.equals("5")) { d.cocuk_allerjisi(); System.out.println("lütfen doktor secimi yapınız(1-2 arası):"); String secim2=s.nextLine(); if(secim2.equals("1")) { System.out.println("doktorun tatil günü salı"); d.hasta_arttır(); } else { System.out.println("doktorun tatil günü cumartesi"); d.hasta_arttır(); } } else if(secim.equals("6")) { d.dahiliye(); System.out.println("hastanemizde sadece 1 tane dahiliye bölümü doktoru vardır." + "doktorun tatil günü perşembe" + "doktordan randevu almak istiyor musunuz:(e/h)"); String secim2=s.nextLine(); s.nextLine(); if(secim2.equals("e")) { d.hasta_arttır(); } s.nextLine(); } else if(secim.equals("7")) { d.dermatoloji(); System.out.println("lütfen doktor secimi yapınız"); String secim2=s.nextLine(); if(secim2.equals("1")) { System.out.println("doktorun tatil günü cumartesi"); d.hasta_arttır(); } else{ System.out.println("doktorun tatil günü cuma"); d.hasta_arttır(); } } else if(secim.equals("8")) { d.estetik(); System.out.println("hastanemizde sadece 1 tane estetik bölümü doktoru vardır." + "doktorun tatil günü perşembe" + "doktordan randevu almak istiyor musunuz:(e/h)"); String secim2=s.nextLine(); s.nextLine(); if(secim2.equals("e")) { d.hasta_arttır(); } s.nextLine(); } else if(secim.equals("9")) { d.genel_cerrahi(); System.out.println("genel cerrahi seçimi yapınız:"); String secim2=s.nextLine(); if(secim2.equals("1")) { System.out.println("doktorun tatil günü perşembe"); d.hasta_arttır(); } else { System.out.println("doktorun tatil günü pazartesi"); d.hasta_arttır(); } } else if(secim.equals("10")) { d.gogus_hastaliklari(); System.out.println("doktor seçimi yapınız:(1-3)"); String secim2=s.nextLine(); s.nextLine(); if(secim2.equals("1")) { System.out.println("doktorun tatil günü cuma"); d.hasta_arttır(); } else if(secim2.equals("2")) { System.out.println("doktorun tatil günü salı"); d.hasta_arttır(); } else{ System.out.println("doktorun tatil günü cumartesi"); d.hasta_arttır(); } } else if(secim.equals("11")) { d.kalp_damar_cerrahisi(); System.out.println("hastanemizde sadece 1 tane damar cerrahisi bölümü doktoru vardır." + "doktorun tatil günü perşembe" + "doktordan randevu almak istiyor musunuz:(e/h)"); String secim2=s.nextLine(); s.nextLine(); if(secim2.equals("e")) { d.hasta_arttır(); } } else if(secim.equals("12")) { d.kbb(); System.out.println("doktor secimi yapınız(1-2 arası)"); String secim2=s.nextLine(); s.nextLine(); if(secim2.equals(1)) { System.out.println("doktorun tatil günü salı:"); d.hasta_arttır(); } else{ System.out.println("doktorun tatil günü çarşamba"); d.hasta_arttır(); } } else if(secim.equals("13")) { d.nefroloji(); System.out.println("hastanemizde sadece 1 tane nefroloji bölümü doktoru vardır." + "doktorun tatil günü salı" + "doktordan randevu almak istiyor musunuz:(e/h)"); String secim2=s.nextLine(); if(secim2.equals("e")) { d.hasta_arttır(); } } else if(secim.equals("14")) { d.noroloji(); System.out.println("hastanemizde sadece 1 tane nöroloji bölümü doktoru vardır." + "doktorun tatil günü salı" + "doktordan randevu almak istiyor musunuz:(e/h)"); String secim2=s.nextLine(); s.nextLine(); if(secim2.equals("e")) { d.hasta_arttır(); } s.nextLine(); } else if(secim.equals("15")) { d.obezite(); System.out.println("doktor secimi yapınız (1-2 arası)"); String secim2=s.nextLine(); if(secim2.equals("1")) { System.out.println("doktorun tatil günü salı"); d.hasta_arttır(); } else{ System.out.println("doktorun tatil günü çarşamba"); d.hasta_arttır(); } } else if(secim.equals("16")) { d.onkoloji(); System.out.println("lütfen doktor secimi yapınız(1-2 arası)"); String secim2=s.nextLine(); s.nextLine(); if(secim2.equals("1")) { System.out.println("doktorun tatil günü çarşamba"); d.hasta_arttır(); } else{ System.out.println("doktorun tatil günü cuma"); d.hasta_arttır(); } } else if(secim.equals("17")) { d.ortopedi(); System.out.println("hastanemizde sadece 1 tane ortopedi bölümü doktoru vardır." + "doktorun tatil günü salı" + "doktordan randevu almak istiyor musunuz:(e/h)"); String secim2=s.nextLine(); s.nextLine(); if(secim2.equals("e")) { d.hasta_arttır(); } } else{ System.out.println("hatalı bir işlem seçimi yaptınız..."); break; } s.nextLine(); } System.out.println(d.getHasta_sayisi());//hastanenin toplam hasta sayısı while(true) { System.out.print("hastanın adı ve soyadı(arada boşluk bırakınız):"); String isim=s.nextLine(); if(isim.equals("q")) { break; } else{ System.out.print("hastanın yaşı:"); int yas=s.nextInt(); s.nextLine(); System.out.println("hangi birimden randevu alacaksınız?"); String hastalık=s.nextLine(); h.hasta_adi_ekle(isim); h.hastalik_ekle(hastalık); h.yas_ekle(yas); randevu1.hasta_adi_ekle(isim); } } h.yazdır(); System.out.println("hastanedeki laboratuvar hizmetleri:"); lab.lab(); System.out.println("laboratuvarların çalışma saatleri 09.00 ile 17.00 arasıdır."); lab.calisma_saati(); } } <file_sep>/HastaneOtomasyonu/HastaneOtomasyonu/src/hastaneotomasyonu/Hastalar.java package hastaneotomasyonu; import java.util.ArrayList; public class Hastalar { private ArrayList<String> isim=new ArrayList<String>(); private ArrayList<Integer> yas=new ArrayList<Integer>(); private ArrayList<String> hastalık=new ArrayList<String>(); public Hastalar(){ } public void hasta_adi_ekle(String ad) { isim.add(ad); } public void yas_ekle(int yası) { yas.add(yası); } public void hastalik_ekle(String hastalik){ hastalık.add(hastalik); } public void yazdır()//hastanın adını yasını ve randevu aldığı tıbbi birimi yazdıran metod { for(int i=0;i<isim.size();i++) { System.out.println(isim.get(i)+" "+yas.get(i)+" "+hastalık.get(i)); } } }
11135b947275e2d1842ae2e52afd6ecba937ef45
[ "Java" ]
2
Java
fehimecapar/proje2
b9d7680cdfa92402a0a47982659738601fb1d0a1
95f0a2543e2da522a40976eca16868ca62439189
refs/heads/master
<file_sep>#!/bin/bash set -e source /build/buildconfig set -x ## Installing postgres $minimal_apt_get_install postgresql-common sed -ri 's/#(create_main_cluster) .*$/\1 = false/' /etc/postgresql-common/createcluster.conf $minimal_apt_get_install postgresql-${POSTGRES_VERSION} postgresql-contrib-${POSTGRES_VERSION} ## Setting up postgres service mkdir /etc/service/postgres cp /build/runit/postgres /etc/service/postgres/run<file_sep>FROM emanueleperuffo/baseimage-debian:latest MAINTAINER <NAME> <<EMAIL>> ENV HOME /root ADD . /build ENV PGDATA /var/lib/postgresql/data ENV POSTGRES_VERSION 9.4 ENV POSTGRES_PASSWORD <PASSWORD> RUN /build/prepare.sh && \ /build/services.sh && \ /build/cleanup.sh VOLUME ["/var/lib/postgresql/data"] EXPOSE 5432 CMD ["/sbin/my_init"] <file_sep>#!/bin/sh set -e PATH=/usr/lib/postgresql/$POSTGRES_VERSION/bin:$PATH chown -R postgres $PGDATA BOOTSTRAPPED="$PGDATA/.bootstrapped" if [ ! -e $BOOTSTRAPPED ]; then gosu postgres initdb gosu postgres postgres --single -jE <<-EOSQL ALTER USER postgres WITH SUPERUSER PASSWORD '$<PASSWORD>'; EOSQL echo { echo; echo "host all all 0.0.0.0/0 md5"; } >> "$PGDATA/pg_hba.conf" cat <<-EOCONF >> "$PGDATA/postgresql.conf" log_destination = 'stderr, syslog' syslog_facility = 'LOCAL0' syslog_ident = 'postgres' logging_collector = on log_directory = 'pg_log' log_filename = 'postgresql-%Y-%m-%d.log' log_file_mode = 0600 log_rotation_age = 1d log_rotation_size = 10MB EOCONF gosu postgres mkdir -m 700 "$PGDATA/pg_log" touch $BOOTSTRAPPED fi exec gosu postgres postgres -e -i
28d3d4f8595cff2a7171f4121f2301b85c6951e4
[ "Dockerfile", "Shell" ]
3
Shell
emanueleperuffo/docker-postgres
537b93f420c55682586d51c21500549b81f2ac58
a2a18f637a89a5af037dc32d970ca980c32903b9
refs/heads/master
<file_sep>package models import ( _ "database/sql" "log" "github.com/golang-migrate/migrate" _ "github.com/golang-migrate/migrate/database/postgres" _ "github.com/golang-migrate/migrate/source/file" "github.com/pkg/errors" _ "github.com/lib/pq" "github.com/jmoiron/sqlx" ) // Client ... type Client struct { DB *sqlx.DB } // PerformPendingMigrations ... func PerformPendingMigrations(path string, connectionString string) error { log.Println(connectionString) m, err := migrate.New(path, connectionString) if err != nil { return errors.Wrap(err, "Connecting to migrations failed") } err = m.Up() if err != nil && err.Error() != "no change" { return errors.Wrap(err, "Creating migrations failed") } m.Close() return nil } // ConnectToDatabase ... func ConnectToDatabase(connectionString string) (*Client, error) { log.Print("Attempting to connect to " + connectionString) db, err := sqlx.Connect("postgres", connectionString) if err != nil { return nil, err } return &Client{DB: db}, nil } // Close ... func (c *Client) Close() { c.DB.Close() } <file_sep>CREATE TABLE rooms ( id bigserial primary key, name varchar(64) NOT NULL UNIQUE ); <file_sep>package models import ( "time" ptypes "github.com/golang/protobuf/ptypes" types "github.com/melonmanchan/dippa-proto/build/go" "github.com/pkg/errors" ) type GoogleResult struct { ID int64 `json:"id" db:"id"` CreatedAt time.Time `json:"created_at" db:"created_at"` DetectionConfidence float32 `json:"detection_confidence" db:"detection_confidence"` Blurred float32 `json:"blurred" db:"blurred"` Joy float32 `json:"joy" db:"joy"` Anger float32 `json:"anger" db:"anger"` Sorrow float32 `json:"sorrow" db:"sorrow"` Surprise float32 `json:"surprise" db:"surprise"` Image []byte `json:"image" db:"image"` UserID int64 `json:"user_id" db:"user_id"` RoomID int64 `json:"room_id" db:"room_id"` } func GoogleProtoToGoStructs(res types.GoogleFacialRecognition) (GoogleResult, User, Room) { timestampAsTime, _ := ptypes.Timestamp(res.CreatedAt) googleResult := GoogleResult{ ID: 0, CreatedAt: timestampAsTime, DetectionConfidence: res.Emotion.DetectionConfidence, Blurred: res.Emotion.Blurred, Joy: res.Emotion.Joy, Sorrow: res.Emotion.Sorrow, Anger: res.Emotion.Anger, Image: res.Image, UserID: 0, } user := User{ Name: res.User.Username, } room := Room{ Name: res.User.Room, } return googleResult, user, room } type Keyword struct { ID int64 `json:"id" db:"id"` Contents string `json:"contents" db:"contents"` Sentiment float32 `json:"sentiment" db:"sentiment"` Relevance float32 `json:"relevance" db:"relevance"` Sadness float32 `json:"sadness" db:"sadness"` Joy float32 `json:"joy" db:"joy"` Fear float32 `json:"fear" db:"fear"` Disgust float32 `json:"disgust" db:"disgust"` Anger float32 `json:"anger" db:"anger"` } type WatsonResult struct { ID int64 `json:"id" db:"id"` CreatedAt time.Time `json:"created_at" db:"created_at"` Contents string `json:"contents" db:"contents"` UserID int64 `json:"user_id" db:"user_id"` RoomID int64 `json:"room_id" db:"room_id"` Keywords []Keyword `json:"keywords" db:"-"` } func WatsonProtoToGoStructs(res types.WatsonNLP) (WatsonResult, User, Room) { timestampAsTime, _ := ptypes.Timestamp(res.CreatedAt) var keywords []Keyword protoKeywords := res.GetKeywords() for _, k := range protoKeywords { kw := Keyword{ Contents: k.Contents, Sentiment: k.Sentiment, Relevance: k.Relevance, } if k.Emotion != nil { kw.Sadness = k.Emotion.Sadness kw.Joy = k.Emotion.Joy kw.Fear = k.Emotion.Fear kw.Disgust = k.Emotion.Disgust kw.Anger = k.Emotion.Anger } keywords = append(keywords, kw) } watsonResult := WatsonResult{ ID: 0, CreatedAt: timestampAsTime, Contents: res.Contents, UserID: 0, Keywords: keywords, } user := User{ Name: res.User.Username, } room := Room{ Name: res.User.Room, } return watsonResult, user, room } func (c Client) CreateGoogleResults(result *GoogleResult) error { _, err := c.DB.NamedExec(` INSERT INTO google_results (detection_confidence, blurred, joy, sorrow, surprise, image, anger, user_id, room_id) VALUES (:detection_confidence, :blurred, :joy, :sorrow, :surprise, :image, :anger, :user_id, :room_id) `, result) if err != nil { return errors.Wrap(err, "Could not insert a new google analytics result") } return nil } func (c Client) CreateWatsonResult(result *WatsonResult) error { var latestId int tx, err := c.DB.Begin() if err != nil { return errors.Wrap(err, "Could not instantiate transaction for inserting new watson result") } err = tx.QueryRow(` INSERT INTO watson_results (contents, user_id, room_id) VALUES ($1, $2, $3) RETURNING id; `, result.Contents, result.UserID, result.RoomID).Scan(&latestId) if err != nil { return errors.Wrap(err, "Could not insert a new watson analytics result") } if len(result.Keywords) == 0 { return tx.Commit() } stmt, err := tx.Prepare(`INSERT INTO keywords (contents, sentiment, relevance, sadness, joy, fear, disgust, anger, watson_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) `) if err != nil { return errors.Wrap(err, "Could not instantiate prepared statement for bulk insert") } defer stmt.Close() for _, k := range result.Keywords { _, err = stmt.Exec(k.Contents, k.Sentiment, k.Relevance, k.Sadness, k.Joy, k.Fear, k.Disgust, k.Anger, latestId) if err != nil { tx.Rollback() return errors.Wrap(err, "Could not insert new keyword") } } return tx.Commit() } <file_sep>ALTER TABLE ONLY google_results ALTER COLUMN created_at SET DEFAULT now(); ALTER TABLE ONLY watson_results ALTER COLUMN created_at SET DEFAULT now(); <file_sep>DROP TABLE watson_results; DROP TABLE keywords; <file_sep>ALTER TABLE goole_results DROP COLUMN room_id; ALTER TABLE watson_results DROP COLUMN room_id; <file_sep>DROP TABLE google_results; <file_sep>CREATE TABLE google_results ( id bigserial primary key, created_at TIMESTAMPTZ, detection_confidence DECIMAL(4) NOT NULL, blurred DECIMAL(4) NOT NULL, joy DECIMAL(4) NOT NULL, sorrow DECIMAL(4) NOT NULL, surprise DECIMAL(4) NOT NULL, image bytea NOT NULL, user_id integer REFERENCES users(id) NOT NULL ); <file_sep>package models import "github.com/pkg/errors" // User ... type User struct { ID int64 `json:"id" db:"id"` Name string `json:"name" db:"name"` } func (c Client) CreateUserByName(user *User) (int64, error) { var lastId int64 err := c.DB.QueryRow(` INSERT INTO users (name) VALUES ($1) ON CONFLICT ON CONSTRAINT constraint_name DO UPDATE SET name = $1 RETURNING id; `, user.Name).Scan(&lastId) if err != nil { return -1, errors.Wrap(err, "Could not insert a new user") } return lastId, nil } <file_sep>package main import ( "log" "sync" "github.com/golang/protobuf/proto" types "github.com/melonmanchan/dippa-proto/build/go" "github.com/melonmanchan/dippa-writer/src/config" "github.com/melonmanchan/dippa-writer/src/models" "github.com/melonmanchan/dippa-writer/src/rabbit" "github.com/streadway/amqp" ) func consumeImagesData(db *models.Client, chann <-chan amqp.Delivery, wg *sync.WaitGroup) { for d := range chann { googleFacialRecognitionRes := &types.GoogleFacialRecognition{} if err := proto.Unmarshal(d.Body, googleFacialRecognitionRes); err != nil { log.Print("Failed to parse input for google: ", err) break } if googleFacialRecognitionRes.Emotion == nil { log.Print("Emotion is nil, not proceeding") break } imageRes, user, room := models.GoogleProtoToGoStructs(*googleFacialRecognitionRes) userId, err := db.CreateUserByName(&user) if err != nil { log.Println(err) break } roomId, err := db.CreateRoomByName(&room) if err != nil { log.Println(err) break } imageRes.UserID = userId imageRes.RoomID = roomId err = db.CreateGoogleResults(&imageRes) if err != nil { log.Println(err) } } wg.Done() } func consumeTextData(db *models.Client, chann <-chan amqp.Delivery, wg *sync.WaitGroup) { for d := range chann { watsonTextRes := &types.WatsonNLP{} if err := proto.Unmarshal(d.Body, watsonTextRes); err != nil { log.Print("Failed to parse input for watson: ", err) break } log.Printf("%v \n", watsonTextRes) textRes, user, room := models.WatsonProtoToGoStructs(*watsonTextRes) userId, err := db.CreateUserByName(&user) if err != nil { log.Println(err) break } roomId, err := db.CreateRoomByName(&room) if err != nil { log.Println(err) break } textRes.UserID = userId textRes.RoomID = roomId err = db.CreateWatsonResult(&textRes) if err != nil { log.Println(err) } } wg.Done() } func main() { var wg sync.WaitGroup wg.Add(2) config := config.ParseConfig() err := models.PerformPendingMigrations(config.MigrationsPath, config.DatabaseURL) c, err := models.ConnectToDatabase(config.DatabaseURL) if err != nil { log.Fatalf("%s", err) } chann, err := rabbit.TryConnectToQueue(config.RabbitMQConn) if err != nil { log.Fatalf("%s", err) } defer chann.Close() images, err := rabbit.GetChannelToConsume(chann, "google_results") if err != nil { log.Fatalf("%s", err) } text, err := rabbit.GetChannelToConsume(chann, "ibm_text") if err != nil { log.Fatalf("%s", err) } log.Println("startup succesful") log.Println("has the cache updated") go consumeImagesData(c, images, &wg) go consumeTextData(c, text, &wg) wg.Wait() log.Println("All goroutines exitted") } <file_sep>package config import "os" // Config ... type Config struct { DatabaseURL string MigrationsPath string RabbitMQConn string } // postgres://mattes:secret@localhost:5432/database var defaultConf = Config{ DatabaseURL: "postgres://mattij@localhost:5432/dippa?sslmode=disable", MigrationsPath: "file://migrations", RabbitMQConn: "amqp://guest:guest@localhost:5672/", } func ParseConfig() Config { cfg := defaultConf path := os.Getenv("MIGRATIONS_PATH") db_path := os.Getenv("DATABASE_URL") rabbitmqConn := os.Getenv("RABBITMQ_ADDRESS") if db_path != "" { cfg.DatabaseURL = db_path } if path != "" { cfg.MigrationsPath = path } if rabbitmqConn != "" { cfg.RabbitMQConn = rabbitmqConn } return cfg } <file_sep>ALTER TABLE google_results DROP COLUMN anger; <file_sep>ALTER TABLE users DROP CONSTRAINT constraint_name; <file_sep>CREATE TABLE watson_results ( id bigserial primary key, created_at TIMESTAMPTZ, contents text, user_id integer REFERENCES users(id) NOT NULL ); CREATE TABLE keywords ( id bigserial primary key, contents text, sentiment float8 NOT NULL, relevance float8 NOT NULL, sadness float8 NOT NULL, joy float8 NOT NULL, fear float8 NOT NULL, disgust float8 NOT NULL, anger float8 NOT NULL, watson_id integer REFERENCES watson_results(id) NOT NULL ); <file_sep>ALTER TABLE google_results ADD COLUMN room_id integer REFERENCES rooms(id) NOT NULL; ALTER TABLE watson_results ADD COLUMN room_id integer REFERENCES rooms(id) NOT NULL; <file_sep>ALTER TABLE google_results ADD anger DECIMAL(4) NOT NULL; <file_sep>package models import "github.com/pkg/errors" // User ... type Room struct { ID int64 `json:"id" db:"id"` Name string `json:"name" db:"name"` } func (c Client) CreateRoomByName(room *Room) (int64, error) { var lastId int64 err := c.DB.QueryRow(` INSERT INTO rooms (name) VALUES ($1) ON CONFLICT ON CONSTRAINT rooms_name_key DO UPDATE SET name = $1 RETURNING id; `, room.Name).Scan(&lastId) if err != nil { return -1, errors.Wrap(err, "Could not insert a new room") } return lastId, nil } <file_sep>ALTER TABLE ONLY google_results ALTER COLUMN created_at DROP DEFAULT; ALTER TABLE ONLY watson_results ALTER COLUMN created_at DROP DEFAULT; <file_sep>package rabbit import ( "log" "time" "github.com/pkg/errors" "github.com/streadway/amqp" ) func TryConnectToQueue(rabbitAddress string) (*amqp.Connection, error) { var conn *amqp.Connection var connErr error for { newConn, err := amqp.Dial(rabbitAddress) if err == nil { conn = newConn break } connErr = err log.Printf("Connection to rabbitmq failed :%s\n", err) time.Sleep(3 * time.Second) } return conn, connErr } func GetChannelToConsume(conn *amqp.Connection, exchangeName string) (<-chan amqp.Delivery, error) { ch, err := conn.Channel() if err != nil { return nil, errors.Wrap(err, "failed to connect to rabbitmq channel") } err = ch.ExchangeDeclare( exchangeName, // name "fanout", // type true, // durable false, // auto-deleted false, // internal false, // no-wait nil, // arguments ) if err != nil { return nil, errors.Wrap(err, "Failed to declare an exchange") } readQueue, err := ch.QueueDeclare( "", // name true, // durable false, // delete when usused false, // exclusive false, // no-wait nil, // arguments ) if err != nil { return nil, errors.Wrap(err, "Failed to declare a queue") } err = ch.QueueBind( readQueue.Name, // queue name "", // routing key exchangeName, // exchange false, nil) if err != nil { return nil, errors.Wrap(err, "Failed to bind a queue") } msgs, err := ch.Consume( readQueue.Name, // queue "", // consumer true, // auto-ack false, // exclusive false, // no-local false, // no-wait nil, // args ) if err != nil { return nil, errors.Wrap(err, "Failed to create a consumer") } return msgs, nil }
9e088232a29b60e6d66eb5f7b7c03d5f5f352e66
[ "SQL", "Go" ]
19
Go
melonmanchan/dippa-writer
88ef2cdad360b0154c4ff04c102edd5c89746cfc
14a9f4cc54b464e936d3b64df5d5583528cd30b6
refs/heads/master
<repo_name>webgilde/edd-advanced-discounts<file_sep>/README.md # edd-advanced-discounts Added more filters for discounts in Easy Digital Downloads Included features: * exclude a discount for lifetime products, needs Software Licensing add-on * exclude specific price options (per ID), needs Software Licensing add-on Notes: Since EDD discounts are not checked when a specific product is added to the cart you should use the option to only apply discounts with product based checks to specific products. Otherwise, a user could add the discount to your cart with a valid product, then add a product to which the conditions fit, but the discount is still used for it. He could even remove the valid product and still get the discount. <file_sep>/edd-advanced-discounts.php <?php /** * Plugin Name: EDD Advanced Discounts * Plugin URI: https://webgilde.com * Text Domain: edd-advanced-discounts * Domain Path: languages * Description: Create advanced discount code conditions * Author: <NAME> * Version: 1.0 * Author URI: https://webgilde.com */ /** * add our custom options to discount page */ add_action( 'edd_add_discount_form_before_start', 'edd_advanced_discounts_exclude_lifetime_field' ); add_action( 'edd_edit_discount_form_before_start', 'edd_advanced_discounts_exclude_lifetime_field', 10, 2 ); function edd_advanced_discounts_exclude_lifetime_field( $discount_id = false, $discount = false ){ // checkbox for option to exclude lifetime licenses from discounts $exclude_lifetime = ( $discount instanceof EDD_Discount ) ? $discount->get_meta( 'exclude_lifetime', true ) : false; ?><tr> <th scope="row" valign="top"> <label for="edd-exclude-lifetime"><?php _e( 'Exclude Lifetime', 'edd-advanced-discounts' ); ?></label> </th> <td> <input type="checkbox" id="edd-exclude-lifetime" name="exclude_lifetime" value="1"<?php checked( true, $exclude_lifetime ); ?>/> <span class="description"><?php _e( 'Exclude lifetime pricing options from this discount.', 'edd-advanced-discounts' ); ?></span> </td> </tr><?php // input field for IDs of price options that should accept the discount $price_options_meta = ( $discount instanceof EDD_Discount ) ? $discount->get_meta( 'price_options', true) : false; $price_options = ( $price_options_meta ) ? implode( ',', $price_options_meta ) : ''; ?><tr> <th scope="row" valign="top"> <label for="edd-price-options"><?php _e( 'Price Options', 'edd-advanced-discounts' ); ?></label> </th> <td> <input type="input" id="edd-price-options" name="price_options" value="<?php echo $price_options; ?>"/> <span class="description"><?php _e( 'Enter comma separated list of price option IDs that can accept this discount.', 'edd-advanced-discounts' ); ?></span> </td> </tr><?php } /** * save our custom options when discount is saved or updated */ add_filter( 'edd_insert_discount', 'edd_advanced_discounts_add_meta' ); add_filter( 'edd_update_discount', 'edd_advanced_discounts_add_meta' ); function edd_advanced_discounts_add_meta( $meta ){ if( isset( $_POST['exclude_lifetime'] ) ){ $meta['exclude_lifetime'] = 1; } else { $meta['exclude_lifetime'] = 0; } if( isset( $_POST['price_options'] ) ){ $meta['price_options'] = trim( $_POST['price_options'] ) ? explode( ',', $_POST['price_options'] ) : ''; } return $meta; } /** * validate discount conditions when discount is used */ add_filter( 'edd_is_discount_valid', 'edd_advanced_discounts_is_discount_valid', 10, 4 ); function edd_advanced_discounts_is_discount_valid( $return, $discount_id, $discount_code, $user ){ // don’t bother to validate if is false already if( ! $return ){ return $return; } $discount = edd_get_discount( $discount_id ); $cart_content = edd_get_cart_contents(); if( $discount instanceof EDD_Discount ){ // check exclude lifetime if( $exclude_lifetime = $discount->get_meta( 'exclude_lifetime', true ) ){ // iterate through cart items foreach( $cart_content as $_item ){ $download = new EDD_SL_Download( $_item['id'] ); $is_lifetime = isset( $_item['options']['price_id'] ) ? $download->is_price_lifetime( $_item['options']['price_id'] ) : false; } if( $is_lifetime && $exclude_lifetime ){ edd_set_error( 'edd-discount-error', _x( 'This discount can only be used for non-lifetime products.', 'error shown when attempting to use a discount that is meant for non-lifetime products on a lifetime price option', 'edd-advanced-discounts' ) ); return false; } } // check price options if( $price_options = $discount->get_meta( 'price_options', true ) ){ // iterate through cart items foreach( $cart_content as $_item ){ $download = new EDD_SL_Download( $_item['id'] ); if( is_array( $price_options ) && $_item['options']['price_id'] && ! in_array( $_item['options']['price_id'], $price_options ) ){ edd_set_error( 'edd-discount-error', _x( 'This discount can only be used for specific price options.', 'error shown when attempting to use a discount that is meant specific price options', 'edd-advanced-discounts' ) ); return false; } } } } // check price options return $return; }
4a329feb742ed10934ecf1b39c98b27d853edfae
[ "Markdown", "PHP" ]
2
Markdown
webgilde/edd-advanced-discounts
101a588e563858ce5578dbc5fc7246d78a1edea9
47f3a6cdcb0227cfd8c5d9516f37bbd93e3c2f46
refs/heads/master
<file_sep>from collections import Counter import csv f = open('assets/absentee11xx08xx2016.csv') reader = csv.reader(f) county_prec_desc = [] #http://stackoverflow.com/questions/16108526/count-how-many-lines-are-in-a-csv-python num_of_votes = sum(1 for row in reader) print(num_of_votes) #combine county_desc and cong_dist_desc for row in reader: county_prec_desc.append(row[22] + ' ' + row[23]) print(row) # print(county_prec_desc) # print(Counter(county_prec_desc).keys()) # print(Counter(county_prec_desc).values()) # print(county_prec_desc) #http://stackoverflow.com/questions/3428532/how-to-import-a-csv-file-using-python-with-headers-intact-where-first-column-is # headers = reader.next() # print(headers) # column = {} # for h,idx in headers: # column[h].append(idx) # print(column) f.close() <file_sep># absentee-nc Using Python to count absentee votes in N.C.
62727bf5d76e72720ca61a7ec3c5af01f6053a18
[ "Markdown", "Python" ]
2
Python
lindsaycarbonell/absentee-nc
d1226b7d7252746d56e25247300053a666437c0d
301341cd784da02409870847df45fcc49a25c969
refs/heads/master
<repo_name>ssz/Database-CS585<file_sep>/HW2/HW2/ReadMe.txt /*-------------------------------------Files:--------------------------------------------*/ Two createdb.sql (One is automatically created by exporting tables, and the other one is programed.) dropdb.sql, HW2.java, mysql-connector-java-5.1.34-bin.jar, ReadMe.txt /*--------------------------------------Run:---------------------------------------------*/ Compile and run as the commmand of HW2. /*-------------------------------------Assumption:---------------------------------------*/ 1. window case: my query doesn't cover the point on the boundry, using st_contains() function. If you want to cover the boundry, use function contains(). contains(g1, g2) uses MBR only (not exact!) st_contains(g1, g2) uses exact shapes 2. Nearest-neighbour case: Only find the same type of objects. For example, if the given object is building b3, you should only find serveral nearest buildings. 3. Nearest-neighbour case: Finding the nearest buildings of a specific building(for example: b3) doesn't consider itself(b3). 4. Fixed 4 case: I checked the result of Oracle, it's a little different. Using Oracle, the output includes the p66, because sdo_nn in Oracle considers the distance beginning from the center. But in MySQL, it considers the distance to the nearest edge. /*-------------------------------------Reference:-----------------------------------------*/ 1. Using the new spatial functions in MySQL 5.6 for geo-enabled applications http://www.percona.com/blog/2013/10/21/using-the-new-spatial-functions-in-mysql-5-6-for-geo-enabled-applications/ 2. How to connect JDBC with MYSQL http://blog.csdn.net/cxwen78/article/details/6863696/<file_sep>/HW2/HW2/query.sql 1. /* AsText function converts the internal representation of a geometry to a string format. */ SET @b = 'POLYGON((0 0, 100000 0, 100000 100000, 0 100000, 0 0))'; /* can use @b in the polygon area. */ SELECT b_id, AsText(b_location) FROM building WHERE contains (GeomFromText('Polygon((0 0, 100000 0, 100000 100000, 0 100000, 0 0))'), b_location); SELECT s_id, AsText(s_location) FROM student WHERE contains (GeomFromText('Polygon((0 0, 100000 0, 100000 100000, 0 100000, 0 0))'), s_location); SELECT t_id, AsText(t_location) FROM tramstop WHERE contains (GeomFromText('Polygon((0 0, 100000 0, 100000 100000, 0 100000, 0 0))'), t_location); 2. SET @point = 'POINT(10 10)'; SET @radius = 200000; SELECT b_id, b_name, AsText(b_location) FROM building WHERE ST_Distance(b_location, GeomFromText(@point)) < @radius; SET @point = 'POINT(10 10)'; SET @radius = 2000; SELECT t_id,AsText(t_location) FROM tramstop WHERE ST_Distance(t_location, GeomFromText(@point)) < @radius; SET @point = 'POINT(10 10)'; SET @radius = 2000; SELECT b_id, b_name FROM building WHERE ST_Distance(b_location, GeomFromText(@point)) < @radius UNION SELECT t_id,AsText(t_location) FROM tramstop WHERE ST_Distance(t_location, GeomFromText(@point)) < @radius; SET @point = (SELECT AsText(s_location) FROM student WHERE s_id = 'p1'); SET @radius = 100; SELECT b_id, FROM building WHERE ST_Distance(b_location, GeomFromText(@point)) < @radius UNION SELECT t_id FROM tramstop WHERE ST_Distance(t_location, GeomFromText(@point)) < @radius; 3. /* SET @s = 'POINT(10,10)'; SET @b = 'POLYGON((0 0, 100000 0, 100000 100000, 0 100000, 0 0))'; SET @T = 'POINT()'; SELECT b_id, b_name, AsText(b_location) FROM building ORDER BY ST_DISTANCE(@spoint, b_location) LIMIT 5 UNION SELECT b_id, b_name, AsText(b_location) FROM building ORDER BY ST_DISTANCE(@spoint, b_location) LIMIT 5; */ SET @s = 'POINT(10,10)'; SET @b = 'POLYGON((0 0, 100 0, 100 100, 0 100, 0 0))'; SET @T = 'POINT()'; SELECT b_id, b_name, AsText(b_location) FROM building ORDER BY ST_DISTANCE(@s, b_location) LIMIT 5; SELECT * FROM ( SELECT b_id, ST_DISTANCE(s_location, b_location) AS dis FROM building, student UNION SELECT t_id, ST_DISTANCE(s_location, t_location) AS dis FROM tramstop, student ) a ORDER BY dis ASC LIMIT 5; SELECT * FROM ( SELECT s_id, ST_DISTANCE(s_location, b_location) AS dis FROM building, student WHERE b_id = 'b3' UNION SELECT t_id, ST_DISTANCE(t_location, b_location) AS dis FROM building, tramstop WHERE b_id = 'b3' ) a ORDER BY dis ASC LIMIT 5; 4.1 SELECT b_id FROM building WHERE st_contains ( (SELECT st_intersects (GeomFromText("SELECT buffer(t_location, t_radius) FROM tramstop WHERE t_id = 't2ohe'"), GeomFromText("SELECT buffer(t_location, t_radius) FROM tramstop WHERE t_id = 't6ssl'"))), b_location ) UNION SELECT s_id FROM student WHERE st_contains ( (SELECT st_intersects (GeomFromText("SELECT buffer(t_location, t_radius) FROM tramstop WHERE t_id = 't2ohe'"), GeomFromText("SELECT buffer(t_location, t_radius) FROM tramstop WHERE t_id = 't6ssl'"))), s_location ) 4.2 SELECT t_id FROM tramstop ORDER BY ST_DISTANCE((SELECT t_location FROM tramstop WHERE t_id = 't1psa' ), (SELECT s_location FROM student WHERE s_id = 'p3')) LIMIT 5; 4.3 SELECT s_id, count(*) AS num FROM tramstop, student WHERE ST_DISTANCE(t_location, s_location) < 250 GROUP BY t_id ORDER BY count(*) DESC LIMIT 1; 4.4 SELECT s_id, s_location, b_id, b_location, st_distance(s_location, b_location) FROM student, building GROUP BY b_id ORDER BY st_distance(s_location, b_location) ASC SELECT count(s_id), s_id FROM ( ( SELECT s_id, s_location, b_id, b_location, st_distance(s_location, b_location) FROM student, building WHERE B_ID = 'b3' ORDER BY st_distance(s_location, b_location) ASC limit 1 ) union ( SELECT s_id, s_location, b_id, b_location, st_distance(s_location, b_location) FROM student, building WHERE B_ID = 'b1' ORDER BY st_distance(s_location, b_location) ASC limit 1 ) union ( SELECT s_id, s_location, b_id, b_location, st_distance(s_location, b_location) FROM student, building WHERE B_ID = 'b2' ORDER BY st_distance(s_location, b_location) ASC limit 1 ) ) a GROUP BY s_id ORDER BY count(s_id) DESC LIMIT 5 ; 4.5 (SELECT min(astext(POINTN(EXTERIORRING(envelope(b_location)),1))) AS p FROM building WHERE b_name like 'SS%' ORDER BY b_id) union (SELECT max(astext(POINTN(EXTERIORRING(envelope(b_location)),3))) AS p FROM building WHERE b_name like 'SS%' ORDER BY b_id) <file_sep>/README.md # Database CS585 This file contains two homework about database(cs585). HW2 is a spatial database project. HW3 is design and implementation of XML Schemas, XML Stylesheets and the use of the XQuery to query XML data, including a web UI. <file_sep>/HW2/HW2/createdb copy.sql CREATE DATABASE IF NOT EXISTS `585_HW2` /*!40100 DEFAULT CHARACTER SET latin1 */; USE `585_HW2`; -- MySQL dump 10.13 Distrib 5.6.19, for osx10.7 (i386) -- -- Host: 127.0.0.1 Database: 585_HW2 -- ------------------------------------------------------ -- Server version 5.6.21 -- -- Table structure for table `buildings` -- DROP TABLE IF EXISTS `building`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `building` ( `b_id` char(10) NOT NULL, `b_name` char(255) NOT NULL, `b_location` polygon NOT NULL, PRIMARY KEY (`b_id`) ) -- -- Dumping data for table `building` -- INSERT INTO building VALUES('b0','PSA',PolygonFromText('polygon(( 79 68, 184 125, 179 133, 189 138, 139 229, 131 225, 127 233, 21 175, 26 168, 18 163, 67 73, 74 76, 79 68))')); INSERT INTO building VALUES('b1','OHE',PolygonFromText('polygon(( 226 150, 254 164, 240 191, 212 176, 226 150))')); INSERT INTO building VALUES('b2','BHE',PolygonFromText('polygon(( 337 209, 389 236, 385 242, 390 244, 385 253, 381 251, 378 255, 327 228, 330 223, 324 219, 328 212, 334 214, 337 209))')); INSERT INTO building VALUES('b3','VHE',PolygonFromText('polygon(( 405 239, 440 257, 426 283, 421 280, 394 329, 401 332, 386 357, 351 339, 365 313, 369 315, 396 266, 391 263, 405 239))')); INSERT INTO building VALUES('b4','HED & PCE',PolygonFromText('polygon(( 267 265, 291 278, 284 290, 290 294, 296 283, 354 314, 348 327, 340 322, 335 330, 290 305, 291 301, 281 295, 277 301, 258 289, 267 265))')); INSERT INTO building VALUES('b5','small building 1',PolygonFromText('polygon(( 207 193, 219 199, 191 251, 179 245, 207 193))')); INSERT INTO building VALUES('b6','small building 2',PolygonFromText('polygon(( 264 174, 273 179, 247 228, 237 222, 264 174))')); INSERT INTO building VALUES('b7','small building 3',PolygonFromText('polygon(( 216 228, 241 241, 225 271, 199 257, 216 228))')); INSERT INTO building VALUES('b8','NBA',PolygonFromText('polygon(( 182 284, 207 298, 202 306, 177 293, 182 284))')); INSERT INTO building VALUES('b9','ABT',PolygonFromText('polygon(( 157 282, 169 288, 158 308, 147 301, 157 282))')); INSERT INTO building VALUES('b10','SBA',PolygonFromText('polygon(( 172 304, 197 317, 191 327, 166 313, 172 304))')); INSERT INTO building VALUES('b11','GER',PolygonFromText('polygon(( 65 226, 122 258, 77 341, 20 310, 65 226))')); INSERT INTO building VALUES('b12','EEB',PolygonFromText('polygon(( 127 346, 184 375, 171 400, 115 370, 127 346))')); INSERT INTO building VALUES('b13','SAL',PolygonFromText('polygon(( 216 370, 266 397, 255 417, 261 420, 247 445, 187 412, 201 388, 206 391, 216 370))')); INSERT INTO building VALUES('b14','SSC',PolygonFromText('polygon(( 232 324, 241 329, 238 333, 245 338, 247 334, 293 358, 277 386, 233 360, 234 356, 228 352, 224 359, 217 354, 232 324))')); INSERT INTO building VALUES('b15','SSL',PolygonFromText('polygon(( 309 371, 325 379, 333 365, 349 374, 342 388, 357 396, 346 416, 331 409, 324 422, 307 413, 313 399, 298 391, 309 371))')); INSERT INTO building VALUES('b16','PHE',PolygonFromText('polygon(( 300 432, 338 452, 322 482, 296 469, 302 459, 289 452, 300 432))')); INSERT INTO building VALUES('b17','LHI & SLH',PolygonFromText('polygon(( 446 339, 478 357, 460 390, 491 408, 488 417, 424 382, 446 339))')); INSERT INTO building VALUES('b18','HLAG',PolygonFromText('polygon(( 420 426, 464 449, 435 503, 392 480, 420 426))')); INSERT INTO building VALUES('b19','RRB & LIS & OCW & CEM & SCI',PolygonFromText('polygon(( 474 285, 529 315, 533 310, 695 397, 644 494, 601 471, 644 390, 627 380, 623 387, 633 393, 609 434, 586 422, 610 371, 524 325, 508 353, 454 323, 474 285))')); INSERT INTO building VALUES('b20','SHS',PolygonFromText('polygon(( 565 357, 596 374, 582 399, 551 383, 565 357))')); INSERT INTO building VALUES('b21','ACP',PolygonFromText('polygon(( 564 425, 585 436, 573 458, 552 447, 564 425))')); INSERT INTO building VALUES('b22','HAR',PolygonFromText('polygon(( 498 459, 574 503, 537 569, 465 530, 458 541, 439 530, 445 517, 462 525, 498 459))')); INSERT INTO building VALUES('b23','MPH',PolygonFromText('polygon(( 586 500, 629 523, 596 578, 569 563, 559 579, 549 574, 586 500))')); INSERT INTO building VALUES('b24','ACC',PolygonFromText('polygon(( 748 427, 791 450, 768 494, 725 471, 748 427))')); INSERT INTO building VALUES('b25','BRI',PolygonFromText('polygon(( 722 483, 735 490, 729 505, 757 518, 746 538, 719 525, 710 535, 698 528, 722 483))')); INSERT INTO building VALUES('b26','SGM',PolygonFromText('polygon(( 297 13, 357 45, 334 87, 312 75, 291 114, 310 125, 295 151, 239 121, 253 95, 275 106, 280 98, 259 86, 270 62, 293 73, 297 66, 275 54, 297 13))')); INSERT INTO building VALUES('b27','GFS',PolygonFromText('polygon(( 380 66, 493 126, 475 157, 363 97, 380 66))')); INSERT INTO building VALUES('b28','BKS',PolygonFromText('polygon(( 607 199, 641 217, 617 257, 584 239, 607 199))')); INSERT INTO building VALUES('b29','HSH',PolygonFromText('polygon(( 552 231, 565 238, 540 284, 527 278, 552 231))')); INSERT INTO building VALUES('b30','YWC',PolygonFromText('polygon(( 514 215, 537 224, 530 237, 521 232, 513 248, 530 258, 527 264, 497 247, 514 215))')); INSERT INTO building VALUES('b31','commons & STU',PolygonFromText('polygon(( 659 228, 700 249, 692 263, 708 272, 718 255, 766 280, 740 329, 646 278, 640 290, 619 278, 640 236, 652 241, 659 228))')); INSERT INTO building VALUES('b32','TSC',PolygonFromText('polygon(( 677 320, 708 337, 690 368, 661 351, 677 320))')); INSERT INTO building VALUES('b33','HNB',PolygonFromText('polygon(( 431 163, 440 160, 443 171, 472 186, 482 183, 485 195, 474 198, 458 227, 462 236, 452 239, 449 230, 421 214, 410 216, 408 207, 417 205, 434 175, 431 163))')); INSERT INTO building VALUES('b34','PKS',PolygonFromText('polygon(( 94 402, 110 412, 105 420, 115 426, 118 422, 176 454, 165 472, 108 441, 110 435, 100 430, 74 480, 57 470, 94 402))')); INSERT INTO building VALUES('b35','STO',PolygonFromText('polygon(( 574 247, 586 254, 577 270, 589 277, 599 259, 610 265, 587 309, 575 302, 581 290, 570 283, 562 296, 552 289, 574 247))')); -- -- Table structure for table `student` -- DROP TABLE IF EXISTS `student`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `student` ( `s_id` char(10) NOT NULL, `s_location` point NOT NULL, PRIMARY KEY (`s_id`) ) -- -- Dumping data for table `student` -- INSERT INTO student VALUES('p0',GeomFromText( ' POINT( 228 102) ' )); INSERT INTO student VALUES('p1',GeomFromText( ' POINT( 220 112) ' )); INSERT INTO student VALUES('p2',GeomFromText( ' POINT( 213 135) ' )); INSERT INTO student VALUES('p3',GeomFromText( ' POINT( 189 177) ' )); INSERT INTO student VALUES('p4',GeomFromText( ' POINT( 180 202) ' )); INSERT INTO student VALUES('p5',GeomFromText( ' POINT( 166 231) ' )); INSERT INTO student VALUES('p6',GeomFromText( ' POINT( 153 257) ' )); INSERT INTO student VALUES('p7',GeomFromText( ' POINT( 138 278) ' )); INSERT INTO student VALUES('p8',GeomFromText( ' POINT( 125 300) ' )); INSERT INTO student VALUES('p9',GeomFromText( ' POINT( 116 320) ' )); INSERT INTO student VALUES('p10',GeomFromText( ' POINT( 94 369) ' )); INSERT INTO student VALUES('p11',GeomFromText( ' POINT( 104 394) ' )); INSERT INTO student VALUES('p12',GeomFromText( ' POINT( 136 409) ' )); INSERT INTO student VALUES('p13',GeomFromText( ' POINT( 171 430) ' )); INSERT INTO student VALUES('p14',GeomFromText( ' POINT( 195 438) ' )); INSERT INTO student VALUES('p15',GeomFromText( ' POINT( 221 453) ' )); INSERT INTO student VALUES('p16',GeomFromText( ' POINT( 250 462) ' )); INSERT INTO student VALUES('p17',GeomFromText( ' POINT( 283 485) ' )); INSERT INTO student VALUES('p18',GeomFromText( ' POINT( 320 505) ' )); INSERT INTO student VALUES('p19',GeomFromText( ' POINT( 342 502) ' )); INSERT INTO student VALUES('p20',GeomFromText( ' POINT( 365 475) ' )); INSERT INTO student VALUES('p21',GeomFromText( ' POINT( 320 531) ' )); INSERT INTO student VALUES('p22',GeomFromText( ' POINT( 318 561) ' )); INSERT INTO student VALUES('p23',GeomFromText( ' POINT( 439 318) ' )); INSERT INTO student VALUES('p24',GeomFromText( ' POINT( 422 344) ' )); INSERT INTO student VALUES('p25',GeomFromText( ' POINT( 412 378) ' )); INSERT INTO student VALUES('p26',GeomFromText( ' POINT( 484 233) ' )); INSERT INTO student VALUES('p27',GeomFromText( ' POINT( 504 208) ' )); INSERT INTO student VALUES('p28',GeomFromText( ' POINT( 518 175) ' )); INSERT INTO student VALUES('p29',GeomFromText( ' POINT( 516 290) ' )); INSERT INTO student VALUES('p30',GeomFromText( ' POINT( 531 299) ' )); INSERT INTO student VALUES('p31',GeomFromText( ' POINT( 588 328) ' )); INSERT INTO student VALUES('p32',GeomFromText( ' POINT( 637 352) ' )); INSERT INTO student VALUES('p33',GeomFromText( ' POINT( 657 363) ' )); INSERT INTO student VALUES('p34',GeomFromText( ' POINT( 448 409) ' )); INSERT INTO student VALUES('p35',GeomFromText( ' POINT( 464 420) ' )); INSERT INTO student VALUES('p36',GeomFromText( ' POINT( 484 428) ' )); INSERT INTO student VALUES('p37',GeomFromText( ' POINT( 491 432) ' )); INSERT INTO student VALUES('p38',GeomFromText( ' POINT( 507 438) ' )); INSERT INTO student VALUES('p39',GeomFromText( ' POINT( 548 462) ' )); INSERT INTO student VALUES('p40',GeomFromText( ' POINT( 583 480) ' )); INSERT INTO student VALUES('p41',GeomFromText( ' POINT( 302 197) ' )); INSERT INTO student VALUES('p42',GeomFromText( ' POINT( 290 188) ' )); INSERT INTO student VALUES('p43',GeomFromText( ' POINT( 297 202) ' )); INSERT INTO student VALUES('p44',GeomFromText( ' POINT( 358 199) ' )); INSERT INTO student VALUES('p45',GeomFromText( ' POINT( 384 214) ' )); INSERT INTO student VALUES('p46',GeomFromText( ' POINT( 281 162) ' )); INSERT INTO student VALUES('p47',GeomFromText( ' POINT( 264 314) ' )); INSERT INTO student VALUES('p48',GeomFromText( ' POINT( 256 302) ' )); INSERT INTO student VALUES('p49',GeomFromText( ' POINT( 221 285) ' )); INSERT INTO student VALUES('p50',GeomFromText( ' POINT( 197 275) ' )); INSERT INTO student VALUES('p51',GeomFromText( ' POINT( 179 338) ' )); INSERT INTO student VALUES('p52',GeomFromText( ' POINT( 161 325) ' )); INSERT INTO student VALUES('p53',GeomFromText( ' POINT( 378 280) ' )); INSERT INTO student VALUES('p54',GeomFromText( ' POINT( 362 267) ' )); INSERT INTO student VALUES('p55',GeomFromText( ' POINT( 530 364) ' )); INSERT INTO student VALUES('p56',GeomFromText( ' POINT( 535 353) ' )); INSERT INTO student VALUES('p57',GeomFromText( ' POINT( 589 448) ' )); INSERT INTO student VALUES('p58',GeomFromText( ' POINT( 691 456) ' )); INSERT INTO student VALUES('p59',GeomFromText( ' POINT( 698 427) ' )); INSERT INTO student VALUES('p60',GeomFromText( ' POINT( 716 430) ' )); INSERT INTO student VALUES('p61',GeomFromText( ' POINT( 723 446) ' )); INSERT INTO student VALUES('p62',GeomFromText( ' POINT( 687 503) ' )); INSERT INTO student VALUES('p63',GeomFromText( ' POINT( 674 525) ' )); INSERT INTO student VALUES('p64',GeomFromText( ' POINT( 652 523) ' )); INSERT INTO student VALUES('p65',GeomFromText( ' POINT( 645 539) ' )); INSERT INTO student VALUES('p66',GeomFromText( ' POINT( 659 309) ' )); INSERT INTO student VALUES('p67',GeomFromText( ' POINT( 716 340) ' )); INSERT INTO student VALUES('p68',GeomFromText( ' POINT( 524 150) ' )); INSERT INTO student VALUES('p69',GeomFromText( ' POINT( 476 258) ' )); INSERT INTO student VALUES('p70',GeomFromText( ' POINT( 241 269) ' )); INSERT INTO student VALUES('p71',GeomFromText( ' POINT( 284 409) ' )); INSERT INTO student VALUES('p72',GeomFromText( ' POINT( 272 409) ' )); INSERT INTO student VALUES('p73',GeomFromText( ' POINT( 204 367) ' )); INSERT INTO student VALUES('p74',GeomFromText( ' POINT( 231 371) ' )); INSERT INTO student VALUES('p75',GeomFromText( ' POINT( 381 424) ' )); INSERT INTO student VALUES('p76',GeomFromText( ' POINT( 466 471) ' )); INSERT INTO student VALUES('p77',GeomFromText( ' POINT( 338 96) ' )); INSERT INTO student VALUES('p78',GeomFromText( ' POINT( 349 78) ' )); INSERT INTO student VALUES('p79',GeomFromText( ' POINT( 409 132) ' )); -- -- Table structure for table `tramstop` -- DROP TABLE IF EXISTS `tramstop`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tramstop` ( `t_id` char(10) NOT NULL, `t_location` point NOT NULL, `t_radius` int(10) NOT NULL, PRIMARY KEY (`t_id`) ) -- -- Dumping data for table `tramstop` -- INSERT INTO tramstop VALUES('t1psa',GeomFromText( ' POINT( 180 120) ' ), 100); INSERT INTO tramstop VALUES('t2ohe',GeomFromText( ' POINT( 204 177) ' ), 70); INSERT INTO tramstop VALUES('t3sgm',GeomFromText( ' POINT( 253 81) ' ), 75); INSERT INTO tramstop VALUES('t4hnb',GeomFromText( ' POINT( 476 229) ' ), 50); INSERT INTO tramstop VALUES('t5vhe',GeomFromText( ' POINT( 447 299) ' ), 50); INSERT INTO tramstop VALUES('t6ssl',GeomFromText( ' POINT( 213 432) ' ), 50); INSERT INTO tramstop VALUES('t7helen',GeomFromText( ' POINT( 378 460) ' ), 100); -- Dump completed on 2014-11-06 0:49:26 <file_sep>/HW2/HW2/dropdb.sql USE `585_HW2`; DROP TABLE building; DROP TABLE student; DROP TABLE tramstop; <file_sep>/HW2/HW2/HW2.java package database; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; public class HW2 { static Connection conn; static Statement st; //static String arg[] = {"window", "student", "100", "100", "300", "300"}; public static Connection getConnection() { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); con = (Connection) DriverManager.getConnection( "jdbc:mysql://localhost:3306/585_HW2", "root", ""); //System.out.println("Successfully!"); } catch (Exception e) { System.out.println("Failed" + e.getMessage()); } return con; } public static void main(String [] args) { conn = getConnection(); try { String sql = null; int num1 = 0, num2 = 0, num3 = 0, num4 = 0; /*--------------------Query1:window--------------------*/ if(args[0].equals("window")) { if(args[1].equals("building")) { //System.out.println(arg[0]); num1 = Integer.parseInt(args[2]); num2 = Integer.parseInt(args[3]); num3 = Integer.parseInt(args[4]); num4 = Integer.parseInt(args[5]); sql = "SELECT b_id " + "FROM building " + "WHERE st_contains (GeomFromText('Polygon((" + num1 + " " + num2 + "," + num3 + " " + num2 + ","+ num3 + " " + num4 + "," + num1 + " " + num4 + "," + num1 + " " + num2 + "))'), b_location)"; System.out.println(sql); st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs1 = st.executeQuery(sql); while(rs1.next()) { String b_id_1 = rs1.getString("b_id"); System.out.println("ID:" + b_id_1 +"\n"); } rs1.close(); } if(args[1].equals("student")) { num1 = Integer.parseInt(args[2]); num2 = Integer.parseInt(args[3]); num3 = Integer.parseInt(args[4]); num4 = Integer.parseInt(args[5]); sql = "SELECT s_id " + "FROM student " + "WHERE st_contains (GeomFromText('Polygon((" + num1 + " " + num2 + "," + num3 + " " + num2 + ","+ num3 + " " + num4 + "," + num1 + " " + num4 + "," + num1 + " " + num2 + "))'), s_location)"; //System.out.println(sql); st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs2 = st.executeQuery(sql); while(rs2.next()) { String s_id_1 = rs2.getString("s_id"); System.out.println("ID:" + s_id_1 +"\n"); } rs2.close(); } if(args[1].equals("tramstop")) { num1 = Integer.parseInt(args[2]); num2 = Integer.parseInt(args[3]); num3 = Integer.parseInt(args[4]); num4 = Integer.parseInt(args[5]); sql = "SELECT t_id " + "FROM tramstop " + "WHERE st_contains (GeomFromText('Polygon((" + num1 + " " + num2 + "," + num3 + " " + num2 + ","+ num3 + " " + num4 + "," + num1 + " " + num4 + "," + num1 + " " + num2 + "))'), t_location)"; System.out.println(sql); st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs3 = st.executeQuery(sql); while(rs3.next()) { String t_id_1 = rs3.getString("t_id"); System.out.println("ID:" + t_id_1 +"\n"); } rs3.close(); } } /*--------------------Query2:within--------------------*/ if(args[0].equals("within")) { String stu = args[1]; num1 = Integer.parseInt(args[2]); sql = "SELECT b_id AS id " + "FROM building, student " + "WHERE s_id = '"+stu+"' AND ST_Distance(b_location, GeomFromText(AsText(s_location))) <" + num1 + " UNION " + "SELECT t_id " + "FROM tramstop, student " + "WHERE s_id = '"+stu+"' AND ST_Distance(t_location, GeomFromText(AsText(s_location))) <" + num1+";"; //System.out.println(sql); st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs4 = st.executeQuery(sql); while(rs4.next()) { String id_1 = rs4.getString("id"); System.out.println("ID:" + id_1 +"\n"); } rs4.close(); } /*--------------------Query3:nearest-neighbor--------------------*/ if(args[0].equals("nearest-neighbor")) { num1 = Integer.parseInt(args[3]); String bn = args[2]; if(args[1].equals("building")) { sql = "SELECT b_id " + "FROM building " + "ORDER BY ST_DISTANCE((SELECT b_location FROM building WHERE b_id = '"+bn+"' ), b_location) ASC " + "LIMIT 1, "+num1; // Another case: if given objects are building, nearest objects are student and tramstop. /* sql = "SELECT * FROM ( " + "SELECT s_id AS id, ST_DISTANCE(s_location, b_location) AS dis " + "FROM building, student " + "WHERE b_id = '"+ bn +"'" + " UNION " + "SELECT t_id AS id, ST_DISTANCE(t_location, b_location) AS dis " + "FROM building, tramstop " + "WHERE b_id = '"+ bn +"') a " + "ORDER BY dis ASC " + "LIMIT "+ num1 + ";"; */ //System.out.println(sql); st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs5 = st.executeQuery(sql); while(rs5.next()) { String q3_1 = rs5.getString("b_id"); System.out.println("Nearest objects ID:" + q3_1 +"\n"); } rs5.close(); } if(args[1].equals("student")) { sql = "SELECT s_id " + "FROM student " + "ORDER BY ST_DISTANCE((SELECT s_location FROM student WHERE s_id = '"+bn+"' ), s_location) ASC " + "LIMIT 1,"+num1; //System.out.println(sql); st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs5 = st.executeQuery(sql); while(rs5.next()) { String q3_2 = rs5.getString("s_id"); System.out.println("Nearest objects ID:" + q3_2 +"\n"); } rs5.close(); } if(args[1].equals("tramstop")) { sql = "SELECT t_id " + "FROM tramstop " + "ORDER BY ST_DISTANCE((SELECT t_location FROM tramstop WHERE t_id = '"+bn+"' ), t_location) ASC " + "LIMIT 1,"+num1; //System.out.println(sql); st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs5 = st.executeQuery(sql); while(rs5.next()) { String q3_3 = rs5.getString("t_id"); System.out.println("Nearest objects ID:" + q3_3 +"\n"); } rs5.close(); } } /*-----------------------Query4:fixed----------------------------*/ if(args[0].equals("fixed")) { if(args[1].equals("1")) { //fixed, query1 sql = "SELECT b_id FROM building WHERE st_contains(" + "(SELECT st_intersects " + "(GeomFromText(\"SELECT buffer(t_location, t_radius) FROM tramstop WHERE t_id = 't2ohe'\"), " + "GeomFromText(\"SELECT buffer(t_location, t_radius) FROM tramstop WHERE t_id = 't6ssl'\"))), " + "b_location) " + " UNION " + "SELECT s_id FROM student WHERE st_contains(" + "(SELECT st_intersects " + "(GeomFromText(\"SELECT buffer(t_location, t_radius) FROM tramstop WHERE t_id = 't2ohe'\"), " + "GeomFromText(\"SELECT buffer(t_location, t_radius) FROM tramstop WHERE t_id = 't6ssl'\"))), " + "s_location)"; // System.out.println(sql); st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs6 = st.executeQuery(sql); while(rs6.next()) { String q4_1 = rs6.getString("b_id"); System.out.println("IDs of all the students and buildings cover by tram stops:" + q4_1 +"\n"); } rs6.close(); } if(args[1].equals("2")) { //fixed, query 2 for(int i = 0; i < 80; i++) { String sid = "p" + i; //System.out.println(sid); sql = "SELECT t_id, s_id " + "FROM tramstop, student WHERE s_id = " + "'"+ sid+"'" + " ORDER BY ST_DISTANCE((SELECT t_location FROM tramstop WHERE t_id = 't1psa' ), (SELECT s_location FROM student WHERE s_id = 'p3')) " + "LIMIT 2;"; //System.out.println(sql); st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs7 = st.executeQuery(sql); while(rs7.next()) { String q4_2 = rs7.getString("t_id"); System.out.println("one of the 2 nearest tramstops of the student whoes id is "+ sid+ ": " + q4_2 +"\n"); } rs7.close(); } } if(args[1].equals("3")) { //fixed, query 3 sql = "SELECT t_id, count(*) AS num " + "FROM tramstop, student " + "WHERE ST_DISTANCE(t_location, s_location) < 250 " + "GROUP BY t_id " + "ORDER BY count(*) DESC " + "LIMIT 1;"; //System.out.println(sql); st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs8 = st.executeQuery(sql); while(rs8.next()) { String q4_3 = rs8.getString("t_id"); System.out.println(" ID’s of the tram stop that cover the most buildings: "+ q4_3 +"\n"); //String q4_32 = rs8.getString("num"); //System.out.println("covered tramstop number:" + q4_32 +"\n"); } rs8.close(); } if(args[1].equals("4")) { //fixed, query 4 String sqll = null; for(int i = 0; i < 36; i++){ String f4 = "b" + i; sql = "(SELECT s_id, s_location, b_id, b_location, st_distance(s_location, b_location) " + "FROM student, building " + "WHERE B_ID = " + "'" + f4 + "'" + " ORDER BY st_distance(s_location, b_location) ASC " + "limit 1)"; if(sqll == null) sqll = sql; else sqll = sqll + " UNION " + sql; } String sqlll = "SELECT s_id, count(s_id) FROM (" + sqll +") a GROUP BY s_id ORDER BY count(s_id) DESC LIMIT 5; "; //System.out.println(sqlll); st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs9 = st.executeQuery(sqlll); while(rs9.next()) { String q4_4 = rs9.getString("s_id"); System.out.println("The ID of the student: "+ q4_4 +"\n"); String q4_42 = rs9.getString("count(s_id)"); System.out.println("The num of the nearest buildings: "+ q4_42 +"\n"); } rs9.close(); } if(args[1].equals("5")) { //fixed, query 5 /* sql = "SELECT b_id, b_name, AsTeXT(b_location) FROM building WHERE b_name LIKE 'SS%';"; st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs10 = st.executeQuery(sql); int j = 0; String temp[] = new String[100]; // initail the array with a large size. while(rs10.next()) { temp[j] = rs10.getString("AsTeXT(b_location)"); //System.out.println(temp[j]+"\n"); j++; } String l = null; for(int i = 0; i<j; i++){ if(l == null) l = temp[i]; else l = l +", " + temp[i]; } //System.out.println(l); String sq = "ExteriorRing(Envelope(ST_Union("+l+")))"; //System.out.println(sq); sql="SELECT AsText(PointN("+sq+",1)) as lowerleft, AsText(PointN("+sq+",3)) as uppperright;"; //System.out.println(sql); rs10.close(); */ sql = "(SELECT min(astext(POINTN(EXTERIORRING(envelope(b_location)),1))) AS p " + "FROM building " + "WHERE b_name LIKE 'SS%' " + "ORDER BY b_id) " + " UNION " + "(SELECT max(astext(POINTN(EXTERIORRING(envelope(b_location)),3))) AS p " + "FROM building " + "WHERE b_name LIKE 'SS%' " + "ORDER BY b_id)"; st = (Statement) conn.createStatement(); //create the Statement object which implement sql. ResultSet rs10 = st.executeQuery(sql); while(rs10.next()) { String q4_5 = rs10.getString("p"); System.out.println("The left lower point and right upper points are: "+ q4_5 +"\n"); } rs10.close(); } } conn.close(); //close connection } catch (SQLException e) { System.out.println("Failed" + e); } } } <file_sep>/HW3/585HW3/ReadMe.txt 1. I submited the files running on local computer. If you want to run it on aludra, please change the path to relative path. For example, change doc("/Users/shuzizhang/585HW3/company.xml") to doc("company.xml"). 2. query 2: As I understand, it asks to find divisions that all employees work for. Reference: 1. http://www.xqueryfunctions.com/xq/functx_value-intersect.html 2. http://www.w3schools.com/
bcb52996b6b506fdb6bcf68514c01cfe727a297c
[ "Markdown", "SQL", "Java", "Text" ]
7
Text
ssz/Database-CS585
9338221f32de87d6be7ca1bfca1a84f65a07eae3
dfdaea5f1324df70e39e203ad33b5634e6290343
refs/heads/main
<file_sep># guess-game-v1.0
b076af3316cc0b46df21118a466b3bc565fe3f9a
[ "Markdown" ]
1
Markdown
i-bm/guess-game-v1.0
a9533f7ecde9829301f2749b9dd29650c87113ae
b95652fcb9f32782e56cce6de27c769bd92738c9
refs/heads/main
<repo_name>Deksters4788/SQL_HW<file_sep>/lessen-4/less_4.sql /* Практическое задание #4. */ /* Задание # 3. * Написать запрос для переименования названий типов медиа (колонка name в media_types) * в осмысленные для полученного дампа с данными (например, в "фото", "видео", ...). */ -- Запрос на смену первого типа UPDATE media_types SET name = 'Photo' WHERE id = 1; -- Запрос на смену второго типа UPDATE media_types SET name = 'Video' WHERE id = 2; -- Запрос на смену третьего типа UPDATE media_types SET name = 'Audio' WHERE id = 3; -- Запрос на смену четвертого типа UPDATE media_types SET name = 'Clip' WHERE id = 4;<file_sep>/lessen_3/less_3.sql /* Практическое задание #3. */ /* Задание # 2. * Придумать 2-3 таблицы для БД vk, которую мы создали на занятии * (с перечнем полей, указанием индексов и внешних ключей). Прислать результат в виде скрипта *.sql. */ -- Создание таблицы образование CREATE TABLE education ( user_id BIGINT UNSIGNED NOT NULL, school VARCHAR(245) DEFAULT NULL, university VARCHAR(245) DEFAULT NULL, INDEX fk_education_users_idx (user_id), CONSTRAINT fk_education_users FOREIGN KEY (user_id) REFERENCES users (id) ); -- Создание таблицы черный список CREATE TABLE black_list( user_send_to_id BIGINT UNSIGNED NOT NULL, user_departing_to_id BIGINT UNSIGNED NOT NULL, INDEX fk_user_send_to_idx (user_send_to_id), INDEX fk_user_departing_to_idx (user_departing_to_id), CONSTRAINT fk_user_send_to FOREIGN KEY (user_send_to_id) REFERENCES users (id), CONSTRAINT fk_user_departing_to FOREIGN KEY (user_departing_to_id) REFERENCES users (id) ); <file_sep>/README.md # SQL_HW
e67fbede0cef3c4364d45fbed39661892a6caf9b
[ "Markdown", "SQL" ]
3
SQL
Deksters4788/SQL_HW
f4a023cf883c2c6e9322fe77eb903c07f50100cf
1df40cac86edb8ea3084e88dbb7ac10cf3c4648f
refs/heads/master
<file_sep>package com.codeup.springblog.models; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Random; @Controller public class rollDice { @GetMapping("/roll-dice") @ResponseBody public String rollDice() { // return "Please guess a number between 1 and 6 "; return "What is your guess?<br/><ul>" + "<li><a href='/roll-dice/1'>1</a></li>" + "<li><a href='/roll-dice/2'>2</a></li>" + "<li><a href='/roll-dice/3'>3</a></li>" + "<li><a href='/roll-dice/4'>4</a></li>" + "<li><a href='/roll-dice/5'>5</a></li>" + "<li><a href='/roll-dice/6'>6</a></li>" + "</ul>"; } @GetMapping("/roll-dice/{n}") @ResponseBody public String checkGuess(@PathVariable Integer n ) { Integer diceRoll = new Random().nextInt(6) + 1; if (n == diceRoll) { return "<h2>You got it!</h2>"; } else return "Sorry, the number rolled was " + diceRoll.toString(); } // @GetMapping("/roll-dice/{n}") // @ResponseBody // public String randomPick(@PathVariable int n ) { // Random rand = new Random(); // int x = rand.nextInt(6 - 1); // if (n == x) { // return "You guessed it correctly!"; // } else { // return "OOPS wrong!! It was " + x; // // } // } } <file_sep>package com.codeup.springblog.services; import com.codeup.springblog.models.Post; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface PostRepository extends CrudRepository<Post, Long> { List<Post> findAllByTitleOrDescription(String str, String str2); }
cfd75eba8dc2dec17ac264e71ea0f710676adb0c
[ "Java" ]
2
Java
brittanyrussell/springblog
d7c3a5869ea92d426b6832a038e8fd428b44c792
8cd889b54650ea0b81ba3d581447da947b76f381
refs/heads/master
<file_sep> package org.exparity.expectamundo.core; import java.util.List; /** * @author <NAME> */ public interface Prototyped<T> { /** * Return the collection of expectations relevant to this protype */ public List<PrototypeValueMatcher> getExpectations(); /** * Return */ public Class<T> getRawType(); } <file_sep> package org.exparity.expectamundo.core; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * @author <NAME> */ /** * Helper class to allow generic type inforrmation to be interrogated when constructing a prototype. * * @author Stewart.Bissett */ public abstract class TypeReference<T> { private final Type type; protected TypeReference() { Type superclass = getClass().getGenericSuperclass(); if (superclass instanceof Class) { throw new IllegalArgumentException("TypeReference must be provided with generic type parameter e.g. TypeReference<List<String>>."); } this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0]; } /** * Gets the referenced type. */ public Type getType() { return this.type; } }<file_sep>package org.exparity.expectamundo.examples; import java.util.Arrays; import java.util.List; import org.exparity.expectamundo.Expectamundo; import org.junit.Test; public class SimpleTypeTest { class SimpleType { private final String firstName, surname; private final List<String> values; public SimpleType(final String firstName, final String surname, final String... values) { this.firstName = firstName; this.surname = surname; this.values = Arrays.asList(values); } public List<String> getValues() { return values; } public String getFirstName() { return firstName; } public String getSurname() { return surname; } } @Test public void canReturnTheCorrectValue() { SimpleType expected = Expectamundo.prototype(SimpleType.class); Expectamundo.expect(expected.getFirstName()).isEqualTo("Jane"); Expectamundo.expect(expected.getSurname()).isEqualTo("Smith"); Expectamundo.expect(expected.getValues()).contains("eXpectamundo lets me test this"); SimpleType actual = new SimpleType("Jane", "Smith", "eXpectamundo lets me test this"); Expectamundo.expectThat(actual).matches(expected); } @Test public void canMatchPrototypeInList() { SimpleType expected = Expectamundo.prototype(SimpleType.class); Expectamundo.expect(expected.getFirstName()).isEqualTo("Jane"); Expectamundo.expect(expected.getSurname()).isEqualTo("Smith"); Expectamundo.expect(expected.getValues()).contains("eXpectamundo lets me test this"); SimpleType actual = new SimpleType("Jane", "Smith", "eXpectamundo lets me test this"); List<SimpleType> actualList = Arrays.asList(actual); Expectamundo.expectThat(actualList).contains(expected); } } <file_sep>package org.exparity.expectamundo.core; /** * @author <NAME> */ public interface PrototypeValue { Object getValue(Object actual); String getLabel(); } <file_sep> package org.exparity.expectamundo.core.date; import java.util.Date; import org.exparity.expectamundo.core.PropertyExpectation; /** * @author <NAME> */ public class IsAfter implements PropertyExpectation<Date> { private Date expected; public IsAfter(final Date expected) { this.expected = expected; } @Override public boolean matches(final Date actual) { return actual.compareTo(expected) > 0; } @Override public String describe() { return "a date after " + expected; } } <file_sep> package org.exparity.expectamundo.core.array; import org.exparity.expectamundo.core.PropertyExpectation; /** * @author <NAME> */ public class IsEmptyArray<T> implements PropertyExpectation<T[]> { @Override public boolean matches(final T[] actual) { return actual == null || actual.length == 0; } @Override public String describe() { return "is empty"; } } <file_sep>package org.exparity.expectamundo.testutils.types; import java.math.BigDecimal; public class BigDecimalReturnType { private BigDecimal value; public BigDecimalReturnType(final BigDecimal value) { this.value = value; } public BigDecimalReturnType() { // TODO Auto-generated constructor stub } public BigDecimal getValue() { return value; } public void setValue(final BigDecimal value) { this.value = value; } }<file_sep> package org.exparity.expectamundo.core.array; import org.exparity.expectamundo.testutils.types.ArrayType; import org.junit.Test; import static org.exparity.expectamundo.Expectamundo.expect; import static org.exparity.expectamundo.Expectamundo.prototype; import static org.exparity.expectamundo.Expectamundo.expectThat; import static org.exparity.stub.random.RandomBuilder.aRandomString; /** * Unit Test for {@link Expectamundo} invocations of the {@link IsEmpty} expectation * * @author <NAME> */ public class IsNotEmptyArrayTest { @Test public void canCheckForIsNotEmpty() { String[] expectedValue = new String[] { aRandomString() }; ArrayType expected = prototype(ArrayType.class); expect(expected.getValue()).isNotEmpty(); expectThat(new ArrayType(expectedValue)).matches(expected); } @Test(expected = AssertionError.class) public void canCheckForIsEmpty() { String[] expectedValue = new String[0]; ArrayType expected = prototype(ArrayType.class); expect(expected.getValue()).isNotEmpty(); expectThat(new ArrayType(expectedValue)).matches(expected); } @Test(expected = AssertionError.class) public void canCheckForIsEmptyForNull() { ArrayType expected = prototype(ArrayType.class); expect(expected.getValue()).isNotEmpty(); expectThat(new ArrayType(null)).matches(expected); } } <file_sep> package org.exparity.expectamundo.testutils.types; /** * @author <NAME> */ public class ToStringType { private final String value; public ToStringType(final String value) { this.value = value; } @Override public String toString() { return value; } } <file_sep> package org.exparity.expectamundo.core; import java.util.List; /** * @author <NAME> */ public class PrototypeListMatchResult<T> { private final T expectation; private final Prototyped<T> prototyped; private List<PrototypeMatchResult<T>> mismatches; @SuppressWarnings("unchecked") public PrototypeListMatchResult(final T expectation, final List<PrototypeMatchResult<T>> mismatches) { this.expectation = expectation; if (!Prototyped.class.isInstance(expectation)) { throw new IllegalArgumentException("Object does not implement Prototyped. Please construct using Expectamundo.prototype"); } this.prototyped = (Prototyped<T>) expectation; this.mismatches = mismatches; } public boolean isMismatch() { return !mismatches.isEmpty(); } public List<PrototypeMatchResult<T>> getMismatches() { return mismatches; } public T getExpectation() { return expectation; } public Prototyped<T> getExpectationAsPrototype() { return prototyped; } public List<PrototypeValueMatcher> getExpectations() { return prototyped.getExpectations(); } } <file_sep> package org.exparity.expectamundo.core.collection; import java.util.Collection; import org.exparity.expectamundo.core.PropertyExpectation; /** * Implementation of a {@link PropertyExpectation} to verify if a {@link Collection} contains a given expected * * @author <NAME> */ public class HasSize<T extends Collection<?>> implements PropertyExpectation<T> { private final int expectedSize; public HasSize(final int expectedSize) { this.expectedSize = expectedSize; } @Override public boolean matches(final T actual) { return actual == null ? expectedSize == 0 : actual.size() == expectedSize; } @Override public String describe() { return "has size " + expectedSize; } } <file_sep> package org.exparity.expectamundo.core; import java.util.Arrays; import java.util.List; import org.exparity.expectamundo.testutils.types.ListReturnType; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; import static org.exparity.expectamundo.Expectamundo.expect; import static org.exparity.expectamundo.Expectamundo.prototype; /** * @author <NAME> */ public class PrototypeVerifierTest { @Test public void canProduceMessageForList() { try { final List<String> expectedValue = Arrays.asList("AB"), differentValue = Arrays.asList("ABC"); ListReturnType expected = prototype(ListReturnType.class); expect(expected.getValue().get(0)).isEqualTo(expectedValue.get(0)); new PrototypeVerifier<>(new ListReturnType(differentValue)).matches(expected); } catch (AssertionError e) { MatcherAssert.assertThat(e.getMessage(), Matchers.equalTo("\nExpected a ListReturnType containing properties:\n\tgetValue().get(0) is equal to AB\nbut actual is a ListReturnType containing properties:\n\tgetValue().get(0) is ABC")); } } } <file_sep> package org.exparity.expectamundo.core.string; import org.exparity.expectamundo.core.PropertyExpectation; /** * Implementation of a {@link PropertyExpectation} to check if a String property is equal to another String property regardless of case * * @author <NAME> */ public class IsEqualToIgnoreCase implements PropertyExpectation<String> { private final String expected; public IsEqualToIgnoreCase(final String expected) { this.expected = expected; } @Override public boolean matches(final String actual) { return expected == null ? actual == null : expected.equalsIgnoreCase(actual); } @Override public String describe() { return "equal to " + expected; } } <file_sep> package org.exparity.expectamundo.core.collection; import java.util.Collection; import org.exparity.expectamundo.Expectamundo; import org.exparity.expectamundo.core.Prototype; import org.exparity.expectamundo.core.PrototypeValue; import org.exparity.expectamundo.core.object.PrototypeObjectExpectation; /** * @author <NAME> */ public class PrototypeCollectionExpectation<E, T extends Collection<E>> extends PrototypeObjectExpectation<T> { public PrototypeCollectionExpectation(final Prototype<?> prototype, final PrototypeValue property) { super(prototype, property); } /** * Set an expectation that the collection is empty. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.myCollection()).isEmpty(); * expectThat(actual).matches(expected); * </pre> */ public void isEmpty() { hasExpectation(new IsEmpty<E, T>()); } /** * Set an expectation that the collection is not empty. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.myCollection()).isNotEmpty(); * expectThat(actual).matches(expected); * </pre> */ public void isNotEmpty() { hasExpectation(new IsNotEmpty<E, T>()); } /** * Set an expectation that the collection is of the given size. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.myCollection()).hasSize(1); * expectThat(actual).matches(expected); * </pre> * @param size the expected size of the collection */ public void hasSize(final int size) { hasExpectation(new HasSize<T>(size)); } /** * Set an expectation that the collection contains an item. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.myCollection()).contains(&quot;ABCD&quot;); * expectThat(actual).matches(expected); * </pre> * @param element the item to find in the collection */ public void contains(final E element) { if (Expectamundo.isPrototype(element)) { containsExpected(element); } else { hasExpectation(new Contains<E, T>(element)); } } /** * Set an expectation that the collection contains an item which matches the expectation. For example</p> * * <pre> * MyChild child = prototype(MyChild.class); * expect(child.getName()).isEqualTo(&quot;Bob&quot;); * * MyObject expected = prototype(MyObject.class); * expect(expected.myCollection()).containsExpected(child); * expectThat(actual).matches(expected); * </pre> * @param element the expectation to find in the collection */ public void containsExpected(final E element) { hasExpectation(new ContainsExpected<E, T>(element)); } } <file_sep> package org.exparity.expectamundo.core.date; import java.util.Date; import java.util.concurrent.TimeUnit; import org.exparity.expectamundo.core.PropertyExpectation; /** * @author <NAME> */ public class IsWithin implements PropertyExpectation<Date> { private int interval; private TimeUnit unit; private Date expected; public IsWithin(final int interval, final TimeUnit unit, final Date expected) { this.interval = interval; this.unit = unit; this.expected = expected; } @Override public boolean matches(final Date actual) { long differenceInMillis = Math.abs(expected.getTime() - actual.getTime()); if (differenceInMillis > TimeUnit.MILLISECONDS.convert(interval, unit)) { return false; } else { return true; } } @Override public String describe() { return "a expected within " + interval + " " + unit.name().toLowerCase() + " of " + expected; } } <file_sep>eXpectamundo [![Build Status](https://travis-ci.org/eXparity/expectamundo.svg?branch=master)](https://travis-ci.org/eXparity/expectamundo) [![Coverage Status](https://coveralls.io/repos/eXparity/expectamundo/badge.png?branch=master)](https://coveralls.io/r/eXparity/expectamundo?branch=master) [![Maven Central](https://img.shields.io/maven-central/v/org.exparity/expectamundo.svg)](http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22expectamundo%22) ============= A Java library for creating a prototype object with expected values and verifying the actual object has matching values Licensed under [BSD License][]. What is eXpectamundo? ----------------- eXpectamundo is a test library to facilitate testing the properties of any Java object to ensure they meet expectations. The expectations are setup by creating a prototype instance of the type you are expecting and defining the expecations on the prototype instance. Downloads --------- You can obtain the expectamundo jar from [maven central][]. To include your project in: A maven project <dependency> <groupId>org.exparity</groupId> <artifactId>expectamundo</artifactId> <version>0.9.20<version> </dependency> Usage ------------- Given a simple class as defined below: class SimpleType { private final String firstName, surname; private final List<String> values; public SimpleType(String firstName, String surname, String ... values) { this.firstName = firstName; this.surname = surname; this.values = Arrays.asList(values); } public List<String> getValues() { return values; } public String getFirstName() { return firstName; } public String getSurname() { return surname; } } You can set up a test to verify the expected outcome as follows: public class SimpleTypeTest { @Test public void canReturnTheCorrectValue() { SimpleType expected = Expectamundo.prototype(SimpleType.class); Expectamundo.expect(expected.getFirstName()).isEqualTo("Jane"); Expectamundo.expect(expected.getSurname()).isEqualTo("Smith"); Expectamundo.expect(expected.getValues()).contains("eXpectamundo lets me test this"); SimpleType actual = new SimpleType("Jane", "Smith", "eXpectamundo lets me test this"); Expectamundo.expectThat(actual).matches(expected); } } You can also set up a test to verify the prototype directly, for example setting expectations on a list as follows: public class SimpleTypeTest { @Test public void canMatchPrototypeInList() { SimpleType expected = Expectamundo.prototype(SimpleType.class); Expectamundo.expect(expected.getFirstName()).isEqualTo("Jane"); Expectamundo.expect(expected.getSurname()).isEqualTo("Smith"); Expectamundo.expect(expected.getValues()).contains("eXpectamundo lets me test this"); SimpleType actual = new SimpleType("Jane", "Smith", "eXpectamundo lets me test this"); List<SimpleType> actualList = Arrays.asList(actual); Expectamundo.expectThat(actualList).contains(expected); } } These examples capture the basics of what you can do with eXpectamundo. eXpectamundo allows you to set expectations on any non-final type or property on a object which returns a value. The library includes expectations for all Object property types: * __isEqualTo__ - Set the expectation that the property value should be equal to an explicit value * __isNotEqualTo__ - Set the expectation that the property value should not be equal to an explicit value * __isNull__ - Set the expectation that the property should be null * __isNotNull__ - Set the expectation that the property should not be null * __matches__ - Set the expectation that the property matches a Hamcrest matcher * __isInstanceOf__ - Set the expectation that the property is an instance of a type * __isOneOf__ - Set the expectation that the property one of a number of values The library includes expectations for Collection properties: * __contains__ - Set the expectation that the collection property contains an object which is equal to the explicit value * __containsExpected__ - Set the expectation that the collection property contains an a prototype with the defined expectations * __isEmpty__ - Set the expectation that the collection property is empty * __isNotEmpty__ - Set the expectation that the collection property is not empty * __hasSize__ - Set the expectation that the collection property is of an explicit size The libary includes expectations for array properties: * __contains__ - Set the expectation that the collection property contains an object which is equal to the explicit value * __isEmpty__ - Set the expectation that the collection property is empty * __isNotEmpty__ - Set the expectation that the collection property is not empty * __hasSize__ - Set the expectation that the collection property is of an explicit size The libary includes expectations for Comparable properties * __isComparableTo__ - Set the expectation that the colllection property is comparable to an explicit value The libary includes expectations for String properties * __hasPattern__ - Set the expectation that the String matches the regular expression * __hasLength__ - Set the expectation that the String is of the given length * __isEqualToIgnoreCase__ - Set the expectation that the String is the same as another regardless of case Contributions are welcome to extend the list of expectations to match types. Source ------ The source is structured along the lines of the maven standard folder structure for a jar project. * Core classes [src/main/java] * Unit tests [src/test/java] The source includes a pom.xml for building with Maven Release Notes ------------- Changes 0.9.18 -> 0.9.20 * Fix issue with expectations on BigDecimal and BigInteger Changes 0.9.16 -> 0.9.18 * Handle IndexOutOfBounds and NullPointerException by returning a null proxy to improve error printing Changes 0.9.15 -> 0.9.16 * Catch IndexOutOfBounds Changes 0.9.11 -> 0.9.15 * Add IsEqualsIgnoreCase to Strings * Add IsSameDay to Date * Add ContainsExpected to collections * Improve handling of array index out of range Changes 0.9.10 -> 0.9.11 * IsEqualTo can check expected null == null (Issue #3) Changes 0.9.9 -> 0.9.10 * Include arguments as strings when printing assertions * Add line break after mismatching property in assertion Changes 0.9.3 -> 0.9.4 * Add support for casting down to subtypes Changes 0.9.2 -> 0.9.3 * Expand expectation options Changes 0.9.1 -> 0.9.2 * Correct typo of expactomundo in package name Changes 0.9.0 -> 0.9.0 * Introduce static Expectamundo class Acknowledgements ---------------- Developers: * <NAME> * <NAME> [BSD License]: http://opensource.org/licenses/BSD-3-Clause [Maven central]: http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22expectamundo%22 <file_sep> package org.exparity.expectamundo.testutils.types; import java.util.Map; /** * @author <NAME> */ public class MapReturnType { private final Map<String, String> value; public MapReturnType(final Map<String, String> value) { this.value = value; } public Map<String, String> getValue() { return value; } } <file_sep> package org.exparity.expectamundo.core.collection; import static org.exparity.expectamundo.Expectamundo.expect; import static org.exparity.expectamundo.Expectamundo.expectThat; import static org.exparity.expectamundo.Expectamundo.prototype; import static org.exparity.stub.random.RandomBuilder.aRandomString; import java.util.Arrays; import java.util.List; import org.exparity.expectamundo.Expectamundo; import org.exparity.expectamundo.core.TypeReference; import org.exparity.expectamundo.testutils.types.ParameterizedListReturnType; import org.exparity.expectamundo.testutils.types.SimpleType; import org.junit.Test; /** * Unit Test for {@link Expectamundo} invocations of the {@link Contains} expectation * * @author <NAME> */ public class ContainsExpectedTest { @Test public void canCheckForContains() { String expectedString = aRandomString(), anotherString = expectedString + aRandomString(); SimpleType expectedValue = prototype(SimpleType.class); expect(expectedValue.getValue()).isEqualTo(expectedString); ParameterizedListReturnType<SimpleType> expected = prototype(new TypeReference<ParameterizedListReturnType<SimpleType>>() {}); expect(expected.getValue()).containsExpected(expectedValue); expectThat(new ParameterizedListReturnType<SimpleType>(Arrays.asList(new SimpleType(expectedString), new SimpleType(anotherString)))).matches(expected); } @Test(expected = AssertionError.class) public void canCheckForNotContains() { String expectedString = aRandomString(), anotherString = expectedString + aRandomString(); SimpleType expectedValue = prototype(SimpleType.class); expect(expectedValue.getValue()).isEqualTo(expectedString); ParameterizedListReturnType<SimpleType> expected = prototype(new TypeReference<ParameterizedListReturnType<SimpleType>>() {}); expect(expected.getValue()).containsExpected(expectedValue); expectThat(new ParameterizedListReturnType<SimpleType>(Arrays.asList(new SimpleType(anotherString)))).matches(expected); } @Test(expected = AssertionError.class) public void canCheckForNotContainsIfNull() { String expectedString = aRandomString(); SimpleType expectedValue = prototype(SimpleType.class); expect(expectedValue.getValue()).isEqualTo(expectedString); ParameterizedListReturnType<SimpleType> expected = prototype(new TypeReference<ParameterizedListReturnType<SimpleType>>() {}); expect(expected.getValue()).containsExpected(expectedValue); expectThat(new ParameterizedListReturnType<SimpleType>((List<SimpleType>)null)).matches(expected); } @Test(expected = IllegalArgumentException.class) public void canFailWithExceptionIfNotExpection() { String expectedString = aRandomString(), anotherString = expectedString + aRandomString(); SimpleType expectedValue = new SimpleType(expectedString); expect(expectedValue.getValue()).isEqualTo(expectedString); ParameterizedListReturnType<SimpleType> expected = prototype(new TypeReference<ParameterizedListReturnType<SimpleType>>() {}); expect(expected.getValue()).containsExpected(expectedValue); expectThat(new ParameterizedListReturnType<SimpleType>(Arrays.asList(new SimpleType(expectedString), new SimpleType(anotherString)))).matches(expected); } } <file_sep>package org.exparity.expectamundo.core; public class PrototypeValueDifference { private final String label; private final Object value; public PrototypeValueDifference(final String path, final Object value) { this.label = path; this.value = value; } public Object getValue() { return value; } public String getPath() { return label; } }<file_sep> package org.exparity.expectamundo.core.date; import java.util.Date; import java.util.concurrent.TimeUnit; import org.exparity.expectamundo.core.Prototype; import org.exparity.expectamundo.core.PrototypeValue; import org.exparity.expectamundo.core.comparable.PrototypeComparableExpectation; /** * @author <NAME> */ public class PrototypeDateExpectation extends PrototypeComparableExpectation<Date> { public PrototypeDateExpectation(final Prototype<?> prototype, final PrototypeValue property) { super(prototype, property); } /** * Set an expectation that the property value is within a given interval of the given date. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.aDate()).isWithin(1, TimeUnit.MINUTES, new Date()); * expectThat(actual).matches(expected); * </pre> * @param interval the interval gap between the property value and the date * @param unit the time unit of the interval * @param date the date to test the value against */ public void isWithin(final int interval, final TimeUnit unit, final Date date) { hasExpectation(new IsWithin(interval, unit, date)); } /** * Set an expectation that the property value is on the same day. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.aDate()).isSameDay(new Date()); * expectThat(actual).matches(expected); * </pre> * @param date the date to test the value against */ public void isSameDay(final Date date) { hasExpectation(new IsSameDay(date)); } /** * Set an expectation that the property value is after a given date. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.aDate()).isAfter(new Date()); * expectThat(actual).matches(expected); * </pre> * @param date the date to test the value against */ public void isAfter(final Date date) { hasExpectation(new IsAfter(date)); } /** * Set an expectation that the property value is before a given date. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.aDate()).isBefore(new Date()); * expectThat(actual).matches(expected); * </pre> * @param date the date to test the value against */ public void isBefore(final Date date) { hasExpectation(new IsBefore(date)); } } <file_sep> package org.exparity.expectamundo.core.string; import org.exparity.expectamundo.testutils.types.SimpleType; import org.junit.Test; import static org.exparity.expectamundo.Expectamundo.expect; import static org.exparity.expectamundo.Expectamundo.prototype; import static org.exparity.expectamundo.Expectamundo.expectThat; import static org.exparity.stub.random.RandomBuilder.aRandomInteger; import static org.exparity.stub.random.RandomBuilder.aRandomString; /** * Unit Test for {@link Expectamundo} invocations of the {@link org.exparity.expectamundo.core.object.HasLength} expectation * * @author <NAME> */ public class HasLengthTest { @Test public void canCheckForSize() { int expectedLength = aRandomInteger(10, 50); SimpleType expected = prototype(SimpleType.class); expect(expected.getValue()).hasLength(expectedLength); expectThat(new SimpleType(aRandomString(expectedLength))).matches(expected); } @Test public void canCheckForIsSizeIfNull() { SimpleType expected = prototype(SimpleType.class); expect(expected.getValue()).hasLength(0); expectThat(new SimpleType(null)).matches(expected); } @Test(expected = AssertionError.class) public void canCheckForWrongSizeIfNull() { SimpleType expected = prototype(SimpleType.class); expect(expected.getValue()).hasLength(aRandomInteger(1, 50)); expectThat(new SimpleType(null)).matches(expected); } @Test(expected = AssertionError.class) public void canCheckForWrongSize() { int expectedLength = 10, differentLength = 20; SimpleType expected = prototype(SimpleType.class); expect(expected.getValue()).hasLength(expectedLength); expectThat(new SimpleType(aRandomString(differentLength))).matches(expected); } } <file_sep> package org.exparity.expectamundo.core.object; import java.util.Arrays; import java.util.Collection; import org.exparity.expectamundo.core.PropertyExpectation; import org.exparity.expectamundo.core.Prototype; import org.exparity.expectamundo.core.PrototypeValue; import org.exparity.expectamundo.core.PrototypeValueMatcher; import org.hamcrest.Matcher; /** * @author <NAME> */ public class PrototypeObjectExpectation<T> { private final Prototype<?> prototype; private final PrototypeValue value; public PrototypeObjectExpectation(final Prototype<?> prototype, final PrototypeValue property) { this.prototype = prototype; this.value = property; } /** * Set an expectation that the property value matches a hamcrest matcher. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.name()).matches(Matchers.equalTo(&quot;Jane&quot;)); * expectThat(actual).matches(expected); * </pre> * @param matcher the hamcrest matcher to use to match the item */ public void matches(final Matcher<T> matcher) { hasExpectation(new Matches<T>(matcher)); } /** * Set an expectation that the property value is equal to another object using the objects equals method. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.name()).isEqualTo(&quot;Jane&quot;); * expectThat(actual).matches(expected); * </pre> * @param expectedValue the value this property should be equal to */ public void isEqualTo(final T expectedValue) { hasExpectation(new IsEqualTo<T>(expectedValue)); } /** * Set an expectation that the property value is not equal to another object using the objects equals method. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.name()).isNotEqualTo(&quot;Jane&quot;); * expectThat(actual).matches(expected); * </pre> * @param expectedValue the value this property should not be equal to */ public void isNotEqualTo(final T expectedValue) { hasExpectation(new IsNotEqualTo<T>(expectedValue)); } /** * Set an expectation that the property value is equal to one of the expected object using the object's equals method. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.name()).isOneOf(&quot;Jane&quot;, &quot;Bob&quot;); * expectThat(actual).matches(expected); * </pre> * @param possibleValues the range of possible value this property should be one of */ @SuppressWarnings("unchecked") public void isOneOf(final T... possibleValues) { isOneOf(Arrays.asList(possibleValues)); } /** * Set an expectation that the property value is equal to one of the expected object using the object's equals method. For example</p> * * <pre> * List&lt;String&gt; options = Arrays.asList(&quot;Jane&quot;, &quot;Bob&quot;); * MyObject expected = prototype(MyObject.class); * expect(expected.name()).isOneOf(options); * expectThat(actual).matches(expected); * </pre> * @param possibleValues the range of possible value this property should be one of */ public void isOneOf(final Collection<T> possibleValues) { hasExpectation(new IsOneOf<T>(possibleValues)); } /** * Set an expectation that the property value is an instance of a type. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.name()).isInstanceOf(String.class); * expectThat(actual).matches(expected); * </pre> * @param expectedValue the type this property should be an instance of */ public void isInstanceOf(final Class<? extends T> expectedValue) { hasExpectation(new IsInstanceOf<T>(expectedValue)); } /** * Set an expectation that the object should be null. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.name()).isNull(); * expectThat(actual).matches(expected); * </pre> */ public void isNull() { hasExpectation(new IsNull<T>()); } /** * Set an expectation that the object should not be null. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.name()).isNotNull(); * expectThat(actual).matches(expected); * </pre> */ public void isNotNull() { hasExpectation(new IsNotNull<T>()); } /** * Set an expectation that the object should not be null. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.name()).isNotNull(); * expectThat(actual).matches(expected); * </pre> */ public void hasExpectation(final PropertyExpectation<T> expectation) { prototype.addExpectation(new PrototypeValueMatcher(value, expectation)); prototype.setActiveProperty(null); } } <file_sep>/** * */ package org.exparity.expectamundo.core; import net.sf.cglib.proxy.Callback; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import org.apache.commons.lang.ArrayUtils; import org.objenesis.Objenesis; import org.objenesis.ObjenesisStd; import org.objenesis.instantiator.ObjectInstantiator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Factory for creating a proxy instance * * @author <NAME> */ public class ProxyFactory { private static final Logger LOG = LoggerFactory.getLogger(ProxyFactory.class); public <T> T createProxy(final Class<T> rawType, final MethodInterceptor callback, final Class<?>... interfaces) { return createProxyInstance(createProxyType(rawType, callback, interfaces)); } private <T> T createProxyInstance(final Class<T> proxyType) { Objenesis instantiatorFactory = new ObjenesisStd(); ObjectInstantiator<T> instanceFactory = instantiatorFactory.getInstantiatorOf(proxyType); T instance = instanceFactory.newInstance(); LOG.debug("Produce Proxy Instance [{}] for [{}]", System.identityHashCode(instance), proxyType.getName()); return instance; } @SuppressWarnings("unchecked") private <T> Class<T> createProxyType(final Class<T> rawType, final MethodInterceptor callback, final Class<?>... interfaces) { Enhancer classFactory = new Enhancer(); if (rawType.isInterface()) { classFactory.setInterfaces((Class[]) ArrayUtils.add(interfaces, rawType)); } else { classFactory.setSuperclass(rawType); if (interfaces.length > 0) { classFactory.setInterfaces(interfaces); } } classFactory.setCallbackType(callback.getClass()); Class<T> proxyType = classFactory.createClass(); Enhancer.registerCallbacks(proxyType, new Callback[] { callback }); return proxyType; } } <file_sep>package org.exparity.expectamundo.core; import java.lang.reflect.Method; import net.sf.cglib.proxy.MethodProxy; /** * @author <NAME> */ public interface PrototypeInterceptor { Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy, Prototype<?> currentPrototype) throws Throwable; } <file_sep> package org.exparity.expectamundo.core.collection; import java.util.Collection; import org.exparity.expectamundo.core.PropertyExpectation; /** * @author <NAME> */ public class IsEmpty<E, T extends Collection<E>> implements PropertyExpectation<T> { @Override public boolean matches(final T actual) { return actual == null || actual.isEmpty(); } @Override public String describe() { return "is empty"; } } <file_sep>package org.exparity.expectamundo; import static java.util.Arrays.asList; import static java.util.Collections.singletonMap; import static org.exparity.expectamundo.Expectamundo.*; import static org.exparity.stub.random.RandomBuilder.aRandomByteArray; import static org.exparity.stub.random.RandomBuilder.aRandomInteger; import static org.exparity.stub.random.RandomBuilder.aRandomString; import static org.junit.Assert.assertEquals; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.exparity.expectamundo.core.PrototypeMatcherContext; import org.exparity.expectamundo.core.TypeReference; import org.exparity.expectamundo.testutils.types.BigDecimalReturnType; import org.exparity.expectamundo.testutils.types.BigIntegerReturnType; import org.exparity.expectamundo.testutils.types.GraphListReturnType; import org.exparity.expectamundo.testutils.types.GraphType; import org.exparity.expectamundo.testutils.types.HashCodeType; import org.exparity.expectamundo.testutils.types.ListReturnType; import org.exparity.expectamundo.testutils.types.MapReturnType; import org.exparity.expectamundo.testutils.types.ParameterizedListReturnType; import org.exparity.expectamundo.testutils.types.PolymorphicReturnType; import org.exparity.expectamundo.testutils.types.PolymorphicSubtype1; import org.exparity.expectamundo.testutils.types.PolymorphicSubtype2; import org.exparity.expectamundo.testutils.types.PrimitiveArrayType; import org.exparity.expectamundo.testutils.types.PrimitiveType; import org.exparity.expectamundo.testutils.types.SimpleType; import org.exparity.expectamundo.testutils.types.StringListReturnType; import org.exparity.expectamundo.testutils.types.ToStringType; import org.exparity.stub.random.RandomBuilder; import org.hamcrest.MatcherAssert; import org.junit.Test; /** * @author <NAME> */ public class ExpectamundoTest { @Test public void canMatchSimpleProperty() { final String expectedValue = aRandomString(5); SimpleType expected = prototype(SimpleType.class); expect(expected.getValue()).isEqualTo(expectedValue); expectThat(new SimpleType(expectedValue)).matches(expected); } @Test(expected = AssertionError.class) public void canFailSimpleProperty() { final String expectedValue = aRandomString(5), differentValue = expectedValue + aRandomString(5); SimpleType expected = prototype(SimpleType.class); expect(expected.getValue()).isEqualTo(expectedValue); expectThat(new SimpleType(differentValue)).matches(expected); } @Test public void canMatchPrimitiveProperty() { final int expectedValue = aRandomInteger(); PrimitiveType expected = prototype(PrimitiveType.class); expect(expected.getValue()).isEqualTo(expectedValue); expectThat(new PrimitiveType(expectedValue)).matches(expected); } @Test(expected = AssertionError.class) public void canFailPrimitiveProperty() { final int expectedValue = aRandomInteger(), differentValue = expectedValue + aRandomInteger(); PrimitiveType expected = prototype(PrimitiveType.class); expect(expected.getValue()).isEqualTo(expectedValue); expectThat(new PrimitiveType(differentValue)).matches(expected); } @Test public void canMatchPrimitiveArrayProperty() { final byte[] expectedValue = aRandomByteArray(); PrimitiveArrayType expected = prototype(PrimitiveArrayType.class); expect(expected.getValue()).isEqualTo(expectedValue); expectThat(new PrimitiveArrayType(expectedValue)).matches(expected); } @Test(expected = AssertionError.class) public void canFailPrimitiveArrayProperty() { final byte[] expectedValue = aRandomByteArray(), differentValue = aRandomByteArray(); PrimitiveArrayType expected = prototype(PrimitiveArrayType.class); expect(expected.getValue()).isEqualTo(expectedValue); expectThat(new PrimitiveArrayType(differentValue)).matches(expected); } @Test public void canMatchObjectProperty() { final SimpleType expectedValue = new SimpleType(aRandomString(5)); GraphType expected = prototype(GraphType.class); expect(expected.getChild()).isEqualTo(expectedValue); expectThat(new GraphType(aRandomString(5), expectedValue)).matches(expected); } @Test public void canMatchBigDecimalProperty() { final BigDecimal expectedValue = new BigDecimal("10"); BigDecimalReturnType expected = prototype(BigDecimalReturnType.class); expect(expected.getValue()).isEqualTo(expectedValue); expectThat(new BigDecimalReturnType(expectedValue)).matches(expected); } @Test public void canMatchBigIntegerProperty() { final BigInteger expectedValue = new BigInteger("10"); BigIntegerReturnType expected = prototype(BigIntegerReturnType.class); expect(expected.getValue()).isEqualTo(expectedValue); expectThat(new BigIntegerReturnType(expectedValue)).matches(expected); } @Test(expected = AssertionError.class) public void canFailObjectProperty() { final SimpleType expectedValue = new SimpleType(aRandomString(5)), differentValue = new SimpleType(aRandomString(5)); GraphType expected = prototype(GraphType.class); expect(expected.getChild()).isEqualTo(expectedValue); expectThat(new GraphType(aRandomString(5), differentValue)).matches(expected); } @Test public void canMatchToStringProperty() { final String expectedValue = aRandomString(5); ToStringType expected = prototype(ToStringType.class); expect(expected.toString()).isEqualTo(expectedValue); expectThat(new ToStringType(expectedValue)).matches(expected); } @Test public void canMatchHashCodeProperty() { final int expectedValue = RandomBuilder.aRandomInteger(); HashCodeType expected = prototype(HashCodeType.class); expect(expected.hashCode()).isEqualTo(expectedValue); expectThat(new HashCodeType(expectedValue)).matches(expected); } @Test public void canMatchGraphProperties() { final String expectedValue = aRandomString(5); GraphType expected = prototype(GraphType.class); expect(expected.getValue()).isEqualTo(expectedValue); expect(expected.getChild().getValue()).isEqualTo(expectedValue); expectThat(new GraphType(expectedValue, new SimpleType(expectedValue))).matches(expected); } @Test(expected = AssertionError.class) public void canFailGraphProperty() { final String expectedValue = aRandomString(5), differentValue = expectedValue + aRandomString(5); GraphType expected = prototype(GraphType.class); expect(expected.getValue()).isEqualTo(expectedValue); expect(expected.getChild().getValue()).isEqualTo(expectedValue); expectThat(new GraphType(expectedValue, new SimpleType(differentValue))).matches(expected); } @Test(expected = AssertionError.class) public void canFailNullGraphProperty() { final String expectedValue = aRandomString(5), differentValue = expectedValue + aRandomString(5); GraphType expected = prototype(GraphType.class); expect(expected.getValue()).isEqualTo(expectedValue); expect(expected.getChild().getValue()).isEqualTo(expectedValue); expectThat(new GraphType(differentValue, null)).matches(expected); } @Test public void canMatchGenericSubclass() { final String expectedValue = aRandomString(5); StringListReturnType expected = prototype(StringListReturnType.class); expect(expected.getValue().get(0)).isEqualTo(expectedValue); expectThat(new StringListReturnType(Arrays.asList(expectedValue))).matches(expected); } @Test(expected = IllegalArgumentException.class) public void canThrowExceptionIfPrototypingGenericType() { prototype(ParameterizedListReturnType.class); } @Test public void canMatchGenericProperties() { final String expectedValue = aRandomString(5); List<String> expected = prototype(new TypeReference<List<String>>() {}); expect(expected.get(0)).isEqualTo(expectedValue); List<String> actual = Arrays.asList(expectedValue); expectThat(actual).matches(expected); } @Test(expected = AssertionError.class) public void canFailGenericProperties() { final String expectedValue = aRandomString(5), differentValue = expectedValue + aRandomString(5); List<String> expected = prototype(new TypeReference<List<String>>() {}); expect(expected.get(0)).isEqualTo(expectedValue); List<String> actual = Arrays.asList(differentValue); expectThat(actual).matches(expected); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test(expected = IllegalArgumentException.class) public void canFailGenericPropertiesIfTypeNotPassed() { prototype(new TypeReference() {}); } @Test public void canMatchSimpleListProperty() { final List<String> expectedValue = Arrays.asList(aRandomString(5)); ListReturnType expected = prototype(ListReturnType.class); expect(expected.getValue().get(0)).isEqualTo(expectedValue.get(0)); expectThat(new ListReturnType(expectedValue)).matches(expected); } @Test(expected = AssertionError.class) public void canFailSimpleListProperty() { final String expectedString = aRandomString(5); final List<String> expectedValue = Arrays.asList(expectedString), differentValue = Arrays.asList(expectedString + aRandomString(5)); ListReturnType expected = prototype(ListReturnType.class); expect(expected.getValue().get(0)).isEqualTo(expectedValue.get(0)); expectThat(new ListReturnType(differentValue)).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfSimpleListPropertySmaller() { final String expectedString = aRandomString(5); final List<String> expectedValue = Arrays.asList(expectedString); ListReturnType expected = prototype(ListReturnType.class); expect(expected.getValue().get(0)).isEqualTo(expectedString); expect(expected.getValue().get(1)).isEqualTo(expectedString); expectThat(new ListReturnType(expectedValue)).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfSimpleListPropertyEmpty() { final String expectedString = aRandomString(5); ListReturnType expected = prototype(ListReturnType.class); expect(expected.getValue().get(0)).isEqualTo(expectedString); expect(expected.getValue().get(1)).isEqualTo(expectedString); List<String> actualValue = new ArrayList<>(); expectThat(new ListReturnType(actualValue)).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfSimpleListPropertyNull() { final String expectedString = aRandomString(5); ListReturnType expected = prototype(ListReturnType.class); expect(expected.getValue().get(0)).isEqualTo(expectedString); expect(expected.getValue().get(1)).isEqualTo(expectedString); List<String> actualValue = null; expectThat(new ListReturnType(actualValue)).matches(expected); } @Test public void canMatchGraphListProperty() { final String expectedValue = aRandomString(5); GraphListReturnType expected = prototype(GraphListReturnType.class); expect(expected.getValue().get(0).getValue()).isEqualTo(expectedValue); expect(expected.getValue().get(0).getChild().getValue()).isEqualTo(expectedValue); GraphListReturnType actual = new GraphListReturnType(new GraphType(expectedValue, new SimpleType(expectedValue))); expectThat(actual).matches(expected); } @Test(expected = AssertionError.class) public void canFailGraphListProperty() { final String expectedValue = aRandomString(5), otherValue = expectedValue + expectedValue; GraphListReturnType expected = prototype(GraphListReturnType.class); expect(expected.getValue().get(0).getValue()).isEqualTo(expectedValue); expect(expected.getValue().get(0).getChild().getValue()).isEqualTo(expectedValue); GraphListReturnType actual = new GraphListReturnType(new GraphType(otherValue, new SimpleType(otherValue))); expectThat(actual).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfGraphListPropertySmaller() { final String expectedValue = aRandomString(5), expectedValue2 = expectedValue + expectedValue; GraphListReturnType expected = prototype(GraphListReturnType.class); expect(expected.getValue().get(0).getValue()).isEqualTo(expectedValue); expect(expected.getValue().get(0).getChild().getValue()).isEqualTo(expectedValue); expect(expected.getValue().get(1).getValue()).isEqualTo(expectedValue2); expect(expected.getValue().get(1).getChild().getValue()).isEqualTo(expectedValue2); GraphListReturnType actual = new GraphListReturnType(new GraphType(expectedValue, new SimpleType(expectedValue))); expectThat(actual).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfGraphListPropertyEmpty() { final String expectedValue = aRandomString(5); GraphListReturnType expected = prototype(GraphListReturnType.class); expect(expected.getValue().get(0).getValue()).isEqualTo(expectedValue); expect(expected.getValue().get(0).getChild().getValue()).isEqualTo(expectedValue); GraphListReturnType actual = new GraphListReturnType(); expectThat(actual).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfGraphListPropertyNull() { final String expectedValue = aRandomString(5); GraphListReturnType expected = prototype(GraphListReturnType.class); expect(expected.getValue().get(0).getValue()).isEqualTo(expectedValue); expect(expected.getValue().get(0).getChild().getValue()).isEqualTo(expectedValue); GraphListReturnType actual = null; expectThat(actual).matches(expected); } @Test public void canMatchParameterizedListProperty() { final String expectedValue = aRandomString(5); ParameterizedListReturnType<String> expected = prototype(new TypeReference<ParameterizedListReturnType<String>>() {}); expect(expected.getValue().get(0)).isEqualTo(expectedValue); ParameterizedListReturnType<String> actual = new ParameterizedListReturnType<String>(expectedValue); expectThat(actual).matches(expected); } @Test(expected = AssertionError.class) public void canFailParameterizedListProperty() { final String expectedValue = aRandomString(5), otherValue = expectedValue + expectedValue; ParameterizedListReturnType<String> expected = prototype(new TypeReference<ParameterizedListReturnType<String>>() {}); expect(expected.getValue().get(0)).isEqualTo(expectedValue); ParameterizedListReturnType<String> actual = new ParameterizedListReturnType<String>(otherValue); expectThat(actual).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfParameterizedListPropertySmaller() { final String expectedValue = aRandomString(5), expectedValue2 = expectedValue + expectedValue; ParameterizedListReturnType<String> expected = prototype(new TypeReference<ParameterizedListReturnType<String>>() {}); expect(expected.getValue().get(0)).isEqualTo(expectedValue); expect(expected.getValue().get(1)).isEqualTo(expectedValue2); ParameterizedListReturnType<String> actual = new ParameterizedListReturnType<String>(expectedValue); expectThat(actual).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfParameterizedListPropertyEmpty() { final String expectedValue = aRandomString(5); ParameterizedListReturnType<String> expected = prototype(new TypeReference<ParameterizedListReturnType<String>>() {}); expect(expected.getValue().get(0)).isEqualTo(expectedValue); ParameterizedListReturnType<String> actual = new ParameterizedListReturnType<String>(); expectThat(actual).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfParameterizedListPropertyNull() { final String expectedValue = aRandomString(5); ParameterizedListReturnType<String> expected = prototype(new TypeReference<ParameterizedListReturnType<String>>() {}); expect(expected.getValue().get(0)).isEqualTo(expectedValue); ParameterizedListReturnType<String> actual = null; expectThat(actual).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfListOfObjectsSmaller() { final String expectedString = aRandomString(5), secondString = aRandomString(5); final List<SimpleType> expectedList = Arrays.asList(new SimpleType(expectedString)); final List<SimpleType> expected = prototype(new TypeReference<List<SimpleType>>() {}); expect(expected.get(0).getValue()).isEqualTo(expectedString); expect(expected.get(1).getValue()).isEqualTo(secondString); expectThat(expectedList).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfListOfObjectsEmpty() { final String expectedString = aRandomString(5); final List<SimpleType> expected = prototype(new TypeReference<List<SimpleType>>() {}); expect(expected.get(0).getValue()).isEqualTo(expectedString); List<SimpleType> actualList = new ArrayList<>(); expectThat(actualList).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfListOfObjectsNull() { final String expectedString = aRandomString(5); final List<SimpleType> expected = prototype(new TypeReference<List<SimpleType>>() {}); expect(expected.get(0).getValue()).isEqualTo(expectedString); List<SimpleType> actualList = null; expectThat(actualList).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfListOfGraphObjectsEmpty() { String expectedString = aRandomString(5); List<GraphType> expected = prototype(new TypeReference<List<GraphType>>() {}); expect(expected.get(0).getValue()).isEqualTo(expectedString); expect(expected.get(0).getChild().getValue()).isEqualTo(expectedString); List<GraphType> actualList = new ArrayList<>(); expectThat(actualList).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfListOfGraphObjectsNull() { String expectedString = aRandomString(5); List<GraphType> expected = prototype(new TypeReference<List<GraphType>>() {}); expect(expected.get(0).getValue()).isEqualTo(expectedString); expect(expected.get(0).getChild().getValue()).isEqualTo(expectedString); List<GraphType> actualList = null; expectThat(actualList).matches(expected); } @Test(expected = AssertionError.class) public void canFailIfListOfGraphObjectsSmaller() { final String expectedString = aRandomString(5), secondString = aRandomString(5); final List<GraphType> expected = prototype(new TypeReference<List<GraphType>>() {}); expect(expected.get(0).getValue()).isEqualTo(expectedString); expect(expected.get(0).getChild().getValue()).isEqualTo(expectedString); expect(expected.get(1).getValue()).isEqualTo(secondString); expect(expected.get(1).getChild().getValue()).isEqualTo(secondString); List<GraphType> actualList = asList(new GraphType(expectedString, new SimpleType(expectedString))); expectThat(actualList).matches(expected); } @Test public void canMatchMapProperties() { String key = aRandomString(5), value = aRandomString(5); MapReturnType expected = prototype(MapReturnType.class); expect(expected.getValue().get(key)).isEqualTo(value); expectThat(new MapReturnType(Collections.singletonMap(key, value))).matches(expected); } @Test(expected = AssertionError.class) public void canFailMapPropertiesBadKey() { String key = aRandomString(5), value = aRandomString(5), aDifferentKey = aRandomString(5); MapReturnType expected = prototype(MapReturnType.class); expect(expected.getValue().get(key)).isEqualTo(value); expectThat(new MapReturnType(singletonMap(aDifferentKey, value))).matches(expected); } @Test(expected = AssertionError.class) public void canFailMapPropertiesBadValue() { String key = aRandomString(5), value = aRandomString(5), aDifferentValue = aRandomString(5); MapReturnType expected = prototype(MapReturnType.class); expect(expected.getValue().get(key)).isEqualTo(value); expectThat(new MapReturnType(singletonMap(key, aDifferentValue))).matches(expected); } @Test(expected = IllegalArgumentException.class) public void canFailIfSettingExpectationOnNormalInstance() { PrototypeMatcherContext.setCurrentPrototype(null); final String expectedValue = aRandomString(5); SimpleType expected = new SimpleType(expectedValue); expect(expected.getValue()).isEqualTo(expectedValue); } @Test public void canMatchUsingHamcrest() { String expectedValue = aRandomString(5); SimpleType expected = prototype(SimpleType.class); expect(expected.getValue()).isEqualTo(expectedValue); SimpleType actual = new SimpleType(expectedValue); MatcherAssert.assertThat(actual, matchesPrototype(expected)); } @Test(expected = AssertionError.class) public void canFailUsingHamcrest() { String expectedValue = aRandomString(5), differentValue = expectedValue + aRandomString(5); SimpleType expected = prototype(SimpleType.class); expect(expected.getValue()).isEqualTo(expectedValue); SimpleType actual = new SimpleType(differentValue); MatcherAssert.assertThat(actual, matchesPrototype(expected)); } @Test(expected = IllegalArgumentException.class) public void canFailUsingHamcrestOnNormalInstance() { SimpleType actual = new SimpleType(aRandomString(5)); MatcherAssert.assertThat(actual, matchesPrototype(new SimpleType(aRandomString(5)))); } @Test(expected = IllegalArgumentException.class) public void canFailIfVerifyingExpectationOnNormalInstance() { SimpleType expected = new SimpleType(aRandomString(5)); expectThat(expected).matches(expected); } @Test(expected = IllegalArgumentException.class) public void canFailToMatchPrimitiveType() { prototype(byte.class); } @Test(expected = IllegalArgumentException.class) public void canFailIfPropertyExpectationNotSet() { SimpleType actual = new SimpleType(aRandomString(5)); expect(actual).isNull(); expectThat(actual).matches(new SimpleType(aRandomString(5))); } @Test public void canMatchIfPrototypeOverSeveralLines() { String expectedValue = aRandomString(5); GraphType expected = prototype(GraphType.class); SimpleType expectedProperty = expected.getChild(); expect(expectedProperty.getValue()).isEqualTo(expectedValue); expectThat(new GraphType(expectedValue, new SimpleType(expectedValue))).matches(expected); } @Test public void canMatchIfDifferentPrototypeOverSeveralLines() { String expectedValue = aRandomString(5); GraphType expected = prototype(GraphType.class); SimpleType expectedProperty = prototype(SimpleType.class); expect(expected.getChild().getValue()).isEqualTo(expectedValue); expect(expectedProperty.getValue()).isEqualTo(expectedValue); expect(expected.getValue()).isEqualTo(expectedValue); expectThat(new GraphType(expectedValue, new SimpleType(expectedValue))).matches(expected); expectThat(new SimpleType(expectedValue)).matches(expectedProperty); } @Test public void canMatchPolymorphicTypes() { Integer expectedValue = aRandomInteger(); PolymorphicReturnType expected = prototype(PolymorphicReturnType.class); expect(cast(expected.getValue(), PolymorphicSubtype1.class).getValue()).isEqualTo(expectedValue); expectThat(new PolymorphicReturnType(new PolymorphicSubtype1(expectedValue))).matches(expected); } @Test(expected = ClassCastException.class) public void canFailIfPolymorphicTypes() { Integer expectedValue = aRandomInteger(); String differnentValue = aRandomString(5); PolymorphicReturnType expected = prototype(PolymorphicReturnType.class); expect(cast(expected.getValue(), PolymorphicSubtype1.class).getValue()).isEqualTo(expectedValue); expectThat(new PolymorphicReturnType(new PolymorphicSubtype2(differnentValue))).matches(expected); } @Test public void canVerifySimpleProperty() { final String expectedValue = aRandomString(5); SimpleType expected = prototype(SimpleType.class); expect(expected.getValue()).isEqualTo(expectedValue); assertEquals(checkThat(new SimpleType(expectedValue)).matches(expected), true); } @Test public void canFailVerificationOfSimpleProperty() { final String expectedValue = aRandomString(5), differentValue = expectedValue + aRandomString(5); SimpleType expected = prototype(SimpleType.class); expect(expected.getValue()).isEqualTo(expectedValue); assertEquals(checkThat(new SimpleType(differentValue)).matches(expected), false); } @Test public void canTestForAPrototype() { assertEquals(isPrototype(prototype(SimpleType.class)), true); } @Test public void canTestForNotAPrototype() { assertEquals(isPrototype(new SimpleType(aRandomString(5))), false); } @Test public void canTestForExpectationInACollection() { String value1 = aRandomString(5), value2 = value1 + aRandomString(5); List<SimpleType> listOfTypes = Arrays.asList(new SimpleType(value1), new SimpleType(value2)); SimpleType expected = prototype(SimpleType.class); expect(expected.getValue()).isEqualTo(value1); expectThat(listOfTypes).contains(expected); } @Test(expected = AssertionError.class) public void canTestForExpectationNotInACollection() { String value1 = aRandomString(5), value2 = value1 + aRandomString(2), value3 = value2 + aRandomString(3); List<SimpleType> listOfTypes = Arrays.asList(new SimpleType(value1), new SimpleType(value2)); SimpleType expected = prototype(SimpleType.class); expect(expected.getValue()).isEqualTo(value3); expectThat(listOfTypes).contains(expected); } @Test public void canMatchAPrototype() { String value = aRandomString(); List<String> expected = prototype(new TypeReference<List<String>>() {}); expect(expected).contains(value); expectThat(Arrays.asList(value)).matches(expected); } } <file_sep> package org.exparity.expectamundo.core.comparable; import org.exparity.expectamundo.core.Prototype; import org.exparity.expectamundo.core.PrototypeValue; import org.exparity.expectamundo.core.object.PrototypeObjectExpectation; /** * @author <NAME> */ public class PrototypeComparableExpectation<T extends Comparable<T>> extends PrototypeObjectExpectation<T> { public PrototypeComparableExpectation(final Prototype<?> prototype, final PrototypeValue property) { super(prototype, property); } /** * Set an expectation that the property value is comparable to a value. For example</p> * * <pre> * MyObject expected = prototype(MyObject.class); * expect(expected.number()).isComparableTo(new BigDecimal("1.01");; * expectThat(actual).matches(expected); * </pre> * @param expectedValue the type this property should be comparable to */ public void isComparableTo(final T expectedValue) { hasExpectation(new IsComparableTo<T>(expectedValue)); } } <file_sep>package org.exparity.expectamundo.testutils.types; import java.util.Arrays; import java.util.List; /** * @author <NAME> */ public class ParameterizedListReturnType<T> { private final List<T> value; public ParameterizedListReturnType(final List<T> value) { this.value = value; } @SafeVarargs public ParameterizedListReturnType(final T... values) { this(Arrays.asList(values)); } public List<T> getValue() { return value; } } <file_sep> package org.exparity.expectamundo.testutils.types; /** * @author <NAME> */ public class PrimitiveType { private final int value; public PrimitiveType(final int value) { this.value = value; } public int getValue() { return value; } } <file_sep> package org.exparity.expectamundo.testutils.types; import java.util.List; /** * @author <NAME> */ public class StringListReturnType extends ParameterizedListReturnType<String> { public StringListReturnType(final List<String> value) { super(value); } } <file_sep> package org.exparity.expectamundo.testutils.types; /** * @author <NAME> */ public class GraphType { private final String value; private final SimpleType child; public GraphType(final String value, final SimpleType child) { this.value = value; this.child = child; } public String getValue() { return value; } public SimpleType getChild() { return child; } }
7cd5c4e6e0480ec881cd54bf0b9c74821ebb9a4d
[ "Markdown", "Java" ]
31
Java
eXparity/expectamundo
de22924a5d1483ec5c087d0db2b2b28e6f47dcfb
828c6311cda5cb69384e1aa064a236f9a4b3da6c