text:
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawner : MonoBehaviour
{
    public GameObject ball;
    public GameObject cube;
    public Transform spawnPoint;
    Vector3 myVector;

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            spawnBall(1);
        }
        if(Input.GetKeyDown(KeyCode.C))
        {
            spawnCube(1);
        }
        if(Input.GetKeyDown(KeyCode.M))
        {
            spawnCube(5);
            spawnBall(10);
        }
    }

    void spawnBall(int num)
    {
        for (int i = 0; i < num; i++)
        {
            myVector = new Vector3(Random.Range(spawnPoint.position.x + 1, spawnPoint.position.x - 1), spawnPoint.position.y, Random.Range(spawnPoint.position.z + 1, spawnPoint.position.z - 1));
            Instantiate(ball, myVector, spawnPoint.rotation);
        }
    }
    void spawnCube(int num)
    {
        for (int i = 0; i < num; i++)
        {
            myVector = new Vector3(Random.Range(spawnPoint.position.x + 1, spawnPoint.position.x - 1), spawnPoint.position.y, Random.Range(spawnPoint.position.z + 1, spawnPoint.position.z - 1));
            Instantiate(cube, myVector, Quaternion.identity);
        }
    }
}
<file_sep>using Leap;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor;
using UnityEngine;

[System.Serializable]
public struct Gesture
{
    public string name;
    public Vector3[] fingerPositions;
}

public class Spinner : MonoBehaviour
{

    public string currentGestureName;

    public float tolerance;
    public Vector3[] leftHandPos = new Vector3[15];
    public Vector3[] rightHandPos = new Vector3[15];
    public bool saveActive = true;

    public List<Gesture> gestureList;

    float smooth = 5.0f;
    float tiltAngle = 60.0f;

    float xPos, yPos, zPos;

    Transform Palm;

    // Update is called once per frame
    void Update()
    {
        try
        {
            if (gameObject.name == "cubeLeft")
            {
                Palm = GameObject.Find("InteractionHand_L").transform.Find("Palm Transform");
            }
            else
            {
                Palm = GameObject.Find("InteractionHand_R").transform.Find("Palm Transform");
            }
            // print("POS " + Palm.transform.position);
            // print("POS " + Palm.transform.position.x);
            xPos = Palm.transform.position.x;
            yPos = Palm.transform.position.y;
            zPos = Palm.transform.position.z;
        }
        catch
        {}

        // if xPos
        // Smoothly tilts a transform towards a target rotation.
        float tiltAroundZ = xPos * tiltAngle;
        float tiltAroundX = -zPos * tiltAngle;

        // Rotate the cube by converting the angles into a quaternion.
        Quaternion target = Quaternion.Euler(tiltAroundX, 0, tiltAroundZ);

        // Dampen towards the target rotation
        transform.rotation = Quaternion.Slerp(transform.rotation, target,  Time.deltaTime * smooth);

        // if (Input.GetKeyDown(KeyCode.U))
        // {
        //     // Rotate the cube by converting the angles into a quaternion.
        //     Quaternion target = Quaternion.Euler(0, 0, 0);

        //     // Dampen towards the target rotation
        //     transform.rotation = Quaternion.Slerp(transform.rotation, target,  Time.deltaTime * smooth);
        // }

    }
}
<file_sep>// using Leap;
// using System.Collections;
// using System.Collections.Generic;
// using TMPro;
// using UnityEditor;
// using UnityEngine;

// [System.Serializable]
// public struct Gesture
// {
//     public string name;
//     public Vector3[] fingerPositions;
// }

// public class gestureDetector : MonoBehaviour
// {
//     public string currentGestureName;

//     public float tolerance;
//     public Vector3[] leftHandPos = new Vector3[15];
//     public Vector3[] rightHandPos = new Vector3[15];
//     public bool saveActive = true;

//     public List<Gesture> gestureList;

//     // Update is called once per frame
//     void Update()
//     {
//         if (Input.GetKeyDown(KeyCode.S) && saveActive)
//         {
//             // SaveL();
//             SaveR();
//             print("saved");
//         }

//         //left hand
//         // try
//         // {
//         //     var leftHand = GameObject.Find("Interaction Hand (Left)");
//         //     LeftHandPos(leftHand);
//         //     SetCurrentGesture(leftHand);
//         //     DrawGestureName();
//         // }
//         // catch
//         // {}

//         // var testPlane = GameObject.Find("Plane");
//         // print(testPlane.transform.position);
//         // var testPlane1 = GameObject.Find("PlaneGrandChild");
//         // print(testPlane1.transform.position);

//         try
//         {
//             // var rightHand = GameObject.Find("InteractionHand_R");
//             var testPlane = GameObject.Find("Palm Transform");
//             print("POS " + testPlane.transform.position);
//             // var rightHand = transform.Find("Interaction Manager/InteractionHand_R/Palm Transform").gameObject;
//             // print(rightHand);
//             // RightHandPos(rightHand);
//             // SetCurrentGesture(rightHand);
//             // DrawGestureName();
//         }
//         catch
//         {}

//     }

//     void DrawGestureName()
//     {
//         // TextMeshPro leftHand = GameObject.Find("LeftGestureName").GetComponent<TextMeshPro>();
//         // leftHand.text = currentGestureName;

//         TextMeshPro rightHand = GameObject.Find("RightGestureName").GetComponent<TextMeshPro>();
//         rightHand.text = currentGestureName;
//     }

//     void SetCurrentGesture(GameObject rightHand)
//     {
//         foreach (Gesture gesture in gestureList)
//         {
//             bool tooFar = false;
//             float totalDiff = 0;

//             for (int i = 0; i < 15; i++)
//             {
//                 Vector3 thisBone = rightHand.transform.InverseTransformPoint(rightHandPos[i]);
//                 float difference = Vector3.Distance(thisBone, gesture.fingerPositions[i]);

//                 if (difference > tolerance)
//                 {
//                     tooFar = true;
//                     break;
//                 }

//                 totalDiff += difference;
//             }

//             if (!tooFar && totalDiff < tolerance)
//             {
//                 currentGestureName = gesture.name;
//             }
//             else
//             {
//                 currentGestureName = "Not Sure";
//             }
//         }
//     }

//     // void LeftHandPos(GameObject leftHand)
//     // {
//     //     int counter = 0;
//     //     for (int i = 0; i < 5; i++)
//     //     {
//     //         Transform finger = leftHand.transform.GetChild(i);

//     //         for (int j = 0; j < 3; j++)
//     //         {
//     //             leftHandPos[counter] = finger.GetChild(j).transform.position;
//     //             counter++;
//     //         }
//     //     }
//     // }
//     void RightHandPos(GameObject rightHand)
//     {
//         int counter = 0;
//         for (int i = 0; i < 5; i++)
//         {
//             Transform finger = rightHand.transform.GetChild(i);

//             for (int j = 0; j < 3; j++)
//             {
//                 rightHandPos[counter] = finger.GetChild(j).transform.position;
//                 counter++;
//             }
//         }
//     }

//     void SaveL()
//     {
//         var tempGesture = new Gesture();
//         tempGesture.name = "Custom Gesture " + (gestureList.Count - 1);

//         try
//         {
//             var leftHand = GameObject.Find("RigidRoundHand_L");
//             Vector3[] tempPos = new Vector3[15];
//             int counter = 0;

//             for (int i = 0; i < 5; i++)
//             {
//                 Transform finger = leftHand.transform.GetChild(i);

//                 for (int j = 0; j < 3; j++)
//                 {
//                     tempPos[counter] = finger.GetChild(j).transform.position;
//                     counter++;
//                 }
//             }

//             tempGesture.fingerPositions = tempPos;

//             gestureList.Add(tempGesture);
//         }
//         catch (System.Exception)
//         {

//         }

//     }

//     void SaveR()
//     {
//         var tempGesture = new Gesture();
//         tempGesture.name = "Custom Gesture " + (gestureList.Count - 1);

//         try
//         {
//             var rightHand = GameObject.Find("RigidRoundHand_R");
//             Vector3[] tempPos = new Vector3[15];
//             int counter = 0;

//             for (int i = 0; i < 5; i++)
//             {
//                 Transform finger = rightHand.transform.GetChild(i);

//                 for (int j = 0; j < 3; j++)
//                 {
//                     tempPos[counter] = finger.GetChild(j).transform.position;
//                     counter++;
//                 }
//             }

//             tempGesture.fingerPositions = tempPos;

//             gestureList.Add(tempGesture);
//         }
//         catch (System.Exception)
//         {

//         }

//     }
// }
<file_sep>using Leap;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor;
using UnityEngine;

public class fingerPointing : MonoBehaviour
{

    public float tolerance;
    public List<Gesture> gestureList;

    float xPos, yPos, zPos;

    Transform Palm;
    Transform thumbFinger;
    Transform pinkyFinger;

    Vector3 thumbPos, pinkyPos;
    Vector3 PreviousLeastPosition = new Vector3(100000f, 10000f, 10000f);
    Vector3 initialPos = new Vector3(0f, 0f, 0f);

    float subtractionX = 0;
    float subtractionY = 0;

    float i = 0;

    void Start() {

        // Thumb is Fingertip Transform 1
        // Pinky is Fingertip Transform 5
        thumbFinger = GameObject.Find("InteractionHand_L").transform.Find("Fingertip Transform 1");
        pinkyFinger = GameObject.Find("InteractionHand_L").transform.Find("Fingertip Transform 5");
    }

    // Update is called once per frame
    void Update()
    {
        try
        {

            thumbPos = thumbFinger.transform.position;
            pinkyPos = pinkyFinger.transform.position;

            subtractionX = thumbPos.x - pinkyPos.x;
            subtractionY = thumbPos.y - pinkyPos.y;

            // print(subtractionY);

            // if (thumbPos != initialPos)
            // {

            // }

            if (Input.GetKeyDown(KeyCode.X))
            {

            }

        }
        catch
        {}
    }
}
<file_sep>using Leap;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor;
using UnityEngine;
using System;

public class swipeDetector : MonoBehaviour
{
    public List<float> positionListX = new List<float>();
    public List<float> positionListY = new List<float>();

    Transform Palm;
    Transform thumbFinger;
    Transform pinkyFinger;

    Vector3 palmPos, IndexPos;
    Vector3 thumbPos, pinkyPos;

    Vector3 initialPos = new Vector3(0f, 0f, 0f);

    float subtractionX = 0;
    float subtractionY = 0;

    public float timeBetweenDetectionsX = 0.25f;
    public float timeBetweenDetectionsY = 0.25f;

    double difference = 0.15;

    void Start() {

        // IndexFinger is Fingertip Transform 2
        // MiddleFinger is Fingertip Transform 3
        // IndexFinger = GameObject.Find("InteractionHand_L").transform.Find("Fingertip Transform 2");
    }

    void Update()
    {
        try
        {
            Palm = GameObject.Find("InteractionHand_L").transform.Find("Palm Transform");
            palmPos = Palm.transform.position;

            thumbFinger = GameObject.Find("InteractionHand_L").transform.Find("Fingertip Transform 1");
            pinkyFinger = GameObject.Find("InteractionHand_L").transform.Find("Fingertip Transform 5");

            thumbPos = thumbFinger.transform.position;
            pinkyPos = pinkyFinger.transform.position;

            subtractionX = thumbPos.x - pinkyPos.x;
            subtractionY = thumbPos.y - pinkyPos.y;

            if (thumbPos != initialPos)
            {
                // Check if the hand is sideways
                // if (subtractionY < -0.07 && subtractionY > -0.12)
                if (subtractionY > 0.1)
                {

                    if (timeBetweenDetectionsX > 0)
                    {
                        timeBetweenDetectionsX -= Time.deltaTime;

                        if (timeBetweenDetectionsX <= 0)
                        {
                            positionListX.Add(palmPos.x);
                            // print(positionListX.Count);

                            timeBetweenDetectionsX = 0.25f;

                            if (positionListX.Count > 1)
                            {
                                if (positionListX[1] - positionListX[0] > difference)
                                {
                                    print("SwipeRight");

                                    var cylinderRenderer = this.GetComponent<Renderer>();
                                    cylinderRenderer.material.SetColor("_Color", Color.red);
                                }

                                else if (positionListX[0] - positionListX[1] > difference)
                                {
                                    print("SwipeLeft");

                                    var cylinderRenderer = this.GetComponent<Renderer>();
                                    cylinderRenderer.material.SetColor("_Color", Color.blue);
                                }
                                positionListX.Clear();
                            }
                        }
                    }

                }
                // Hand facing up
                else if (subtractionX > -0.4 && subtractionX < -0.2)
                {
                    if (timeBetweenDetectionsY > 0)
                    {
                        timeBetweenDetectionsY -= Time.deltaTime;

                        if (timeBetweenDetectionsY <= 0)
                        {
                            positionListY.Add(palmPos.y);
                            // print(positionListX.Count);

                            timeBetweenDetectionsY = 0.25f;
                            if (positionListY.Count > 1)
                            {
                                if (positionListY[1] - positionListY[0] > difference)
                                {
                                    print("SwipeUp");

                                    // var cylinderRenderer = this.GetComponent<Renderer>();
                                    // cylinderRenderer.material.SetColor("_Color", Color.red);
                                }

                                // else if (positionListY[0] - positionListY[1] > difference)
                                // {
                                //     print("SwipeDown");

                                //     // var cylinderRenderer = this.GetComponent<Renderer>();
                                //     // cylinderRenderer.material.SetColor("_Color", Color.blue);
                                // }
                                positionListY.Clear();
                            }
                        }
                    }
                }
                // Hand facing down
                else if (subtractionX < 0.4 && subtractionX > 0.2 && subtractionY >-0.07)
                {
                    if (timeBetweenDetectionsY > 0)
                    {
                        timeBetweenDetectionsY -= Time.deltaTime;

                        if (timeBetweenDetectionsY <= 0)
                        {
                            positionListY.Add(palmPos.y);
                            // print(positionListX.Count);

                            timeBetweenDetectionsY = 0.25f;
                            if (positionListY.Count > 1)
                            {
                                // if (positionListY[1] - positionListY[0] > difference)
                                // {
                                //     print("SwipeUp");

                                //     // var cylinderRenderer = this.GetComponent<Renderer>();
                                //     // cylinderRenderer.material.SetColor("_Color", Color.red);
                                // }

                                if (positionListY[0] - positionListY[1] > difference)
                                {
                                    print("SwipeDown");

                                    // var cylinderRenderer = this.GetComponent<Renderer>();
                                    // cylinderRenderer.material.SetColor("_Color", Color.blue);
                                }
                                positionListY.Clear();
                            }
                        }
                    }
                }
            }

        }
        catch
        {}
    }
}<file_sep>using Leap;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor;
using UnityEngine;
using System;

// [System.Serializable]
// public struct Gesture
// {
//     public string name;
//     public Vector3[] fingerPositions;
// }

public class grabSpin : MonoBehaviour
{

    Transform Palm;
    Transform IndexFinger;

    Vector3 palmPos, IndexPos;
    Vector3 initialPos = new Vector3(0f, 0f, 0f);

    float tiltAroundZ;
    public float tiltAngle = 360.0f;
    float smooth = 5.0f;

    GameObject targetObj;
    GameObject targetObj2;

    double distanceBW;

    void Start() {
        targetObj = GameObject.Find("grabSpin");
        targetObj2 = GameObject.Find("car 1203 blue");

        // IndexFinger is Fingertip Transform 2
        // MiddleFinger is Fingertip Transform 3
        Palm = GameObject.Find("InteractionHand_L").transform.Find("Palm Transform");
        IndexFinger = GameObject.Find("InteractionHand_L").transform.Find("Fingertip Transform 2");
    }

    void Update()
    {
        try
        {
            palmPos = Palm.transform.position;
            IndexPos = IndexFinger.transform.position;

            if (palmPos != initialPos)
            {
                // Finding dist b/w Index finger and palm using 3D coordinate geometry
                distanceBW = Math.Sqrt(Math.Pow((palmPos.x - IndexPos.x), 2) + Math.Pow((palmPos.y - IndexPos.y), 2) + Math.Pow((palmPos.z - IndexPos.z), 2));

                if (distanceBW < 0.08 && distanceBW > 0.06)
                {
                    print("fist");

                    tiltAroundZ = palmPos.x * tiltAngle;

                    Quaternion target = Quaternion.Euler(0, -tiltAroundZ, 0);

                    // Dampen towards the target rotation
                    targetObj.transform.rotation = Quaternion.Slerp(transform.rotation, target,  Time.deltaTime * smooth);
                    targetObj2.transform.rotation = Quaternion.Slerp(transform.rotation, target,  Time.deltaTime * smooth);
                }
            }

        }
        catch
        {}
    }
}
<file_sep>// using System.Collections;
// using System.Collections.Generic;
// using UnityEngine;
// using Leap;

// public class GestureHands : MonoBehaviour
// {
//     Controller controller;

//     // Start is called before the first frame update
//     void Start()
//     {
//         controller = new Controller();
//         controller.EnableGesture(Gesture.GestureType.TYPESWIPE);
//         controller.Config.SetFloat("Gesture.Swipe.MinLength", 200.0f);
//         controller.Config.SetFloat("Gesture.Swipe.MinVelocity", 750f);
//         controller.Congig.Save();

//     }

//     // Update is called once per frame
//     void Update()
//     {
//         Frame frame = controller.Frame ();
//         GestureList gestures = frame.Gestures();

//         for (int i = 0; i < gestures.Count; i++)
//         {
//             Gesture gesture = gestures[i];

//             if(gesture.Type == Gesture.GestureType.TYPESWIPE)
//             {
//                 SwipeGesture Swipe = new SwipeGesture(gesture);
//                 Vector swipeDirection = Swipe.Direction;
//                 if(swipeDirection.x < 0)
//                 {
//                     print("LEFT");
//                 }
//                 else if (swipeDirection.x > 0)
//                 {
//                     print("RIGHT");
//                 }
//             }
//         }
//     }
// }

repo_language: C#

repo_name: SiddiqMohammed/LeapMotionTests


text:
<repo_name>plusevcoin/plusevcoin-old<file_sep>/README.md
PlusEVCoin (PEVC)
=================

Cryptocurrency of the poker community.

branch_name: refs/heads/master

repo_language: Markdown

repo_name: plusevcoin/plusevcoin-old


text:
<repo_name>jhilzheber/myapi<file_sep>/src/Controller/SubscriptionController.php
<?php

namespace App\Controller;

use App\Entity\Subscription;
use App\Repository\SubscriptionRepository;
use Doctrine\ORM\EntityManagerInterface;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;

class SubscriptionController extends AbstractFOSRestController
{
    private $subscriptionRepository;
    private $em;

    public function __construct(SubscriptionRepository $subscriptionRepository,EntityManagerInterface $entityManager )
    {
        $this->subscriptionRepository = $subscriptionRepository;
        $this->em = $entityManager;
    }

    /**
     * @Rest\Get("/api/subscription/{name}")
     * @param Subscription $subscription
     * @return \FOS\RestBundle\View\View
     */
    public function getApiSubscription(Subscription $subscription){
        return $this->view($subscription);
    }
    /**
     * @Rest\Get("/api/subscriptions")
     * @Rest\View(serializerGroups={"subscriptions"})
     */
    public function getApiSubscriptions (){
        $subscriptions = $this->subscriptionRepository ->findAll();
        return $this->view($subscriptions);
    }

    /**
     * @Rest\Post("/api/subscription")
     * @ParamConverter("subscription", converter="fos_rest.request_body")
     * @param Subscription $subscription
     * @return \FOS\RestBundle\View\View
     */
    public function postApiSubscription(Subscription $subscription)
    {
        $this->em->persist($subscription);
        $this->em->flush();
        return $this->view($subscription);
    }

    /**
     * @Rest\Patch("/api/subscription/{id}")
     * @param Subscription $subscription
     * @param Request $request
     * @return \FOS\RestBundle\View\View
     */
    public function patchApiSubscription(Subscription $subscription, Request $request){

        $name = $request->get('name');
        $slogan = $request->get('slogan');
        $url = $request->get('url');

        if($name !== null){
            $subscription->setName($name);
        }
        if($slogan !== null){
            $subscription->setSlogan($slogan);
        }
        if($url !== null){
            $subscription->setUrl($url);
        }
        $this->em->persist($subscription);
        $this->em->flush();
        return $this->view($subscription);
    }

    /**
     * @Rest\Delete("/api/subscription/{name}")
     * @param Subscription $subscription
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function deleteApiSubscription(Subscription $subscription){
        $this->em->remove($subscription);
        $this->em->flush();
        return $this->json('OK');
    }
}<file_sep>/src/Entity/Card.php
<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Expr\Value;
use Doctrine\ORM\Mapping as ORM;
use Swagger\Annotations as SWG;

/**
 * @ORM\Entity(repositoryClass="App\Repository\CardRepository")
 */
class Card
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @SWG\Property(description="The name of the card.")
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @SWG\Property(description="The creditCardType of the card.")
     * @ORM\Column(type="string", length=255)
     */
    private $creditCardType;

    /**
     * @SWG\Property(description="The creditCardNumber of the card.")
     * @ORM\Column(type="bigint")
     */
    private $creditCardNumber;

    /**
     * @SWG\Property(description="The currencyCode of the card.")
     * @ORM\Column(type="string", columnDefinition="ENUM ('EUR','USD','GBP')")
     */
    /**
     * private $currencyCode;
     */

    /**
     * @SWG\Property(description="The value of the card.")
     * @ORM\Column(type="integer", nullable=true)
     */
    private $value;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getCreditCardType(): ?string
    {
        return $this->creditCardType;
    }

    public function setCreditCardType(string $creditCardType): self
    {
        $this->creditCardType = $creditCardType;

        return $this;
    }

    public function getCreditCardNumber(): ?int
    {
        return $this->creditCardNumber;
    }

    public function setCreditCardNumber(int $creditCardNumber): self
    {
        $this->creditCardNumber = $creditCardNumber;

        return $this;
    }

    public function getCurrencyCode(): ?string
    {
        return $this->currencyCode;
    }

    public function setCurrencyCode(string $currencyCode): self
    {
        $this->currencyCode = $currencyCode;

        return $this;
    }

    public function getValue(?Value $value): ?int
    {
        $this->getValue($value<'100 000');
        $this->getValue($value>'0');
        return $this->value;
    }

    public function setValue(int $value): self
    {
        $this->setValue($value<'100 000');
        $this->setValue($value>'0');
        $this->value = $value;
        return $this;
    }

    public function setUser(?User $user): self
    {
        $this->user = $user;

        return $this;
    }

    public function getUser()
    {
        return $this->user;
    }
}
<file_sep>/fixtures/card.yml
## fixtures/card.yml
App\Entity\Card:
  card_1:
    name: Gold
    creditCardType: <creditCardType()>
    creditCardNumber: <creditCardNumber()>

  card_2:
    name: Green
    creditCardType: <creditCardType()>
    creditCardNumber: <creditCardNumber()>

  card_3:
    name: Black
    creditCardType: <creditCardType()>
    creditCardNumber: <creditCardNumber()><file_sep>/src/Controller/CardController.php
<?php

namespace App\Controller;

use App\Entity\Card;
use App\Repository\CardRepository;
use Doctrine\ORM\EntityManagerInterface;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;

class CardController extends AbstractFOSRestController
{
    private $cardRepository;
    private $em;

    public function __construct(CardRepository $cardRepository,EntityManagerInterface $entityManager )
    {
        $this->cardRepository = $cardRepository;
        $this->em = $entityManager;
    }

    /**
     * @Rest\Get("/api/card/{name}")
     * @param Card $card
     * @return \FOS\RestBundle\View\View
     */
    public function getApiCard(Card $card){
        return $this->view($card);
    }
    /**
     * @Rest\Get("/api/cards")
     * @Rest\View(serializerGroups={"cards"})
     */
    public function getApiCards (){
        $cards = $this->cardRepository ->findAll();
        return $this->view($cards);
    }

    /**
     * @Rest\Post("/api/card")
     * @ParamConverter("card", converter="fos_rest.request_body")
     * @param Card $card
     * @return \FOS\RestBundle\View\View
     */
    public function postApiCard(Card $card)
    {
        $this->em->persist($card);
        $this->em->flush();
        return $this->view($card);
    }

    /**
     * @Rest\Patch("/api/card/{id}")
     * @param Card $card
     * @param Request $request
     * @return \FOS\RestBundle\View\View
     */
    public function patchApiCard(Card $card, Request $request){

        $name = $request->get('name');
        $creditCardType = $request->get('creditCardType');
        $creditCardNumber = $request->get('creditCardNumber');
        $currencyCode = $request->get('currencyCode');
        $value = $request->get('value');
        $user = $request->get( 'user' );

        if($name !== null){
            $card->setName($name);
        }
        if($creditCardType !== null){
            $card->setCreditCardType($creditCardType);
        }
        if($creditCardNumber !== null){
            $card->setCreditCardNumber($creditCardNumber);
        }
        if($currencyCode !== null){
            $card->setCurrencyCode($currencyCode);
        }
        if($value !== null){
            $card->setValue($value);
        }
        $this->em->persist($card);
        $this->em->flush();
        return $this->view($card);
    }

    /**
     * @Rest\Delete("/api/card/{name}")
     * @param Card $card
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function deleteApiSubscription(Card $card){
        $this->em->remove($card);
        $this->em->flush();
        return $this->json('OK');
    }
}<file_sep>/src/Controller/AdminController.php
<?php

namespace App\Controller;

use App\Entity\User;
use App\Repository\SubscriptionRepository;
use App\Repository\CardRepository;
use App\Repository\UserRepository;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use Nelmio\ApiDocBundle\Annotation\Model;
use Nelmio\ApiDocBundle\Annotation\Security;
use Swagger\Annotations as SWG;
use Symfony\Component\Routing\Annotation\Route;

class AdminController extends AbstractFOSRestController
{
    /**
     * @Route("/admin", name="admin")
     * @param UserRepository $userRepository
     * @param SubscriptionRepository $subscriptionRepository
     * @param CardRepository $cardRepository
     */

    public function index(UserRepository $userRepository, SubscriptionRepository $subscriptionRepository, CardRepository $cardRepository)
    {
        $users = $userRepository->findAll();
        $subscriptions = $subscriptionRepository->findAll();
        $cards = $cardRepository->findAll();
    }
}<file_sep>/tests/UserControllerTest.php
<?php

namespace App\Tests;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class UserControllerTest extends WebTestCase
{
    public function testGetUsers()
    {
        $client = static::createClient();
        $client->request( 'GET', '/api/users', [], [], ['HTTP_ACCEPT' => 'application/json'] );
        $response = $client->getResponse();
        $content = $response->getContent();
        $this->assertEquals( 200, $response->getStatusCode() );
        $this->assertJson( $content );
        $arrayContent = \json_decode( $content, true );
        $this->assertCount( 10, $arrayContent );
    }

    public function testPostUsers ()
    {
        $client = static::createClient();
        $client->request('POST', '/api/user' , [], [],
            [
                'HTTP_ACCEPT' => 'application/json' ,
                'CONTENT_TYPE' => 'application/json' ,
                'HTTP_X-AUTH-TOKEN' => 'admin'
            ],
            '{"apiKey": "testPost","email": "<EMAIL>","firstname": "testPost", "lastname": "testPost","createdAt": "2017-05-12 00:00:00", "adress": "testPostAddress","country": "France", "subscription": "Premium", "card": "Gold"}'
        );
        $response = $client->getResponse ();
        $content = $response->getContent ();

        $this->assertEquals (200, $response->getStatusCode ());
        $this->assertJson ($content);
    }
}

languages: YAML PHP

repo_language: YAML

repo_name: jhilzheber/myapi


text:
<file_sep><?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Model\User;

class UserSeeder extends Seeder {

	public function run()
	{
	    DB::table('users')->delete();

        User::create(array(
            'email' => '<EMAIL>',
            'username' => 'TestAcct',
			'password' =>  Hash::make('<PASSWORD>'),
        ));

		User::create(array(
            'email' => '<EMAIL>',
            'username' => 'Test2',
			'password' =>  Hash::<PASSWORD>('<PASSWORD>'),
        ));
	}
}<file_sep><?php namespace App\Http\Controllers;

use Auth, View, Response, Input, File;
use App\Model\FollowingEvent;
use App\Model\Following;
use App\Model\User;
use App\Model\Files;
use App\Http\Requests\ProfileRequest;
use App\Model\Entities\Image;
use ValidationService;

class UserController extends Controller {
	/*
	|--------------------------------------------------------------------------
	| User Controller
	|--------------------------------------------------------------------------
	|
	| This controller handles the restful for user and makes the profile pages
	| It also handles profile uploads.
	|
	*/
	public function store()
	{
		//First we need to check if the user is logged in, if so, he can post.
		$success =  Response::json(array('success' => true));
		$fail =  Response::json(array('success' => false));
		//We also need to check whether a user has posted less than 140 characters.

		if(Auth::user() && count(Input::get('text')) > 0 &&  preg_match('/^[a-zA-Z ]*$/', Input::get('text')))
		{

			$alreadyFollowed = FollowingEvent::where("userid", '=', Auth::user()->id)
									->where("hashtag",'=', Input::get('text'))
									->first() != null;

			if($alreadyFollowed)
			{
				return Response::json(array('success'=>false, "error"=>"Already followed this event"));
			}

			$newFollowingEvent = FollowingEvent::create(array(
						"userid"=>Auth::user()->id,
						"hashtag"=>Input::get('text'),
					));

 			//here we check if the newpost entered the db, if it did then the newPost will have an id, otherwise it will not.
			return $newFollowingEvent->id ? $success : $fail;
		}

		//Otherwise, we'll return a fail response.
		return $fail;
	}

	public function userPage(User $user)
	{
		if($user->id == null)
		{
 			return View::make("errors.user");
		}
		$data['user'] = $user;

		return View::make('users.page', $data);
	}

	public function profilePage()
	{
		return View::make('users.fullprofile');
	}

	public function getCurrentUser()
	{
		 return Response::json(Auth::user());
	}

	public function getAllUsers()
	{
		return Response::json(User::allUsernames());
	}

	public function updateProfile(ProfileRequest $response)
	{
		$user = Auth::user();
		if($user)
		{
			$id = Input::file('profile') ?  $this->uploadImage(Input::file('profile')) : $user->files->id;
			$user->fill(array(
				"profileId" => $id,
				"biography" => Input::get('bio')
			));
			$user->save();
		}

		return redirect('/profile');
	}

	private function uploadImage($file)
	{
		$serverDir =  "uploaded_images/".Auth::user()->username;
		$dir = public_path($serverDir);

		$mb = 5;											// Valid Mega bytes.
		$validExt = array('mp4', 'png', 'jpg', 'gif');		// Valid file extensions.
		$validSize = $mb * pow(1024, 2 );      	 	// Valid image size in Mb.

		if( File::exists($dir) or File::makeDirectory($dir) )
		{
			$extension = $file->getClientOriginalExtension();
			$fileSize = $file->getSize();
			// Checks if the file extension is valid AND
			// if the image size doesn't exceeds the limit.
			if( in_array($extension, $validExt) && $fileSize <= $validSize )
			{
				$filename = 'profile.'.$extension;
			    $path = $dir."/".$filename;

				$file = new Image($file);
				$file->squareCrop(140);
				$file->getFileInstance()->move($dir,$filename);
				//Create an image with a url
				$newImage = Files::create(array(
						"url"=> ''.$serverDir.'/'.$filename
				));

				return $newImage->id;
			}
		}
		return null;
	}

	public function subscribePerson(User $user)
	{
		$success =  Response::json(array('success' => true));
		$fail =  Response::json(array('success' => false));

		$alreadyFollow = Following::where('userid', Auth::user())
								->where('followingid', $user->id)
								->first() != null;

		if($alreadyFollow)
		{
			return $fail;
		}

		$follow = Following::create(array(
			"userid" => Auth::user()->id,
			"followingid" => $user->id
		));

		return $follow->id ? $success : $fail;
	}

	// Unsubscribe a user:
	public function unsubscribePersone(User $user)
	{
		$success =  Response::json(array('success' => true));
		$fail =  Response::json(array('success' => false));

		$follow = Following::where('userid', '=',Auth::user()->id)
						->where('followingid', '=', $user->id)
						->first();

		//Valid record found
		if($follow->id)
		{
			$follow->delete();
			return $success;
		}

		return $fail;

	}

	public function isFollowing()
	{
		return Response::json(array('success'=> true, 'users'=>User::find(Auth::user()->getFollowing())));
	}
	public function removeUserTag($id)
	{
		$tag = FollowingEvent::where('id', '=', $id)->first();

		//Do we have permission to do so?
		if($tag->userid == Auth::user()->id)
		{
			$tag->delete();
			return redirect('/profile');
		}

		abort(404);
		return false;
	}
}
<file_sep><?php namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Response, Auth, Input;
use Log;

class ImageRequest extends FormRequest
{
    //All the rules are defined in the Validator, as they're more complicated'
    //Than the rules function allows.
	public function rules()
    {
        return [
        ];
    }

    public function authorize()
    {
        return Auth::check();
    }

     public function getValidatorInstance() {
        $validator = parent::getValidatorInstance();
        $mb = 5;
        $sizeLim = $mb * pow(1024,2);
        $file = Input::file('image');
         $validator->after(function() use ($validator, $sizeLim, $file, $mb) {
            if(!in_array($file->getClientOriginalExtension(), array('mp4', 'png', 'jpg', 'gif')))
            {
                $validator->errors()->add('Bio', 'Incorrect File Type used.');
            }
            if($file->getSize() > $sizeLim)
            {
                $validator->error()->add('Size', 'File exceeds upload limit of '.$mb.' mb');
            }

        });
        return $validator;
    }

}<file_sep><?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Model\Posts;
use App\Model\Story;
use App\Model\StoryPost;
use App\Http\Requests\PostRequest;
use App\Http\Requests\StoryAddRequest;
use Auth, View, Response, Input;

class StoryController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| Story Controller
	|--------------------------------------------------------------------------
	|
	| This Story Controller handles the RESTful api and creates views.
	|
	*/
	//This is our VIEW commands.
	public function viewStory(Story $story)
	{
		$storyPosts = Posts::getPostsFromStory($story->id);
		$data['story'] = $story;
		$data['posts'] = $storyPosts;
		return View::make('story.viewstory')->with($data);
	}

	public function createStory()
	{
		$title= isset($_GET["title"]) ? $_GET["title"] : "";
		return View::make('story.createstory')->with('title', $title);
	}

	/**
	 * Display a listing of the resource.
	 * GET request
	 * @return Response
	 */
	 //These are our API commands. Restful and CRUD
	public function index()
	{
		if(Auth::user())
		{
			return Response::json(Story::getAllUserStories(Auth::user()));
		}
		return Response::json(Story::all());
	}

	public function store(StoryAddRequest $req)
	{
		$newPost = Story::create(array(
					"name"=>Input::get('title'),
					"userId" => Auth::user()->id,
					"description" => Input::get('description'),
					"hashtag" => Input::get("hashtag")
				));
		$id = $newPost->id;

		$posts = Input::get('posts');
		if($posts)
		{
			foreach($posts as $value)
			{
				StoryPost::create(array('storyid' => $id, 'postid' => $value));
			}
		}
		//here we check if the newpost entered the db, if it did then the newPost will have an id, otherwise it will not.
		return $newPost->id ? Response::json(array("success"=>true, "id" => $newPost->id)) : Response::json(array("fail"=>true, "id" => $newPost->id));
	}

	/**
	 * Store a newly created resource in storage.
	 * DELETE request.
	 * @return Response
	 */
	public function destroy($id)
	{
		$story = Story::where('id', $id)->first();

		//For later:: Auth::user()->admin
		if(Auth::user()->id == $story->userId)
		{
			Story::destroy($id);
			return Response::json(array('success'=>true));
		}

		return Response::json(array('success'=>false));
	}

	public function getStoryPosts($id)
	{
		return Response::json(Posts::getPostsFromStory($id));
	}
	// ----------------added by me --------------------//
	public function getUserStories($user){
		return Response::json(Story::getUserStories($user));
	}
	// ----------------------------------------------- //
	public function getTag($id)
	{
		return Response::json(Story::getTagged($id));
	}
}
<file_sep>

		@include("story.storycontent")

<dir-pagination-controls
	pagination-id="story"
	template-url="{{asset('/js/dirPagination.tpl.htm')}}">
</dir-pagination-controls>

<file_sep><?php namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class FollowingEvent extends Model {

	public $timestamps = false;
	protected $table = "followingevent";
	protected $fillable = ['userid', 'hashtag'];

	//A following event belongs to User. With the Userid.
	public function user()
	{
		return $this->belongsTo('App\Model\User', 'userid');
	}

}
<file_sep>function ChangeFile(angularEl) {
     if(angular.element(angularEl).scope().FileChange())
     {
        var Reader = new FileReader();

        Reader.readAsDataURL(document.getElementById("imageUploaded").files[0]);

        Reader.onload = function (oFREvent) {
            $("#preview").show();
            document.getElementById("preview").src = oFREvent.target.result;
        };
     }
};

/* Old Code for Tabs
$(document).ready(function () {
    var tabSelect = $(".tabSelecter");
    var selector = $('.tabSelecter  .selector');

    selector.bind('click', ActiveTab);

    function ActiveTab(event) {
        var divClass = event.target.className.split(' ')[0];
        console.log(divClass, tabSelect.children());

        tabSelect.children('div').each(function () {
            console.log('div', $(this));
            $(this).removeClass('active');
            $(this).addClass('inactive');
        });
        selector.removeClass('active').addClass('inactive');

        $('.' + divClass).removeClass('inactive').addClass('active');

    };
});
*/
<file_sep>

//Starting point for Angular
var postApp = angular.module('postApp', ['postCtrl', 'postService','dirTabs', 'userCtrl', 'userService', 'storyCtrl', 'storyService', 'angularUtils.directives.dirPagination'],function($interpolateProvider) {
        $interpolateProvider.startSymbol('<%');
        $interpolateProvider.endSymbol('%>');
    });

<file_sep>

<form name="postForm" ng-submit="submitPost()" enctype="multipart/form-data">

			<input type="file" name="image" onchange="ChangeFile(this)"  id="imageUploaded" style="padding-right:50px">

	    <input
			type="text"
			class="form-control input-lg postInput"
		 	name="text"
			maxlength="140"
			ng-maxlength="140"
			ng-model="postData.text"
			ng-pattern="/\S*#(?:\[[^\]]+\]|\S+)/"
			placeholder="Add a Post."
		>

			<button type="submit" class="btn btn-primary btn-lg" ng-disabled="postForm.$invalid">Submit</button>

<% postData.text.length != undefined ? postData.text.length : 0 %> of 140

Sheets need a HashTag (#) !

</form>

 0">
		Sorry, there were some problems with your sheet..

<% error %>

<file_sep><?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder {

    public function run()
    {
        $this->call('UserSeeder');
        $this->call('PostSeeder');
        $this->call('FollowingEventSeeder');
        $this->call('StorySeeder');
        $this->call('StoryPostSeeder');

        $this->command->info('User table seeded!');
    }

}<file_sep>

			<a class="text-muted" href="{{url('/<% post.username %>') }}">
				<% post.username %>  <% post.relativeTime %>

<% post.adText %>

Delete

<a href = "{{ url( 'posts/<% post.id %>') }}" style = "float: right; padding-right: 10px;" class = "text-muted">Display post

  Tags <a href="/tag/<% tags.replace('#', '') %>"> <% tags %>

<file_sep>@extends('template.nav')

@section('title')
	Tag: post
@endsection

@section('angularApp')

@endsection

@section('content')

{{ $post->users->username }}

			{{ $time }}

			{{$post->text}}

			#
			tags:
			@foreach ($tags as $tag)
     		 	 {{$tag}}
    		@endforeach

		@if ($post->url)
			url }}">
		@endif

			Go back

@endsection<file_sep><?php namespace App\Model\Entities;

use \Symfony\Component\HttpFoundation\File\UploadedFile;
use \Symfony\Component\HttpFoundation\File\File;
class Image
{
	protected $image;
    protected $uploadedFile;

    /**
     * The UPLOAD_ERR_XXX constant provided by the uploader.
     *
     * @var int
     */
    private $error;

	public function getImage()
	{
		return $this->image;
	}

    public function __construct(UploadedFile $file)
    {
       $this->uploadedFile = $file;
    }

    public function getFileInstance()
    {
        return $this->uploadedFile;
    }

    public function cropImage($targetHeight, $targetWidth)
    {

    }

    public function squareCrop($size)
    {
        $imageProps = getimagesize( $this->uploadedFile );
        echo $imageProps[0];

		$imageW = $imageProps[0];
		$imageH = $imageProps[1];
        $extension = $this->uploadedFile->getClientOriginalExtension();
		switch($extension)
		{
			case 'jpg':
            case 'jpeg':
                 $oldImage = imagecreatefromjpeg( $this->uploadedFile );
                 break; // The current file is a JPG extension.
			case 'png':
                $oldImage = imagecreatefrompng(  $this->uploadedFile );
                break; // The current file is a PNG extension.
			case 'gif':
                $oldImage = imagecreatefromgif(  $this->uploadedFile );
                break; // The current file is a GIF extension.
		}

		$this->image = imagecreatetruecolor($size,$size); 		// Create a new cropped image as the new profile image.

		$cropH = 0;
		$cropW = 0;

		if($imageW > $imageH)         						// The original image has an aspect greater than 1.
		{
			$cropW = ($imageW - $imageH) / 2;
			$cropH = 0;
			$imageW = $imageH;
		}
		else 												// The original image has an aspect less than 1.
		{
			$cropW = 0;
			$cropH = ($imageH - $imageW) /2;
			$imageH = $imageW;
		}

		imagecopyresampled($this->image, $oldImage, 0, 0, $cropW, $cropH,  $size, $size, $imageW, $imageH);
        $filename = $this->uploadedFile->getPathname();
		switch( $extension )
		{
			case 'jpg':  $this->image = imagejpeg($this->image,$filename, 100);   break; // The current file is a JPG extension.
			case 'png':   $this->image =imagepng($this->image, $filename, 0); 	 break; // The current file is a PNG extension.
			case 'gif':   $this->image =imagegif($this->image,$filename);		 break; // The current file is a GIF extension.
		}
    }

    private function getAspectRatio($width, $height)
    {
        return $width/$height;
    }

}
<file_sep>

	 	<a href = "{{ url( 'story/<% story.id %>') }}" class = "text-muted"> <% story.name %> (#<% story.hashtag %>)
		<a style="float:right" class="text-muted" href="{{url('/<% story.username %>') }}">
			by: <% story.username %>

<% story.description %>

Delete

<a href = "{{ url( 'story/<% story.id %>') }}" style = "float: right; padding-right: 10px;" class = "text-muted">Display story

  Posts in this Story:  <% story.PostAmount %>

<file_sep>@extends('template.nav')

@section('title')
	Stories: Posts
@endsection

@section('angularApp')

@endsection

@section('content')

		@if(Auth::user())

				@include('users.profile', array("user"=>Auth::user()))

		@else

		@endif

				@if (Auth::user())
					@include('posts.form')
				@endif

Posts feed

					@include('posts.post')

@endsection
<file_sep>@extends('template.nav')

@section('title')
	Tag: {{$tag}}
@endsection

@section('angularApp')

@endsection

@section('content')

			<dir-tab>
				<tab-content title="Posts">

Posts

							@include('posts.post')

				</tab-content>

				<tab-content title="Stories">

Stories

							@include('story.story')

				</tab-content>
			</dir-tab>

@endsection
<file_sep><?php namespace App\Model;
//A terrible name for a model, but I couldn't think of a better one '
use Illuminate\Database\Eloquent\Model;

//Cannot initialize a TimeModel, it exists as an abstact class.
abstract class TimeModel extends Model {

	protected $appends = array("relativeTime");

	//Append Function; Amazing.
	public function getRelativeTimeAttribute()
	{
		return $this->getRelativeTime();
	}

	//Here we want to implement a Method that tells you the relative time
	//since Object Creation.
	public function getRelativeTime() 				// Show dynamic post time:
	{
		if(!$this->created_at)
		{
			return null;
		}

		$createdDate = date_create(date('Y-m-d', 		// Create date var. from the post.
		strtotime($this->created_at)) );
		$currentDate = date_create(date('Y-m-d'));		// Create date var. of the current date.

		$diff=date_diff($createdDate,$currentDate); 	// Get the time difference.

		$d = $diff->format('%a');						// Number of days.
		$m = $diff->format('%m');						// Number of months.

		if ($d <= 31) 									// Posted the past 31 days:
		{
			switch($d)
			{
				case 0:		     			return 'Today'; 		break;
				case 1:		     			return 'Yesterday'; 	break;
				case ($d < 7):   		    return $d ." days ago"; break;
				case ($d >= 7 && $d < 14):  return '1 week ago'; 	break;
				case ($d >= 14 && $d < 21): return '2 weeks ago'; 	break;
				case ($d >= 21 && $d < 28): return '3 weeks ago'; 	break;
				case ($d >= 28):  			return '4 weeks ago'; 	break;
			}
		}
		else if( $m > 0 ) 								// Posted over a month ago:
			return "$m month(s), $d day(s) ago";
	}

}
<file_sep><?php namespace App\Model;

use App\Model\TimeModel;
use DB, Auth;

class Story extends TimeModel {

	protected $fillable = ['name', 'description', "userId", "hashtag"];
	protected $table = "story";

	//Relationships.
	public function posts()
	{
		return $this->hasMany('App\Model\StoryPost', 'postid');
	}

	public function users()
	{
		return $this->belongsTo('App\Model\User', 'userId');
	}

	public static function getAllUserStories(User $user)
	{
		$followingEv = $user->getFollowingEvents();
		$following = $user->getFollowing();

		$stories = Story::join('users', function($join){
				$join->on('users.id', '=', 'story.userId');
			})
			->where('story.userId', $user->id)
			->orWhere(function($query) use ($followingEv, $following){
				foreach($followingEv as $follow)
				{
					$query->orWhere('story.hashtag', '=',$follow);
				}
				foreach($following as $follow)
				{
					$query->orWhere('story.userId', '=', $follow);
				}
			})
			->leftJoin('storypost', function($join){
				$join->on('storypost.storyid', '=', 'story.id');
			})
			->groupBy('story.id')
			->orderBy('story.created_at', 'desc')
			->select( array('story.*',
						'users.username',
						DB::raw('CASE WHEN story.userId = '.$user->id.' THEN 1 ELSE 0 END AS editable'),
						DB::raw('count(storypost.id) as PostAmount')
						)
					)
			->get();

		return $stories;
	}
		//--------------- Dette har jeg addet-----------------//
		public static function getUserStories(User $user)
	{
			$stories = Story::join('users', function($join){
				$join->on('users.id', '=', 'story.userId');
			})
			->where('story.userId', $user->id)

			->leftJoin('storypost', function($join){
				$join->on('storypost.storyid', '=', 'story.id');
			})
			->groupBy('story.id')
			->orderBy('story.created_at', 'desc')
			->select( array('story.*',
						'users.username',
						DB::raw('CASE WHEN story.userId = '.$user->id.' THEN 1 ELSE 0 END AS editable'),
						DB::raw('count(storypost.id) as PostAmount')
						)
					)
			->get();

		return $stories;
	}
	// -----------------------------------------------------------//
		//To do
		//User Stories.
		//Tagged Stories.

	public static function getTagged($id)
	{
		$stories = Story::join('users', function($join){
				$join->on('users.id', '=', 'story.userId');
			})
			->where('hashtag', '=', $id)
			->leftJoin('storypost', function($join){
				$join->on('storypost.storyid', '=', 'story.id');
			})
			->groupBy('story.id')
			->orderBy('story.created_at', 'desc')
			->select( array('story.*',
						'users.username',
						DB::raw('CASE WHEN story.userId = '.Auth::user()->id.' THEN 1 ELSE 0 END AS editable'),
						DB::raw('count(storypost.id) as PostAmount')
						)
					)
			->get();

		return $stories;
	}

}
<file_sep><?php namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Response, Auth, Input;
use App\Model\Posts;

class StoryAddRequest extends FormRequest
{
	public function rules()
    {
        return [
            'title' => array('max:140', 'required'),
            'hashtag' => array('max:140', 'required', 'regex:/^[a-zA-Z0-9]+$/'),
            'description' => "max:255"
        ];
    }

    public function authorize()
    {
        return Auth::check();
    }

    public function getValidatorInstance() {
        $validator = parent::getValidatorInstance();

         $validator->after(function() use ($validator) {
            if(count(Input::get('posts')) == 0 )
            {
                $validator->errors()->add('Posts', 'A story post should contain some posts.');
            }
            foreach(Input::get('posts') as $value)
            {
                $post = Posts::where("id", '=', $value)->first();
                if(strpos($post->text,Input::get('hashtag')) === FALSE){
                    $validator->errors()->add('A post', 'A post does not contain your hashtag');
                }
            }

        });
        return $validator;
    }

}<file_sep><?php namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class StoryPost extends Model {
	public $timestamps = false;
	protected $fillable = ['postid', 'storyid'];
	protected $table = "storypost";

	//Relationships.
	public function users()
	{
		$this->belongsTo('App\Model\Story', 'storyid');
	}
}
<file_sep><?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.
|
*/

//Binds
Route::bind('user', function($value, $route){
	return App\Model\User::where('username', $value)->first();
});
Route::bind('storyid', function($value, $route){
	return App\Model\Story::where('id', $value)->first();
});
Route::bind('postid', function($value, $route){
	return App\Model\Posts::where('id', $value)->first();
});

//Gets
Route::get('/', 'HomeController@index');
//We just make the View inside the routes, no logic needs to be done as that is handled in angulars
Route::get('/posts', function(){
	return View::make("posts.index");
});
Route::get('/profile',[
    'middleware' => 'auth',
    'uses' => 'UserController@profilePage'
]);
Route::get('/story', function(){
	Return View::make('story.index');
});
//Similar to before, except we get the tag.
Route::get('/tag/{tags}', function($tag){
	return View::make('posts.Tags')->with('tag', $tag);
});
Route::get('/{user}', 'UserController@userPage');
Route::get('/api/user/following', 'UserController@isFollowing');

/*
Route::get('/api/post/{postID}', 'PostsController@GetPost');
Route::get('/posts/{id}', function($postID){
	return View::make('posts.post')->with('postID', $postID);
}); */

Route::get('/api/tag/delete/{id}', "UserController@removeUserTag");
Route::get('/api/story/posts/{id}', "StoryController@getStoryPosts");
Route::get('/api/posts/all', "PostsController@getAllPosts");

Route::get('/story/create', [
    'middleware' => 'auth',
    'uses' => 'StoryController@CreateStory'
]);
Route::get('/story/{storyid}', 'StoryController@viewStory');
Route::post('/api/story/edit/{id}', 'StoryController@edit');

//This is where the API stuff happens
Route::group(array('prefix' => 'api'), function(){
    Route::resource('posts', 'PostsController',
           //We use index, get, store and destroy only.
		    //Laravel produces these routes.
			array('only'=> array('index', 'get', 'store', 'destroy')));
	Route::resource('images', 'FileController',
		array('only'=>array('store'))
	);
	Route::resource('story', 'StoryController',
		array('only'=>array('index', 'get', 'store', 'destroy'))
	);
	Route::resource('user/follow', 'UserController',
		array('only'=>array('store'))
	);
	Route::resource('allUsers', 'UserController',
		array('only'=>array('allUsers'))
	);
});
//-----------Dette har jeg addet -----------//
Route::get('/api/story/user/{user}', 'StoryController@getUserStories');
Route::get('/api/story/{tag}', 'StoryController@getTag');
//-----------------------------------------//
Route::get('api/allUsers', 'UserController@getAllUsers');
Route::get('/api/posts/{tag}', 'PostsController@getTag');
Route::get('/api/user/follow/{user}', 'UserController@subscribePerson');
Route::get('/api/user/delete/{user}', 'UserController@unsubscribePersone');
Route::get('/posts/{postid}', 'PostsController@viewPost');
Route::get('/api/posts/user/{username}', 'PostsController@getUserPosts');

Route::controllers([
	'auth' => 'Auth\AuthController',
	'password' => '<PASSWORD>',
]);

Route::post('/profile', 'UserController@updateProfile');<file_sep><?php namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Response, Auth, Input;

class ProfileRequest extends FormRequest
{
	public function rules()
    {
        return [
            'bio' => 'max:500'
        ];
    }

    public function authorize()
    {
        // Only allow logged in users
        return Auth::check();
    }

    //Check if the Biography has illegal characters in it And if the image doesn't exceeds the limit.
    public function getValidatorInstance() {
        $validator = parent::getValidatorInstance();

        $mb = 2;
        $sizeLim = $mb * pow(1024,2);
        $file = Input::file('profile');
        $illegal = "#%^&[]/{}|:<>";

         $validator->after(function() use ($validator, $sizeLim, $file, $illegal) {

            if(strpbrk(Input::get('bio'), $illegal))
            {
                $validator->errors()->add('Bio', 'Cannot contain illegal characters');
            }

           if(!in_array($file->getClientOriginalExtension(), array('png', 'jpg', 'gif')))
            {
                $validator->errors()->add('Bio', 'Incorrect File Type used.');
            }

            if($file->getSize() > $sizeLim)
            {
                $validator->errors()->add('Size', 'File exceeds upload limit of '.$mb.' mb');
            }

        });
        return $validator;
    }
}<file_sep>@extends('template.nav')

@section('title')
	{{$user->username}}
@endsection

@section('angularApp')

@endsection

@section('content')

username }}"  ng-init="GetUserStory('{{$user->username}}')">

		@if($user)

				@include('users.profile', array("user"=>$user))

		@else

		@endif

				<dir-tab>
					<tab-content title="Stories">

{{$user->username}}s Stories

								@include('story.story')

					</tab-content>

					<tab-content title="Posts">

{{$user->username}}s Posts

								@include('posts.post')

					</tab-content>
				</dir-tab>

@endsection
<file_sep>

		<a class="text-muted" href="{{url('/<% post.username %>') }}">

			<% post.username %>

		<% post.relativeTime %>
		@if (Auth::user())
			<span ng-show="<% post.following %> == 0 && <% post.editable %> == 0" class="<% post.username %>-nf addIndicator" ng-click="submitUser(post.username)">

			<span class="<% post.username %>-f addIndicator" ng-show="<% post.following %> && <% post.editable %> == 0">

		@endif

<% post.adText %>

Delete

<a href = "{{ url( 'posts/<% post.id %>') }}" style = "float: right; padding-right: 10px;" class = "text-muted">Display post

  Tags  <% tags %>

<file_sep>Read Me:
This is a MVC Twitter-a-like used to handle Events (Via a hashtag) and create stories based upon them. It uses AngularJS and Ajax to be as dynamic as possible without needing to reload etc.

as such the  application relies on a RESTful api.

:::::HOW TO USE:::::

**FIRST do a composer install on the root of the folder.
**Then Create a database named mystories in MSQL in PHP myAdmin (The process for creating a database in laravel is quite indepth, it is much easier this way).
**Then run php artisan migrate
**Then run php artisan db:seed
**Then run php artisan serve

Default User is TestAct with password <PASSWORD>.

The application will then be running on localhost:8000.

<file_sep><?php namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Response, Auth, Input;

class PostRequest extends FormRequest
{
	public function rules()
    {
        //Regex here checks if there is one ore more instance of #Hashtags.
        return [
            'text' => array('max:140', 'required', 'regex:/\S*#(?:\[[^\]]+\]|\S+)/')
        ];
    }

    public function authorize()
    {
        return Auth::check();
    }

}<file_sep><?php namespace App\Model;

use App\Model\TimeModel;
use DB, Auth;
class Posts extends TimeModel {

	protected $fillable = ['userId', 'text', 'imgId'];
	protected $table = "posts";

	//Define the relationships.
	public function users()
	{
		return $this->belongsTo('App\Model\User', 'userId');
	}

	//This is the Query most
	public static function defaultQuery()
	{
		return Posts::join('users', function($join){
				$join->on('users.id', '=', 'posts.userId');
			})
			->leftJoin('files', function($join){
				$join->on('files.id', '=', 'posts.imgId');
			})
			->leftJoin('following', function($join){
				$join->on('following.followingid', '=', 'posts.userId');
			})
			->groupBy('posts.id')
			->orderBy('posts.created_at', 'desc');
	}

	public static function getSelect()
	{
		$arr = array('posts.*',
						'users.username',
						'files.url',
						DB::raw('CASE WHEN posts.userId = following.followingid THEN 1 ELSE 0 END AS following'));
		if(Auth::user())
		{
			array_push($arr, DB::raw('CASE WHEN '.Auth::user()->id.' = posts.userId THEN 1 ELSE 0 END AS editable'));

		}
		return $arr;
	}

	//Override of All, we need to ensure we get the username.
	public static function all($columns = array('*'))
	{
		return self::defaultQuery()
			->select(array(
					'posts.*',
					'users.username',
					'files.url'
					))
			->get();
	}

	//This is where all the home posts are gotten.
	public static function getAllHome(User $user)
	{
		//Get homepage posts.
		//This will get all of the users posts and all
		//of the events they're following.
		$followingEv = $user->getFollowingEvents();
		$following = $user->getFollowing();
		$posts = self::defaultQuery()
			->where('posts.userId', $user->id)
			->orWhere(function($query) use ($followingEv, $following){
				foreach($followingEv as $follow)
				{
					$query->orWhere('text', 'RLIKE', '(#'.$follow.')[[:>:]]');

				}
				foreach($following as $follow)
				{
					$query->orWhere('posts.userId', '=', $follow);
				}
			});

		return $posts->select(self::getSelect())->get();
	}

	public static function getUserPosts($user)
	{
			$posts = self::defaultQuery()
				->where('users.username', $user);

			return $posts->select(self::getSelect())->get();
	}

	public static function getPostsFromStory($id)
	{
		$posts = self::defaultQuery()
			->leftJoin('storypost', function($join){
				$join->on('storypost.postid', '=', 'posts.id');
			})
			->where('storypost.storyid', $id);

		return $posts->select(self::getSelect())->get();
	}

	public static function getPost($id)
	{

		$posts = self::defaultQuery()
				->where('posts.id', $id);

		return $posts->select(self::getSelect())->get();

	}

	public static function getTagged($id)
	{
		$posts = self::defaultQuery()
			->where('text', 'RLIKE', '(#'.$id.')[[:>:]]');

		return $posts->select(self::getSelect())->get();
	}

	public function getPostTags() 				// Create link for each tag.
	{
		return preg_grep("/#(\[[\w\s]+\])|#(\w+)/", explode(' ', $this->text));
	}

}
<file_sep><?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Model\Posts;
use App\Http\Requests\PostRequest;
use Auth, View, Response, Input;

class PostsController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| Posts Controller
	|--------------------------------------------------------------------------
	|
	| This controller handles the RESTful side of the posts.
	|
	|
	|
	*/
	/**
	 * Display a listing of the resource.
	 * GET request
	 * @return Response
	 */
	public function index()
	{
		if(Auth::user())
		{
			return Response::json(Posts::getAllHome(Auth::user()));
		}
		return Response::json(Posts::all());
	}

	public function getAllPosts()
	{
		return Response::json(Posts::all());
	}

	public function store(PostRequest $req)
	{
		//First we need to check if the user is logged in, if so, he can post.
		$success =  Response::json(array('success' => true));
		$fail =  Response::json(array('success' => false));
		//We also need to check whether a user has posted less than 140 characters.

		if(Auth::user() && count(Input::get('text')) <= 140 &&  preg_match('/\S*#(?:\[[^\]]+\]|\S+)/', Input::get('text')))
		{
			$newPost = Posts::create(array(
						"text"=>Input::get('text'),
						"userId"=>Auth::user()->id,
						"imgId"=>Input::get('imgID') ? Input::get('imgID') : null
					));

 			//here we check if the newpost entered the db, if it did then the newPost will have an id, otherwise it will not.
			return $newPost->id ? $success : $fail;
		}

		//Otherwise, we'll return a fail response.
		return $fail;
	}

	/**
	 * Store a newly created resource in storage.
	 * DELETE request.
	 * @return Response
	 */
	public function destroy($id)
	{
		$post = Posts::where('id', $id)->first();

		//For later:: Auth::user()->admin
		if(Auth::user()->id == $post->userId)
		{

			Posts::destroy($id);
			return Response::json(array('success'=>true));
		}

		return Response::json(array('success'=>false));
	}

	public function getTag($id)
	{
		return Response::json(Posts::getTagged($id));
	}

	public function getUserPosts($user)
	{
		return Response::json(Posts::getUserPosts($user));
	}

	//Get Specific Post.
	public function viewPost(Posts $post) 					// Get Specific Post:
	{
		$data["post"] = $post;
		$data["tags"] = $post->getPostTags();
		$data["time"] = $post->getRelativeTime();

		return View::make('posts.thisPost')->with($data);	// Return the data to the view.
	}

}<file_sep>//set up a directive for tabbing
angular.module('dirTabs', [])
    .directive('dirTab', function(){
        return {
            //Means that you can only use it like <dir-tab></dir-tab>
            restrict: 'E',
            transclude: true,
            scope: {},
            controller: ["$scope", function($scope){
                //Set up a small controller for it to bind the two together.
                var tabs = $scope.tabs = [];
                $scope.select = function(tab){
                    //Basically do what we did in main.js but with objects
                    $.each(tabs, function(index,tab){
                        tab.active = false;
                    });
                    //Activate the one we've selected
                    tab.active = true;
                }

                //This is more of a dynamic way of adding tabs in.
                this.addTab = function(tab){
                    //If this is the first tab we've added then select it.
                    if(tabs.length == 0)
                    {
                        $scope.select(tab);
                    }
                    tabs.push(tab);
                }
            }],
            //Use basically the same code as before.
            template:
                '
'
                +   '
'
                +       '
'
                +           "<%tab.title%>"
                +       '
'
                +   '
'
                +   '

'
                +   '
',
            replace: true
        };
    }).
    //Then the content can be added here.
    directive('tabContent', [ function(){
        return{
            require: '^dirTab',
            restrict: 'E',
            scope: { title: '@' },
            link: function (scope, element,attrs,dirTabCtrl) {
                dirTabCtrl.addTab(scope);
            },
            transclude:true,
            template:
                '

',
            replace:true
        };
    }]);

<file_sep><?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Http\Requests\ImageRequest;
use App\Model\Files;
use Auth, View, Response, Input, Image, File, FilesystemIterator;

class FileController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| File Controller
	|--------------------------------------------------------------------------
	|
	| This controller handles the request of file uploads if the users
	| are authenticated.
	|
	|
	*/

    // now save your image to your $path
	//All we need. This will return an id for an Image Item when uploaded.
	public function store(ImageRequest $request)
	{

		//To upload an image a user needs to be logged in.
		if(Auth::user())
		{
			//We get where the post is on the server ( to store in an image object.)
			$serverDir =  "/uploaded_images/".Auth::user()->username;
			$dir = public_path($serverDir);

			$mb = 2;											// Valid Mega bytes.
			$validExt = array('mp4', 'png', 'jpg', 'gif');		// Valid file extensions.
			$validSize = $mb * pow(pow(2, 10), 2 );      	 	// Valid image size in Mb.

			if( File::exists($dir) or File::makeDirectory($dir) )
			{
				//FileSystemIterator is just to get the count of objects.
				$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
				//We get the extensions (ie:.ping)
				//TODO: Add check to make sure object is image, both client and server side.
				$extension = Input::file('image')->getClientOriginalExtension();
				$fileSize = Input::file('image')->getSize();

				if( in_array($extension, $validExt) && $fileSize <= $validSize ) // Checks if the file extension is valid AND
																					// if the image size doesn't exceeds the limit.
				{
					//Get Random Generated Number + Amount of File to avoid users being able to go /userimages/img/whatever
	      			$filename = rand(11111,99999).iterator_count($fi).'.'.$extension;
					  //Get Path.
				    $path = $dir."/".$filename;
					//Get Move the file to the directory.
					Input::file('image')->move($dir,$filename);
					//Create an image with a url
					$newImage = Files::create(array(
							"url"=> ''.$serverDir.'/'.$filename
						));

					//Return the ID to use on the post.
					return Response::json(array('success' => true, 'id' =>$newImage->id));
				}
				else
				{
					//break;
					return Response::json(array('success' => false, 'id' =>null));
				}
			}
		}

		//Otherwise, we'll return a fail response.
		return Response::json(array('success' => false, 'id' =>null));
	}

}
<file_sep>
Posts with Tag:  <% custom %>  showing. Click to go back

		@include("posts.postcontent")

<dir-pagination-controls
	pagination-id="post"
	template-url="{{asset('/js/dirPagination.tpl.htm')}}">
</dir-pagination-controls>

<file_sep><form name="followForm" ng-submit="submitFollow()" enctype="multipart/form-data">

	    <input
			type="text"
			class="form-control input-lg postInput"
		 	name="follow"
			ng-model="followData.text"
			ng-pattern="/^[a-zA-Z ]*$/"
			placeholder="Follow an event hashtag."
		>

Only use text.

			<button type="submit" class="btn btn-primary btn-lg" ng-disabled="followForm.$invalid">Submit</button>

</form><file_sep>@extends('template.nav')

@section('title')
	{{$story->name . ' by '. $story->users->username}}
@endsection

@section('angularApp')

@endsection

@section('content')

id}})">

Story: {{$story->name}} (#{{$story->hashtag}})

{{$story->description}}

								@include("story.postcontent")

@endsection
<file_sep><?php namespace App\Model;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

	use Authenticatable, CanResetPassword;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = ['username', 'email', 'password', 'profileId', 'biography'];

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = ['password', 'remember_token', 'email'];

	//Get all the relationships.
	public function followingevent()
	{
		return $this->hasMany('App\Model\FollowingEvent', 'userid');
	}

	public function following()
	{
		return $this->hasMany('App\Model\Following', 'userid');
	}

	public function post()
	{
		return $this->hasMany('App\Model\Posts', 'userId');
	}

	public function story()
	{
		return $this->hasMany('App\Model\Story', 'userId');
	}

	public function files()
	{
		return $this->hasOne('App\Model\Files', 'id', 'profileId');
	}

	public static function allUsernames()
	{
		return User::select('username')->get();
	}

	//Get the following events we have.
	public function getFollowingEvents()
	{
		$hashTags = array();
        foreach ($this->followingevent as $followObject) {
            $hashTags[] = $followObject->hashtag;
        }
        return $hashTags;
	}

	public function getFollowing()
	{
		$following = array();
        foreach ($this->following as $followObject) {
            $following[] = $followObject->followingid;
        }
        return $following;
	}
}
<file_sep><?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Model\Posts;

class PostSeeder extends Seeder {

	public function run()
	{
	    DB::table('posts')->delete();

        Posts::create(array(
            'text' => '#test post',
            'userId' => 1,
			'imgId' =>  null,
        ));

		Posts::create(array(
            'text' => '#test post2',
            'userId' => 1,
			'imgId' =>  null,
        ));
		Posts::create(array(
            'text' => '#test post3',
            'userId' => 2,
			'imgId' =>  null,
        ));
		Posts::create(array(
            'text' => '#nepal hanging out in nepal',
            'userId' => 2,
			'imgId' =>  null,
        ));

		 Posts::create(array(
            'text' => '#Nepal testing if Nepal hashtag works',
            'userId' => 2,
			'imgId' =>  null,
        ));
	}
}<file_sep><?php namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Files extends Model {
	public $timestamps = false;
	protected $fillable = ['url'];
	protected $table = "files";

	//Define relationship.
	public function user()
    {
        return $this->belongsTo('App\Model\User', 'profileId');
    }
}

<file_sep><?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Model\FollowingEvent;

class FollowingEventSeeder extends Seeder {

	public function run()
	{
	    DB::table('FollowingEvent')->delete();

        FollowingEvent::create(array(
            'userid' => 1,
            'hashtag' => "TestHash",
        ));

		FollowingEvent::create(array(
            'userid' => 1,
            'hashtag' => "TextHas",
        ));

        FollowingEvent::create(array(
            'userid' => 2,
            'hashtag' => "Need",
        ));

        FollowingEvent::create(array(
            'userid' => 1,
            'hashtag' => "Nepal",
        ));
	}
}<file_sep>@extends('template.nav')

@section('content')

		  		@include('auth.loginform')

@endsection
<file_sep>@extends('template.nav')

@section('title')
	Create a Story
@endsection

@section('angularApp')

@endsection

@section('content')

Create a story

 0">
							Sorry, there were some problems with your input..

<% error %>

				   <form name="storyForm" ng-submit="submitStory()" enctype="multipart/form-data">

						  <input
							type="text"
							class="form-control input-lg postInput storyInput"
							ng-model="storyData.title"
							placeholder="Story Title."
						>

						<input
							type="text"
							class="form-control input-lg postInput storyInput"
							ng-model="storyData.hashtag"
							placeholder="Topic (Enter Hashtag without #)"
							ng-model-options="{ updateOn: 'blur' }"
							ng-change="GetTags(storyData.hashtag, true);ResetPosts()"
						>

						<input
							type="text"
							class="form-control input-lg postInput storyInput"
						 	name="desc"
							ng-model="storyData.description"
							placeholder="Story Description."
						>

 Select Posts

 No Posts for this topic

									<div class="storypost-<%post.id%>" ng-click="ModifyStoryPosts(post.id)">
										@include("story.postcontent")

						<button type="submit" class="btn btn-primary btn-lg storyButton" ng-disabled="postForm.$invalid">Submit</button>

				</form>

@endsection
<file_sep>angular.module('storyService', [])

  //This is the Post Factor, where the http and ajax requests happen
.factory('Story', function($http){
	return {
		//We get the posts from /api/posts, which fires the index() item in PostController
		get: function(){
			return $http.get('/api/story');
		},
		//Save grabs some data, and POSTs it to the server. This fires the store() event
		save: function(data){
			return $http({
					method: 'POST',
					url: '/api/story',
					headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
					data: $.param(data)
			});
		},
		//Fires the destroy even and gets story id.
		destroy: function(id){
			return $http.delete('/api/story/'+id);
		},
			//------------Dette har jeg addet ------------//
		getUserStory: function(user)
		{
			return $http.get('/api/story/user/' + user);
		},
		getTags: function(tag){
			return $http.get('/api/story/'+tag);
		},

		//-----------------------------------------------//
	}
});
<file_sep>@extends('template.nav')

@section('title')
	{{Auth::user()->username}} Profile
@endsection

@section('angularApp')

@endsection

@section('content')

@section('content')

Your Profile

					@if (count($errors) > 0)

							Sorry, there were some problems with your input..

								@foreach ($errors->all() as $error)

{{ $error }}

								@endforeach

					@endif

					<form class="form-horizontal" role="form" method="POST" action="{{ url('/profile') }}"  enctype="multipart/form-data">
						<input type="hidden" name="_token" value="{{ csrf_token() }}">

									@if (Auth::user()->files)
										files->url)}}">
									@else

									@endif

Profile Picture

							    	<input type="file" name="profile" id="ImageUpload" style="padding-left:50px; display:inline;">

							Biography

								<textarea class="form-control" rows="5" id="bio" name="bio">{{Auth::user()->biograpghy}}</textarea>

								<button type="submit" class="btn btn-primary">
									Update
								</button>

					</form>

			          Following Events

     				@foreach (Auth::user()->followingEvent as $event)

hashtag)}}"> {{$event->hashtag}}   id)}}"> Delete!

					@endforeach

@endsection

@endsection
<file_sep>
<form name="storyForm" ng-submit="SetName(storyData.title)" action="/story/create" method="get">

			<button type="submit" class="btn btn-primary btn-lg" style="width:100%" ng-disabled="postForm.$invalid">Create a story.</button>

</form>

 0">

		Sorry, there were some problems with your input..

<% error %>

<file_sep>angular.module('postService', [])

//So we need to be able VIEW html content in our app
//but on top of this, it'll have a click component to it
//So we need to compile too.
//Hence, NG-HTML-COMPILE.
.directive('compile', ['$compile', function ($compile) {

  return function(scope, element, attribute) {
	  //Here we set up a watch on a variable, in this instance it's the directives
	  //attribute.
	scope.$watch(
		//Here is where we get the attr, and compile it, revealing it's value
      function(scope) {
        return scope.$eval(attribute.compile);
      },
	  //We then pass it to a callback, where we append the html to then element it was
	  //a part of, then compile the element. This is important.
      function(value) {
        element.html(value);
        $compile(element.contents())(scope);
      }
   )};
  }])

  //This is the Post Factor, where the http and ajax requests happen
.factory('Post', function($http){
	return {
		//We get the posts from /api/posts, which fires the index() item in PostController
		get: function(){
			return $http.get('/api/posts');
		},
		//Save grabs some data, and POSTs it to the server. This fires the store() event
		save: function(data){
			return $http({
					method: 'POST',
					url: '/api/posts',
					headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
					data: $.param(data)
			});
		},
		//Fires the destroy even and gets post id.
		destroy: function(id){
			return $http.delete('/api/posts/'+id);
		},
		//We get the tag from the api at PostController@getTags
		getTags: function(tag){
			return $http.get('/api/posts/'+tag);
		},
		// Get the post id from the API at PostController@getPost
		getPost: function(id)
		{
			return $http.get('/api/posts/id/' + id);
		},

		getStoryPosts: function(id)
		{
			return $http.get('/api/story/posts/'+id);
		},

		getUserPost: function(user)
		{
			return $http.get('/api/posts/user/' + user);
		}

	}
})

.factory('Images', function($http){
	//Where we post the image.
	return{
		save: function(image){
			return $http.post('/api/images', image, {
		        withCredentials: true,
		        headers: {'Content-Type': undefined },
		        transformRequest: angular.identity
		    });
		}
	}
})

//This is where we define the post object for use in scope with Angular
.factory('PostObject', function($sce){
	function Post(text, created_at, username, id, editable, url, updated_at) {
	    this.text = text;
		this.adText = "";
	    this.created_at = created_at;
	    this.username = username;
	    this.editable = editable;
	    this.updated_at = updated_at;
	    this.id = id;
		this.url = url;
		this.following = null;
		this.ytEmbed = null;
		this.relativeTime = null;
  	}

	//We get the tags here, by matching the tags against a regex statement.
	Post.prototype.getTags = function() {
	  return (this.text.match(/#(\[[\w\s]+\])|#(\w+)/g)) ? this.text.match(/#(\[[\w\s]+\])|#(\w+)/g) : [];
	};

	//We create a tag out of these statements
	Post.prototype.createLinks = function(isRelative){
	  var tags = this.getTags();

	  //We need to escape the HTML, because we are trusting this as html.
	  var text = this.text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
	  //this is that Adjusted Text, we do this so that we don't modify the original object (If it needs to be used elsewhere.)
	  this.adText = text;
	  //We then go through tags and replace things with lings.
	  for(var tag in tags){
		  var str = tags[tag];
		 if(isRelative){
 		  	text = text.replace(str, "" + str + "");
		 }else {
		  	text = text.replace(str, "" + str + "");
		 }
		  this.adText = text;
	  }
	}

	Post.prototype.GetMediaHTML = function(){
			if(this.url == null)
			{
				return;
			}
			var url = this.url;
			var extension = url.split('.').pop();

			if(extension == "mp4" || extension == "ogg")
			{
				this.url='<video width="100%" controls>\
							  <source src="'+this.url+'" type="video/'+ extension +'">\
							Your browser does not support the video tag.\
							</video>';
			} else {
				this.url = "";
			}
	}

	Post.prototype.hasYouTube = function(){
		if(this.url != null || this.url != undefined)
		{
			//We already have some media in this post and we therefore don't need more.
			return;
		}

		//Next we detect if there's an applicable youtube link.
		var regex = /\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i;
		var yt = regex.exec(this.text);

		if(yt && yt[0].length > 0)
		{
			this.url  = '

';
		}
	}
	Post.prototype.initialize = function(isRelative){
		this.createLinks(isRelative);
		this.GetMediaHTML();
		this.hasYouTube();
		//Should maybe be called in a ctor.
	}

 	return Post;
});<file_sep><?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Model\Story;

class StorySeeder extends Seeder {

	public function run()
	{
	    DB::table('story')->delete();

        Story::create(array(
            'name' => 'Nepal story',
            'hashtag' => 'nepal',
			'description' =>  'Hanging out in Nepal',
			'userId' => 2,
        ));
        Story::create(array(
        	'name' => 'Test story',
        	'hashtag' => 'test',
        	'description' => 'testing story',
        	'userId' => 1,
        ));
        Story::create(array(
        	'name' => 'test story 2',
        	'hashtag' => 'test',
        	'description' => 'test story 2',
        	'userId' => 2,
        ));
	}
}<file_sep>

			@if ($user->files)
				files->url)}}">
			@else

			@endif

			{{$user->username}}

			{{count($user->post)}} post(s)

			{{count($user->story)}} storie(s)

Bio:
 {{$user->biography }}

	@if (Auth::user() && Auth::user()->username != $user->username)

username}}-nf'" ng-click="submitUser('{{$user->username}}')" ng-show="!userFollows('{{$user->username}}')">
			Follow

username}}-f'" ng-click="unfollowUser('{{$user->username}}')" style = "background: #dd5454;" ng-show="userFollows('{{$user->username}}')">
			Unfollow

	@endif

	@if(Auth::user() == $user)

			@include('users.forms')

	@endif

<file_sep>//Search

$(document).ready(function()
{

	$('.searchResults').undelegate('click');

/*---------------------------------------------------------------------------*/
/*								   A r r a y s			  					 */
/*---------------------------------------------------------------------------*/

	var tagsList = []; 									// Store all tags.
	var userList = [];									// Store all users.
	var searchList = [];								// Store all tags that match the search value.

/*---------------------------------------------------------------------------*/
/*								V a r i a b l e s		  					 */
/*---------------------------------------------------------------------------*/

	var searchField 	= $('.searchField');			// The search field.
	var searchButton 	= $('.searchButton');			// The search button.
	var searchResults 	= $('.searchResults'); 			// The unordered list.
	var userIcon 		= '';

/*---------------------------------------------------------------------------*/
/*							   I n i t i a l i z e		  					 */
/*---------------------------------------------------------------------------*/

	// hide:
	searchResults.hide(); 								// Hide the search results on defualt.

	url = window.location.origin; 						// Get root path.

	$.ajax												// Get all tags and store them in tagsList.
	({
		url: url + '/api/posts/all',						// Get all posts from json.
		success: function(posts) 						// Success callback:
		{
			$.each(posts, function (i, post)			// Find all hashtags and store unambiguously:
			{

				var string = post.text.toString();		// Store the post text.
				var array = string.split(' ');			// Split to array on ' ' (space)
				var tags = [];							// Array to store the tags from the text.

				for(var i = 0; i < array.length; i++)	// Loop through all words in the text.
				{
					if (array[i].indexOf('#') !== -1) 	// The text contains a '#'
					{
						tags.push(array[i]); 			// Push the word to tags.
					}
				}
				 $.each(tags, function(i, elem) 		// Filter ambigious tags:
				{
					if($.inArray(elem, tagsList)==-1){
						tagsList.push(elem);
					}
				})
			});
		}
	});

	$.ajax												// Get all users and store them in userlist.
	({
		url: url + '/api/allUsers',						// Get all users from json.
		success: function(users) 						// Success callback:
		{
			$.each(users, function (i, user)			// Find all users
			{
				res = user.username;
				res = res.toString();
				userList.push(res);						// Store into the the userList array.
			});
		}
	});

/*---------------------------------------------------------------------------*/
/*								F u n c t i o n s		  					 */
/*---------------------------------------------------------------------------*/

	function search( searchInput, type ) 				// Search after this input.
	{
		if( searchInput != "" ) 						// The input must have a value.
		{
			if (type == "tag") 							// The input is a tag.
			{
   				url = window.location.origin+"/tag/" + searchInput;
				window.location.href = url;
			}
			else
			{
				url = window.location.origin+"/" + searchInput;
				window.location.href = url;
			}
		}
	}

/*---------------------------------------------------------------------------*/
/*								K e y   E v e n t s		  					 */
/*---------------------------------------------------------------------------*/

	searchField.bind('keyup change', function(e) 			// When the user presses a key.
	{
		var type = "tag";									// Defualt on search.
		var input = searchField.val(); 						// Get input value.

		searchList = []; 									// Reset search array.
		searchResults.html(''); 							// Reset the search output.

		if( input == "" ) 									// The user backspaced the input value:
		{
			searchResults.slideUp();
			searchField.css({'border-radius':'10px 0px 0px 10px'});
			searchResults.html('');
			searchList = [];
		}

		if (e.which == 13 || e.keyCode == 13) 				// Pressed Enter:
			search(input, type );								// Perform a search.

		var result = false; 								// Boolean to check if there was any results.

		for(var i = 0; i < tagsList.length; i++) 			// Loop through all tags:
		{
			if( tagsList[i].indexOf(input) != -1 ) 			// Found a match with the stored tags.
			{
				result = true;								// Found a tag, boolean is true.

				if (searchList.length != 0)					// The search list array is NOT empty.
				{
					if( searchResults.text() 				// The tag isn't a duplicate of the current search results:
						.indexOf(tagsList[i]) == -1 )
					{ 										// Add this tag to into search results.
				    	searchList.push('
' + tagsList[i] + '
');
				    }
				}
				else										// The search list array is empty:
																// Add the tag into search results.
				    searchList.push('
' + tagsList[i] + '
');
			}

		}
		for (var j = 0; j < userList.length; j++)
		{
			if(userList[j].indexOf(input) != -1 )
			{
				result = true;								// Found a tag, boolean is true.

				if (searchList.length != 0)
				{
					if( searchResults.text() 				// The tag isn't a duplicate of the current search results:
						.indexOf(userList[j]) == -1 )
					{ 										// Add this tag to into search results.
				    	searchList.push('
' + userIcon + ' ' + userList[j] + '
');
				    }
				}
				else
				{
					searchList.push('
' + userIcon + ' ' + userList[j] + '
');
				}
			}

			if (j == userList.length-1 && input != '') 		// looped through all tags AND input is NOT empty.
			{
				searchResults.slideDown();					// Display the search results container.
				searchField.css({'border-radius':'10px 0px 0px 0px'});

				if (result)									// The search input resulted positive:
					searchResults.append(searchList); 		// Display all search results.
				else
					searchResults.append('
Sorry, no results for
"'+ input +'"
');
			}
		}

	});

/*---------------------------------------------------------------------------*/
/*							  C l i c k   E v e n t s		  				 */
/*---------------------------------------------------------------------------*/

	searchButton.click( function() 							// Clicked on the search button:
	{
		search( searchField.val() );						// Search with the current input.
	});

	$('.searchResults').delegate('li', 'click',function() 	// Clicked on a search reuslt from the list:
	{
		var type = "tag";									// Search type: defualt tag.
		var searchValue = $(this).attr('name');				// Get this search value by attr name.

		if (searchValue[0] != '#')							// There was no hastag in the search input.
			type = "user";

		else
			searchValue = searchValue.substring(1);			// Remove hashtag from search value.

		search(searchValue, type);							// Search with this input.

	});

/*---------------------------------------------------------------------------*/
});		// End document ready.<file_sep><?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Model\StoryPost;

class StoryPostSeeder extends Seeder {

	public function run()
	{
	    DB::table('storyPost')->delete();

        StoryPost::create(array(
            'storyid' => 1,
            'postid' => 5,
        ));
        StoryPost::create(array(
        	'storyid' => 2,
        	'postid' =>1,
        ));
        StoryPost::create(array(
        	'storyid' => 2,
        	'postid' => 2,
        ));
        StoryPost::create(array(
        	'storyid' => 3,
        	'postid' => 3,
        ));
	}
}

languages: Text JavaScript Blade PHP

repo_language: Text

repo_name: Podginator/Twitter-Clone


text:
<file_sep>package com.avsoftsol.app;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
    private ArrayList<AndroidVersion> android_versions;
    private Context context;

    public DataAdapter(Context context, ArrayList<AndroidVersion> android_versions) {
        this.context = context;
        this.android_versions = android_versions;

    }

    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_row, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int i) {

        viewHolder.tv_android.setText(android_versions.get(i).getAndroid_version_name());
        Picasso.with(context).setLoggingEnabled(true);
        Picasso.with(context).load(android_versions.get(i).getAndroid_image_url()).resize(100, 100).into(viewHolder.img_android);
    }

    @Override
    public int getItemCount() {
        return android_versions.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView tv_android;
        ImageView img_android;
        CardView cardView;

        public ViewHolder(final View view) {
            super(view);

            tv_android = (TextView) view.findViewById(R.id.title);
            img_android = (ImageView) view.findViewById(R.id.image);
            cardView = (CardView) view.findViewById(R.id.card_view);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, ProductActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
            });
        }
    }
}<file_sep>package com.avsoftsol.util;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Toast;

import com.avsoftsol.app.AndroidVersion;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by kashivivek on 03-26-2017.
 */
public class ViewInitiatorTask {
    private Context mContext;
    public ArrayList<String> NameList;
    public ArrayList<String> CategoryList;
    public ArrayList<String> ImagePathList;
    public ArrayList PriceList;
    public static String[] android_version_names, android_image_urls;

    public ViewInitiatorTask(Context context) {
        mContext = context;
    }

    public static final String MyPREFERENCES = "MyPrefs";
    ProgressDialog progressDialog;
    DatabaseHandler db;
    SharedPreferences pref;
    SharedPreferences.Editor editor;

    public HashMap<String, String[]> execute(String params) {
        //onPreExecute();
        HashMap<String, String[]> resp = new HashMap<String, String[]>();
        String category = params;
        db = new DatabaseHandler(mContext);
        NameList = new ArrayList();
        CategoryList = new ArrayList();
        ImagePathList = new ArrayList();
        PriceList = new ArrayList();

        List<Product> products = db.getAllProducts(category);
        for (Product p : products) {
            NameList.add(p.getName());
            CategoryList.add(p.getCategory());
            ImagePathList.add(p.getImagepath());
            PriceList.add(p.getPrice());
        }
        android_version_names = NameList.toArray(new String[NameList.size()]);
        android_image_urls = ImagePathList.toArray(new String[ImagePathList.size()]);
        resp.put("version", android_version_names);
        resp.put("image", android_image_urls);
        return resp;
    }

    public static ArrayList<AndroidVersion> prepareData(String[] android_version_names, String[] android_image_urls) {

        ArrayList<AndroidVersion> android_version = new ArrayList<>();
        for (int i = 0; i < android_version_names.length; i++) {
            AndroidVersion androidVersion = new AndroidVersion();
            androidVersion.setAndroid_version_name(android_version_names[i]);
            androidVersion.setAndroid_image_url(android_image_urls[i]);
            android_version.add(androidVersion);
        }
        return android_version;
    }

    protected void onPostExecute(String result) {
        // execution of result of Long time consuming operation
        progressDialog.dismiss();
        Toast.makeText(mContext, result, Toast.LENGTH_SHORT).show();

    }

    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(mContext, "", "Refreshing the products list");
    }

}<file_sep>package com.avsoftsol.app;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by kashivivek on 04-15-2017.
 */

public class SplashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, HomePageActivity.class);
        startActivity(intent);
        finish();
    }
}

repo_language: Java

repo_name: kashivivek/HomeSome