text:
<?php

namespace Cothema\OpeningHours\Test;

use Cothema\OpeningHours\Model\OpeningHours;
use Cothema\OpeningHours\Status as Tested;
use Nette\Utils\DateTime;
use Tester\Assert;

require_once __DIR__ . '/../bootstrap.php';

class Status extends \Tester\TestCase
{

    public function testCase1()
    {
        $openingHoursStatus = $this->getOpeningHours1();
        $openingHoursStatus->setTime(new DateTime('2015-12-01 16:00:00')); // Tuesday

        Assert::true($openingHoursStatus->isOpened());
        Assert::false($openingHoursStatus->getClosingAtWarning());
    }

    private function getOpeningHours1()
    {
        $openingHours = new OpeningHours;
        $openingHours->setOpeningHours([
            '0' => ['8:00', '20:00'], // Sunday
            '1' => ['15:00', '23:00'], // Monday
            '2' => ['15:00', '23:00'], // Tuesday
            '3' => ['14:00', '23:00'], // Wednesday
            '4' => ['20:00', '24:00'], // Thursday
            '5' => ['10:00', '12:00'], // Friday
            '6' => ['9:00', '16:00'] // Saturday
        ]);
        return new Tested($openingHours);
    }

    public function testCase2()
    {
        $openingHoursStatus = $this->getOpeningHours1();
        $openingHoursStatus->setTime(new DateTime('2015-11-30 11:00:00')); // Monday

        Assert::false($openingHoursStatus->isOpened());
        Assert::false($openingHoursStatus->getClosingAtWarning());
    }

    public function testCase3()
    {
        $openingHoursStatus = $this->getOpeningHours1();
        $openingHoursStatus->setTime(new DateTime('2015-11-30 21:05:00')); // Monday

        Assert::true($openingHoursStatus->isOpened());
        Assert::truthy($openingHoursStatus->getClosingAtWarning());
    }

    public function testCaseClosingNextDay1()
    {
        $openingHoursStatus = $this->getOpeningHoursClosingNextDay();

        $openingHoursStatus->setTime(new DateTime('2015-11-30 16:30:00')); // Monday

        Assert::true($openingHoursStatus->isOpened(), '1.1');
        Assert::false($openingHoursStatus->getClosingAtWarning(), '1.2');

        $openingHoursStatus->setTime(new DateTime('2015-11-30 14:30:00')); // Monday

        Assert::false($openingHoursStatus->isOpened(), '2.1');
        Assert::false($openingHoursStatus->getClosingAtWarning(), '2.2');
    }

    private function getOpeningHoursClosingNextDay()
    {
        $openingHours = new OpeningHours;
        $openingHours->setOpeningHours([
            '0' => ['8:00', '02:00 +1 day'], // Sunday
            '1' => ['15:00', '04:00 +1 day'], // Monday
            '2' => ['15:00', '02:00 +1 day'], // Tuesday
            '3' => ['14:00', '06:00 +1 day'], // Wednesday
            '4' => ['20:00', '08:00 +1 day'], // Thursday
            '5' => ['10:00', '01:00 +1 day'], // Friday
            '6' => ['9:00', '01:00 +1 day'] // Saturday
        ]);
        return new Tested($openingHours);
    }

    public function testCaseClosingNextDay2()
    {
        $openingHoursStatus = $this->getOpeningHoursClosingNextDay();

        $openingHoursStatus->setTime(new DateTime('2015-12-01 01:30:00')); // Tuesday (monday opening hours)

        Assert::true($openingHoursStatus->isOpened(), '1.1');
        Assert::false($openingHoursStatus->getClosingAtWarning(), '1.2');

        $openingHoursStatus->setTime(new DateTime('2015-12-01 05:30:00')); // Tuesday (monday opening hours)

        Assert::false($openingHoursStatus->isOpened(), '2.1');
        Assert::false($openingHoursStatus->getClosingAtWarning(), '2.2');

        $openingHoursStatus->setTime(new DateTime('2015-12-01 03:30:00')); // Tuesday (monday opening hours)

        Assert::true($openingHoursStatus->isOpened(), '3.1');
        Assert::contains('04:00', $openingHoursStatus->getClosingAtWarning(), '3.2');
    }

    public function testCaseClosingSpecificDay()
    {
        $openingHoursStatus = $this->getOpeningHoursSpecificDay();

        $openingHoursStatus->setTime(new DateTime('2015-12-01 10:30:00'));

        Assert::true($openingHoursStatus->isOpened(), '1.1');
        Assert::truthy($openingHoursStatus->getClosingAtWarning(), '1.2');

        $openingHoursStatus->setTime(new DateTime('2015-12-01 09:30:00'));

        Assert::false($openingHoursStatus->isOpened(), '2.1');
        Assert::false($openingHoursStatus->getClosingAtWarning(), '2.2');

        $openingHoursStatus->setTime(new DateTime('2015-12-02 05:30:00'));

        Assert::false($openingHoursStatus->isOpened(), '3.1');
        Assert::false($openingHoursStatus->getClosingAtWarning(), '3.2');

        $openingHoursStatus->setTime(new DateTime('2015-12-02 15:00:00'));

        Assert::false($openingHoursStatus->isOpened(), '4.1');
        Assert::false($openingHoursStatus->getClosingAtWarning(), '4.2');

        $openingHoursStatus->setTime(new DateTime('2015-12-01 16:00:00'));

        Assert::false($openingHoursStatus->isOpened(), '5.1');
        Assert::false($openingHoursStatus->getClosingAtWarning(), '5.2');

        $openingHoursStatus->setTime(new DateTime('2015-12-03 16:00:00'));

        Assert::false($openingHoursStatus->isOpened(), '6.1');
        Assert::false($openingHoursStatus->getClosingAtWarning(), '6.2');

        $openingHoursStatus->setTime(new DateTime('2015-12-04 16:00:00'));

        Assert::false($openingHoursStatus->isOpened(), '7.1');
        Assert::false($openingHoursStatus->getClosingAtWarning(), '7.2');

        $openingHoursStatus->setTime(new DateTime('2015-12-03 10:30:00'));

        Assert::true($openingHoursStatus->isOpened(), '8.1');
        Assert::truthy($openingHoursStatus->getClosingAtWarning(), '8.2');

        $openingHoursStatus->setTime(new DateTime('2015-12-04 10:30:00'));

        Assert::true($openingHoursStatus->isOpened(), '9.1');
        Assert::truthy($openingHoursStatus->getClosingAtWarning(), '9.2');
    }

    /* TO DO
      public function testCaseTimeRange1() {
      $openingHoursStatus = $this->getOpeningHoursNonstop();

      $result = $openingHoursStatus->isOpenedByTimeRange(new DateTime('2015-11-28 10:00:00'), new DateTime('2015-12-02 08:00:00'));
      Assert::true($result, '1.1');
      }

      public function testCaseTimeRange2() {
      $openingHoursStatus = $this->getEmptyHours();

      $result = $openingHoursStatus->isOpenedByTimeRange(new DateTime('2015-11-28 10:00:00'), new DateTime('2015-12-02 08:00:00'));
      Assert::false($result, '1.1');
      }
     */

    private function getOpeningHoursSpecificDay()
    {
        $openingHours = new OpeningHours;
        $openingHours->setOpeningHours([
            '0' => ['8:00', '02:00 +1 day'], // Sunday
            '1' => ['15:00', '04:00 +1 day'], // Monday
            '2' => ['15:00', '02:00 +1 day'], // Tuesday
            '3' => ['14:00', '06:00 +1 day'], // Wednesday
            '4' => ['20:00', '08:00 +1 day'], // Thursday
            '5' => ['10:00', '01:00 +1 day'], // Friday
            '6' => ['9:00', '01:00 +1 day'] // Saturday
        ]);
        $openingHours->addSpecificDay('2015-12-01', ['10:00', '11:00']); // Thuesday
        $openingHours->addSpecificDay('2015-12-02', FALSE); // Wednesday
        $openingHours->addSpecificDays(['2015-12-03', '2015-12-04'], ['10:00', '11:00']); // Thursday, Friday
        return new Tested($openingHours);
    }

    public function testCaseUndefined()
    {
        $openingHoursStatus = $this->getEmptyHours();

        $openingHoursStatus->setTime(new DateTime('2015-12-01 01:30:00')); // Tuesday

        Assert::false($openingHoursStatus->isOpened(), '1.1');
        Assert::false($openingHoursStatus->getClosingAtWarning(), '1.2');
    }

    private function getEmptyHours()
    {
        $openingHours = new OpeningHours;
        return new Tested($openingHours);
    }

    public function testCaseOpenedNonstop()
    {
        $openingHoursStatus = $this->getOpeningHoursNonstop();

        $openingHoursStatus->setTime(new DateTime('2015-12-01 01:30:00')); // Tuesday

        Assert::true($openingHoursStatus->isOpened(), '1.1');
        Assert::false($openingHoursStatus->getClosingAtWarning(), '1.2');
        Assert::true($openingHoursStatus->isOpenedNonstop(), '1.3');
    }

    private function getOpeningHoursNonstop()
    {
        $openingHours = new OpeningHours;
        $openingHours->setOpeningHours([
            '0' => TRUE, // Sunday
            '1' => TRUE, // Monday
            '2' => TRUE, // Tuesday
            '3' => TRUE, // Wednesday
            '4' => TRUE, // Thursday
            '5' => TRUE, // Friday
            '6' => TRUE // Saturday
        ]);
        return new Tested($openingHours);
    }

}

(new Status)->run();


text:
(function() {
  'use strict';

  log.d('-->bombwindow.LOADING_MODULE');

  // --------------------------------------------------------------------- //
  // -- Private, static members

  var _NORMAL_STROKE_WIDTH = 1; // in pixels
  var _PRIMED_STROKE_WIDTH = 6; // in pixels

  var _PRIMED_SIZE_RATIO = 1.75;

  function BombWindow(bombType, bombCount) {
    log.d('-->bombwindow.BombWindow');

    // ----------------------------------------------------------------- //
    // -- Private members

    var _rect = { x: 0, y: 0, w: 0, h: 0 }; // in pixels

    var _fontString = 'bold ' + 0 + 'px monospace';

    var _ellapsedTime = 0;

    var _bombCount = bombCount;

    var _bombType = bombType;

    var _isPrimed = false;

    function _update(deltaTime) {
      _ellapsedTime += deltaTime;
    }

    // The window, its current cool-down progress, and the next block.
    // The size of the window increases as the cool down progresses.
    function _draw(context) {
      if (game.bombsOn) {
        var x;
        var y;
        var w;
        var h;
        var strokeWidth;
        var fill;
        var stroke;
        var squareX;
        var squareY;

        if (_isPrimed) {
          w = _rect.w * _PRIMED_SIZE_RATIO;
          h = _rect.h * _PRIMED_SIZE_RATIO;
          x = _rect.x - (w - _rect.w) / 2;
          y = _rect.y - (h - _rect.h) / 2;
          strokeWidth = _PRIMED_STROKE_WIDTH;
          fill = game.MEDIUM_COLORS[2].str;
          stroke = game.LIGHT_COLORS[2].str;
        } else {
          x = _rect.x;
          y = _rect.y;
          w = _rect.w;
          h = _rect.h;
          strokeWidth = _NORMAL_STROKE_WIDTH;
          fill = game.DEFAULT_FILL.str;
          stroke = game.DEFAULT_STROKE.str;
        }

        // Draw the background and the border
        context.beginPath();
        context.lineWidth = strokeWidth;
        context.fillStyle = fill;
        context.strokeStyle = stroke;
        context.rect(x, y, w, h);
        context.fill();
        context.stroke();

        // Draw the square representing the bomb
        squareX = x + w * 0.45 - gameWindow.squarePixelSize;
        squareY = y + h * 0.5 - gameWindow.squarePixelSize * 0.5;
        Block.prototype.drawSquare(context, 7 + _bombType, squareX, squareY, 0);

        // Draw the text representing how many bombs are left
        x = x + w * 0.5;
        y = squareY + gameWindow.squarePixelSize;
        context.fillStyle = 'white';
        context.font = _fontString;
        context.fillText('x' + _bombCount, x, y);
      }
    }

    function _isPointOverWindow(point) {
      return point.x >= _rect.x &&
        point.x <= _rect.x + _rect.w &&
        point.y >= _rect.y &&
        point.y <= _rect.y + _rect.h;
    }

    // Return true if there are any bombs to prime
    function _primeBomb() {
      if (_bombCount > 0) {
        if (_isPrimed) {
          sound.playSfx('unableToMove');
        } else {
          sound.playSfx('bombPrimed');
        }

        // Un-prime the other bomb window
        game.unPrimeBomb();

        game.primedWindowIndex = game.keyboardControlOn ? 0 : 4;
        game.primedBombType = _bombType;
        _isPrimed = true;
        input.selectedKeyboardBlock = null;
        return true;
      } else {
        return false;
      }
    }

    function _releaseBomb() {
      game.previewWindows[game.primedWindowIndex].releaseBomb();
      --_bombCount;
      _isPrimed = false;
      game.primedWindowIndex = -1;
      game.primedBombType = -1;
      input.selectedKeyboardBlock = gameWindow.blocksOnGameWindow[0];
    }

    function _unPrimeBomb() {
      _isPrimed = false;
    }

    function _addBomb() {
      ++_bombCount;
    }

    function _getBombCount() {
      return _bombCount;
    }

    function _setBombCount(bombCount) {
      _bombCount = bombCount;
    }

    function _getIsPrimed() {
      return _isPrimed;
    }

    function _updateDimensions(x, y, w, h) {
      _rect.x = x;
      _rect.y = y;
      _rect.w = w;
      _rect.h = h;

      _fontString = 'bold ' + Math.floor(h / 2) + 'px monospace';
    }

    // ----------------------------------------------------------------- //
    // -- Privileged members

    this.update = _update;
    this.draw = _draw;
    this.isPointOverWindow = _isPointOverWindow;
    this.primeBomb = _primeBomb;
    this.releaseBomb = _releaseBomb;
    this.unPrimeBomb = _unPrimeBomb;
    this.addBomb = _addBomb;
    this.getBombCount = _getBombCount;
    this.setBombCount = _setBombCount;
    this.getIsPrimed = _getIsPrimed;
    this.updateDimensions = _updateDimensions;

    log.d('<--bombwindow.BombWindow');
  }

  // Make BombWindow available to the rest of the program
  window.BombWindow = BombWindow;

  BombWindow.prototype.COLLAPSE_BOMB_RADIUS = 5;

  BombWindow.prototype.COLLAPSE_BOMB = 0;
  BombWindow.prototype.SETTLE_BOMB = 1;

  log.i('<--bombwindow.LOADING_MODULE');
}());

redpajama_set_name: RedPajamaGithub


text:
const {
  castArray,
  defaults,
  debounce,
  zip,
} = require('lodash/fp');
const nodeWatch = require('node-watch');

const { series } = require('./utils');
const {
  execCommand,
  promisifyChildProcess,
} = require('./children');

const defaultOptions = {
  restartSignal: 'SIGUSR2',
  signals: ['SIGINT', 'SIGTERM'],
  watch: [],
};

function runCommand(command, signals, options) {
  return promisifyChildProcess(execCommand(command, { signals, options }));
}

function start(commands, signals, spawnOptions) {
  const promises = zip(commands, spawnOptions)
    .map(([command, options]) => () => runCommand(command, signals, options));
  return series(promises);
}

function watchAndReload(fn, files, restartSignal) {
  return nodeWatch(files, { recursive: true }, () => {
    process.kill(process.pid, restartSignal);
    fn();
  });
}

function main(commands, options = {}) {
  const {
    signals,
    watch,
    restartSignal,
    spawnOptions,
  } = defaults(defaultOptions)(options);

  const fn = () => start(commands, [restartSignal].concat(signals), spawnOptions);
  if (watch.length) {
    const watcher = watchAndReload(debounce(1000)(fn), castArray(watch), restartSignal);
    process.on('SIGINT', watcher.close);
    process.on('SIGTERM', watcher.close);
  }
  fn();
}

module.exports = main;


text:
#import "DynamoDBAttributeValue.h"

#import "DynamoDBResponse.h"
#import "../AmazonServiceExceptionUnmarshaller.h"

#import "DynamoDBProvisionedThroughputExceededException.h"
#import "DynamoDBConditionalCheckFailedException.h"
#import "DynamoDBInternalServerErrorException.h"
#import "DynamoDBResourceNotFoundException.h"

/**
 * Delete Item Result
 *
 * \ingroup DynamoDB
 */

@interface DynamoDBDeleteItemResponse:DynamoDBResponse

{
    NSMutableDictionary *attributes;
    NSNumber            *consumedCapacityUnits;
}

-(void)setException:(AmazonServiceException *)theException;

/**
 * Default constructor for a new  object.  Callers should use the
 * property methods to initialize this object after creating it.
 */
-(id)init;

/**
 * If the ReturnValues parameter is provided as ALL_OLD in the request,
 * Amazon DynamoDB returns an array of attribute name-value pairs
 * (essentially, the deleted item). Otherwise, the response contains an
 * empty set.
 */
@property (nonatomic, retain) NSMutableDictionary *attributes;

/**
 * The number of Capacity Units of the provisioned throughput of the
 * table consumed during the operation. GetItem, BatchGetItem, Query, and
 * Scan operations consume Read Capacity Units, while PutItem,
 * UpdateItem, and DeleteItem operations consume Write Capacity Units.
 */
@property (nonatomic, retain) NSNumber *consumedCapacityUnits;

/**
 * Returns a value from the attributes dictionary for the specified key.
 */
-(DynamoDBAttributeValue *)attributesValueForKey:(NSString *)theKey;

/**
 * Returns a string representation of this object; useful for testing and
 * debugging.
 *
 * @return A string representation of this object.
 */
-(NSString *)description;

@end


text:
<?php

namespace casamunoz\empresaBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use casamunoz\empresaBundle\Entity\Sucursal;
use casamunoz\empresaBundle\Form\SucursalType;

/**
 * Sucursal controller.
 *
 * @Route("/sucursal")
 */
class SucursalController extends Controller
{

    /**
     * Lists all Sucursal entities.
     *
     * @Route("/", name="sucursal")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('casamunozempresaBundle:Sucursal')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new Sucursal entity.
     *
     * @Route("/", name="sucursal_create")
     * @Method("POST")
     * @Template("casamunozempresaBundle:Sucursal:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Sucursal();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('sucursal_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a Sucursal entity.
     *
     * @param Sucursal $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Sucursal $entity)
    {
        $form = $this->createForm(new SucursalType(), $entity, array(
            'action' => $this->generateUrl('sucursal_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Sucursal entity.
     *
     * @Route("/new", name="sucursal_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Sucursal();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Sucursal entity.
     *
     * @Route("/{id}", name="sucursal_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('casamunozempresaBundle:Sucursal')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Sucursal entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Sucursal entity.
     *
     * @Route("/{id}/edit", name="sucursal_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('casamunozempresaBundle:Sucursal')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Sucursal entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Sucursal entity.
    *
    * @param Sucursal $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Sucursal $entity)
    {
        $form = $this->createForm(new SucursalType(), $entity, array(
            'action' => $this->generateUrl('sucursal_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Sucursal entity.
     *
     * @Route("/{id}", name="sucursal_update")
     * @Method("PUT")
     * @Template("casamunozempresaBundle:Sucursal:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('casamunozempresaBundle:Sucursal')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Sucursal entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('sucursal_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Sucursal entity.
     *
     * @Route("/{id}", name="sucursal_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('casamunozempresaBundle:Sucursal')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Sucursal entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('sucursal'));
    }

    /**
     * Creates a form to delete a Sucursal entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('sucursal_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Persona - A Better Way to Sign In</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="css/reveal.min.css">
    <link rel="stylesheet" href="css/theme/serif.css" id="theme">

    <link rel="stylesheet" href="lib/css/zenburn.css">

A Better Way to Sign In

            @hai_np

Các vấn đề với password

#1 - Khó để có sự an toàn

Từ việc sinh ra password...

              Cần một chuỗi dài ít nhất 8 ký tự, có cả chữ, số,
              các ký tự đặc biệt, viết hoa, viết thường, ...

... đến việc giữ chúng

Server

Mã hóa: bcrypt/scrypt/...

Các chính sách về password

Cơ chế khôi phục an toàn

            ALTER TABLE user

            DROP COLUMN password;

#2 - Khó nhớ password

Chọn một password thế này

và dùng khắp nơi

Password cần được reset

Sở hữu (các) email

=

Sở hữu nhiều tài khoản

Passwordlesss!

Các hệ thống hiện tại

Client Certificate - Chứng chỉ máy khách

OpenID

Đơn giản

Phân tán

Theo chuẩn web

Tương thích với các trình duyệt hiện đại

Cách hoạt động

Demo - 123done.org

Triển khai đơn giản

Relying Party

              navigator.id.watch({

                loggedInUser: 'bob@example.org',

                onlogin: function(assertion) {

                  //Call to backend API

                },
                onlogout: function() {

                  //Call to backend API

                }
              });

Identity Provider

Demo - eyedee.me

              {
                  "public-key": {
                     "algorithm":"RS",
                     "n":"a long number",
                     "e":"65537"
                  },
                  "authentication": "/browserid/sign_in.html",
                  "provisioning": "/browserid/provision.html"
              }

Nguồn tham khảo:

              Persona Protocol Overview

IdP Implementation

Francois Marrier - Slideshare

Thank you!

BY Nguyễn Phan Hải / @hai_np


text:
#include <string>
#include <stdexcept>

#include "cashka.h"

using std::string;
using std::invalid_argument;

namespace cashka
{
	/**
	 * Сгенерировать исключение
	 *
	 * @param string type
	 * @param string message
	 * @return void
	 */
	void err (string message, string type)
	{
		if (type == "default")
		{

		}
		else if (type == "cli")
		{
			message = (string)"Командная строка. " + message;
		}
		else if (type == "config")
		{
			message = (string)"Конфигурационный файл. " + message;
		}

		throw invalid_argument (message);
	}
}


text:
<?php

namespace Bitrix24;

use \Bitrix24\Im\Attach\Item\Message;
use \Psr\Log\NullLogger;

/**
 * Class MessageTest
 * @package Bitrix24
 */
class MessageTest extends \PHPUnit_Framework_TestCase
{
	/**
	 * @covers \Bitrix24\Im\Attach\Item\Message::getAttachTypeCode
	 */
	public function testUserListWithNullArgument()
	{
		$obItem = new Message('Test message');
		$this->assertSame($obItem->getAttachTypeCode(), 'MESSAGE');
	}
}


text:
function cvx_solve( presolve )
global cvx___
prob = evalin( 'caller', 'cvx_problem', '[]' );
if ~isa( prob, 'cvxprob' ),
    error( 'No cvx problem exists in this scope.' );
else
    if nargin < 1 || presolve, eliminate( prob ); end
    solve( prob, cvx___.quiet );
    assignin( 'caller', 'cvx_status', prob.status );
    assignin( 'caller', 'cvx_optval', prob.result );
end

% Copyright 2012 CVX Research, Inc.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


text:
source ./setup.sh

SERVER_PATH=${JC2LI_PATH}/server
SERVER_APP=main.py

echo 'Running server.'
python ${SERVER_PATH}/${SERVER_APP}
echo 'Server stopped.'


text:
#include "tensorflow/compiler/xla/permutation_util.h"

#include "tensorflow/compiler/xla/test.h"

namespace xla {
namespace {

TEST(PermutationUtilTest, IsPermutation) {
  EXPECT_TRUE(IsPermutation({}));
  EXPECT_TRUE(IsPermutation({0}));
  EXPECT_FALSE(IsPermutation({-3}));
  EXPECT_TRUE(IsPermutation({0, 1}));
  EXPECT_FALSE(IsPermutation({1, 1}));
  EXPECT_TRUE(IsPermutation({1, 0}));
  EXPECT_TRUE(IsPermutation({3, 1, 0, 2}));
  EXPECT_FALSE(IsPermutation({3, 0, 2}));
}

}  // namespace
}  // namespace xla


text:
package org.apache.tomcat.util.http;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.SocketException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.startup.SimpleHttpClient;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.catalina.valves.TesterAccessLogValve;

public class TestMimeHeaders extends TomcatBaseTest {

    private HeaderCountLogValve alv;

    private void setupHeadersTest(Tomcat tomcat) {
        Context ctx = tomcat.addContext("", getTemporaryDirectory()
                .getAbsolutePath());
        Tomcat.addServlet(ctx, "servlet", new HttpServlet() {
            private static final long serialVersionUID = 1L;

            @Override
            public void service(ServletRequest req, ServletResponse res)
                    throws ServletException, IOException {
                res.setContentType("text/plain; charset=ISO-8859-1");
                res.getWriter().write("OK");
            }
        });
        ctx.addServletMapping("/", "servlet");

        alv = new HeaderCountLogValve();
        tomcat.getHost().getPipeline().addValve(alv);
    }

    private void runHeadersTest(final boolean successExpected,
            final Tomcat tomcat, final int count,
            final int expectedMaxHeaderCount) throws Exception {
        tomcat.start();

        String header = "A:B" + SimpleHttpClient.CRLF;
        StringBuilder request = new StringBuilder();
        request.append("GET / HTTP/1.0" + SimpleHttpClient.CRLF);
        for (int i = 0; i < count; i++) {
            request.append(header);
        }
        request.append(SimpleHttpClient.CRLF);

        Client client = new Client(tomcat);
        client.setRequest(new String[] { request.toString() });
        try {
            client.connect();
            client.processRequest();
            client.disconnect();
        } catch (SocketException ex) {
            // Connection was closed by Tomcat
            if (successExpected) {
                // unexpected
                log.error(ex.getMessage(), ex);
            } else {
                log.warn(ex.getMessage(), ex);
            }
        }
        if (successExpected) {
            alv.validateAccessLog(1, 200, 0, 3000);
            // Response 200
            assertTrue("Response line is: " + client.getResponseLine(),
                    client.getResponseLine() != null && client.isResponse200());
            assertEquals("OK", client.getResponseBody());
        } else {
            alv.validateAccessLog(1, 400, 0, 0);
            // Connection aborted or response 400
            assertTrue("Response line is: " + client.getResponseLine(),
                    client.getResponseLine() == null || client.isResponse400());
        }
        int maxHeaderCount = tomcat.getConnector().getMaxHeaderCount();
        assertEquals(expectedMaxHeaderCount, maxHeaderCount);
        if (maxHeaderCount > 0) {
            assertEquals(maxHeaderCount, alv.arraySize);
        } else if (maxHeaderCount < 0) {
            int maxHttpHeaderSize = ((Integer) tomcat.getConnector()
                    .getAttribute("maxHttpHeaderSize")).intValue();
            int headerCount = Math.min(count,
                    maxHttpHeaderSize / header.length() + 1);
            int arraySize = 1;
            while (arraySize < headerCount) {
                arraySize <<= 1;
            }
            assertEquals(arraySize, alv.arraySize);
        }
    }

    @Test
    public void testHeaderLimits1() throws Exception {
        // Bumping into maxHttpHeaderSize
        Tomcat tomcat = getTomcatInstance();
        setupHeadersTest(tomcat);
        tomcat.getConnector().setMaxHeaderCount(-1);
        runHeadersTest(false, tomcat, 8 * 1024, -1);
    }

    @Test
    public void testHeaderLimits2() throws Exception {
        // Can process 100 headers
        Tomcat tomcat = getTomcatInstance();
        setupHeadersTest(tomcat);
        runHeadersTest(true, tomcat, 100, 100);
    }

    @Test
    public void testHeaderLimits3() throws Exception {
        // Cannot process 101 header
        Tomcat tomcat = getTomcatInstance();
        setupHeadersTest(tomcat);
        runHeadersTest(false, tomcat, 101, 100);
    }

    @Test
    public void testHeaderLimits4() throws Exception {
        // Can change maxHeaderCount
        Tomcat tomcat = getTomcatInstance();
        setupHeadersTest(tomcat);
        tomcat.getConnector().setMaxHeaderCount(-1);
        runHeadersTest(true, tomcat, 300, -1);
    }

    private static final class HeaderCountLogValve extends TesterAccessLogValve {
        public volatile int arraySize = -1;

        @Override
        public void log(Request request, Response response, long time) {
            super.log(request, response, time);
            try {
                MimeHeaders mh = request.getCoyoteRequest().getMimeHeaders();
                Field headersArrayField = MimeHeaders.class
                        .getDeclaredField("headers");
                headersArrayField.setAccessible(true);
                arraySize = ((Object[]) headersArrayField.get(mh)).length;
            } catch (Exception ex) {
                assertNull(ex.getMessage(), ex);
            }
        }
    }

    private static final class Client extends SimpleHttpClient {
        public Client(Tomcat tomcat) {
            setPort(tomcat.getConnector().getLocalPort());
        }

        @Override
        public boolean isResponseBodyOK() {
            return true;
        }
    }
}


text:
// Copyright (C) 2002-2012 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine" and the "irrXML" project.
// For conditions of distribution and use, see copyright notice in irrlicht.h

#ifndef __IRR_PATH_H_INCLUDED__
#define __IRR_PATH_H_INCLUDED__

#include "irrString.h"

namespace irr
{
namespace io
{

//! Type used for all file system related strings.
/** This type will transparently handle different file system encodings. */
typedef core::string<fschar_t> path;

//! Used in places where we identify objects by a filename, but don't actually work with the real filename
/** Irrlicht is internally not case-sensitive when it comes to names.
    Also this class is a first step towards support for correctly serializing renamed objects.
*/
struct SNamedPath
{
	//! Constructor
	SNamedPath() {}

	//! Constructor
	SNamedPath(const path& p) : Path(p), InternalName( PathToName(p) )
	{
	}

	//! Is smaller comparator
	bool operator <(const SNamedPath& other) const
	{
		return InternalName < other.InternalName;
	}

	//! Set the path.
	void setPath(const path& p)
	{
		Path = p;
		InternalName = PathToName(p);
	}

	//! Get the path.
	const path& getPath() const
	{
		return Path;
	};

	//! Get the name which is used to identify the file.
	//! This string is similar to the names and filenames used before Irrlicht 1.7
	const path& getInternalName() const
	{
		return InternalName;
	}

	//! Implicit cast to io::path
	operator core::stringc() const
	{
		return core::stringc(getPath());
	}
	//! Implicit cast to io::path
	operator core::stringw() const
	{
		return core::stringw(getPath());
	}

protected:
	// convert the given path string to a name string.
	path PathToName(const path& p) const
	{
		path name(p);
		name.replace( '\\', '/' );
		name.make_lower();
		return name;
	}

private:
	path Path;
	path InternalName;
};

} // io
} // irr

#endif // __IRR_PATH_H_INCLUDED__


text:
{% extends "registration/accounts.html" %}
{% load i18n %}

{% block title  %}
Password Change Done
{% endblock title  %}

{% block breadcrumbs %}
{{ block.super }} > Password Change Done
{% endblock breadcrumbs %}

{% block content %}
<p>{% trans "Password changed" %}</p>
{% endblock %}


text:
bbc\_iplayer\_search is a Ruby gem which provides a page scraped API for
searching the programmes available for streaming from the BBC iPlayer

# Installation

    $ gem install bbc_iplayer_search

Or with Bundler in your Gemfile.

    gem 'bbc_iplayer_search'

# Usage

    require 'bbc_iplayer_search'

    iplayer_search = BBCIplayerSearch::Search.new

    results = iplayer_search.search('eastenders')

Where the results are an array containing a hash for each result. Each
result has `title`, `url`, `image_url` and 'available' keys.


text:
class DayO < Cask
  version :latest
  sha256 :no_check

  url 'http://shauninman.com/assets/downloads/Day-O.zip'
  homepage 'http://www.shauninman.com/archive/2011/10/20/day_o_mac_menu_bar_clock'
  license :unknown

  app 'Day-O/Day-O.app'
end


text:
Amazon Order Scraper
====================

This is a simple script using the Python selenium library to scrape all your Amazon
orders and create handy PDFs for receipt/tax purposes.

To use::

    mkvirtualenv -p python3.9 amzscraper
    pip install git+https://github.com/tobiasmcnulty/amzscraper.git
    amscraper -u <email> -p <pass> 2021

If it does need to download a page from Amazon, a random sleep is inserted to throttle
connections to the server.

Orders will be downloaded to the ``orders/`` directory in your current directory by
default

For further options, see::

    amzscraper -h

Requirements
------------

* Python 3.7+
* ``virtualenv`` and ``virtualenvwrapper``
* ``wkhtmltopdf`` installed and in your ``PATH``
* ``chromedriver`` installed and in your ``PATH``

Credits
-------

This is loosely based on an `earlier project <http://chase-seibert.github.io/blog/2011/01/15/backup-your-amazon-order-history-with-python.html>`_
by Chase Seibert.


text:
<component name="libraryTable">
  <library name="multidex-instrumentation-1.0.1">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/mobile/build/intermediates/exploded-aar/com.android.support/multidex-instrumentation/1.0.1/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/mobile/build/intermediates/exploded-aar/com.android.support/multidex-instrumentation/1.0.1/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
module Glysellin
  module DiscountTypeCalculator
    class OrderPercentage < Glysellin::DiscountTypeCalculator::Base
      register 'order-percentage', self

      attr_accessor :discountable, :value

      def initialize(discountable, value)
        @discountable = discountable
        @value = (value.to_f / 100.0) # Convert to percentage
      end

      def calculate
        (-(discountable.discountable_amount * value)).round(2)
      end
    end
  end
end


text:
#include "brsample_pch.h"  //precompiled header

// include here

AcBr::ErrorStatus
meshDump(const AcBrMesh2d& mesh)
{
    AcBr::ErrorStatus returnValue = AcBr::eOk;

	// make a global element traverser
	AcBrMesh2dElement2dTraverser meshElemTrav;
	returnValue = meshElemTrav.setMesh(mesh);
	if (returnValue != AcBr::eOk) {
		acutPrintf(ACRX_T("\n Error in AcBrMesh2dElement2dTraverser::setMesh:"));
		errorReport(returnValue);
		return returnValue;
	}

	// count the elements
	int elemCount = 0;
	while (!meshElemTrav.done() && (returnValue == AcBr::eOk) && !acedUsrBrk()) {
	    elemCount++;
	    acutPrintf(ACRX_T("\n ***Element No: %d \n"), elemCount);

		AcBrElement2d currentElem;
		returnValue = meshElemTrav.getElement(currentElem);
		if (returnValue != AcBr::eOk) {
		    acutPrintf(ACRX_T("\n Error in AcBrMesh2dElement2dTraverser::getElement:"));
			errorReport(returnValue);
			return returnValue;
		}

		AcGeVector3d normal;
		returnValue = currentElem.getNormal(normal);
		if (returnValue != AcBr::eOk) {
			acutPrintf(ACRX_T("\n Error in AcBrElement2d::getNormal:"));
			errorReport(returnValue);
			return returnValue;
		}
        acutPrintf(ACRX_T("\n Element Normal is ("));
        acutPrintf (ACRX_T("%lf, "), normal.x);
        acutPrintf (ACRX_T("%lf, "), normal.y);
        acutPrintf (ACRX_T("%lf"), normal.z);
        acutPrintf(ACRX_T(")\n"));

    	// Determine the entity which contains this element
    	AcBrEntity* entityAssociated = NULL;
    	returnValue = currentElem.getEntityAssociated(entityAssociated);
    	if (returnValue != AcBr::eOk) {
    		acutPrintf(ACRX_T("\n Error in AcBrElement2d::getEntityAssociated:"));
    		errorReport(returnValue);
    		delete entityAssociated;
    		return returnValue;
    	}
    	entityAssociatedReport(entityAssociated);
    	delete entityAssociated;

    	// count the nodes
		int nodeCount = 0;
		AcBrElement2dNodeTraverser elemNodeTrav;
		returnValue = elemNodeTrav.setElement(meshElemTrav);
		if (returnValue != AcBr::eOk) {
			acutPrintf(ACRX_T("\n Error in AcBrElement2dNodeTraverser::setElement:"));
			errorReport(returnValue);
			return returnValue;
		}

		while (!elemNodeTrav.done() && (returnValue == AcBr::eOk)) {
		    nodeCount++;

			AcBrNode node;
			returnValue = elemNodeTrav.getNode(node);
		     if (returnValue != AcBr::eOk) {
			    acutPrintf(ACRX_T("\n Error in AcBrElement2dNodeTraverser::getNode:"));
			    errorReport(returnValue);
			    return returnValue;
		    }

			// dump the node geometry data
			returnValue = nodeDump(node);
	    	if (returnValue != AcBr::eOk) {
				acutPrintf(ACRX_T("\n Error in nodeDump:"));
			    errorReport(returnValue);
			    return returnValue;
		    }

			// dump the node surface data
			AcGePoint2d point;
			returnValue = elemNodeTrav.getParamPoint(point);
		    if (returnValue != AcBr::eOk) {
			    acutPrintf(ACRX_T("\n Error in AcBrElement2dNodeTraverser::getParamPoint:"));
			    errorReport(returnValue);
			    return returnValue;
		    }
        	acutPrintf(ACRX_T("\n Node Param Point is ("));
        	acutPrintf (ACRX_T("%lf, "), point.x);
        	acutPrintf (ACRX_T("%lf, "), point.y);
        	acutPrintf(ACRX_T(")\n"));

			AcGeVector3d normal;
			returnValue = elemNodeTrav.getSurfaceNormal(normal);
		    if (returnValue != AcBr::eOk) {
			    acutPrintf(ACRX_T("\n Error in AcBrElement2dNodeTraverser::getSurfaceNormal:"));
			    errorReport(returnValue);
			    return returnValue;
		    }
        	acutPrintf(ACRX_T("\n Node Surface Normal is ("));
        	acutPrintf (ACRX_T("%lf, "), normal.x);
        	acutPrintf (ACRX_T("%lf, "), normal.y);
        	acutPrintf (ACRX_T("%lf"), normal.z);
        	acutPrintf(ACRX_T(")\n"));

			returnValue = elemNodeTrav.next();
	    	if (returnValue != AcBr::eOk) {
		    	acutPrintf(ACRX_T("\n Error in AcBrElement2dNodeTraverser::next:"));
			    errorReport(returnValue);
			    return returnValue;
		    }
		} // end element while

	    acutPrintf(ACRX_T("\n ****Element No. %d has %d nodes\n"), elemCount, nodeCount);

		returnValue = meshElemTrav.next();
		if (returnValue != AcBr::eOk) {
			acutPrintf(ACRX_T("\n Error in AcBrMesh2dElement2dTraverser::next:"));
			errorReport(returnValue);
			return returnValue;
		}

	}  // end mesh while

	acutPrintf(ACRX_T("\n ***Mesh has %d elements\n"), elemCount);

	return returnValue;
}

AcBr::ErrorStatus
meshDisplay(const AcBrMesh2d& mesh)
{
    AcBr::ErrorStatus returnValue = AcBr::eOk;

	// make a global element traverser
	AcBrMesh2dElement2dTraverser meshElemTrav;
	returnValue = meshElemTrav.setMesh(mesh);
	if (returnValue != AcBr::eOk) {
		acutPrintf(ACRX_T("\n Error in AcBrMesh2dElement2dTraverser::setMesh:"));
		errorReport(returnValue);
		return returnValue;
	}

	// display the elements
	while (!meshElemTrav.done() && (returnValue == AcBr::eOk) && !acedUsrBrk()) {
    	// convert the nodes into a 3d point array for AcDbPolyline
        AcGePoint3dArray pts;

		AcBrElement2dNodeTraverser elemNodeTrav;
		returnValue = elemNodeTrav.setElement(meshElemTrav);
		if (returnValue != AcBr::eOk) {
			acutPrintf(ACRX_T("\n Error in AcBrElement2dNodeTraverser::setElement:"));
			errorReport(returnValue);
			return returnValue;
		}

		while (!elemNodeTrav.done() && (returnValue == AcBr::eOk)) {
			AcBrNode node;
			returnValue = elemNodeTrav.getNode(node);
		     if (returnValue != AcBr::eOk) {
			    acutPrintf(ACRX_T("\n Error in AcBrElement2dNodeTraverser::getNode:"));
			    errorReport(returnValue);
			    return returnValue;
		    }

			// add the node geometry data to the lightweight polyline point array
			returnValue = nodeDisplay(node, pts);
	    	if (returnValue != AcBr::eOk) {
				acutPrintf(ACRX_T("\n Error in nodeDisplay:"));
			    errorReport(returnValue);
			    return returnValue;
		    }

			returnValue = elemNodeTrav.next();
	    	if (returnValue != AcBr::eOk) {
		    	acutPrintf(ACRX_T("\n Error in AcBrElement2dNodeTraverser::next:"));
			    errorReport(returnValue);
			    return returnValue;
		    }
		} // end element while

        // create a simple, closed polygon from the element node list
        AcDb3dPolyline* pline = new AcDb3dPolyline(AcDb::k3dSimplePoly, pts, Adesk::kTrue);
        if (pline == NULL) {
            returnValue = (AcBr::ErrorStatus)Acad::eOutOfMemory;
            acutPrintf(ACRX_T("\n Unable to allocate memory for polyline"));
            return returnValue;
		}

		// post the polyline to the database (this should display the element)
        AcDbObjectId objId;
        if (addToDatabase(pline, objId) != AcBr::eOk) {
            acutPrintf(ACRX_T("\n addToDatabase failed"));
            return returnValue;
        }

        // close the database object
        if (pline->close() != AcBr::eOk) {
            acutPrintf(ACRX_T("\n AcDb3dPolyline::close() failed"));
            return returnValue;
        }

		returnValue = meshElemTrav.next();
		if (returnValue != AcBr::eOk) {
			acutPrintf(ACRX_T("\n Error in AcBrMesh2dElement2dTraverser::next:"));
			errorReport(returnValue);
			return returnValue;
		}

	}  // end mesh while

    return returnValue;
}


text:
/*****************************************************************************/
/* Copyright (c) 2009 NXP Semiconductors BV                                  */
/*                                                                           */
/* This program is free software; you can redistribute it and/or modify      */
/* it under the terms of the GNU General Public License as published by      */
/* the Free Software Foundation, using version 2 of the License.             */
/*                                                                           */
/* This program is distributed in the hope that it will be useful,           */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of            */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the              */
/* GNU General Public License for more details.                              */
/*                                                                           */
/* You should have received a copy of the GNU General Public License         */
/* along with this program; if not, write to the Free Software               */
/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307       */
/* USA.                                                                      */
/*                                                                           */
/*****************************************************************************/
#if defined(CONFIG_MTK_WFD_SUPPORT)

#define _tx_c_
#include <generated/autoconf.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/fb.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/earlysuspend.h>
#include <linux/kthread.h>
#include <linux/rtpm_prio.h>
#include <linux/vmalloc.h>
#include <linux/disp_assert_layer.h>

#include <asm/uaccess.h>
#include <asm/atomic.h>
#include <asm/mach-types.h>
#include <asm/cacheflush.h>
#include <asm/io.h>

#include <mach/dma.h>
#include <mach/irqs.h>

#include <linux/miscdevice.h>
#include <linux/platform_device.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/mm.h>
#include <linux/cdev.h>
#include <asm/tlbflush.h>
#include <asm/page.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <linux/slab.h>

#include <generated/autoconf.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/fb.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/earlysuspend.h>
#include <linux/kthread.h>
#include <linux/rtpm_prio.h>
#include <linux/list.h>

#include <asm/uaccess.h>
#include <asm/atomic.h>
#include <asm/mach-types.h>
#include <asm/cacheflush.h>
#include <asm/io.h>

#include <mach/dma.h>
#include <mach/irqs.h>
#include <linux/vmalloc.h>

#include <asm/uaccess.h>

#include "hdmi_drv.h"

#include "disp_drv_platform.h"
#include "ddp_reg.h"
#include "ddp_dpfd.h"
#include "ddp_drv.h"

#include "dpi_drv.h"
#include "dpi1_drv.h"

/* #include "lcd_reg.h" */
#include "dsi_drv.h"
#include "dpi_reg.h"
#include "mach/eint.h"
#include "mach/irqs.h"
#include "linux/hdmitx.h"

#include <linux/switch.h>

#include "disp_drv.h"

/* / if resize to zoom out, please set to 5 normally. DO NOT bigger than 10 */
#define WFD_DISPLAY_ZOOM_OUT_FACTOR 0

/* / for lower cpu loading to skip some frame in lcm video mode,
SKIP_FRAME(define in 2-->5) means wfd driver will skip a lcm frame per PERFORMANCE_TUNING_SKIP_FRAME. */
#define PERFORMANCE_TUNING_SKIP_FRAME 3

int wfd_log_on = 1;
#define WFD_LOG(fmt, arg...) \
do { \
	if (wfd_log_on) { \
		pr_info("[wfd]%s,#%d ", __func__, __LINE__); \
		pr_info(fmt, ##arg); \
	} \
} while (0)

#define WFD_FUNC()    \
do { \
	if (wfd_log_on) { \
		pr_info("[wfd] %s\n", __func__); \
	} \
} while (0)

#define WFD_LINE()    \
do { \
	if (wfd_log_on) { \
		pr_info("[wfd]%s,%d ", __func__, __LINE__); \
		pr_info(fmt, ##arg); \
	} \
} while (0)

#define RETIF(cond, rslt)       {if ((cond)) {WFD_LOG("return in %d\n", __LINE__); return (rslt); } }
#define RET_VOID_IF(cond)       {if ((cond)) {WFD_LOG("return in %d\n", __LINE__); return; } }
#define RETIF_NOLOG(cond, rslt)       {if ((cond)) return (rslt); }
#define RET_VOID_IF_NOLOG(cond)       {if ((cond)) return; }
#define RETIFNOT(cond, rslt)    {if (!(cond)) {WFD_LOG("return in %d\n", __LINE__); return (rslt); } }

#define ALIGN_TO(x, n)  \
	(((x) + ((n) - 1)) & ~((n) - 1))

#include <mach/m4u.h>
#include <mach/mt_typedefs.h>
/* #include <mach/mt_gpio.h> */

extern int m4u_config_port(M4U_PORT_STRUCT* pm4uport);
extern void HDMI_DBG_Init(void);
extern bool mtkfb_is_suspend(void);
extern UINT32 DISP_GetScreenHeight(void);
extern UINT32 DISP_GetScreenWidth(void);
extern BOOL DISP_IsVideoMode(void);
extern int disp_lock_mutex(void);
extern int disp_unlock_mutex(int id);
extern 	void hdmi_dsi_waitnotbusy(void);

static void hdmi_update_impl(void);

static struct switch_dev hdmi_switch_data;

/* extern int pll_fsel(enum mt65xx_pll_id id, unsigned int pll_value); */
#define HDMI_DEVNAME "ext_display"
HDMI_PARAMS _s_wfd_params = { 0 };

static HDMI_PARAMS *hdmi_params = &_s_wfd_params;
static HDMI_DRIVER *hdmi_drv;

static struct timeval timestamp[16];

/* mediatek, this is for exernal display driver blocking "get buffer" method */
static atomic_t wfd_buffer_update_flag = ATOMIC_INIT(0);
#define WFD_PUT_NEW_BUFFER() atomic_set(&wfd_buffer_update_flag, 1)
#define WFD_CLEAR_NEW_BUFFER() atomic_set(&wfd_buffer_update_flag, 0)
#define WFD_GET_NEW_BUFFER() atomic_read(&wfd_buffer_update_flag)

static wait_queue_head_t external_display_getbuffer_wq;

static DEFINE_SEMAPHORE(hdmi_update_mutex);
struct  {
	bool is_wfd;
	bool is_wfd_suspend;
	bool is_ipo_poweroff;	/* IPO power off or not, like hdmi_suspend(), hdmi_resume() */
	/* whether memory is forced to be rotated in Camera, no need to set orientation again */
	bool is_force_fullscreen;
	bool is_force_portrait;	/* whether forced portrait mode, priority is higher than is_force_fullscreen */
	bool is_reconfig_needed;	/* whether need to reset HDMI memory */
	bool is_enabled;	/* whether HDMI is enabled or disabled by user */
	/* bool is_active;     // whether HDMI is actived with cable pluged in. */
	bool is_force_disable;	/* used for camera scenario. */
	bool is_clock_on;	/* DPI is running or not */
	bool is_factory_mode;
	atomic_t state;		/* HDMI_POWER_STATE state */
	bool is_audio_avaliable;
	int lcm_width;		/* LCD write buffer width */
	int lcm_height;		/* LCD write buffer height */
	bool lcm_is_video_mode;
	int hdmi_width;		/* DPI read buffer width */
	int hdmi_height;	/* DPI read buffer height */
	HDMI_VIDEO_RESOLUTION output_video_resolution;
	HDMI_AUDIO_FORMAT output_audio_format;
	/* MDP's orientation, 0 means 0 degree, 1 means 90 degree, 2 means 180 degree, 3 means 270 degree */
	int orientation;
	int orientation_store;	/* Store orientation setting when HDMI driver is_force_fullscreen */
	int orientation_store_portrait;	/* Store orientation setting when HDMI driver is_force_portrait */
}_t_hdmi_context;

struct hdmi_video_buffer_list {
	struct hdmi_video_buffer_info buffer_info;
	pid_t pid;
	void *file_addr;
	unsigned int buffer_mva;
	struct list_head list;
};

static struct list_head hdmi_video_mode_buffer_list;
/* static struct list_head *hdmi_video_buffer_list_head = &hdmi_video_mode_buffer_list; */
static atomic_t hdmi_video_mode_flag = ATOMIC_INIT(0);
/* static int hdmi_add_video_buffer(struct hdmi_video_buffer_info *buffer_info, struct file *file); */
/* static struct hdmi_video_buffer_list
*hdmi_search_video_buffer(struct hdmi_video_buffer_info *buffer_info, struct file *file); */
/* static void hdmi_destory_video_buffer(void); */
#define IS_HDMI_IN_VIDEO_MODE()        atomic_read(&hdmi_video_mode_flag)
#define SET_HDMI_TO_VIDEO_MODE()       atomic_set(&hdmi_video_mode_flag, 1)
#define SET_HDMI_LEAVE_VIDEO_MODE()    atomic_set(&hdmi_video_mode_flag, 0)
static wait_queue_head_t hdmi_video_mode_wq;
static atomic_t hdmi_video_mode_event = ATOMIC_INIT(0);
static atomic_t hdmi_video_mode_dpi_change_address = ATOMIC_INIT(0);
#define IS_HDMI_VIDEO_MODE_DPI_IN_CHANGING_ADDRESS()    atomic_read(&hdmi_video_mode_dpi_change_address)
#define SET_HDMI_VIDEO_MODE_DPI_CHANGE_ADDRESS()        atomic_set(&hdmi_video_mode_dpi_change_address, 1)
#define SET_HDMI_VIDEO_MODE_DPI_CHANGE_ADDRESS_DONE()   atomic_set(&hdmi_video_mode_dpi_change_address, 0)

static _t_hdmi_context hdmi_context;
static _t_hdmi_context *p = &hdmi_context;

#define IS_HDMI_ON()			(HDMI_POWER_STATE_ON == atomic_read(&p->state))
#define IS_HDMI_OFF()			(HDMI_POWER_STATE_OFF == atomic_read(&p->state))
#define IS_HDMI_STANDBY()	    (HDMI_POWER_STATE_STANDBY == atomic_read(&p->state))

#define IS_HDMI_NOT_ON()		(HDMI_POWER_STATE_ON != atomic_read(&p->state))
#define IS_HDMI_NOT_OFF()		(HDMI_POWER_STATE_OFF != atomic_read(&p->state))
#define IS_HDMI_NOT_STANDBY()	(HDMI_POWER_STATE_STANDBY != atomic_read(&p->state))

#define SET_HDMI_ON()	        atomic_set(&p->state, HDMI_POWER_STATE_ON)
#define SET_HDMI_OFF()	        atomic_set(&p->state, HDMI_POWER_STATE_OFF)
#define SET_HDMI_STANDBY()	    atomic_set(&p->state, HDMI_POWER_STATE_STANDBY)

extern int m4u_alloc_mva_stub(M4U_MODULE_ID_ENUM eModuleID, const unsigned int BufAddr, const unsigned int BufSize, unsigned int *pRetMVABuf);
extern int m4u_dealloc_mva_stub(M4U_MODULE_ID_ENUM eModuleID, const unsigned int BufAddr, const unsigned int BufSize, const unsigned int MVA);
extern int m4u_config_port_stub(M4U_PORT_STRUCT* pM4uPort);

extern int m4u_insert_tlb_range_stub(M4U_MODULE_ID_ENUM eModuleID, unsigned int MVAStart, const unsigned int MVAEnd, M4U_RANGE_PRIORITY_ENUM ePriority, unsigned int entryCount);
extern int m4u_invalid_tlb_range_stub(M4U_MODULE_ID_ENUM eModuleID, unsigned int MVAStart, unsigned int MVAEnd);
/* TODO: refine to a single structure */
static unsigned int overlay_dst_mva, overlay_dst_va, ddp_dst_va, ddp_dst_mva /*, fb_pa, fb_va, fb_size */;

static dev_t hdmi_devno;
static struct cdev *hdmi_cdev;
static struct class *hdmi_class;

static UINT32 const DPI_PAD_CON = 0xf2080900;
static UINT32 const NLI_ARB_CS = 0xf100d014;

static int hdmi_bpp = 4;

static int hdmi_default_width = 1280;
static int hdmi_default_height = 720;
static int hdmi_temp_buffer_number = 0;

static int hdmi_buffer_write_id = 0;
static int hdmi_buffer_read_id = 0;
static int hdmi_buffer_lcdw_id = 0;
static int hdmi_buffer_lcdw_id_tmp = 0;
static int hdmi_buffer_lcdw_cnt = 0;

static struct timeval timestamp[16];

static struct task_struct *hdmi_update_task = NULL;
static struct task_struct *hdmi_overlay_config_task = NULL;

static wait_queue_head_t hdmi_update_wq;
static wait_queue_head_t hdmi_overlay_config_wq;

static wait_queue_head_t external_display_getbuffer_wq;
static atomic_t hdmi_update_event = ATOMIC_INIT(0);
static atomic_t hdmi_overlay_config_event = ATOMIC_INIT(0);
static int wfd_pattern_output = 0;
static int wfd_pattern_output_index = 0;

#include <linux/mmprofile.h>
struct WFD_MMP_Events_t {
	MMP_Event WFD;
	MMP_Event Rotate;
	MMP_Event UpdateRequest;
	MMP_Event DDPKBitblt;
	MMP_Event Getbuffer;
	MMP_Event OverlayDone;
	MMP_Event WFDEnter;
	MMP_Event WFDLeave;
	MMP_Event WFDStart;
	MMP_Event WFDStop;
} WFD_MMP_Events;

/* --------------------------------------------------------------------------- */
/* Information Dump Routines */
/* --------------------------------------------------------------------------- */

void init_wfd_mmp_events(void)
{
	if (WFD_MMP_Events.WFD == 0) {
		WFD_MMP_Events.WFD = MMProfileRegisterEvent(MMP_RootEvent, "WFD");
		WFD_MMP_Events.Rotate = MMProfileRegisterEvent(WFD_MMP_Events.WFD, "Rotate");
		WFD_MMP_Events.OverlayDone =
		    MMProfileRegisterEvent(WFD_MMP_Events.WFD, "OverlayDone");
		WFD_MMP_Events.UpdateRequest =
		    MMProfileRegisterEvent(WFD_MMP_Events.WFD, "UpdateRequest");
		WFD_MMP_Events.DDPKBitblt =
		    MMProfileRegisterEvent(WFD_MMP_Events.WFD, "DDPKBitblt");
		WFD_MMP_Events.Getbuffer = MMProfileRegisterEvent(WFD_MMP_Events.WFD, "Getbuffer");
		WFD_MMP_Events.WFDEnter = MMProfileRegisterEvent(WFD_MMP_Events.WFD, "WFDEnter");
		WFD_MMP_Events.WFDLeave = MMProfileRegisterEvent(WFD_MMP_Events.WFD, "WFDLeave");
		WFD_MMP_Events.WFDStart = MMProfileRegisterEvent(WFD_MMP_Events.WFD, "WFDStart");
		WFD_MMP_Events.WFDStop = MMProfileRegisterEvent(WFD_MMP_Events.WFD, "WFDStop");
		MMProfileEnableEventRecursive(WFD_MMP_Events.WFD, 1);
	}
}

static void hdmi_udelay(unsigned int us)
{
	udelay(us);
}

static void hdmi_mdelay(unsigned int ms)
{
	msleep(ms);
}

/* Will be called in LCD Interrupt handler to check whether HDMI is actived */
bool is_wfd_active(void)
{
	return IS_HDMI_ON();
}

/* Used for HDMI Driver update */
static int hdmi_update_kthread(void *data)
{
	/* struct sched_param param = { .sched_priority = RTPM_PRIO_SCRN_UPDATE }; */
	struct sched_param param = {.sched_priority = RTPM_PRIO_FB_THREAD };
	sched_setscheduler(current, SCHED_RR, &param);

	for (;;) {

		wait_event_interruptible(hdmi_update_wq, atomic_read(&hdmi_update_event));
		/* HDMI_LOG("wq wakeup\n"); */
		/* hdmi_update_impl(); */

		atomic_set(&hdmi_update_event, 0);

		hdmi_update_impl();

		if (kthread_should_stop())
			break;
	}

	return 0;
}

/* Used for HDMI Driver update */
static int hdmi_overlay_config_kthread(void *data)
{
	unsigned int addr = 0;
	struct sched_param param = {.sched_priority = RTPM_PRIO_SCRN_UPDATE };
	sched_setscheduler(current, SCHED_RR, &param);

	for (;;) {

		wait_event_interruptible(hdmi_overlay_config_wq,
					 atomic_read(&hdmi_overlay_config_event));
		atomic_set(&hdmi_overlay_config_event, 0);

		if (p->lcm_is_video_mode) {
			disp_path_get_mutex();

			hdmi_buffer_lcdw_id_tmp =
			    (hdmi_buffer_lcdw_id + 1) % hdmi_temp_buffer_number;
			addr =
			    overlay_dst_mva +
			    hdmi_buffer_lcdw_id_tmp * p->lcm_width * p->lcm_height * 3;

			DISP_REG_SET(0x1000 + DISP_REG_WDMA_DST_ADDR, addr);

			disp_path_release_mutex();
		} else {
			addr =
			    overlay_dst_mva +
			    hdmi_buffer_lcdw_id * p->lcm_width * p->lcm_height * 3;
			DISP_Config_Overlay_to_Memory(addr, 1);
		}

		/* atomic_set(&hdmi_overlay_config_event, 0); */

		if (kthread_should_stop())
			break;
	}

	return 0;
}

/* Switch LCD write buffer, will be called in LCD Interrupt handler */
void wfd_source_buffer_switch(void)
{
	/* pr_info("lcd write buffer:%d\n", hdmi_buffer_lcdw_id); */

	RET_VOID_IF_NOLOG(IS_HDMI_NOT_ON());
	RET_VOID_IF_NOLOG(IS_HDMI_IN_VIDEO_MODE());

	if (!p->lcm_is_video_mode)
		hdmi_buffer_lcdw_id = (hdmi_buffer_lcdw_id + 1) % hdmi_temp_buffer_number;

	/* hdmi_buffer_lcdw_id = 0; */

	MMProfileLog(WFD_MMP_Events.OverlayDone, MMProfileFlagStart);

	atomic_set(&hdmi_overlay_config_event, 1);
	wake_up_interruptible(&hdmi_overlay_config_wq);

	/* LCD_CHECK_RET(LCD_FBSetAddress(LCD_FB_0, temp_mva + p->lcm_width*p->lcm_height*3*hdmi_buffer_lcdw_id)); */
	MMProfileLog(WFD_MMP_Events.OverlayDone, MMProfileFlagEnd);
}

/* Switch DPI read buffer, will be called in DPI Interrupt handler */
void wfd_update_buffer_switch(void)
{
	/* WFD_LOG("DPI read buffer:%d\n", hdmi_buffer_read_id); */

	RET_VOID_IF_NOLOG(IS_HDMI_NOT_ON());

	if (IS_HDMI_IN_VIDEO_MODE()) {
		if (IS_HDMI_VIDEO_MODE_DPI_IN_CHANGING_ADDRESS()) {
			if (0 == *((volatile unsigned int *)(0xF208C020))) {
				SET_HDMI_VIDEO_MODE_DPI_CHANGE_ADDRESS_DONE();
				atomic_set(&hdmi_video_mode_event, 1);
				wake_up_interruptible(&hdmi_video_mode_wq);
			}
		}
	} else {
	/* DPI_CHECK_RET(DPI_FBSetAddress(DPI_FB_0, hdmi_mva + p->hdmi_width*p->hdmi_height*3*hdmi_buffer_read_id)); */
	/* hdmi_buffer_read_id = (hdmi_buffer_read_id + 1) % hdmi_temp_buffer_number; */
	}
}

/* hdmi update api, will be called in LCD Interrupt handler */
void wfd_update(void)
{
	/* WFD_FUNC(); */
#if 1
	RET_VOID_IF(IS_HDMI_NOT_ON());
	RET_VOID_IF(!p->is_wfd);

	MMProfileLog(WFD_MMP_Events.UpdateRequest, MMProfileFlagStart);
	atomic_set(&hdmi_update_event, 1);
	wake_up_interruptible(&hdmi_update_wq);	/* wake up hdmi_update_kthread() to do update */
	MMProfileLog(WFD_MMP_Events.UpdateRequest, MMProfileFlagEnd);

#else
	hdmi_update_impl();
#endif
}

static long int get_current_time_us(void)
{
	struct timeval t;
	do_gettimeofday(&t);
	return (t.tv_sec & 0xFFF) * 1000000 + t.tv_usec;
}

static int ovl_dst_buffer_size = 0;
static int ddp_dst_buffer_size = 0;

static void hdmi_update_impl(void)
{
	/* WFD_LOG("hdmi_update_impl\n"); */

	int ret = 0;
	DdpkBitbltConfig pddp;
	int pixelSize = p->hdmi_width * p->hdmi_height;
	int ovl_read_id;
	bool portraitOutput = false;
	long int profile_t;

	WFD_FUNC();

	if (wfd_pattern_output)
		return;

	if (pixelSize == 0) {
		WFD_LOG("ignored[resolution is null]\n");
		return;
	}
	/* WFD_FUNC(); */
	if (down_interruptible(&hdmi_update_mutex)) {
		WFD_LOG("[HDMI] can't get semaphore in\n");
		return;
	}

	if (IS_HDMI_NOT_ON()) {
		/* goto done*/
		goto done;
	}
	if (IS_HDMI_IN_VIDEO_MODE()) {
		/* goto done*/
		goto done;
	}

	DBG_OnTriggerHDMI();
	/* LCD_WaitForNotBusy(); */
	/* hdmi_buffer_write_id = (hdmi_buffer_write_id+1) % hdmi_temp_buffer_number; */

	if (p->is_reconfig_needed || p->is_wfd_suspend) {
		int i = 0;
		for (i = 0; i < hdmi_temp_buffer_number; i++) {
			memset((void *)(ddp_dst_va + i * p->hdmi_width * p->hdmi_height * 3), 0x00,
			       p->hdmi_width * p->hdmi_height);
			memset((void *)(ddp_dst_va + i * p->hdmi_width * p->hdmi_height * 3 +
					p->hdmi_width * p->hdmi_height), 0x80,
			       p->hdmi_width * p->hdmi_height);
		}
		if (p->is_reconfig_needed) {
			/* is_reconfig_needed = false */
			p->is_reconfig_needed = false;
		}
	}

	if (p->is_wfd_suspend) {
		MMProfileLogEx(WFD_MMP_Events.DDPKBitblt, MMProfileFlagStart, hdmi_buffer_write_id,
			       0);
		hdmi_buffer_write_id = ((hdmi_buffer_write_id + 1) % hdmi_temp_buffer_number);

		WFD_PUT_NEW_BUFFER();
		wake_up_interruptible(&external_display_getbuffer_wq);
		MMProfileLogEx(WFD_MMP_Events.DDPKBitblt, MMProfileFlagEnd, hdmi_buffer_write_id,
			       0);
		up(&hdmi_update_mutex);
		return;
	}
#if PERFORMANCE_TUNING_SKIP_FRAME
	int skipperframe = PERFORMANCE_TUNING_SKIP_FRAME;
	if (skipperframe > 5)
		skipperframe = 5;

	if (skipperframe < 2)
		skipperframe = 2;

	hdmi_buffer_lcdw_cnt++;

	if ((p->lcm_is_video_mode) && (hdmi_buffer_lcdw_cnt % skipperframe == 0)) {
		WFD_LOG("skip frame %d, id--%d from %d\n", skipperframe, hdmi_buffer_lcdw_id_tmp,
			hdmi_buffer_lcdw_cnt);
		up(&hdmi_update_mutex);
		return;
	}
#endif

	memset((void *)&pddp, 0, sizeof(DdpkBitbltConfig));
	pddp.srcX = pddp.srcY = 0;
	pddp.srcW = p->lcm_width;
	pddp.srcH = p->lcm_height;
	pddp.srcWStride = p->lcm_width;
	pddp.srcHStride = p->lcm_height;

	pddp.srcFormat = eRGB888_K;

	ovl_read_id =
	    ((hdmi_buffer_lcdw_id + (hdmi_temp_buffer_number - 1)) % hdmi_temp_buffer_number);
	pddp.srcAddr[0] = overlay_dst_mva + p->lcm_width * p->lcm_height * 3 * ovl_read_id;
	/* pddp.srcAddr[0] = overlay_dst_va; */
	pddp.srcAddr[1] = 0;
	pddp.srcAddr[2] = 0;

	pddp.srcBufferSize[0] = p->lcm_width * p->lcm_height * 3;
	pddp.srcBufferSize[1] = 0;
	pddp.srcBufferSize[2] = 0;
	pddp.srcPlaneNum = 1;
	pddp.srcMemType = DISP_MEMTYPE_MVA;
	pddp.orientation = p->orientation;

	portraitOutput = ((pddp.orientation == 0 || pddp.orientation == 180)
			  && p->lcm_height > p->lcm_width) || ((pddp.orientation == 90
								|| pddp.orientation == 270)
							       && p->lcm_height < p->lcm_width);

#if 0
	/* mediatek, this is for IT only */
	{
		MMP_MetaDataBitmap_t Bitmap;
		Bitmap.data1 = hdmi_buffer_lcdw_id;
		Bitmap.width = p->lcm_width;
		Bitmap.height = p->lcm_height;
		Bitmap.format = MMProfileBitmapBGR888;
		Bitmap.start_pos = 0;
		Bitmap.pitch = p->lcm_width * 3;
		Bitmap.data_size = Bitmap.pitch * Bitmap.height;
		Bitmap.down_sample_x = 6;
		Bitmap.down_sample_y = 6;
		Bitmap.pData =
		    (void *)overlay_dst_va +
		    p->lcm_width * p->lcm_height * 3 *
		    ((hdmi_buffer_lcdw_id +
		      (hdmi_temp_buffer_number - 1)) % hdmi_temp_buffer_number);
		Bitmap.bpp = 24;
		MMProfileLogMetaBitmap(WFD_MMP_Events.DDPKBitblt, MMProfileFlagStart, &Bitmap);
	}
#else
	MMProfileLogEx(WFD_MMP_Events.DDPKBitblt, MMProfileFlagStart, hdmi_buffer_write_id, 0);
#endif
	int scaling = (100 - WFD_DISPLAY_ZOOM_OUT_FACTOR);
	if (scaling < 90)
		scaling = 90;

	if (portraitOutput) {
		/* make sure in portrait mode, MDP resize must be as propotion */
		/* that is p.dstW/p.dstH == lcm_width/lcm_height */
		pddp.dstX = pddp.dstY = 0;
		if (p->lcm_height > p->lcm_width)
			pddp.dstW =
			    ALIGN_TO(p->lcm_width * p->hdmi_height / p->lcm_height * scaling / 100,
				     4);
		else
			pddp.dstW =
			    ALIGN_TO(p->lcm_height * p->hdmi_height / p->lcm_width * scaling / 100,
				     4);
		pddp.dstH = ALIGN_TO(p->hdmi_height * scaling / 100, 4);

		if (p->is_wfd) {
			/* dst format*/
			pddp.dstFormat = eYUV_420_3P_K;
		} else {
			/* dst format */
			pddp.dstFormat = eRGB888_K;
		}

		/* setting memory write start address */
		if (pddp.dstFormat == eRGB888_K) {
			pddp.dstAddr[0] =
			    ddp_dst_mva +
			    hdmi_buffer_write_id * p->hdmi_width * p->hdmi_height * 3 +
			    (p->hdmi_height - pddp.dstH) / 2 * p->hdmi_width * 3 + (p->hdmi_width -
										    pddp.dstW) / 2 *
			    3;
			pddp.dstAddr[1] = 0;
			pddp.dstAddr[2] = 0;
			pddp.dstBufferSize[0] = p->hdmi_width * p->hdmi_height * 3;
			pddp.dstBufferSize[1] = 0;
			pddp.dstBufferSize[2] = 0;
			pddp.dstPlaneNum = 1;
		} else if (pddp.dstFormat == eYUV_420_3P_K) {
			pddp.dstAddr[0] =
			    ddp_dst_mva +
			    hdmi_buffer_write_id * p->hdmi_width * p->hdmi_height * 3 +
			    (p->hdmi_height - pddp.dstH) / 2 * p->hdmi_width + (p->hdmi_width -
										pddp.dstW) / 2;
			pddp.dstAddr[1] =
			    ddp_dst_mva +
			    hdmi_buffer_write_id * p->hdmi_width * p->hdmi_height * 3 +
			    p->hdmi_width * p->hdmi_height + (p->hdmi_height -
							      pddp.dstH) / 2 * p->hdmi_width / 4 +
			    (p->hdmi_width - pddp.dstW) / 2 / 2;
			pddp.dstAddr[2] =
			    ddp_dst_mva +
			    hdmi_buffer_write_id * p->hdmi_width * p->hdmi_height * 3 +
			    p->hdmi_width * p->hdmi_height / 4 * 5 + (p->hdmi_height -
								      pddp.dstH) / 2 *
			    p->hdmi_width / 4 + (p->hdmi_width - pddp.dstW) / 2 / 2;
			pddp.dstBufferSize[0] = p->hdmi_width * p->hdmi_height;
			pddp.dstBufferSize[1] = p->hdmi_width * p->hdmi_height / 4;
			pddp.dstBufferSize[2] = p->hdmi_width * p->hdmi_height / 4;
			pddp.dstPlaneNum = 3;
		}

		pddp.pitch = p->hdmi_width;
		pddp.dstWStride = p->hdmi_width;
		pddp.dstHStride = p->hdmi_height;

		pddp.dstMemType = DISP_MEMTYPE_MVA;
	} else {
		pddp.dstX = pddp.dstY = 0;
		pddp.dstW = ALIGN_TO(p->hdmi_width * scaling / 100, 4);
		pddp.dstH = ALIGN_TO(p->hdmi_height * scaling / 100, 4);

		if (p->is_wfd) {
			/* add mark for coding style */
			pddp.dstFormat = eYUV_420_3P_K;
		} else {
			/* add mark for coding style */
			pddp.dstFormat = eRGB888_K;
		}

		if (pddp.dstFormat == eRGB888_K) {
			pddp.dstAddr[0] =
			    ddp_dst_mva +
			    hdmi_buffer_write_id * p->hdmi_width * p->hdmi_height * 3 +
			    (p->hdmi_height - pddp.dstH) / 2 * p->hdmi_width * 3 + (p->hdmi_width -
										    pddp.dstW) / 2 *
			    3;
			pddp.dstAddr[1] = 0;
			pddp.dstAddr[2] = 0;
			pddp.dstBufferSize[0] = p->hdmi_width * p->hdmi_height * 3;
			pddp.dstBufferSize[1] = 0;
			pddp.dstBufferSize[2] = 0;
			pddp.dstPlaneNum = 1;
		} else if (pddp.dstFormat == eYUV_420_3P_K) {
			pddp.dstAddr[0] =
			    ddp_dst_mva +
			    hdmi_buffer_write_id * p->hdmi_width * p->hdmi_height * 3 +
			    (p->hdmi_height - pddp.dstH) / 2 * p->hdmi_width + (p->hdmi_width -
										pddp.dstW) / 2;
			pddp.dstAddr[1] =
			    ddp_dst_mva +
			    hdmi_buffer_write_id * p->hdmi_width * p->hdmi_height * 3 +
			    p->hdmi_width * p->hdmi_height + (p->hdmi_height -
							      pddp.dstH) / 2 * p->hdmi_width / 4 +
			    (p->hdmi_width - pddp.dstW) / 2 / 2;
			pddp.dstAddr[2] =
			    ddp_dst_mva +
			    hdmi_buffer_write_id * p->hdmi_width * p->hdmi_height * 3 +
			    p->hdmi_width * p->hdmi_height / 4 * 5 + (p->hdmi_height -
								      pddp.dstH) / 2 *
			    p->hdmi_width / 4 + (p->hdmi_width - pddp.dstW) / 2 / 2;
			pddp.dstBufferSize[0] = p->hdmi_width * p->hdmi_height;
			pddp.dstBufferSize[1] = p->hdmi_width * p->hdmi_height / 4;
			pddp.dstBufferSize[2] = p->hdmi_width * p->hdmi_height / 4;
			pddp.dstPlaneNum = 3;
		}

		pddp.pitch = p->hdmi_width;
		pddp.dstWStride = p->hdmi_width;
		pddp.dstHStride = p->hdmi_height;

		pddp.dstMemType = DISP_MEMTYPE_MVA;
	}

	/* WFD_LOG("dstw=%d, dsth=%d, ori=%d\n", p.dstW, p.dstH, p.orientation); */
	do_gettimeofday(&timestamp[hdmi_buffer_write_id]);
	WFD_LOG("ts:sec=%d, nsec=%d\n", timestamp[hdmi_buffer_write_id].tv_sec,
		timestamp[hdmi_buffer_write_id].tv_usec);

	profile_t = get_current_time_us();

	ret = DDPK_Bitblt_Config(DDPK_CH_HDMI_0, &pddp);
	if (ret) {
		/* error log */
		WFD_LOG("DDPK_Bitblt fail!, ret=%d\n", ret);
	}

	ret = DDPK_Bitblt(DDPK_CH_HDMI_0);
	if (ret) {
		/*  error log */
		WFD_LOG("DDPK_Bitblt fail!, ret=%d\n", ret);
	}
	WFD_LOG("profile: %dms\n", (get_current_time_us() - profile_t) / 1000);

	hdmi_buffer_write_id = ((hdmi_buffer_write_id + 1) % hdmi_temp_buffer_number);
	WFD_LOG("after bitblt, src addr = 0x%08x, dst addr = 0x%08x, write_id=%d\n",
		pddp.srcAddr[0], pddp.dstAddr[0], hdmi_buffer_write_id);

	WFD_PUT_NEW_BUFFER();
	wake_up_interruptible(&external_display_getbuffer_wq);
	MMProfileLogEx(WFD_MMP_Events.DDPKBitblt, MMProfileFlagEnd, hdmi_buffer_write_id, 0);

 done:
	up(&hdmi_update_mutex);

	return;
}

static void _register_updated_irq_handler(unsigned int param)
{
	RET_VOID_IF_NOLOG(!is_wfd_active());

	if (param & 1) {
		hdmi_buffer_lcdw_id = hdmi_buffer_lcdw_id_tmp;
		/* WFD_LOG("wdma1 register updated, ovl_w=%d\n", hdmi_buffer_lcdw_id); */

		wfd_source_buffer_switch();
	}
}

int wfd_display_path_overlay_config(bool enable)
{
	WFD_FUNC();
	if (enable) {
		struct disp_path_config_mem_out_struct wdma1Config = { 0 };

		/* Config OVL->WDMA1 */
		wdma1Config.enable = 1;
		wdma1Config.dstAddr = overlay_dst_mva;
		wdma1Config.outFormat = WDMA_OUTPUT_FORMAT_RGB888;

		/* ROI for WDMA1 */
		wdma1Config.srcROI.x = 0;
		wdma1Config.srcROI.y = 0;
		wdma1Config.srcROI.width = p->lcm_width;
		wdma1Config.srcROI.height = p->lcm_height;

		disp_path_get_mutex();
		disp_path_config_mem_out(&wdma1Config);
		disp_path_release_mutex();
	} else {
		struct disp_path_config_mem_out_struct wdma1Config = { 0 };

		disp_path_get_mutex();
		disp_path_config_mem_out(&wdma1Config);
		disp_path_release_mutex();

		msleep(100);
	}

	return 0;
}

/* Allocate memory, set M4U, LCD, MDP, DPI */
/* LCD overlay to memory -> MDP resize and rotate to memory -> DPI read to HDMI */
/* Will only be used in ioctl(MTK_HDMI_AUDIO_VIDEO_ENABLE) */
static HDMI_STATUS hdmi_drv_init(void)
{
	int ret = 0;
	int lcm_width = 0;
	int lcm_height = 0;
	M4U_PORT_STRUCT portStruct;

	WFD_FUNC();

	lcm_width = DISP_GetScreenWidth();
	lcm_height = DISP_GetScreenHeight();

	p->lcm_width = lcm_width;
	p->lcm_height = lcm_height;
	p->lcm_is_video_mode = DISP_IsVideoMode();

	WFD_LOG("lcm_width=%d, lcm_height=%d\n", lcm_width, lcm_height);

	ret = m4u_alloc_mva(M4U_CLNTMOD_WDMA,
			    overlay_dst_va, ovl_dst_buffer_size, 0, 0, &overlay_dst_mva);
	if (ret != 0) {
		pr_info("m4u_alloc_mva() fail!\n");
		return HDMI_STATUS_OK;
	}

	m4u_dma_cache_maint(M4U_CLNTMOD_WDMA,
			    (void const *)overlay_dst_va, ovl_dst_buffer_size, DMA_BIDIRECTIONAL);

	ret = m4u_alloc_mva(M4U_CLNTMOD_WDMA, ddp_dst_va, ddp_dst_buffer_size, 0, 0, &ddp_dst_mva);
	if (ret != 0) {
		pr_info("m4u_alloc_mva() fail!\n");
		return HDMI_STATUS_OK;
	}

	m4u_dma_cache_maint(M4U_CLNTMOD_WDMA,
			    (void const *)ddp_dst_va, ddp_dst_buffer_size, DMA_BIDIRECTIONAL);

	portStruct.ePortID = M4U_PORT_WDMA1;	/* hardware port ID, defined in M4U_PORT_ID_ENUM */
	portStruct.Virtuality = 1;
	portStruct.Security = 0;
	portStruct.domain = 0;	/* domain : 0 1 2 3 */
	portStruct.Distance = 1;
	portStruct.Direction = 0;
	m4u_config_port(&portStruct);

	if (p->lcm_is_video_mode) {
		wfd_display_path_overlay_config(true);
		disp_register_irq(DISP_MODULE_MUTEX, _register_updated_irq_handler);
	} else
		DISP_Config_Overlay_to_Memory(overlay_dst_mva, 1);

	WFD_LOG("overlay_dst_va=0x%08x, overlay_dst_mva=0x%08x, buffer size=0x%08x\n",
		overlay_dst_va, overlay_dst_mva, ovl_dst_buffer_size);

	return HDMI_STATUS_OK;
}

/* Release memory */
/* Will only be used in ioctl(MTK_HDMI_AUDIO_VIDEO_ENABLE) */
static HDMI_STATUS hdmi_drv_deinit(void)
{
	int ret = 0;
	M4U_PORT_STRUCT portStruct;

	WFD_FUNC();
	if (down_interruptible(&hdmi_update_mutex)) {
		WFD_LOG("[HDMI] can't get semaphore in\n");
		return;
	}

	if (p->lcm_is_video_mode) {
		disp_unregister_irq(DISP_MODULE_MUTEX, _register_updated_irq_handler);
		wfd_display_path_overlay_config(false);
	} else
		DISP_Config_Overlay_to_Memory(overlay_dst_mva, 0);
	WFD_LOG("disable overlay output to memory\n");

	portStruct.ePortID = M4U_PORT_WDMA1;	/* hardware port ID, defined in M4U_PORT_ID_ENUM */
	portStruct.Virtuality = 0;
	portStruct.Security = 0;
	portStruct.domain = 0;	/* domain : 0 1 2 3 */
	portStruct.Distance = 1;
	portStruct.Direction = 0;
	m4u_config_port(&portStruct);
	WFD_LOG("disable WDMA1 m4u link\n");

	ret = m4u_dealloc_mva(M4U_CLNTMOD_WDMA,
			      overlay_dst_va, ovl_dst_buffer_size, overlay_dst_mva);
	WFD_LOG("overlay_dst_va mva dealloced\n");

	ret = m4u_dealloc_mva(M4U_CLNTMOD_WDMA, ddp_dst_va, ddp_dst_buffer_size, ddp_dst_mva);
	WFD_LOG("ddp_dst_va mva dealloced\n");
	up(&hdmi_update_mutex);

	return HDMI_STATUS_OK;
}

/* Set HDMI orientation, will be called in mtkfb_ioctl(SET_ORIENTATION) */
/*static*/ void wfd_setorientation(int orientation)
{
	WFD_FUNC();
	/* RET_VOID_IF(!p->is_enabled); */

	if (down_interruptible(&hdmi_update_mutex)) {
		pr_info("[hdmi][HDMI] can't get semaphore in %s\n", __func__);
		return;
	}

	WFD_LOG("old ori=%d, new ori=%d\n", p->orientation, orientation);
	p->orientation = orientation;
	p->is_reconfig_needed = true;
	WFD_LOG("old ori=%d, new ori=%d\n", p->orientation, orientation);
	MMProfileLog(WFD_MMP_Events.Rotate, MMProfileFlagPulse);

	/* done: */
	up(&hdmi_update_mutex);
}

static int hdmi_release(struct inode *inode, struct file *file)
{
	return 0;
}

static int hdmi_open(struct inode *inode, struct file *file)
{
	return 0;
}

static BOOL hdmi_drv_init_context(void);

static char *_hdmi_ioctl_spy(unsigned int cmd)
{
	switch (cmd) {
	case MTK_EXT_DISPLAY_ENTER:
		return "MTK_EXT_DISPLAY_ENTER";
	case MTK_EXT_DISPLAY_LEAVE:
		return "MTK_EXT_DISPLAY_LEAVE";
	case MTK_EXT_DISPLAY_START:
		return "MTK_EXT_DISPLAY_START";
	case MTK_EXT_DISPLAY_STOP:
		return "MTK_EXT_DISPLAY_STOP";
	case MTK_EXT_DISPLAY_SET_MEMORY_INFO:
		return "MTK_EXT_DISPLAY_SET_MEMORY_INFO";
	case MTK_EXT_DISPLAY_GET_MEMORY_INFO:
		return "MTK_EXT_DISPLAY_GET_MEMORY_INFO";
	case MTK_EXT_DISPLAY_GET_BUFFER:
		return "MTK_EXT_DISPLAY_GET_BUFFER";
	case MTK_HDMI_AUDIO_VIDEO_ENABLE:
		return "MTK_HDMI_AUDIO_VIDEO_ENABLE";
	case MTK_HDMI_AUDIO_ENABLE:
		return "MTK_HDMI_AUDIO_ENABLE";
	case MTK_HDMI_VIDEO_ENABLE:
		return "MTK_HDMI_VIDEO_ENABLE";
	case MTK_HDMI_GET_CAPABILITY:
		return "MTK_HDMI_GET_CAPABILITY";
	case MTK_HDMI_GET_DEVICE_STATUS:
		return "MTK_HDMI_GET_DEVICE_STATUS";
	case MTK_HDMI_VIDEO_CONFIG:
		return "MTK_HDMI_VIDEO_CONFIG";
	case MTK_HDMI_AUDIO_CONFIG:
		return "MTK_HDMI_AUDIO_CONFIG";
	case MTK_HDMI_FORCE_FULLSCREEN_ON:
		return "MTK_HDMI_FORCE_FULLSCREEN_ON";
	case MTK_HDMI_FORCE_FULLSCREEN_OFF:
		return "MTK_HDMI_FORCE_FULLSCREEN_OFF";
	case MTK_HDMI_IPO_POWEROFF:
		return "MTK_HDMI_IPO_POWEROFF";
	case MTK_HDMI_IPO_POWERON:
		return "MTK_HDMI_IPO_POWERON";
	case MTK_HDMI_POWER_ENABLE:
		return "MTK_HDMI_POWER_ENABLE";
	case MTK_HDMI_PORTRAIT_ENABLE:
		return "MTK_HDMI_PORTRAIT_ENABLE";
	case MTK_HDMI_FORCE_OPEN:
		return "MTK_HDMI_FORCE_OPEN";
	case MTK_HDMI_FORCE_CLOSE:
		return "MTK_HDMI_FORCE_CLOSE";
	case MTK_HDMI_IS_FORCE_AWAKE:
		return "MTK_HDMI_IS_FORCE_AWAKE";
	case MTK_HDMI_ENTER_VIDEO_MODE:
		return "MTK_HDMI_ENTER_VIDEO_MODE";
	case MTK_HDMI_LEAVE_VIDEO_MODE:
		return "MTK_HDMI_LEAVE_VIDEO_MODE";
	case MTK_HDMI_REGISTER_VIDEO_BUFFER:
		return "MTK_HDMI_REGISTER_VIDEO_BUFFER";
	case MTK_HDMI_POST_VIDEO_BUFFER:
		return "MTK_HDMI_POST_VIDEO_BUFFER";
	case MTK_HDMI_FACTORY_MODE_ENABLE:
		return "MTK_HDMI_FACTORY_MODE_ENABLE";
#ifdef CONFIG_MTK_MT8193_HDMI_SUPPORT
	case MTK_HDMI_WRITE_DEV:
		return "MTK_HDMI_WRITE_DEV";
	case MTK_HDMI_READ_DEV:
		return "MTK_HDMI_READ_DEV";
	case MTK_HDMI_ENABLE_LOG:
		return "MTK_HDMI_ENABLE_LOG";
	case MTK_HDMI_CHECK_EDID:
		return "MTK_HDMI_CHECK_EDID";
	case MTK_HDMI_INFOFRAME_SETTING:
		return "MTK_HDMI_INFOFRAME_SETTING";
	case MTK_HDMI_ENABLE_HDCP:
		return "MTK_HDMI_ENABLE_HDCP";
	case MTK_HDMI_STATUS:
		return "MTK_HDMI_STATUS";
	case MTK_HDMI_HDCP_KEY:
		return "MTK_HDMI_HDCP_KEY";
	case MTK_HDMI_GET_EDID:
		return "MTK_HDMI_GET_EDID";
	case MTK_HDMI_SETLA:
		return "MTK_HDMI_SETLA";
	case MTK_HDMI_GET_CECCMD:
		return "MTK_HDMI_GET_CECCMD";
	case MTK_HDMI_SET_CECCMD:
		return "MTK_HDMI_SET_CECCMD";
	case MTK_HDMI_CEC_ENABLE:
		return "MTK_HDMI_CEC_ENABLE";
	case MTK_HDMI_GET_CECADDR:
		return "MTK_HDMI_GET_CECADDR";
	case MTK_HDMI_CECRX_MODE:
		return "MTK_HDMI_CECRX_MODE";
	case MTK_HDMI_SENDSLTDATA:
		return "MTK_HDMI_SENDSLTDATA";
	case MTK_HDMI_GET_SLTDATA:
		return "MTK_HDMI_GET_SLTDATA";
#endif
	default:
		return "unknown ioctl command";
	}
}

extern int external_display_trigger_update(void);

void wfd_force_pattern_output(int enable)
{
	wfd_pattern_output = enable;
	if (wfd_pattern_output) {
		/* mark */
		wfd_pattern_output_index = 0;
	}
}

void wfd_suspend(void)
{
	RET_VOID_IF(IS_HDMI_NOT_ON());
	RET_VOID_IF(!p->is_wfd);

	if (down_interruptible(&hdmi_update_mutex)) {
		WFD_LOG("[HDMI] can't get semaphore in\n");
		return;
	}

	p->is_wfd_suspend = true;
	MMProfileLogEx(WFD_MMP_Events.DDPKBitblt, MMProfileFlagPulse, 100, 0);
	{
		int i = 0;
		for (i = 0; i < hdmi_temp_buffer_number; i++) {
			memset((void *)(ddp_dst_va + i * p->hdmi_width * p->hdmi_height * 3), 0x00,
			       p->hdmi_width * p->hdmi_height);
			memset((void *)(ddp_dst_va + i * p->hdmi_width * p->hdmi_height * 3 +
					p->hdmi_width * p->hdmi_height), 0x80,
			       p->hdmi_width * p->hdmi_height);
		}
	}
	WFD_PUT_NEW_BUFFER();
	wake_up_interruptible(&external_display_getbuffer_wq);

	up(&hdmi_update_mutex);
}

void wfd_resume(void)
{
	RET_VOID_IF(IS_HDMI_NOT_ON());
	RET_VOID_IF(!p->is_wfd);

	if (down_interruptible(&hdmi_update_mutex)) {
		WFD_LOG("[HDMI] can't get semaphore in\n");
		return;
	}

	p->is_wfd_suspend = false;
	MMProfileLogEx(WFD_MMP_Events.DDPKBitblt, MMProfileFlagPulse, 900, 0);

	up(&hdmi_update_mutex);
}

static long hdmi_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
	void __user *argp = (void __user *)arg;

	int r = 0;

	WFD_LOG("[HDMI] hdmi ioctl= %s(%d)\n", _hdmi_ioctl_spy(cmd), cmd & 0xff);

	switch (cmd) {
	case MTK_HDMI_POWER_ENABLE:
		{
			RETIF(!p->is_enabled, 0);

			if (arg) {
				/* add mark for coding style */
				wfd_resume();
			} else {
				/* add mark for coding style */
				wfd_suspend();
			}
			break;
		}
	case MTK_EXT_DISPLAY_ENTER:
		{

			MMProfileLog(WFD_MMP_Events.WFDEnter, MMProfileFlagPulse);
			p->is_wfd = TRUE;
			if (p->is_enabled)
				return 0;

			p->is_enabled = true;
			WFD_CLEAR_NEW_BUFFER();
			init_wfd_mmp_events();

			break;
		}
	case MTK_EXT_DISPLAY_LEAVE:
		{
			MMProfileLog(WFD_MMP_Events.WFDLeave, MMProfileFlagPulse);
			p->is_wfd = FALSE;
			break;
		}
	case MTK_EXT_DISPLAY_START:
		{
			MMProfileLog(WFD_MMP_Events.WFDStart, MMProfileFlagPulse);
			SET_HDMI_ON();
			HDMI_CHECK_RET(hdmi_drv_init());
			hdmi_buffer_lcdw_cnt = 0;
			/* external_display_trigger_update(); */

			break;
		}
	case MTK_EXT_DISPLAY_STOP:
		{
			RETIF(IS_HDMI_NOT_ON(), -1);

			MMProfileLog(WFD_MMP_Events.WFDStop, MMProfileFlagPulse);
			SET_HDMI_OFF();
			HDMI_CHECK_RET(hdmi_drv_deinit());
			WFD_LOG("overlay_dst_va and ddp_dst_va will be freed\n");
			vfree((void const *)overlay_dst_va);
			vfree((void const *)ddp_dst_va);
			overlay_dst_va = 0;
			ddp_dst_va = 0;
			WFD_CLEAR_NEW_BUFFER();
			memset((void *)&timestamp, 0, sizeof(struct timeval) * 16);
			break;
		}
	case MTK_EXT_DISPLAY_SET_MEMORY_INFO:
		{
			int i = 0;
			struct ext_memory_info info;
			if (copy_from_user
			    (&info, (void __user *)argp, sizeof(struct ext_memory_info))) {
				WFD_LOG("copy_from_user failed! line\n");
				r = -EFAULT;
				break;
			}

			WFD_LOG
			    ("MTK_EXT_DISPLAY_SET_MEMORY_INFO, width=%d, height=%d, buffer number=%d, bpp=%d\n",
			     info.width, info.height, info.buffer_num, info.bpp);
			p->hdmi_width = info.width;
			p->hdmi_height = info.height;
			hdmi_temp_buffer_number = info.buffer_num;
			WFD_LOG("p->hdmi_width=%d, p->hdmi_height=%d\n", p->hdmi_width,
				p->hdmi_height);

			ovl_dst_buffer_size =
			    DISP_GetScreenWidth() * DISP_GetScreenHeight() * 3 *
			    hdmi_temp_buffer_number;
			ddp_dst_buffer_size =
			    p->hdmi_width * p->hdmi_height * 3 * hdmi_temp_buffer_number;

			overlay_dst_va = (unsigned int)vmalloc(ovl_dst_buffer_size);
			if (((void *)overlay_dst_va) == NULL) {
				WFD_LOG("vmalloc %dbytes fail\n", ovl_dst_buffer_size);
				return -1;
			}

			ddp_dst_va = (unsigned int)vmalloc(ddp_dst_buffer_size);
			if (((void *)ddp_dst_va) == NULL) {
				WFD_LOG("vmalloc %dbytes fail\n", ddp_dst_buffer_size);
				return -1;
			}

			WFD_LOG("ddp_dst_va=0x%08x, overlay_dst_va=0x%08x\n", ddp_dst_va,
				overlay_dst_va);

			for (i = 0; i < hdmi_temp_buffer_number; i++) {
				memset((void *)(ddp_dst_va +
						i * p->hdmi_width * p->hdmi_height * 3), 0x00,
				       p->hdmi_width * p->hdmi_height);
				memset((void *)(ddp_dst_va +
						i * p->hdmi_width * p->hdmi_height * 3 +
						p->hdmi_width * p->hdmi_height), 0x80,
				       p->hdmi_width * p->hdmi_height);
			}

			break;
		}
	case MTK_EXT_DISPLAY_GET_BUFFER:
		{
			int ret = 0;
			int get_buffer_id = 0;
			struct ext_buffer buf = { 0, 0, 0 };

			MMProfileLogEx(WFD_MMP_Events.Getbuffer, MMProfileFlagStart,
				       wfd_pattern_output_index, 0);

			if (wfd_pattern_output) {
				struct timeval t;
				{
					memset((void *)(ddp_dst_va +
							wfd_pattern_output_index * p->hdmi_width *
							p->hdmi_height * 3), 0x00,
					       p->hdmi_width * p->hdmi_height);
					memset((void *)(ddp_dst_va +
							wfd_pattern_output_index * p->hdmi_width *
							p->hdmi_height * 3 +
							p->hdmi_width * p->hdmi_height), 0x80,
					       p->hdmi_width * p->hdmi_height);

					memset((void *)(ddp_dst_va +
							wfd_pattern_output_index * p->hdmi_width *
							p->hdmi_height * 3 +
							wfd_pattern_output_index * p->hdmi_width *
							p->hdmi_height / 8), 0xFF,
					       p->hdmi_width * p->hdmi_height / 8);
				}

				do_gettimeofday(&t);
				buf.id = wfd_pattern_output_index;
				buf.ts_sec = t.tv_sec;
				buf.ts_nsec = t.tv_usec;

				wfd_pattern_output_index =
				    ((wfd_pattern_output_index + 1) % hdmi_temp_buffer_number);

				ret = copy_to_user(argp, &buf, sizeof(struct ext_buffer));

				MMProfileLogEx(WFD_MMP_Events.Getbuffer, MMProfileFlagEnd,
					       buf.ts_sec, buf.ts_nsec);

				return ret;
			}

			if (WFD_GET_NEW_BUFFER()) {
				WFD_CLEAR_NEW_BUFFER();
			} else {
				interruptible_sleep_on(&external_display_getbuffer_wq);
				WFD_CLEAR_NEW_BUFFER();
			}
			get_buffer_id =
			    ((hdmi_buffer_write_id +
			      (hdmi_temp_buffer_number - 1)) % hdmi_temp_buffer_number);

			if (p->is_wfd_suspend) {
				memset((void *)(ddp_dst_va + p->hdmi_width * p->hdmi_height * 3),
				       0x00, p->hdmi_width * p->hdmi_height);
				memset((void *)(ddp_dst_va + p->hdmi_width * p->hdmi_height * 3 +
						p->hdmi_width * p->hdmi_height), 0x80,
				       p->hdmi_width * p->hdmi_height);
				get_buffer_id = 0;
			}

			buf.id = get_buffer_id;
			buf.ts_sec = timestamp[buf.id].tv_sec;
			buf.ts_nsec = timestamp[buf.id].tv_usec;
			WFD_LOG("get buffer, id=%d, ts: sec=%d, usec=%d\n", buf.id,
				timestamp[buf.id].tv_sec, timestamp[buf.id].tv_usec);

			ret = copy_to_user(argp, &buf, sizeof(struct ext_buffer));

			MMProfileLogEx(WFD_MMP_Events.Getbuffer, MMProfileFlagEnd, 2,
				       hdmi_buffer_write_id);

#if 0
			/* mediatek, this is for IT only */
			{
				MMP_MetaDataBitmap_t Bitmap;
				Bitmap.data1 = buf.id;
				Bitmap.width = p->hdmi_width;
				Bitmap.height = p->hdmi_height;
				Bitmap.format = MMProfileBitmapBGR888;
				Bitmap.start_pos = 0;
				Bitmap.pitch = p->hdmi_width * 3;
				Bitmap.data_size = Bitmap.pitch * Bitmap.height;
				Bitmap.down_sample_x = 10;
				Bitmap.down_sample_y = 10;
				Bitmap.pData =
				    (void *)ddp_dst_va +
				    buf.id * p->hdmi_width * p->hdmi_height * 3;
				Bitmap.bpp = 24;
				MMProfileLogMetaBitmap(WFD_MMP_Events.Getbuffer, MMProfileFlagPulse,
						       &Bitmap);
			}
#endif
			return ret;
		}

	default:
		{
			pr_info("[hdmi][HDMI] arguments error\n");
			break;
		}
	}

	return r;
}

static int hdmi_remove(struct platform_device *pdev)
{
	return 0;
}

static void __exit hdmi_exit(void)
{
	device_destroy(hdmi_class, hdmi_devno);
	class_destroy(hdmi_class);
	cdev_del(hdmi_cdev);
	unregister_chrdev_region(hdmi_devno, 1);

}

static int hdmi_mmap(struct file *file, struct vm_area_struct *vma)
{
	int i;

	int buffer_size = (p->hdmi_width * p->hdmi_height * 3 * hdmi_temp_buffer_number);
	pr_info("[hdmi_mmap] vma->vm_pgoff=0x%08x\n", (unsigned int)(vma->vm_pgoff));
	pr_info("[hdmi_mmap] vma->vm_start=0x%08x\n", (unsigned int)(vma->vm_start));
	pr_info("[hdmi_mmap] vma->vm_end=0x%08x\n", (unsigned int)(vma->vm_end));
	pr_info("[hdmi_mmap] vma->vm_page_prot=0x%08x\n", (unsigned int)(vma->vm_page_prot));
	pr_info("[hdmi_mmap] vma->vm_flags=0x%08x\n", (unsigned int)(vma->vm_flags));

	vma->vm_flags |= VM_RESERVED;
	vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);

	pr_info("[hdmi_mmap] vma->vm_flags=0x%08x\n", (unsigned int)vma->vm_flags);
	for (i = 0; i < buffer_size; i += PAGE_SIZE) {
		if (remap_pfn_range((struct vm_area_struct *)vma,
				    (vma->vm_start + i),
				    vmalloc_to_pfn((unsigned int)ddp_dst_va + i),
				    PAGE_SIZE, vma->vm_page_prot | PAGE_SHARED)) {
			return -EAGAIN;
		}
	}

	return 0;
}

const struct file_operations wfd_fops = {
	.owner = THIS_MODULE,
	.unlocked_ioctl = hdmi_ioctl,
	.open = hdmi_open,
	.release = hdmi_release,
	.mmap = hdmi_mmap
};

static int hdmi_probe(struct platform_device *pdev)
{
	int ret = 0;
	struct class_device *class_dev = NULL;

	pr_info("[hdmi]%s\n", __func__);

	/* Allocate device number for hdmi driver */
	ret = alloc_chrdev_region(&hdmi_devno, 0, 1, HDMI_DEVNAME);
	if (ret) {
		pr_info("[hdmi]alloc_chrdev_region fail\n");
		return -1;
	}

	/* For character driver register to system, device number binded to file operations */
	hdmi_cdev = cdev_alloc();
	hdmi_cdev->owner = THIS_MODULE;
	hdmi_cdev->ops = &wfd_fops;
	ret = cdev_add(hdmi_cdev, hdmi_devno, 1);

	/* For device number binded to device name(hdmitx), one class is corresponeded to one node */
	hdmi_class = class_create(THIS_MODULE, HDMI_DEVNAME);
	/* mknod /dev/hdmitx */
	class_dev =
	    (struct class_device *)device_create(hdmi_class, NULL, hdmi_devno, NULL, HDMI_DEVNAME);

	pr_info("[hdmi][%s] current=0x%08x\n", __func__, (unsigned int)current);

	init_waitqueue_head(&hdmi_update_wq);
	init_waitqueue_head(&external_display_getbuffer_wq);
	init_waitqueue_head(&hdmi_overlay_config_wq);

	hdmi_update_task = kthread_create(hdmi_update_kthread, NULL, "hdmi_update_kthread");
	wake_up_process(hdmi_update_task);

	hdmi_overlay_config_task =
	    kthread_create(hdmi_overlay_config_kthread, NULL, "hdmi_overlay_config_kthread");
	wake_up_process(hdmi_overlay_config_task);
	HDMI_DBG_Init();

	return 0;
}

static struct platform_driver hdmi_driver = {
	.probe = hdmi_probe,
	.remove = hdmi_remove,
	.driver = {.name = HDMI_DEVNAME}
};

static struct platform_device hdmi_device = {
	.name = HDMI_DEVNAME,
	.id = 0,
};

static int __init hdmi_init(void)
{
	pr_info("[hdmi]%s\n", __func__);

	if (platform_device_register(&hdmi_device)) {
		/* add mark for coding style */
		pr_info("[hdmi]failed to register hdmi device");
	}
	if (platform_driver_register(&hdmi_driver)) {
		pr_info("[hdmi]failed to register hdmi driver\n");
		return -1;
	}

	SET_HDMI_OFF();

	return 0;
}

module_init(hdmi_init);
module_exit(hdmi_exit);
MODULE_AUTHOR("<www.mediatek.com>");
MODULE_DESCRIPTION("WFD Driver");
MODULE_LICENSE("GPL");

#endif


text:
package org.akhikhl.gretty;

import org.eclipse.jetty.http.HttpMethods;
import org.eclipse.jetty.security.ServerAuthException;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.security.authentication.DeferredAuthentication;
import org.eclipse.jetty.security.authentication.SessionAuthentication;
import org.eclipse.jetty.server.AbstractHttpConnection;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.MultiMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static org.eclipse.jetty.security.authentication.FormAuthenticator.__J_POST;
import static org.eclipse.jetty.security.authentication.FormAuthenticator.__J_URI;

/**
 *
 * @author akhikhl
 */
public class SSOBasicAuthenticator extends BasicAuthenticator {

    private static final Logger LOG = LoggerFactory.getLogger(SSOBasicAuthenticator.class);

    // "login" is copied without changes from FormAuthenticator
    @Override
    public UserIdentity login(String username, Object password, ServletRequest request)
    {

        UserIdentity user = super.login(username,password,request);
        if (user!=null)
        {
            HttpSession session = ((HttpServletRequest)request).getSession(true);
            Authentication cached=new SessionAuthentication(getAuthMethod(),user,password);
            session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, cached);
        }
        return user;
    }

    @Override
    public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
    {
        HttpServletRequest request = (HttpServletRequest)req;

        if (!mandatory)
            return new DeferredAuthentication(this);

        // ++ copied from FormAuthenticator

        HttpSession session = request.getSession(true);

        // Look for cached authentication
        Authentication authentication = (Authentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
        if (authentication != null)
        {
            // Has authentication been revoked?
            if (authentication instanceof Authentication.User &&
                _loginService!=null &&
                !_loginService.validate(((Authentication.User)authentication).getUserIdentity()))
            {

                session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
            }
            else
            {
                String j_uri=(String)session.getAttribute(__J_URI);
                if (j_uri!=null)
                {
                    MultiMap<String> j_post = (MultiMap<String>)session.getAttribute(__J_POST);
                    if (j_post!=null)
                    {
                        StringBuffer buf = request.getRequestURL();
                        if (request.getQueryString() != null)
                            buf.append("?").append(request.getQueryString());

                        if (j_uri.equals(buf.toString()))
                        {
                            // This is a retry of an original POST request
                            // so restore method and parameters

                            session.removeAttribute(__J_POST);
                            Request base_request = (req instanceof Request)?(Request)req:AbstractHttpConnection.getCurrentConnection().getRequest();
                            base_request.setMethod(HttpMethods.POST);
                            base_request.setParameters(j_post);
                        }
                    }
                    else
                        session.removeAttribute(__J_URI);

                }
                return authentication;
            }
        }
        // -- copied from FormAuthenticator

        return super.validateRequest(req, res, mandatory);
    }
}


text:
<?php

namespace Oro\Bundle\UIBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

use Oro\Bundle\ActivityBundle\EntityConfig\ActivityScope;

class ConstantsPass implements CompilerPassInterface
{
    protected $parameters = [
        'oro_ui.widget_provider.view_actions.page_type' => ActivityScope::VIEW_PAGE,
        'oro_ui.widget_provider.update_actions.page_type' => ActivityScope::UPDATE_PAGE,
    ];

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        foreach ($this->parameters as $key => $value) {
            $container->setParameter($key, $value);
        }
    }
}


text:
from collections import namedtuple

from django.utils.translation import ugettext_lazy as _

Notification = namedtuple(
    'Notification', (
        'id', 'group', 'short', 'label', 'mandatory', 'default_checked'
    )
)

RemoteNotification = namedtuple(
    'RemoteNotification', (
        'id', 'group', 'short', 'label', 'mandatory', 'default_checked',
        'basket_newsletter_id',
    )
)

reply = Notification(
    id=3,
    group='user',
    short='reply',
    label=_('an add-on developer replies to my review'),
    mandatory=False,
    default_checked=True)

new_features = Notification(
    id=4,
    group='user',
    short='new_features',
    label=_('new add-ons or Firefox features are available'),
    mandatory=False,
    default_checked=True)

upgrade_success = Notification(
    id=5,
    group='dev',
    short='upgrade_success',
    label=_('my add-on\'s compatibility is upgraded successfully'),
    mandatory=False,
    default_checked=True)

sdk_upgrade_success = Notification(
    id=6,
    group='dev',
    short='sdk_upgrade_success',
    label=_('my sdk-based add-on is upgraded successfully'),
    mandatory=False,
    default_checked=True)

new_review = Notification(
    id=7,
    group='dev',
    short='new_review',
    label=_('someone writes a review of my add-on'),
    mandatory=False,
    default_checked=True)

# This is the about-addons newsletter.
#
# The newsletter is managed in Salesforce and syncronized via
# basket. It's not used in addons-server except for the user
# profile forms.
announcements = RemoteNotification(
    id=8,
    group='dev',
    short='announcements',
    label=_('stay up-to-date with news and events relevant to add-on '
            'developers (including the about:addons newsletter)'),
    mandatory=False,
    default_checked=False,
    basket_newsletter_id='about-addons')

upgrade_fail = Notification(
    id=9,
    group='dev',
    short='upgrade_fail',
    label=_('my add-on\'s compatibility cannot be upgraded'),
    mandatory=True,
    default_checked=True)

sdk_upgrade_fail = Notification(
    id=10,
    group='dev',
    short='sdk_upgrade_fail',
    label=_('my sdk-based add-on cannot be upgraded'),
    mandatory=True,
    default_checked=True)

reviewer_reviewed = Notification(
    id=11,
    group='dev',
    short='reviewer_reviewed',
    label=_('my add-on is reviewed by a reviewer'),
    mandatory=True,
    default_checked=True)

individual_contact = Notification(
    id=12,
    group='dev',
    short='individual_contact',
    label=_('Mozilla needs to contact me about my individual add-on'),
    mandatory=True,
    default_checked=True)

NOTIFICATION_GROUPS = {'dev': _('Developer'),
                       'user': _('User Notifications')}

AMO_NOTIFICATIONS = [
    reply, new_features, upgrade_success, sdk_upgrade_success,
    new_review, upgrade_fail, sdk_upgrade_fail, reviewer_reviewed,
    individual_contact
]

REMOTE_NOTIFICATIONS = [
    announcements,
]

NOTIFICATIONS_COMBINED = AMO_NOTIFICATIONS + REMOTE_NOTIFICATIONS

NOTIFICATIONS_BY_ID = {l.id: l for l in NOTIFICATIONS_COMBINED}
NOTIFICATIONS_BY_ID_NOT_DEV = {
    l.id: l for l in NOTIFICATIONS_COMBINED if l.group != 'dev'}

REMOTE_NOTIFICATIONS_BY_BASKET_ID = {
    l.basket_newsletter_id: l for l in REMOTE_NOTIFICATIONS}

NOTIFICATIONS_BY_SHORT = {l.short: l for l in NOTIFICATIONS_COMBINED}
NOTIFICATIONS_DEFAULT = [
    l.id for l in NOTIFICATIONS_COMBINED if l.default_checked]