text:
import DenaliObject from '../metal/object';
import Request from '../runtime/request';
import { ResponderParams } from '../runtime/action';

/**
 * Denali's Parsers are responsible for taking the incoming request body of an
 * HTTP request and transforming it into a consistent object structure that can
 * be used by Actions.
 *
 * For example, if your app uses JSON-API, you can use the JSON-API parser to
 * transform the incoming JSON-API request body structure into something easier
 * to work with in your Action layer.
 *
 * Other examples of common tasks include parsing and type casting query
 * params, and transforming keys (i.e. kebab-case to camelCase).
 *
 * @package parse
 * @since 0.1.0
 */
export default abstract class Parser extends DenaliObject {

  /**
   * Take an incoming request and return an object that will be passed in as
   * the argument to your Action.
   *
   * The object should include some common properties:
   *
   *    body    - usually the primary data payload of the incoming request
   *    query   - parsed and typecast query string parameters
   *    headers - the headers of the incoming HTTP request
   *    params  - parsed and typecast parameters from the dynamic segments of the
   *              incoming request URL
   *
   * Beyond that, each parser can add it's own additional properties based on
   * how it parses. For example, the JSON-API parser adds any sideloaded
   * records from the request body under the `included` property.
   *
   * @since 0.1.0
   */
  abstract async parse(request: Request): Promise<ResponderParams>;

}


text:
<?php

namespace ApiBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use DataBundle\Entity\Users;
use DataBundle\Entity\Slugs;
use DataBundle\Entity\UsersWalls;
use Facebook\Facebook;
use JMS\Serializer\SerializationContext;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\Tools\Pagination\Paginator;

class UsersController extends Controller {

    public function timeoutAction() {
        $data = array("error" => "timeout");
        $response = new Response(json_encode($data));
        $response->headers->set('Content-Type', 'application/json');
        $response->setStatusCode(401);
        return $response;
    }

    public function loginFacebookAction(Request $request) {
        $fb = new Facebook([
            'app_id' => '379273575598190',
            'app_secret' => '8ac96ca853850f8e634b814d7c478cb4',
            'default_graph_version' => 'v2.5',
        ]);
        $helper = $fb->getRedirectLoginHelper();
        try {
            $accessToken = $helper->getAccessToken();
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
            // When Graph returns an error
            echo 'Graph returned an error: ' . $e->getMessage();
            exit;
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            // When validation fails or other local issues
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }
        try {
            // Returns a `Facebook\FacebookResponse` object
            $response = $fb->get('/me?fields=id,name,email,gender,birthday,location,hometown', $accessToken);
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
            echo 'Graph returned an error: ' . $e->getMessage();
            exit;
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }

        $fbuser = $response->getGraphUser();
        $user = $this->getDoctrine()->getRepository("DataBundle:Users")->findOneByEmail($fbuser['email']);
        $em = $this->getDoctrine()->getEntityManager();
        if ($user) {
            $user->setLastlogin(time());
            $em->persist($user);
            $em->flush();
        } else {
            $password = rand(100000, 999999);

            $user = new Users();
            $user->setFullname($fbuser['name']);
            $user->setGender($fbuser['gender']);
            $user->setBirthday($fbuser['birthday']);
            $user->setEmail($fbuser['email']);
            $user->setUsername($fbuser['email']);
            $user->setPassword(password_hash($password, PASSWORD_BCRYPT));
            $user->setToken(password_hash($fbuser['email'], PASSWORD_BCRYPT));
            $user->setCreateTime(time());
            $user->setLastlogin(time());
            $user->setActive(1);
            $em->persist($user);
            $em->flush();
            $url = 'http://graph.facebook.com/' . $fbuser['id'] . '/picture?type=large';
            $data = file_get_contents($url);
            $fileName = '/www/iskun.net/web/avatars/' . $user->getId() . '.jpg';
            $file = fopen($fileName, 'w+');
            fputs($file, $data);
            fclose($file);
            $user->setAvatar($user->getId() . '.jpg');
            $em->persist($user);
            $em->flush();
            $slug = $this->slug($fbuser['name']);
            for ($i = 0; $i <= 1000; $i++) {
                $newslug = $slug;
                if ($i >= 1) {
                    $newslug = $slug . "-" . $i;
                }
                $exist = $this->getDoctrine()->getRepository("DataBundle:Slugs")->findOneBySlug($newslug);
                if (!$exist) {
                    $slugs = new \DataBundle\Entity\Slugs();
                    $slugs->setSlug($newslug);
                    $slugs->setEntity("Users");
                    $em->persist($slugs);
                    $em->flush();
                    $user->setSlugs($slugs);
                    $em->persist($user);
                    $em->flush();
                    break;
                }
            }

            $data = $this->forward('ApiBundle:Email:send', array("type" => "facebook_register", "data" => array("password" => $password, "slugs" => $slugs), "user" => $user));
        }
        $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
        $this->get('security.token_storage')->setToken($token);
        return $this->redirectToRoute('home', array(), 301);
    }

    public function typeAction(Request $request) {
        $user = $this->getUser();
        if ($request->get("type") == "teacher") {
            $user->setType("teacher");
        }
        if ($request->get("type") == "student") {
            $user->setType("student");
        }
        if ($request->get("type") == "parent") {
            $user->setType("parent");
        }
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($user);
        $em->flush();
        $this->forward('ApiBundle:Email:send', array("type" => "user-set-type", "data" => array("type" => $request->get("type")), "user" => $user));
        $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
        $this->get('security.token_storage')->setToken($token);
        $serializer = $this->container->get('serializer');
        $data = $serializer->serialize($user, 'json', SerializationContext::create()->setGroups(array('basic')));
        return new Response($data);
    }

    public function slug($str, $char = "-") {
        $unicode = array(
            'a' => 'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ',
            'd' => 'đ',
            'e' => 'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ',
            'i' => 'í|ì|ỉ|ĩ|ị',
            'o' => 'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ',
            'u' => 'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự',
            'y' => 'ý|ỳ|ỷ|ỹ|ỵ',
            'A' => 'Á|À|Ả|Ã|Ạ|Ă|Ắ|Ặ|Ằ|Ẳ|Ẵ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ',
            'D' => 'Đ',
            'E' => 'É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ',
            'I' => 'Í|Ì|Ỉ|Ĩ|Ị',
            'O' => 'Ó|Ò|Ỏ|Õ|Ọ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ',
            'U' => 'Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự',
            'Y' => 'Ý|Ỳ|Ỷ|Ỹ|Ỵ',
            '-' => ' ',
            '' => ':',
            '' => "'",
        );

        foreach ($unicode as $nonUnicode => $uni) {

            $str = preg_replace("/($uni)/i", $nonUnicode, $str);
        }
        // Lower case the string and remove whitespace from the beginning or end
        $str = trim(strtolower($str));

        // Remove single quotes from the string
        $str = str_replace("'", "", $str);

        // Every character other than a-z, 0-9 will be replaced with a single dash (-)
        $str = preg_replace("/[^a-z0-9]+/", $char, $str);

        // Remove any beginning or trailing dashes
        $str = trim($str, $char);

        return $str;
    }

    public function getAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $this->getUser();
        $serializer = $this->container->get('serializer');
        $user = $serializer->serialize($user, 'json', SerializationContext::create()->setGroups(array('full'))->enableMaxDepthChecks());
        $user = json_decode($user, true);
        $folders = $em->getRepository("DataBundle:Folders")->findBy(array('parent' => null, 'users' => $this->getUser()->getId()));
        $folders = $serializer->serialize($folders, 'json', SerializationContext::create()->setGroups(array('basic'))->enableMaxDepthChecks());
        $folders = json_decode($folders, true);
        $user['folders'] = $folders;
        $questionstypes = $em->getRepository("DataBundle:QuestionsTypes")->findAll();
        $questionstypes = $serializer->serialize($questionstypes, 'json', SerializationContext::create()->setGroups(array('basic'))->enableMaxDepthChecks());
        $questionstypes = json_decode($questionstypes, true);
        $user['questionstypes'] = $questionstypes;
        $response= new Response(json_encode($user));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function postsAction($page, $min, $max) {
        // hàm lấy ra các post cho timeline
        if (!$this->getUser()) {
            return $this->timeoutAction();
        }
        $where = " WHERE ";
        if ($page == "home") {
            $where.=" w.home = 1 ";
        }
        if ($page == "private") {
            $where.=" w.private = 1 ";
        }
        if ($min > 0) {
            $where.=" AND w.id < $min ";
        }
        $em = $this->getDoctrine()->getEntityManager();
        $dql = "SELECT w FROM DataBundle:UsersWalls w $where ORDER BY w.id DESC ";
        $query = $em->createQuery($dql)
                ->setFirstResult(0)
                ->setMaxResults(10);
        $posts = new Paginator($query, $fetchJoinCollection = true);
        $older = array();
        foreach ($posts as $index => $post) {

            $older[] = $post;
        }
        $serializer = $this->container->get('serializer');
        $older = $serializer->serialize($older, 'json', SerializationContext::create()->setGroups(array('basic')));
        $older = json_decode($older);
        $olders = array();
        foreach ($older as $index => $post) {
            $dql = "SELECT c FROM DataBundle:Comments c LEFT JOIN c.posts p WHERE c.status='finish' AND p.id=" . $post->posts->id . " ORDER BY c.id DESC";
            $comments = $em->createQuery($dql)->setFirstResult(0)->setMaxResults(5)->getResult();
            $comments = $serializer->serialize($comments, 'json', SerializationContext::create()->setGroups(array('basic')));
            $comments = json_decode($comments, true);
            $comments = array_reverse($comments);
            $post->posts->comments = $comments;
            $dql = "SELECT c FROM DataBundle:Comments c LEFT JOIN c.posts p LEFT JOIN c.users u WHERE c.status='temporary' AND p.id=" . $post->posts->id . " AND u.id=" . $this->getUser()->getId() . " ORDER BY c.id DESC";
            $temporaryComment = $em->createQuery($dql)->setFirstResult(0)->setMaxResults(1)->getResult();
            $temporaryComment = $serializer->serialize($temporaryComment, 'json', SerializationContext::create()->setGroups(array('basic')));
            $temporaryComment = json_decode($temporaryComment, true);
            if (isset($temporaryComment[0])) {
                $temporaryComment = $temporaryComment[0];
            }
            $post->posts->comment = $temporaryComment;
            $olders[] = $post;
        }
        $data['olders'] = $older;
        $response = new Response(json_encode($data));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function postCommentsAction($id, $min, $max) {
        if (!$this->getUser()) {
            return $this->timeoutAction();
        }
        $where = "";
        if ($min > 0) {
            $where.=" AND c.id < $min";
        }
        $em = $this->getDoctrine()->getEntityManager();
        $serializer = $this->container->get('serializer');
        $dql = "SELECT c FROM DataBundle:Comments c LEFT JOIN c.posts p WHERE p.id=" . $id . " $where ORDER BY c.id DESC";
        $comments = $em->createQuery($dql)->setFirstResult(5)->setMaxResults(10)->getResult();
        $comments = $serializer->serialize($comments, 'json', SerializationContext::create()->setGroups(array('basic')));
        $comments = json_decode($comments, true);
        //$comments= array_reverse($comments);
        $data['olders'] = $comments;
        $response = new Response(json_encode($data));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function uploadCommentFileAction(Request $request) {
        if (!$this->getUser()) {
            return $this->timeoutAction();
        }
        $em = $this->getDoctrine()->getEntityManager();
        $id = $request->get("post");
        $content = $request->get("content");
        $commentId = $request->get("comment");
        if ($commentId) {
            $comment = $em->getRepository("DataBundle:Comments")->find($commentId);
        } else {
            $comment = $em->getRepository("DataBundle:Comments")->findOneBy(array('status' => "temporary", 'posts' => $id, 'users' => $this->getUser()->getId()));
        }
        if (!$comment) {
            $comment = new \DataBundle\Entity\Comments();
            $comment->setPosts($em->getRepository("DataBundle:Posts")->find($id));
            $comment->setIp($request->getClientIp());
            $comment->setUsers($this->getUser());
            $comment->setContent($content);
            $comment->setStatus("temporary");
            $comment->setLikes(0);
            $em->persist($comment);
            $em->flush();
        }
        $comment->setContent($content);
        $comment->setStatus("temporary");
        $comment->setTime(time());
        $comment->setLikes(0);
        $em->persist($comment);
        $em->flush();
        if ($_FILES['file']['name']) {
            if (!$_FILES['file']['error']) {
                $name = md5(rand(100, 200));
                $ext = explode('.', $_FILES['file']['name']);
                $filename = $name . '.' . $ext[1];
                $destination = '/www/iskun.net/web/files/' . $filename; //change this directory
                $location = $_FILES["file"]["tmp_name"];
                move_uploaded_file($location, $destination);
                $file = new \DataBundle\Entity\Files();
                $file->setFilename($_FILES['file']['name']);
                $file->setFilepath($filename);
                $file->setFormat($_FILES['file']['type']);
                $file->setThumbnail();
                $file->setUsers($this->getUser());
                $file->setSize($_FILES['file']['size']);
                $em->persist($file);
                $em->flush();
                $file->setThumbnail($this->createFileThumbnailAction($file->getId()));
                $em->persist($file);
                $em->flush();
                $commentfile = new \DataBundle\Entity\CommentsFiles();
                $commentfile->setComments($comment);
                $commentfile->setFiles($file);
                $em->persist($commentfile);
                $em->flush();
            }
        }
        $em->refresh($comment);
        $em->flush();
        $serializer = $this->container->get('serializer');
        $comment = $serializer->serialize($comment, 'json', SerializationContext::create()->setGroups(array('basic')));
        $response = new Response($comment);
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function deleteCommentAttachmentAction($commentId, $fileId) {
        $em = $this->getDoctrine()->getEntityManager();
        $comment = $em->getRepository("DataBundle:Comments")->find($commentId);
        foreach ($comment->getCommentsFiles() as $commentFile) {
            if ($fileId == $commentFile->getId()) {
                $file = $commentFile->getFiles();
                $em->remove($commentFile);
                $em->flush();
                // trước khi xóa file phải kiểm tra file có attach tới 1 post hoặc comment nào khác.
                // $em->remove($file);
                // $em->flush();
            }
        }
        $em->refresh($comment);
        $em->flush();
        $serializer = $this->container->get('serializer');
        $comment = $serializer->serialize($comment, 'json', SerializationContext::create()->setGroups(array('basic')));
        $response = new Response($comment);
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function postCommentAction($postId, Request $request) {
        if (!$this->getUser()) {
            return $this->timeoutAction();
        }
        $em = $this->getDoctrine()->getEntityManager();
        $content = $request->getContent();
        $inputs = json_decode($content, true); // 2nd param to get as array
        if (isset($inputs['id'])) {
            $comment = $em->getRepository("DataBundle:Comments")->find($inputs['id']);
            $comment->setContent($inputs['content']);
            $comment->setStatus("finish");
            $comment->setUsers($this->getUser());
            $em->persist($comment);
            $em->flush();
        } else {
            $comment = new \DataBundle\Entity\Comments();
            $comment->setPosts($em->getRepository("DataBundle:Posts")->find($postId));
            $comment->setContent($inputs['content']);
            $comment->setStatus("finish");
            $comment->setUsers($this->getUser());
            $comment->setTime(time());
            $em->persist($comment);
            $em->flush();
        }
        $em->refresh($comment);
        $em->flush();
        $serializer = $this->container->get('serializer');
        $comment = $serializer->serialize($comment, 'json', SerializationContext::create()->setGroups(array('basic')));
        $response = new Response($comment);
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function deleteCommentAction($commentId) {
        $em = $this->getDoctrine()->getEntityManager();
        $comment = $em->getRepository("DataBundle:Comments")->find($commentId);
        foreach ($comment->getCommentsFiles() as $commentfile) {
            $em->remove($commentfile);
            $em->flush();
        }
        $em->remove($comment);
        $em->flush();
        $response = new Response(json_encode(array("status" => "deleted")));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function createFileThumbnailAction($id) {
        $em = $this->getDoctrine()->getEntityManager();
        $file = $em->getRepository("DataBundle:Files")->find($id);
        if (in_array($file->getFormat(), array("image/jpeg", "image/png"))) {
            $imagick = new \Imagick("/www/iskun.net/web/files/" . $file->getFilepath());
            $imagick->setImageFormat('jpg');
            $imagick->setbackgroundcolor('rgb(64, 64, 64)');
            $imagick->cropThumbnailImage(300, 300);
            $imagick->setImageCompression(\Imagick::COMPRESSION_JPEG);
            // Set compression level (1 lowest quality, 100 highest quality)
            $imagick->setImageCompressionQuality(75);
            // Strip out unneeded meta data
            $imagick->stripImage();
            // Writes resultant image to output directory
            $name = md5(rand(100, 200)) . ".jpg";
            $imagick->writeImage('/www/iskun.net/web/thumbnail/' . $name);
            // Destroys Imagick object, freeing allocated resources in the process
            $imagick->destroy();
            return $name;
        }
    }

    public function dumpAction(Request $request) {
        phpinfo();
        die();
        $em = $this->getDoctrine()->getEntityManager();
        $dql = "SELECT c FROM DataBundle:Comments c";
        $comments = $em->createQuery($dql)->setFirstResult(0)->getResult();
        foreach ($comments as $comment) {
            //$em->remove($comment);
            // $em->flush();
        }
        $dql = "SELECT p FROM DataBundle:Posts p ORDER BY p.id DESC";
        $posts = $em->createQuery($dql)->setFirstResult(0)->setMaxResults(200)->getResult();
        foreach ($posts as $post) {
            //  $post->setCommentsnumber(0);
            //  $em->persist($post);
            //  $em->flush();
        }

        $dql = "SELECT p FROM DataBundle:Posts p ORDER BY p.id DESC";
        $posts = $em->createQuery($dql)->setFirstResult(3)->setMaxResults(10)->getResult();
        foreach ($posts as $post) {
            for ($i = 1; $i <= rand(1, 15); $i++) {
                $comment = new \DataBundle\Entity\Comments();
                $comment->setContent("Comment thứ " . $i . " post thứ " . $post->getId());
                $comment->setPosts($post);
                $comment->setTime(time());
                $comment->setUsers($em->getRepository("DataBundle:Users")->find(rand(1, 4)));
                $em->persist($comment);
                $em->flush();
                $post->setCommentsnumber($i);
                $em->persist($post);
                $em->flush();
            }
        }

        die();

        for ($i = 2; $i <= 200; $i++) {
            $post = new \DataBundle\Entity\Posts();
            $post->setContent("Đây là bài viết thứ " . $i);
            $post->setTime(time());
            $post->setIp($request->getClientIp());
            $post->setTitle("Tiêu đề bài viết thứ " . $i);
            $post->setUsers($em->getRepository("DataBundle:Users")->find(1));
            $post->setPoststypes($em->getRepository("DataBundle:PostsTypes")->find(1));
            $em->persist($post);
            $em->flush();
            $postclass = new \DataBundle\Entity\PostsClasses();
            $postclass->setPosts($post);
            $postclass->setClasses($em->getRepository("DataBundle:Classes")->find(1));
            $em->persist($postclass);
            $em->flush();
            $userwall = new UsersWalls();
            $userwall->setPosts($post);
            $userwall->setUsers($this->getUser());
            $userwall->setHome(1);
            $userwall->setPrivate(1);
            $em->persist($userwall);
            $em->flush();
        }
    }

    public function logoutAction() {
        $this->get('security.token_storage')->setToken(null);
        $this->get('request')->getSession()->invalidate();
        $data = array("logout" => "true");
        $response = new Response(json_encode($data));
        $response->headers->set('Content-Type', 'application/json');
        $response->setStatusCode(200);
        return $response;
    }

    public function reloginFacebookAction(Request $request) {
        $em = $this->getDoctrine()->getEntityManager();
        $content = $request->getContent();
        $inputs = json_decode($content, true);
        $user = $em->getRepository("DataBundle:Users")->findOneByEmail($inputs['email']);
        if (!$user) {
            $response = new Response(json_encode(array("error" => "noneexist")));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
        if ($user->getToken() == $inputs['token']) {
            $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
            $this->get('security.token_storage')->setToken($token);
            $serializer = $this->container->get('serializer');
            $user = $serializer->serialize($user, 'json', SerializationContext::create()->setGroups(array('basic')));
            $response = new Response($user);
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        } else {
            $response = new Response(json_encode(array("error" => "invalidtoken")));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
    }

    public function createFolderAction(Request $request, $id = false) {
        $em = $this->getDoctrine()->getEntityManager();
        if (!$this->getUser()) {
            return $this->timeoutAction();
        }
        $content = $request->getContent();
        $inputs = json_decode($content, true);
        $folder = new \DataBundle\Entity\Folders();
        $folder->setName($inputs['name']);
        $folder->setSlug($this->slug($inputs['name']));
        $folder->setUsers($this->getUser());
        if ($id) {
            $folder->setParent($em->getRepository("DataBundle:Folders")->find($id));
        }
        $em->persist($folder);
        $em->flush();

        $response = new Response(json_encode(array("status" => "success")));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getFolderFilesAction($id = false) {
        $em = $this->getDoctrine()->getEntityManager();

        if ($id) {
            $condition['folders'] = $id;
            $files = $em->getRepository("DataBundle:Files")->findBy($condition);
        } else {
            $condition['users'] = $this->getUser()->getId();
            $condition['folders'] = null;
            $files = $em->getRepository("DataBundle:Files")->findBy($condition);
        }

        $serializer = $this->container->get('serializer');
        $files = $serializer->serialize($files, 'json', SerializationContext::create()->setGroups(array('basic')));
        $response = new Response($files);
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function uploadFileAction(Request $request) {
        if (!$this->getUser()) {
            return $this->timeoutAction();
        }
        $em = $this->getDoctrine()->getEntityManager();
        $id = $request->get("folder");
        if ($_FILES['file']['name']) {
            if (!$_FILES['file']['error']) {
                $name = md5(rand(100, 200));
                $ext = explode('.', $_FILES['file']['name']);
                $filename = $name . '.' . $ext[1];
                $destination = '/www/iskun.net/web/files/' . $filename; //change this directory
                $location = $_FILES["file"]["tmp_name"];
                move_uploaded_file($location, $destination);
                $file = new \DataBundle\Entity\Files();
                $file->setFilename($_FILES['file']['name']);
                $file->setFilepath($filename);
                $file->setFormat($_FILES['file']['type']);
                $file->setThumbnail("");
                $file->setUsers($this->getUser());
                $file->setSize($_FILES['file']['size']);
                $file->setTime(time());
                if ($id) {
                    $file->setFolders($em->getRepository("DataBundle:Folders")->find($id));
                }
                $em->persist($file);
                $em->flush();
                $file->setThumbnail($this->createFileThumbnailAction($file->getId()));
                $em->persist($file);
                $em->flush();
            }
        }
        return $this->getFolderFilesAction($id);
    }

    public function getStagesSubjectsAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $stages=$em->getRepository("DataBundle:Stages")->findAll();
        $serializer = $this->container->get('serializer');
        $stages = $serializer->serialize($stages, 'json', SerializationContext::create()->setGroups(array('full')));
        $response = new Response($stages);
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
    public function addTeachingSubjectsAction(Request $request){
        $content = $request->getContent();
        $inputs = json_decode($content, true);
        $em = $this->getDoctrine()->getEntityManager();
        $ts = $em->getRepository("DataBundle:TeachingSubjects")->findBy(array('subjects' => $inputs['id'], 'users' => $this->getUser()->getId()));
        if (!$ts)
        {
        $ts = new \DataBundle\Entity\TeachingSubjects();
        $ts->setSubjects($em->getRepository("DataBundle:Subjects")->find($inputs['id']));
        $ts->setUsers($this->getUser());
        $em->persist($ts);
        $em->flush();
        }
        $response = new Response(json_encode(array("status"=>"success")));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
    public function getQuestionsAction($source,$subject,$chapter,$questiontype,$page){
        $em = $this->getDoctrine()->getEntityManager();
        $where["subjects"]=$subject;
        $dql="SELECT q FROM DataBundle:Questions q JOIN q.subjects s JOIN q.subjectschapters c JOIN q.questionstypes qt JOIN q.users u WHERE s.id = ".$subject;
        if($chapter>0) {$dql.=" AND c.id=".$chapter;}
        if($questiontype>0) {$dql.=" AND qt.id=".$questiontype;}
        if($source=="private") {$dql.=" AND u.id=".$this->getUser()->getId();}
        if($source=="network") {$dql.=" AND q.share=2";}
        if($source=="friends") {$dql.=" AND q.share>1 AND u.id IN (1,2,3)";}
        $allQuestions = $em->createQuery($dql)->getResult();

        $query = $em->createQuery($dql)->setFirstResult(($page-1)*50)->setMaxResults(50);
        $questions = new Paginator($query, $fetchJoinCollection = true);
        $aQuestions=array();
        foreach ($questions as $question)
        {
            $aQuestions[]=$question;
        }

        $serializer = $this->container->get('serializer');
        $jQuestions = $serializer->serialize($aQuestions, 'json', SerializationContext::create()->setGroups(array('full')));
        $aQuestions=  json_decode($jQuestions,true);
        $data['questions']=$aQuestions;
        $data['total']=count($allQuestions);
        $data['itemsperpage']=50;
        $data['currentpage']=$page;
        $data['pages']=ceil($data['total']/$data['itemsperpage']);
        $response = new Response(json_encode($data));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:theme="@style/Theme.MyApp.WidgetContainer.Dark.Transparent.Material">

    <include layout="@layout/widget_value_solid" />

</FrameLayout>


text:
package cn.droidlover.xdroid.event;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by wanglei on 2016/11/28.
 */

public class EventBusImpl implements IBus {

    @Override
    public void register(Object object) {
        if (!EventBus.getDefault().isRegistered(object)) {
            EventBus.getDefault().register(object);
        }
    }

    @Override
    public void unregister(Object object) {
        if (EventBus.getDefault().isRegistered(object)) {
            EventBus.getDefault().unregister(object);
        }
    }

    @Override
    public void post(IEvent event) {
        EventBus.getDefault().post(event);
    }

    @Override
    public void postSticky(IEvent event) {
        EventBus.getDefault().postSticky(event);
    }
}


text:
/**
 * Test utilities to run application contexts for testing.
 */
package org.springframework.boot.test.context.runner;


text:
// Copyright (C) 2013  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#undef DLIB_REMOVE_UnOBTAINABLE_RECTANGLES_ABSTRACT_H__
#ifdef DLIB_REMOVE_UnOBTAINABLE_RECTANGLES_ABSTRACT_H__

#include "scan_image_pyramid_abstract.h"
#include "scan_image_boxes_abstract.h"
#include "scan_image_custom_abstract.h"
#include "../svm/structural_object_detection_trainer_abstract.h"
#include "../geometry.h"

namespace dlib
{

// ----------------------------------------------------------------------------------------

    template <
        typename image_array_type,
        typename Pyramid_type,
        typename Feature_extractor_type
        >
    std::vector<std::vector<rectangle> > remove_unobtainable_rectangles (
        const structural_object_detection_trainer<scan_image_pyramid<Pyramid_type, Feature_extractor_type> >& trainer,
        const image_array_type& images,
        std::vector<std::vector<rectangle> >& object_locations
    );
    /*!
        requires
            - images.size() == object_locations.size()
        ensures
            - Recall that the scan_image_pyramid object can't produce all possible rectangles
              as object detections since it only considers a limited subset of all possible
              object positions.  Moreover, the structural_object_detection_trainer requires
              its input training data to not contain any object positions which are unobtainable
              by its scanner object.  Therefore, remove_unobtainable_rectangles() is a tool
              to filter out these unobtainable rectangles from the training data before giving
              it to a structural_object_detection_trainer.
            - This function interprets object_locations[i] as the set of object positions for
              image[i], for all valid i.
            - In particular, this function removes unobtainable rectangles from object_locations
              and also returns a vector V such that:
                - V.size() == object_locations.size()
                - for all valid i:
                    - V[i] == the set of rectangles removed from object_locations[i]
    !*/

// ----------------------------------------------------------------------------------------

    template <
        typename image_array_type,
        typename feature_extractor,
        typename box_generator
        >
    std::vector<std::vector<rectangle> > remove_unobtainable_rectangles (
        const structural_object_detection_trainer<scan_image_boxes<feature_extractor, box_generator> >& trainer,
        const image_array_type& images,
        std::vector<std::vector<rectangle> >& object_locations
    );
    /*!
        requires
            - images.size() == object_locations.size()
        ensures
            - Recall that the scan_image_boxes object can't produce all possible rectangles
              as object detections since it only considers a limited subset of all possible
              object positions.  Moreover, the structural_object_detection_trainer requires
              its input training data to not contain any object positions which are unobtainable
              by its scanner object.  Therefore, remove_unobtainable_rectangles() is a tool
              to filter out these unobtainable rectangles from the training data before giving
              it to a structural_object_detection_trainer.
            - This function interprets object_locations[i] as the set of object positions for
              image[i], for all valid i.
            - In particular, this function removes unobtainable rectangles from object_locations
              and also returns a vector V such that:
                - V.size() == object_locations.size()
                - for all valid i:
                    - V[i] == the set of rectangles removed from object_locations[i]
    !*/

// ----------------------------------------------------------------------------------------

    template <
        typename image_array_type,
        typename feature_extractor
        >
    std::vector<std::vector<rectangle> > remove_unobtainable_rectangles (
        const structural_object_detection_trainer<scan_image_custom<feature_extractor> >& trainer,
        const image_array_type& images,
        std::vector<std::vector<rectangle> >& object_locations
    );
    /*!
        requires
            - images.size() == object_locations.size()
        ensures
            - Recall that the scan_image_custom object can't produce all possible rectangles
              as object detections since it only considers a limited subset of all possible
              object positions.  Moreover, the structural_object_detection_trainer requires
              its input training data to not contain any object positions which are unobtainable
              by its scanner object.  Therefore, remove_unobtainable_rectangles() is a tool
              to filter out these unobtainable rectangles from the training data before giving
              it to a structural_object_detection_trainer.
            - This function interprets object_locations[i] as the set of object positions for
              image[i], for all valid i.
            - In particular, this function removes unobtainable rectangles from object_locations
              and also returns a vector V such that:
                - V.size() == object_locations.size()
                - for all valid i:
                    - V[i] == the set of rectangles removed from object_locations[i]
    !*/

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_REMOVE_UnOBTAINABLE_RECTANGLES_ABSTRACT_H__


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <artifactId>kylo-catalog-service</artifactId>
    <groupId>com.thinkbiganalytics.kylo</groupId>
    <version>0.10.1-SNAPSHOT</version>
  </parent>

  <artifactId>kylo-catalog-api</artifactId>

  <properties>
    <plugin.license.parentRelative>../../../</plugin.license.parentRelative>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.google.code.findbugs</groupId>
      <artifactId>jsr305</artifactId>
    </dependency>
    <dependency>
      <groupId>com.thinkbiganalytics.kylo</groupId>
      <artifactId>kylo-catalog-model</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>com.thinkbiganalytics.kylo</groupId>
      <artifactId>kylo-schema-discovery-model2</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-common</artifactId>
      <exclusions>
        <exclusion>
          <groupId>javax.ws.rs</groupId>
          <artifactId>jsr311-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
    </dependency>
  </dependencies>
</project>


text:
package org.basex.query.value;

import java.util.*;

import org.basex.query.value.item.*;
import org.basex.query.value.seq.*;
import org.basex.query.value.seq.tree.*;
import org.basex.query.value.type.*;

/**
 * A builder for efficiently creating a {@link Value} by prepending and appending
 * {@link Item}s and {@link Value}s.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Leo Woerteler
 */
public final class ValueBuilder {
  /** The first added value is cached. */
  private Value firstValue;
  /** Underlying sequence builder, only instantiated if there are at least two items. */
  private TreeSeqBuilder builder;

  /**
   * Concatenates two values.
   * @param v1 first value to concatenate
   * @param v2 second value to concatenate
   * @return value which contains all items of {@code v1} followed by all items of {@code v2}
   */
  public static Value concat(final Value v1, final Value v2) {
    final long s1 = v1.size();
    if(s1 == 0) return v2;
    final long s2 = v2.size();
    if(s2 == 0) return v1;
    if(s1 > 1) return ((Seq) v1).insertBefore(s1, v2);
    if(s2 > 1) return ((Seq) v2).insert(0, (Item) v1);
    return TreeSeqBuilder.value(new Item[] { (Item) v1, (Item) v2 }, 2, null);
  }

  /**
   * Returns a {@link Value} representation of the given items.
   * @param items array containing the items
   * @param n number of items
   * @param type item type of the resulting value (not checked), may be {@code null}
   * @return the value
   */
  public static Value value(final Item[] items, final int n, final Type type) {
    return n == 0 ? Empty.SEQ : n == 1 ? items[0] : TreeSeqBuilder.value(items, n, type);
  }

  /**
   * Adds an item to the front of the built value.
   * @param item item to add
   * @return reference to this builder for convenience
   */
  public ValueBuilder addFront(final Item item) {
    final TreeSeqBuilder tree = builder;
    if(tree != null) {
      tree.addFront(item);
    } else {
      final Value first = firstValue;
      if(first != null) {
        builder = new TreeSeqBuilder().add(first).addFront(item);
        firstValue = null;
      } else {
        firstValue = item;
      }
    }
    return this;
  }

  /**
   * Adds a value to the front of the built value.
   * @param value value to append
   * @return reference to this builder for convenience
   */
  public ValueBuilder add(final Value value) {
    if(value.isEmpty()) return this;

    final TreeSeqBuilder tree = builder;
    if(tree != null) {
      tree.add(value);
    } else {
      final Value first = firstValue;
      if(first != null) {
        builder = new TreeSeqBuilder().add(first).add(value);
        firstValue = null;
      } else {
        firstValue = value;
      }
    }
    return this;
  }

  /**
   * Returns a {@link Value} representation of the items currently stored in this builder.
   * @return contents of this builder
   */
  public Value value() {
    return value(null);
  }

  /**
   * Returns a {@link Value} representation of the items currently stored in this builder
   * annotated with the given item type.
   * @param type item type, may be {@code null}
   * @return contents of this builder
   */
  public Value value(final Type type) {
    final Value first = firstValue;
    if(first != null) return first;
    final TreeSeqBuilder tree = builder;
    return tree != null ? tree.seq(type) : Empty.SEQ;
  }

  @Override
  public String toString() {
    final StringBuilder sb = new StringBuilder(getClass().getSimpleName()).append('[');
    final Iterator<Item> iter = firstValue != null ? firstValue.iterator() :
      builder != null ? builder.iterator() : Collections.<Item>emptyIterator();
    if(iter.hasNext()) {
      sb.append(iter.next());
      while(iter.hasNext()) sb.append(", ").append(iter.next());
    }
    return sb.append(']').toString();
  }
}


text:
package com.darkhouse.gdefence.Level.Ability.Mob;

import com.darkhouse.gdefence.GDefence;
import com.darkhouse.gdefence.Helpers.AssetLoader;
import com.darkhouse.gdefence.Helpers.FontLoader;
import com.darkhouse.gdefence.Level.Ability.Tools.DamageType;
import com.darkhouse.gdefence.Level.Ability.Tools.Effect;
import com.darkhouse.gdefence.Level.Ability.Mob.Modifiers.Evasion;
import com.darkhouse.gdefence.Level.Ability.Tools.Cooldown;
import com.darkhouse.gdefence.Level.Mob.Mob;
import com.darkhouse.gdefence.Level.Tower.Tower;
import com.darkhouse.gdefence.Objects.DamageSource;

public class GreatEvasion extends MobAbility implements MobAbility.ISpawn{

    private static class GreatEvasionBuff extends Effect<Mob> implements IGetDmg, IListener{
        private Evasion evasion;

        public GreatEvasionBuff(float cdCap) {
            super(true, false, -1, "greatEvasion", IGetDmg.class);
            evasion = new Evasion(1);
            setCooldownable(new Cooldown(cdCap));
        }

        @Override
        public void apply() {

        }

        @Override
        public float getDmg(DamageSource source, DamageType type, float dmg) {
            if (getCooldownObject().isReady() && type == DamageType.Physic && evasion.getDmg(source, type,  dmg) == 0){
                getCooldownObject().resetCooldown();
                return 0;
            }else return dmg;
        }

//        @Override
//        public void act(float delta) {
//            //super.act(delta);
//            getCooldownObject().act(delta);
//        }
    }
    public static class P extends AbilityPrototype {
        private float cdCap;

        public P(float cdCap) {
            super("greatEvasion", false, ISpawn.class);
            this.cdCap = cdCap;

        }
        public MobAbility getAbility(){
            return new GreatEvasion(this);
        }

        @Override
        public String getTooltip() {
            AssetLoader l = GDefence.getInstance().assetLoader;
             return l.getWord("greatEvasionTooltip1") + System.getProperty("line.separator") +
                     l.getWord("greatEvasionTooltip2") + " " + FontLoader.colorString(Float.toString(cdCap), 10) + " " +
                     l.getWord("greatEvasionTooltip3");
        }
    }

    private GreatEvasionBuff buff;

    public GreatEvasion(P prototype) {
        super(prototype);
//        super("Great Evasion", false);
        buff = new GreatEvasionBuff(prototype.cdCap);
    }

    @Override
    public void init() {
//        evasion = new Evasion(1);
        buff.setOwner(owner);
    }

    @Override
    public void spawned() {
        owner.addEffect(buff);
    }

}


text:
//
//  OALAction.h
//  ObjectAL
//
//  Created by Karl Stenerud on 10-09-18.
//
//  Copyright (c) 2009 Karl Stenerud. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall remain in place
// in this source code.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Attribution is not required, but appreciated :)
//

#import <Foundation/Foundation.h>
#import "ObjectALConfig.h"

#if OBJECTAL_CFG_USE_COCOS2D_ACTIONS

#pragma mark Cocos2d Subclassing

#import "cocos2d.h"

/** Generates common code required to subclass from a cocos2d action
 * while maintaining the functionality of an OALAction.
 */
#define COCOS2D_SUBCLASS_HEADER(CLASS_A,CLASS_B)	\
@interface CLASS_A: CLASS_B	\
{	\
	bool started_;	\
}	\
	\
@property(nonatomic,readonly,assign) bool running;	\
- (void) runWithTarget:(id) target;	\
- (void) prepareWithTarget:(id) target;	\
- (void) stopAction;	\
- (void) updateCompletion:(float) proportionComplete;	\
	\
@end

/** Generates common code required to subclass from a cocos2d action
 * while maintaining the functionality of an OALAction.
 */
#define COCOS2D_SUBCLASS(CLASS_A)	\
@implementation CLASS_A	\
	\
- (id) init	\
{	\
	return [self initWithDuration:0];	\
}	\
	\
-(void) startWithTarget:(id) targetIn	\
{	\
	[super startWithTarget:targetIn];	\
	[self prepareWithTarget:targetIn];	\
	started_ = YES;	\
	[self runWithTarget:targetIn];	\
}	\
	\
- (void) update:(float) proportionComplete	\
{	\
	[super update:proportionComplete];	\
	[self updateCompletion:proportionComplete];	\
}	\
	\
- (bool) running	\
{	\
	return !self.isDone;	\
}	\
	\
- (void) runWithTarget:(id) targetIn	\
{	\
	if(!started_)	\
	{	\
		[[CCActionManager sharedManager] addAction:self target:targetIn paused:NO];	\
	}	\
}	\
	\
- (void) stopAction	\
{	\
	[[CCActionManager sharedManager] removeAction:self];	\
}	\

#endif /* OBJECTAL_CFG_USE_COCOS2D_ACTIONS */

/* There are two versions of the actions which can be used: ObjectAL and Cocos2d.
 * It's usually more convenient when using Cocos2d to have all actions as part of
 * the Cocos2d action system.  You can set this in ObjectALConfig.h
 */
#if !OBJECTAL_CFG_USE_COCOS2D_ACTIONS

#pragma mark -
#pragma mark OALAction (ObjectAL version)

/**
 * Represents an action that can be performed on an object.
 */
@interface OALAction : NSObject
{
    /** \cond */
	float duration_;
	float elapsed_;
	bool running_;
    /** \endcond */

	/** If TRUE, this action is running via OALActionManager. */
	bool runningInManager_;
}

#pragma mark Properties

/** The target to perform the action on.  WEAK REFERENCE. */
@property(nonatomic,readonly,assign) id target;

/** The duration of the action, in seconds. */
@property(nonatomic,readonly,assign) float duration;

/** The amount of time that has elapsed for this action, in seconds. */
@property(nonatomic,readwrite,assign) float elapsed;

/** If true, the action is currently running. */
@property(nonatomic,readonly,assign) bool running;

#pragma mark Object Management

/** Initialize an action.
 *
 * @param duration The duration of this action in seconds.
 * @return The initialized action.
 */
- (id) initWithDuration:(float) duration;

#pragma mark Functions

/** Run this action on a target.
 *
 * @param target The target to run the action on.
 */
- (void) runWithTarget:(id) target;

/** Called by runWithTraget to do any final preparations before running.
 * Subclasses must ensure that duration is valid when this method returns.
 *
 * @param target The target to run the action on.
 */
- (void) prepareWithTarget:(id) target;

/** Called by runWithTarget to start the action running.
 */
- (void) startAction;

/** Called by OALActionManager to update this action's progress.
 *
 * @param proportionComplete The proportion of this action's duration that has elapsed.
 */
- (void) updateCompletion:(float) proportionComplete;

/** Stop this action.
 */
- (void) stopAction;

@end

#else /* !OBJECTAL_CFG_USE_COCOS2D_ACTIONS */

COCOS2D_SUBCLASS_HEADER(OALAction, CCActionInterval);

#endif /* !OBJECTAL_CFG_USE_COCOS2D_ACTIONS */

#pragma mark -
#pragma mark OALPropertyAction

@interface OALPropertyAction: OALAction

/** The value that the property in the target will hold at the start of the action. */
@property(nonatomic,readwrite,assign) float startValue;

/** The value that the property in the target will hold at the end of the action. */
@property(nonatomic,readwrite,assign) float endValue;

#pragma mark Object Management

/** Create a new action using the default function.
 * The start value will be the current value of the target this action is applied to.
 *
 * @param duration The duration of this action in seconds.
 * @param propertyKey The property to modify.
 * @param endValue The "ending" value that this action will converge upon when setting the target's property.
 * @return A new action.
 */
+ (id) actionWithDuration:(float) duration
              propertyKey:(NSString*) propertyKey
                 endValue:(float) endValue;

/** Create a new action.
 *
 * @param duration The duration of this action in seconds.
 * @param propertyKey The property to modify.
 * @param startValue The "starting" value that this action will diverge from when setting the target's
 *                   property. If NAN, use the current value from the target.
 * @param endValue The "ending" value that this action will converge upon when setting the target's property.
 * @return A new action.
 */
+ (id) actionWithDuration:(float) duration
              propertyKey:(NSString*) propertyKey
			   startValue:(float) startValue
				 endValue:(float) endValue;

/** Initialize an action using the default function.
 * The start value will be the current value of the target this action is applied to.
 *
 * @param duration The duration of this action in seconds.
 * @param propertyKey The property to modify.
 * @param endValue The "ending" value that this action will converge upon when setting the target's property.
 * @return The initialized action.
 */
- (id) initWithDuration:(float) duration
            propertyKey:(NSString*) propertyKey
               endValue:(float) endValue;

/** Initialize an action.
 *
 * @param duration The duration of this action in seconds.
 * @param propertyKey The property to modify.
 * @param startValue The "starting" value that this action will diverge from when setting the target's
 *                   property. If NAN, use the current value from the target.
 * @param endValue The "ending" value that this action will converge upon when setting the target's property.
 * @return The initialized action.
 */
- (id) initWithDuration:(float) duration
            propertyKey:(NSString*) propertyKey
			 startValue:(float) startValue
			   endValue:(float) endValue;

@end

#pragma mark -
#pragma mark OALEaseAction

typedef float (*EaseFunctionPtr)(float);

typedef enum
{
    kOALEaseIn,
    kOALEaseOut,
    kOALEaseInOut,
} OALEasePhase;

typedef enum
{
    kOALEaseShapeSine,
    kOALEaseShapeExponential,
} OALEaseShape;

/**
 * Applies an easing function to another action.
 * Normally, an action progresses at a linear rate. An ease changes that to a
 * curve.
 */
@interface OALEaseAction: OALAction
{
    OALAction* action_;
}

/** Create a new ease action.
 *
 * @param shape The shape of the curve to apply.
 * @param phase What phase of the action to apply the curve to.
 * @action The action to apple the curve to.
 * @return A new action.
 */
+ (OALEaseAction*) actionWithShape:(OALEaseShape) shape
                             phase:(OALEasePhase) phase
                            action:(OALAction*) action;

/** Initialize an ease action.
 *
 * @param shape The shape of the curve to apply.
 * @param phase What phase of the action to apply the curve to.
 * @action The action to apple the curve to.
 * @return The initialized action.
 */
- (id) initWithShape:(OALEaseShape) shape
               phase:(OALEasePhase) phase
              action:(OALAction*) action;

/** Get a pointer to an ease function of the specified shape and phase.
 *
 * @param shape The shape of the curve to apply.
 * @param phase What phase of the action to apply the curve to.
 * @return a pointer to the appropriate function.
 */
+ (EaseFunctionPtr) easeFunctionForShape:(OALEaseShape) shape
                                   phase:(OALEasePhase) phase;

@end


text:
stgo-makerspace
===============

Repositorio para la aplicación movil a desarrollar


text:
var get = Ember.get;

module("Ember.hasMany");

test("it exists", function() {
  ok(Ember.hasMany);
});

test("is a CP macro", function() {
  var Comment = Ember.Model.extend({
        token: Ember.attr(String)
      }),
      cp = Ember.hasMany(Comment, { key: 'comments', embedded: true }),
      Article = Ember.Model.extend({
        comments: cp
      });

  Comment.primaryKey = 'token';

  ok(cp instanceof Ember.ComputedProperty);

  var article = Article.create();
  Ember.run(article, article.load, 1, {comments: Ember.A([{token: 'a'}, {token: 'b'}])});
  var comments = Ember.run(article, article.get, 'comments');

  ok(comments instanceof Ember.EmbeddedHasManyArray);
  equal(comments.get('modelClass'), Comment);
  equal(comments.get('parent'), article);
});

test("creates Ember.HasManyArray if embedded is set to false", function() {
var Comment = Ember.Model.extend({
        token: Ember.attr(String)
      }),
      cp = Ember.hasMany(Comment, { key: 'comments' }),
      Article = Ember.Model.extend({
        comments: cp
      });

  Comment.primaryKey = 'token';

  ok(cp instanceof Ember.ComputedProperty);

  var article = Article.create();
  Ember.run(article, article.load, 1, {comments: Ember.A([1, 2])});
  var comments = Ember.run(article, article.get, 'comments');

  ok(comments instanceof Ember.HasManyArray);
  equal(comments.get('modelClass'), Comment);
  equal(comments.get('parent'), article);
});

test("using it in a model definition", function() {
  var Comment = Ember.Model.extend({
        token: Ember.attr(String)
      }),
      Article = Ember.Model.extend({
        comments: Ember.hasMany(Comment, { key: 'comments', embedded: true })
      });

  Comment.primaryKey = 'token';

  var article = Article.create();
  Ember.run(article, article.load, 1, {comments: Ember.A([{token: 'a'}, {token: 'b'}])});

  equal(article.get('comments.length'), 2);
  equal(Ember.run(article, article.get, 'comments.firstObject.token'), 'a');
});

test("model can be specified with a string instead of a class", function() {
  var Article = Ember.Model.extend({
      comments: Ember.hasMany('Ember.CommentModel', { key: 'comments', embedded: true })
      }),
      Comment = Ember.CommentModel = Ember.Model.extend({
        token: Ember.attr(String)
      });

  Comment.primaryKey = 'token';

  var article = Article.create();
  Ember.run(article, article.load, 1, {comments: Ember.A([{token: 'a'}, {token: 'b'}])});

  equal(article.get('comments.length'), 2);
  equal(Ember.run(article, article.get, 'comments.firstObject.token'), 'a');
});

test("when fetching an association getHasMany is called", function() {
  expect(4);

  var Comment = Ember.Model.extend({
        token: Ember.attr(String)
      }),
      Article = Ember.Model.extend({
        comments: Ember.hasMany(Comment, { key: 'comments', embedded: true })
      });

  Comment.primaryKey = 'token';

  var article = Article.create();
  article.getHasMany = function(key, type, meta) {
    equal(key, 'comments', "key passed to getHasMany should be the same as key in hasMany options");
    equal(type, Comment, "type of the association should be passed to getHasMany");
    equal(meta.kind, 'hasMany', "metadata should be passed to getHasMany");

    return 'foobar';
  };

  Ember.run(article, article.load, 1, {comments: Ember.A([{token: 'a'}, {token: 'b'}])});

  equal(article.get('comments'), 'foobar', "value returned from getHasMany should be returned as an association");
});

test("toJSON uses the given relationship key", function() {
  expect(1);

  var Comment = Ember.Model.extend({
        token: Ember.attr(String)
      }),
      Article = Ember.Model.extend({
        comments: Ember.hasMany(Comment, { key: 'comment_ids' })
      });

  Comment.primaryKey = 'token';

  var article = Article.create();

  Ember.run(article, article.load, 1, { comment_ids: Ember.A(['a'] )});

  deepEqual(article.toJSON(), { comment_ids: ['a'] }, "Relationship ids should be serialized only under the given key");
});

test("materializing the relationship should not dirty the record", function() {
  expect(2);

  var Author = Ember.Model.extend({
        id: Ember.attr()
      }),
      Post = Ember.Model.extend({
        id: Ember.attr(),
        authors: Ember.hasMany(Author, {key: 'author_ids'})
      });

  Post.adapter = Ember.FixtureAdapter.create();
  Author.adapter = Ember.FixtureAdapter.create();

  var post = Ember.run(Post, Post.create);
  post.get('id');
  ok(!post.get('isDirty'), 'is not dirty before materializing the relationship');
  post.get('authors');
  ok(!post.get('isDirty'), 'is not dirty after materializing the relationship');
});

test("has many records created are available from reference cache", function() {

  var Company = Ember.Company = Ember.Model.extend({
     id: Ember.attr('string'),
     title: Ember.attr('string'),
     projects: Ember.hasMany('Ember.Project', {key:'projects', embedded: true})
  }),
    Project = Ember.Project = Ember.Model.extend({
        id: Ember.attr('string'),
        title: Ember.attr('string'),
        posts: Ember.hasMany('Ember.Post', {key: 'posts', embedded: true}),
        company: Ember.belongsTo('Ember.Company', {key:'company'})
    }),
    Post = Ember.Post = Ember.Model.extend({
        id: Ember.attr('string'),
        title: Ember.attr('string'),
        body: Ember.attr('string'),
        project: Ember.belongsTo('Ember.Project', {key:'project'})
    });

  var compJson = {
    id:1,
    title:'coolio',
    projects:[{
          id: 1,
          title: 'project one title',
          company: 1,
          posts: [{id: 1, title: 'title', body: 'body', project:1 },
                  {id: 2, title: 'title two', body: 'body two', project:1 }]
      }]
    };

  Company.load([compJson]);
  var company = Company.find(1);

  var project = company.get('projects.firstObject');
  var projectFromCacheViaFind = Project.find(project.get('id'));
  var projectRecordFromCache = Project._referenceCache[project.get('id')].record;

  equal(project, projectFromCacheViaFind);
  equal(project, projectRecordFromCache);

  var post = project.get('posts.firstObject');
  var postFromCache = Post.find(post.get('id'));
  equal(post, postFromCache);

});


text:
package financial.market;

import agents.EconomicAgent;
import agents.firm.GeographicalFirm;
import agents.firm.sales.SalesDepartment;
import agents.firm.sales.SalesDepartmentFactory;
import agents.firm.sales.SalesDepartmentOneAtATime;
import agents.firm.sales.exploration.SimpleBuyerSearch;
import agents.firm.sales.exploration.SimpleSellerSearch;
import agents.firm.sales.pricing.pid.SalesControlWithFixedInventoryAndPID;
import com.google.common.collect.Multimap;
import financial.utilities.Quote;
import financial.utilities.ShopSetPricePolicy;
import goods.Good;
import goods.GoodType;
import goods.UndifferentiatedGoodType;
import model.MacroII;
import model.scenario.Scenario;
import model.utilities.ActionOrder;
import model.utilities.dummies.GeographicalCustomer;
import model.utilities.scheduler.Priority;
import model.utilities.stats.collectors.enums.MarketDataType;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import sim.engine.SimState;
import sim.engine.Steppable;

import static org.mockito.Mockito.*;

/**
 *
Description

 *

 *

 *

 *
Notes

 * Created with IntelliJ
 *

 *

 *
References

 *
 * @author carrknight
 * @version 2013-11-04
 * @see
 */
public class GeographicalMarketTest
{

    final public static GoodType INPUT = new UndifferentiatedGoodType("testInput","Input");

    //make sure it schedule itself correctly
    @Test
    public void testMakeSureItSchedules() throws Exception
    {

        //make sure start() puts it on the schedule
        MacroII mocked = mock(MacroII.class);
        GeographicalMarket market = new GeographicalMarket(INPUT);

        market.start(mocked);
        verify(mocked,times(1)).scheduleSoon(ActionOrder.TRADE,market, Priority.FINAL);
        //now check that step makes it schedule again!
        market.step(mocked);
        verify(mocked,times(1)).scheduleTomorrow(ActionOrder.TRADE,market,Priority.FINAL);

        market.turnOff();
        mocked = mock(MacroII.class);
        market.step(mocked);
        verify(mocked,never()).scheduleTomorrow(ActionOrder.TRADE,market,Priority.FINAL); //shouldn't reschedule

    }

    //simple trade test
    // 1 seller with supply = 2 at price 10
    //3 customers maxPrice 20-30-40, only the last 2 buy
    //this is all mocked so that I can check the right methods are called!
    @Test
    public void testSellsToTheHigherCustomers()
    {
        //model to step
        MacroII macroII = new MacroII(1);

        //geographical market for oil!
        final GeographicalMarket market = new GeographicalMarket(INPUT);
        market.setPricePolicy(new ShopSetPricePolicy());
        market.start(macroII);

        //create the seller
        final GeographicalFirm seller = mock(GeographicalFirm.class);
        market.registerSeller(seller);

        //schedule the seller to sell two goods
        macroII.scheduleSoon(ActionOrder.TRADE, new Steppable() {
            @Override
            public void step(SimState state) {
                for (int i = 0; i < 2; i++) {
                    Good toSell = Good.getInstanceOfUndifferentiatedGood(INPUT);
                    Quote quote = market.submitSellQuote(seller, 10, toSell);
                    when(seller.has(toSell)).thenReturn(true);
                    //it should not have been cleared!
                    Assert.assertTrue(quote.getPriceQuoted() == 10);
                }

            }
        });

        //create 3 fake buyers
        //create and start the 3 buyers
        final GeographicalCustomer customers[] = new GeographicalCustomer[3];
        for(int i=0; i<3; i++)
        {
            customers[i] = mock(GeographicalCustomer.class);
            when(customers[i].getModel()).thenReturn(macroII);
            //if they are ever asked to choose, choose the seller
            when(customers[i].chooseSupplier(any(Multimap.class))).thenReturn(seller);
            //make sure buyer is never bankrupt
            when(customers[i].hasHowMany(UndifferentiatedGoodType.MONEY)).thenReturn(Integer.MAX_VALUE);
            market.registerBuyer(customers[i]);
        }
        //step them so that they place a quote during trade!
        macroII.scheduleSoon(ActionOrder.TRADE,new Steppable() {
            @Override
            public void step(SimState state) {

                for(int i=0; i<3; i++)
                {
                    when(customers[i].getMaxPrice()).thenReturn(Integer.valueOf(20+i*10)); //need this so that the market sorts the customers correctly
                    //make the customers buy
                    Quote quote = market.submitBuyQuote(customers[i],20+i*10);
                    //it should not have been cleared!
                    Assert.assertTrue(quote.getPriceQuoted() ==20+i*10);

                }

            }
        });

        macroII.start();
        macroII.schedule.step(macroII);

        //only the last two customers should have received it!
        verify(customers[1],times(1)).reactToFilledBidQuote(any(), any(Good.class), anyInt(), any(EconomicAgent.class));
        verify(customers[2],times(1)).reactToFilledBidQuote(any(), any(Good.class), anyInt(), any(EconomicAgent.class));
        verify(customers[0],never()).reactToFilledBidQuote(any(), any(Good.class), anyInt(), any(EconomicAgent.class));

    }

    //like above, but the most expensive customer replaces its bid with a new one so that it should be the only one buying
    //simple trade test
    @Test
    public void testSellsToTheHighestCustomer()
    {
        //model to step
        MacroII macroII = new MacroII(1);

        //geographical market for oil!
        final GeographicalMarket market = new GeographicalMarket(INPUT);
        market.setPricePolicy(new ShopSetPricePolicy());
        market.start(macroII);

        //create the seller
        final GeographicalFirm seller = mock(GeographicalFirm.class);
        market.registerSeller(seller);

        //schedule the seller to sell two goods
        macroII.scheduleSoon(ActionOrder.TRADE, new Steppable() {
            @Override
            public void step(SimState state) {
                for (int i = 0; i < 2; i++) {
                    Good toSell = Good.getInstanceOfUndifferentiatedGood(INPUT);
                    Quote quote = market.submitSellQuote(seller, 10, toSell);
                    when(seller.has(toSell)).thenReturn(true);
                    //it should not have been cleared!
                    Assert.assertTrue(quote.getPriceQuoted() == 10);
                }

            }
        });

        //create 3 fake buyers
        //create and start the 3 buyers
        final GeographicalCustomer customers[] = new GeographicalCustomer[3];
        for(int i=0; i<3; i++)
        {
            customers[i] = mock(GeographicalCustomer.class);
            when(customers[i].getModel()).thenReturn(macroII);
            //if they are ever asked to choose, choose the seller
            when(customers[i].chooseSupplier(any(Multimap.class))).thenReturn(seller);
            //make sure buyer is never bankrupt
            when(customers[i].hasHowMany(UndifferentiatedGoodType.MONEY)).thenReturn(Integer.MAX_VALUE);
            market.registerBuyer(customers[i]);
        }
        //step them so that they place a quote during trade!
        macroII.scheduleSoon(ActionOrder.TRADE,new Steppable() {
            @Override
            public void step(SimState state) {

                for(int i=0; i<3; i++)
                {
                    when(customers[i].getMaxPrice()).thenReturn(Integer.valueOf(20+i*10)); //need this so that the market sorts the customers correctly
                    //make the customers buy
                    Quote quote = market.submitBuyQuote(customers[i],20+i*10);
                    //it should not have been cleared!
                    Assert.assertTrue(quote.getPriceQuoted() ==20+i*10);

                }

            }
        });

        //ADDITION:
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                //a new quote!
                Quote quote = market.submitBuyQuote(customers[2],40);
                //it should not have been cleared!
                Assert.assertTrue(quote.getPriceQuoted() ==40);
                return null;
            }
        }).when(customers[2]).reactToFilledBidQuote(any(), any(Good.class), anyInt(), any(EconomicAgent.class));

        macroII.start();
        macroII.schedule.step(macroII);

        //only the last two customers should have received it!
        verify(customers[1],never()).reactToFilledBidQuote(any(), any(Good.class), anyInt(), any(EconomicAgent.class));
        verify(customers[2],times(2)).reactToFilledBidQuote(any(), any(Good.class), anyInt(), any(EconomicAgent.class));
        verify(customers[0],never()).reactToFilledBidQuote(any(), any(Good.class), anyInt(), any(EconomicAgent.class));

    }

    @Test
    public void noSuccesfulSale()
    {

        //the only seller prices its good to high, nobody buys.
        //model to step
        MacroII macroII = new MacroII(1);

        //geographical market for oil!
        final GeographicalMarket market = new GeographicalMarket(INPUT);
        market.setPricePolicy(new ShopSetPricePolicy());
        market.start(macroII);

        //create the seller
        final GeographicalFirm seller = mock(GeographicalFirm.class);
        market.registerSeller(seller);

        //schedule the seller to sell two goods
        macroII.scheduleSoon(ActionOrder.TRADE, new Steppable() {
            @Override
            public void step(SimState state) {
                for (int i = 0; i < 2; i++) {
                    Good toSell = Good.getInstanceOfUndifferentiatedGood(INPUT);
                    Quote quote = market.submitSellQuote(seller, 10000, toSell);
                    when(seller.has(toSell)).thenReturn(true);
                    //it should not have been cleared!
                    Assert.assertTrue(quote.getPriceQuoted() == 10000);
                }

            }
        });

        //create 3 fake buyers
        //create and start the 3 buyers
        final GeographicalCustomer customers[] = new GeographicalCustomer[3];
        for(int i=0; i<3; i++)
        {
            customers[i] = mock(GeographicalCustomer.class);
            //if they are ever asked to choose, choose the seller
            when(customers[i].chooseSupplier(any(Multimap.class))).thenReturn(null);
            //make sure buyer is never bankrupt
            when(customers[i].hasHowMany(UndifferentiatedGoodType.MONEY)).thenReturn(Integer.MAX_VALUE);
            market.registerBuyer(customers[i]);
        }
        //step them so that they place a quote during trade!
        macroII.scheduleSoon(ActionOrder.TRADE,new Steppable() {
            @Override
            public void step(SimState state) {

                for(int i=0; i<3; i++)
                {
                    when(customers[i].getMaxPrice()).thenReturn(Integer.valueOf(20+i*10)); //need this so that the market sorts the customers correctly
                    //make the customers buy
                    Quote quote = market.submitBuyQuote(customers[i],20+i*10);
                    //it should not have been cleared!
                    Assert.assertTrue(quote.getPriceQuoted() ==20+i*10);

                }

            }
        });

        macroII.start();
        macroII.schedule.step(macroII);

        //only the last two customers should have received it!
        verify(customers[1],never()).reactToFilledBidQuote(any(), any(Good.class), anyInt(), any(EconomicAgent.class));
        verify(customers[2],never()).reactToFilledBidQuote(any(), any(Good.class), anyInt(), any(EconomicAgent.class));
        verify(customers[0],never()).reactToFilledBidQuote(any(), any(Good.class), anyInt(), any(EconomicAgent.class));

    }

    //a test with no mocks
    @Test
    public void dressedSimpleSellerTest()
    {

        //the only seller prices its good to high, nobody buys.
        //model to step
        MacroII macroII = new MacroII(1);
        final GeographicalCustomer customers[] = new GeographicalCustomer[100];
        final GeographicalCustomer farCustomers[] = new GeographicalCustomer[100];

        Scenario simpleSellerOilScenario = new Scenario(macroII) {
            @Override
            public void start() {

                //geographical market for oil!
                final GeographicalMarket market = new GeographicalMarket(INPUT);
                market.setPricePolicy(new ShopSetPricePolicy());
                getMarkets().put(INPUT,market);

                //create the seller
                final GeographicalFirm seller =new GeographicalFirm(getModel(),0,0);
                getAgents().add(seller);
                //add the sales department to the seller
                SalesDepartment salesDepartment = SalesDepartmentFactory.incompleteSalesDepartment(seller, market,
                        new SimpleBuyerSearch(market,seller), new SimpleSellerSearch(market,seller), SalesDepartmentOneAtATime.class);
                //give the sale department a simple PID
                salesDepartment.setAskPricingStrategy(new SalesControlWithFixedInventoryAndPID(salesDepartment,50));
                //finally register it!
                seller.registerSaleDepartment(salesDepartment, INPUT);

                //receive 10 units a day!

                //schedule the seller to sell two goods
                getModel().scheduleSoon(ActionOrder.PRODUCTION, new Steppable() {
                    @Override
                    public void step(SimState state) {
                        for (int i = 0; i < 10; i++) {
                            Good toSell = Good.getInstanceOfUndifferentiatedGood(INPUT);
                            seller.receive(toSell,null);
                            seller.reactToPlantProduction(toSell);

                        }
                        getModel().scheduleTomorrow(ActionOrder.PRODUCTION,this);

                    }

                });

                //create 100 fake buyers, with max price from 1 to 100
                //create and start the 3 buyers
                for(int i=0; i<customers.length; i++)
                {
                    customers[i] =new GeographicalCustomer(getModel(),i+1,0,0,market);
                    getAgents().add(customers[i]);
                }
                //create another 100 fake buyers that all want to pay 200 but they are very very far. They shouldn't be able to buy anything!
                for(int i=0; i<farCustomers.length; i++)
                {
                    farCustomers[i] =new GeographicalCustomer(getModel(),200,500,500,market);
                    getAgents().add(farCustomers[i]);
                }
            }
        };
        macroII.setScenario(simpleSellerOilScenario);
        macroII.start();
        Market market = macroII.getMarket(INPUT);
        for(int i=0; i< 3000; i++)
        {
            macroII.schedule.step(macroII); //make 3000 step pass
            System.out.println(market.getLatestObservation(MarketDataType.CLOSING_PRICE));
        }
        //last price should be 90
        Assert.assertEquals(10,market.getLatestObservation(MarketDataType.VOLUME_TRADED),.0001d);
        Assert.assertEquals(91d,market.getLatestObservation(MarketDataType.CLOSING_PRICE),.0001d);

        //all distant agents bought nothing
        for(GeographicalCustomer farCustomer : farCustomers)
            Assert.assertEquals(0,farCustomer.hasHowMany(INPUT));

        //cheap people got nothing
        for(int i=0; i<90; i++)
        {
            Assert.assertEquals(0,customers[i].hasHowMany(INPUT));
        }

        //rich people got everything
        for(int i=90; i<customers.length; i++)
        {
            Assert.assertEquals(1,customers[i].hasHowMany(INPUT));
        }

    }

    //treemap consistency errors
    @Test
    public void samePriceDoesNotMeanSamePerson()
    {
        MacroII macroII = new MacroII(1);
        macroII.start();

        final GeographicalMarket market = new GeographicalMarket(INPUT);
        market.setPricePolicy(new ShopSetPricePolicy());
        market.start(macroII);

        //add two customers with the same price. then remove one. If the backing tree map is done correctly it will not remove both quotes
        final GeographicalCustomer customers[] = new GeographicalCustomer[2];
        customers[0] = new GeographicalCustomer(macroII,100,0,0,market);
        customers[1] = new GeographicalCustomer(macroII,100,0,0,market);
        customers[0].start(macroII);
        customers[1].start(macroII);

        macroII.schedule.step(macroII); //one step

        Assert.assertEquals(1,market.removeAllBuyQuoteByBuyer(customers[0]).size());

    }

}


text:
package com.intellij.ide.errorTreeView;

import com.intellij.openapi.vfs.VirtualFile;
import javax.annotation.Nonnull;

public class SimpleErrorData {
  private final ErrorTreeElementKind myKind;
  private final String[] myMessages;
  private final VirtualFile myVf;

  public SimpleErrorData(@Nonnull ErrorTreeElementKind kind, String[] messages, VirtualFile vf) {
    myKind = kind;
    myMessages = messages;
    myVf = vf;
  }

  @Nonnull
  public ErrorTreeElementKind getKind() {
    return myKind;
  }

  public String[] getMessages() {
    return myMessages;
  }

  public VirtualFile getVf() {
    return myVf;
  }
}


text:
import React from 'react'
import {expect} from 'chai'
import {createStore} from 'redux'
import {shallow} from 'enzyme'

import rootReducer from 'APP/app/reducers/index'
import {setProduct, addProductToOrder} from './product'
import {AllProducts} from 'APP/app/components/AllProducts'

describe('Product actions', () => {
  const testProduct = {
      name: 'TheBike',
      category: 'Test',
      price: 1000,
      color: ['White', 'Red', 'Black'],
      size: ['Large', 'Medium', 'Small'],
      images: ['http://www.bikesdirect.com/products/gravity/images/avenue-a-xiv-org-2100.jpg'],
      quantity: 8,
      reviewStars: 4.5,
      description: 'This is a bike created only for this test'
      }
    describe('setProduct', () => {

        it('returns properly formatted action', () => {

            expect(setProduct(testProduct)).to.be.deep.equal({
                type: 'SET_SELECTED_PRODUCT',
                selectedProduct: testProduct
            })
        })
    })

    describe('addProductToOrder', () => {

        it('returns properly formatted action', () => {

            expect(addProductToOrder(testProduct)).to.be.deep.equal({
                type: 'ADD_PRODUCT_TO_ORDER',
                product: testProduct
            })
        })
    })
})

describe('Product reducer', () => {
    const testProduct = {
      name: 'TheBike',
      category: 'Test',
      price: 1000,
      color: ['White', 'Red', 'Black'],
      size: ['Large', 'Medium', 'Small'],
      images: ['http://www.bikesdirect.com/products/gravity/images/avenue-a-xiv-org-2100.jpg'],
      quantity: 8,
      reviewStars: 4.5,
      description: 'This is a bike created only for this test'
      }
    let testStore
    beforeEach('Create testing store', () => {
        testStore = createStore(rootReducer)
    })

    it('has expected initial state', () => {
        expect(testStore.getState().product).to.be.deep.equal(
            {
              products: [],
              selectedProduct: {}
            }
        )
    })

    describe('SET_SELECTED_PRODUCT', () => {

        it('sets selectedProduct to action selectedProduct', () => {
            testStore.dispatch({ type: 'SET_SELECTED_PRODUCT', selectedProduct: testProduct })
            const newState = testStore.getState()
            expect(newState.product.selectedProduct).to.be.deep.equal(testProduct)
        })
    })
})

describe.only('AllProducts Component', () => {
  let products = [
{
id: 1,
name: "RoadMaster X-Treme",
category: "Road",
price: 135900,
images: [
"http://www.bikesdirect.com/products/gravity/images/avenue-a-xiv-org-2100.jpg",
"http://www.bikesdirect.com/products/gravity/images/avenue-a-xiv-wht-2100.jpg",
"http://www.bikesdirect.com/products/gravity/images/avenue-a-xiv-blk-2100.jpg"
],
color: [
"White",
"Red",
"Black"
],
size: [
"Large",
"Medium",
"Small"
],
quantity: 7480,
reviewStars: "3.9",
description: "SO EXTREME YOUR FACE WILL MELT! us vestibulum sagittis sapien cum sociis natoque penatibus et magnis dis parturient montes nascetur ridiculus mus etiam vel augue vestibulum rutrum rutrum neque aenean auctor gravida sem praesent id massa id nisl venenatis lacinia aenean sit amet justo morbi ut odio cras mi pede malesuada in",
created_at: "2017-04-24T18:13:57.174Z",
updated_at: "2017-04-24T18:13:57.174Z"
},
{
id: 2,
name: "Mount-Pain X-FIRE",
category: "Mountain",
price: 210051,
images: [
"http://www.bikesdirect.com/products/gravity/images/avenue-a-xiv-org-2100.jpg",
"http://www.bikesdirect.com/products/gravity/images/avenue-a-xiv-wht-2100.jpg"
],
color: [
"White",
"Red",
"Pink"
],
size: [
"Large",
"Medium",
"Small"
],
quantity: 2403,
reviewStars: "3.9",
description: "SUCH PAIN AHHH! us vestibulum sagittis sapien cum sociis natoque penatibus et magnis dis parturient montes nascetur ridiculus mus etiam vel augue vestibulum rutrum rutrum neque aenean auctor gravida sem praesent id massa id nisl venenatis lacinia aenean sit amet justo morbi ut odio cras mi pede malesuada in",
created_at: "2017-04-24T18:13:57.174Z",
updated_at: "2017-04-24T18:13:57.174Z"
},
{
id: 3,
name: "Mount-Pain X-FIRE",
category: "Mountain",
price: 210052,
images: [
"http://www.bikesdirect.com/products/gravity/images/avenue-a-xiv-blk-2100.jpg"
],
color: [
"Red",
"Blue"
],
size: [
"Large",
"Medium",
"Small"
],
quantity: 2403,
reviewStars: "3.2",
description: "SUCH PAIN AHHH! MEDIUM IS ON THE SMALL SIDE OF THINGS! us vestibulum sagittis sapien cum sociis natoque penatibus et magnis dis parturient montes nascetur ridiculus mus etiam vel augue vestibulum rutrum rutrum neque aenean auctor gravida sem praesent id massa id nisl venenatis lacinia aenean sit amet justo morbi ut odio cras mi pede malesuada in",
created_at: "2017-04-24T18:13:57.175Z",
updated_at: "2017-04-24T18:13:57.175Z"
}
]
let all_products = shallow(<AllProducts products={products}/>)

it('should be a <div> ', () => {
        expect(all_products.is('div')).to.be.equal(true);
    })
})


text:
with open('022.txt') as f:
    names = f.read()[1:-1]
    names = names.split('","')
    names.sort()

print sum(pos * sum(ord(letter) - ord('A') + 1 for letter in name) for pos, name in enumerate(names, start=1))


text:
Button demo
###########

Overview
********

A simple button demo showcasing the use of GPIO input with interrupts.

Requirements
************

The demo assumes that a push button is connected to one of GPIO lines. The
sample code is configured to work on boards with user defined buttons and that
have defined the SW0_* variable in board.h

To use this sample, you will require a board that defines the user switch in its
header file. The :file:`board.h` must define the following variables:

- SW0_GPIO_NAME
- SW0_GPIO_PIN

The following boards currently define the above variables:

- bbc_microbit
- cc3200_launchxl
- frdm_k64f
- nrf51_pca10028
- nrf52840_pca10056
- nrf52_pca10040
- nucleo_f103rb
- :ref:`quark_d2000_devboard`
- quark_se_c1000_devboard
- quark_se_c1000_ss_devboard

Building and Running
********************

This sample can be built for multiple boards, in this example we will build it
for the nucleo_f103rb board:

.. code-block:: console

   $ cd samples/basic/button
   $ make BOARD=nucleo_f103rb

After startup, the program looks up a predefined GPIO device, and configures the
pin in input mode, enabling interrupt generation on falling edge. During each
iteration of the main loop, the state of GPIO line is monitored and printed to
the serial console. When the input button gets pressed, the interrupt handler
will print an information about this event along with its timestamp.


text:
<?php defined('SYSPATH') or die('No direct script access.');

return array
(
	// File used
	// FALSE or name of message file (ex: 'label_messages')
	'label_message_file'      => FALSE,
	// File used for validation messages
	// FALSE or name of the message file (ex: 'validation_messages')
	'validation_message_file' => 'validation',
	// Whether to translate labels and error messages
	'translate'               => FALSE,
	// Close single html tags (TRUE =
. FALSE =
)
	'close_single_html_tags'  => TRUE,
	// Auto-generate IDs on form elements
	'auto_id'                 => TRUE,
	// The directory for the formo templates (ex: 'formo' or 'formo_bootstrap')
	'template_dir'            => 'bootstrap/',
	// The extension for the formo templates
	// FALSE or extension (ex: FALSE looks for 'template.php', 'html' looks for 'template.html.php')
	'template_ext'            => FALSE,
	// Namespace fields (name="parent_alias[field_alias]")
	'namespaces'              => TRUE,
	// Driver used for ORM integration (Deprecated in favor of using the Formo_ORM trait)
	'orm_driver'              => 'kohana',
	// When using ORM driver, whether to automatically add mysql field base rules to formo field
	'model_base_rules'        => TRUE,
	// Automatically add these rules to 'input' fields for html5 compatability
	'input_rules' => array
	(
		'email'          => array(array('email')),
		'tel'            => array(array('phone')),
		'url'            => array(array('url')),
		'date'           => array(array('date')),
		'datetime'       => array(array('date')),
		'datetime-local' => array(array('date')),
		'color'          => array(array('color')),
		'week'           => array(array('regex', array(':value', '/^\d{4}-[Ww](?:0[1-9]|[1-4][0-9]|5[0-2])$/'))),
		'time'           => array(array('regex', array(':value', '/^(?:([0-1]?[0-9])|([2][0-3])):(?:[0-5]?[0-9])(?::([0-5]?[0-9]))?$/'))),
		'month'          => array(array('regex', array(':value', '/^\d{4}-(?:0[1-9]|1[0-2])$/'))),
		'range'          => array(
			array('digit'),
			array('Formo::range', array(':field', ':form')),
		),
		'number'        => array(
			array('digit'),
			array('Formo::range', array(':field', ':form')),
		),
	),
);