text:
import Router from 'koa-router'
import convert from 'koa-convert'
import _validate from 'koa-req-validator'
import Test from '../model/test'
import Config from '../config'
import User from '../model/user'
import Anchor from '../model/anchor'
import Room from '../model/room'
import Profit from '../model/profit'
import { Token, TokenVerify } from '../utils/token'

const validate = (...args) => convert(_validate(...args))
const router = new Router({
  prefix: `/api/${Config.apiversion}/room`
})

//建立直播間
router.post('/new',
  validate({
      'title:body':['require',  'title is required'],
      'image:body':['require', 'isBase64', 'image is required'],
    }),
  async(ctx, next) => {
    try {
      const { authorization, deviceid} = ctx.request.header
      const {title, image} = ctx.request.body
      const userID = await TokenVerify(authorization)
      const user = await User.findOne({userID})
      if (user) {
        //image decoded and save to img folder and get imgUrl
        //get streamUrl
        //get streamKey
        //asign roomID
        const imgUrl = "https://livebet9457.com/images/92801371.png"
        const streamUrl = "rtmp://livebet9457.com/live"
        const streamKey = "QiLCJhbGciO"
        const maxNum = 1000000
        const code = ('000000' + Math.floor(Math.random() * maxNum)).substr(-6)
        const roomID = "rn"+code//不該重複, 先放著之後再做檢查functoin
        //get status from media server
        const status = 1
        const d = new Date()
        const begin = d.getTime()
        if (status) {
          const exist = await Room.findOne( { userID } )
          const { anchorID } = await Anchor.findOne( { userID } )
          if (exist) {
            await Room.findOneAndUpdate( { userID },{
              userID,
              anchorID,
              room:{
                roomID,
                title,
                imgUrl,
                streamUrl,
                streamKey
              },
              begin,
              end: 0,
              profit: {
                viewers:0,
                likes: 0,
                giftIncome:0,
                stake: 0
              },
              leaders: []
            })
          }else {
            let room = new Room({
              userID,
              anchorID,
              room:{
                roomID,
                title,
                imgUrl,
                streamUrl,
                streamKey
              },
              begin,
              end: 0
            })
            await room.save()
          }
          ctx.status = 200
          ctx.response.body = {
            roomID,
            title,
            imgUrl,
            streamUrl,
            streamKey,
            begin
          }
        }else {
          const NotAcceptable = '直播建立失敗 - 媒體伺服器無回應'
          ctx.status = 406
          ctx.message = "error"
          ctx.response.body = {
            error: NotAcceptable
          }
        }
      }else {
        const Unauthorized = '未授權的用戶'
        ctx.status = 401
        ctx.message = "error"
        ctx.response.body = {
          error: Unauthorized
        }
      }
    } catch (err) {
      if(err.output.statusCode){
        ctx.throw(err.output.statusCode, err)
      }else {
        ctx.throw(500, err)
      }
    }
  }
)

//關閉直播間
router.post('/:roomID/close',
  async (ctx, next) => {
    try {
      const { authorization, deviceid} = ctx.request.header
      const { roomID } = ctx.params
      const  userID  = await TokenVerify(authorization)
      const user = await Room.findOne({userID})
      if (user) {
        const room = await Room.findOne({'room.roomID' : roomID})
        if ( room && room.end == 0 ) { // room.end == 0 =>  room still open
          const { anchorID, begin, profit } = room
          const { roomID, title } = room.room
          const d = new Date()
          const end = d.getTime()
          await room.update({end})

          let profit_ = new Profit({
            userID, anchorID, roomID, title, begin, end, profit })
          profit_.save()
          //when close, record and save the profit into the profit DB

          ctx.status = 200
          ctx.response.body = {
            roomID,
            title,
            begin,
            end,
            profit
          }
        }else {
          const NotFound = '錯誤的直播間ID'
          ctx.status = 404
          ctx.message = "error"
          ctx.response.body = {
            error: NotFound
          }
        }
      }else {
        const Unauthorized = '未授權的用戶'
        ctx.status = 401
        ctx.message = "error"
        ctx.response.body = {
          error: Unauthorized
        }
      }
    } catch (err) {
      const Unauthorized = '未授權的用戶'
      ctx.status = 401
      ctx.message = "error"
      ctx.response.body = {
        error: Unauthorized
      }
      // if(err.output.statusCode){
      //   ctx.throw(err.output.statusCode, err)
      // }else {
      //   ctx.throw(500, err)
      // }
    }
  }
)

//加入直播間
router.post('/:roomID/join',
  async (ctx, next) => {
    try {
      const { authorization, deviceid} = ctx.request.header
      const { roomID } = ctx.params
      const  userID  = await TokenVerify(authorization)
      const user = await User.findOne({userID})
      if (user) {
        const room = await Room.findOne({'room.roomID' : roomID})
        if ( room && room.end == 0) {// room.end == 0 =>  room still open
          const { anchorID, begin, profit } = room
          let { viewers } = profit
          const { streamUrl, title } = room.room
          let { name, imgs, fans, likes } = await Anchor.findOne({ anchorID })
          viewers++
          await room.update({
            'profit.viewers': viewers
          })
          ctx.status = 200
          ctx.response.body = {
            streamUri:streamUrl,
            backupUri:streamUrl,
            announcement: title,
            host:{
              hostID: anchorID,
              hostName: name,
              hostImg: imgs,
              fans,
              likes
            }
          }
        }else {
          const NotFound = '直播間不存在'
          ctx.status = 404
          ctx.message = "error"
          ctx.response.body = {
            error: NotFound
          }
        }
      }else {
        const Unauthorized = '未授權的用戶'
        ctx.status = 401
        ctx.message = "error"
        ctx.response.body = {
          error: Unauthorized
        }
      }
    } catch (err) {
      const Unauthorized = '未授權的用戶'
      ctx.status = 401
      ctx.message = "error"
      ctx.response.body = {
        error: Unauthorized
      }
      // if(err.output.statusCode){
      //   ctx.throw(err.output.statusCode, err)
      // }else {
      //   ctx.throw(500, err)
      // }
    }
  }
)

//離開直播間
router.post('/:roomID/leave',
  async (ctx, next) => {
    try {
      const { authorization, deviceid} = ctx.request.header
      const { roomID } = ctx.params
      const  userID  = await TokenVerify(authorization)
      const user = await User.findOne({userID})
      if (user) {
        const room = await Room.findOne({'room.roomID' : roomID})
        if ( room && room.end == 0) {// room.end == 0 =>  room still open
          const { anchorID, begin, profit } = room
          let { viewers } = profit
          const { roomID } = room.room

          viewers--
          await room.update({
            'profit.viewers': viewers
          })
          ctx.status = 200
          ctx.response.body = {
          }
        }else {
          const NotFound = '直播間不存在'
          ctx.status = 404
          ctx.message = "error"
          ctx.response.body = {
            error: NotFound
          }
        }
      }else {
        const Unauthorized = '未授權的用戶'
        ctx.status = 401
        ctx.message = "error"
        ctx.response.body = {
          error: Unauthorized
        }
      }
    } catch (err) {
      const Unauthorized = '未授權的用戶'
      ctx.status = 401
      ctx.message = "error"
      ctx.response.body = {
        error: Unauthorized
      }
      // if(err.output.statusCode){
      //   ctx.throw(err.output.statusCode, err)
      // }else {
      //   ctx.throw(500, err)
      // }
    }
  }
)

//傳送訊息
router.post('/:roomID/message',
  validate({
    'body:body':['require','body is required'],
    'time:body':['require', 'isDecimal', 'time is required'],
  }),
  async (ctx, next) => {
    try {
      const { authorization, deviceid} = ctx.request.header
      const { roomID } = ctx.params
      const { body, time } = ctx.request.body
      const  userID  = await TokenVerify(authorization)
      const user = await User.findOne({userID})
      if (user) {
        const room = await Room.findOne({'room.roomID' : roomID})
        if ( room && room.end == 0) {// room.end == 0 =>  room still open
          ctx.status = 200
          ctx.response.body = {
          }
        }else {
          const NotFound = '直播間不存在'
          ctx.status = 404
          ctx.message = "error"
          ctx.response.body = {
            error: NotFound
          }
        }
      }else {
        const Unauthorized = '未授權的用戶'
        ctx.status = 401
        ctx.message = "error"
        ctx.response.body = {
          error: Unauthorized
        }
      }
    } catch (err) {
      const Unauthorized = '未授權的用戶'
      ctx.status = 401
      ctx.message = "error"
      ctx.response.body = {
        error: Unauthorized
      }
      // if(err.output.statusCode){
      //   ctx.throw(err.output.statusCode, err)
      // }else {
      //   ctx.throw(500, err)
      // }
    }
  }
)

//送禮排行榜
router.post('/:roomID/leaderboard',
  async (ctx, next) => {
    try {
      const { authorization, deviceid} = ctx.request.header
      const { roomID } = ctx.params
      const { body, time } = ctx.request.body
      const  userID  = await TokenVerify(authorization)
      const user = await User.findOne({userID})
      if (user) {
        const room = await Room.findOne({'room.roomID' : roomID})
        if ( room && room.end == 0) {// room.end == 0 =>  room still open
          // const { leaders } = room
          // leaders.forEach( ( val ) => {
          //
          // })
          ctx.status = 200
          ctx.response.body = {
            "leaders": [
              {
                "userID": "aac_1224",
                "totalGift": 32097,
                "ranking": 1
              },
              {
                "userID": "w918_ma",
                "totalGift": 24578,
                "ranking": 2
              },
              {
                "userID": "john9808",
                "totalGift": 22001,
                "ranking": 3
              }
            ]
          }
        }else {
          const NotFound = '直播間不存在'
          ctx.status = 404
          ctx.message = "error"
          ctx.response.body = {
            error: NotFound
          }
        }
      }else {
        const Unauthorized = '未授權的用戶'
        ctx.status = 401
        ctx.message = "error"
        ctx.response.body = {
          error: Unauthorized
        }
      }
    } catch (err) {
      const Unauthorized = '未授權的用戶'
      ctx.status = 401
      ctx.message = "error"
      ctx.response.body = {
        error: Unauthorized
      }
      // if(err.output.statusCode){
      //   ctx.throw(err.output.statusCode, err)
      // }else {
      //   ctx.throw(500, err)
      // }
    }
  }
)

export default router


text:
button {
  background: -ms-linear-gradient(top, black, white);
  background: -moz-linear-gradient(top, black, white);
  background: -webkit-linear-gradient(top, black, white);
  background: linear-gradient(top, black, white);
}

redpajama_set_name: RedPajamaGithub


text:
using UnityEditor;

//[UnityEditor.CustomEditor(typeof(Waypoint))]
public class WaypointEditor : Editor {

    public override void OnInspectorGUI() {
        Waypoint waypoint = (Waypoint)target;

        for (int i = 0; i < waypoint.subpoints.Count; i++) {
            //EditorGUILayout.ObjectField();
        }
    }
}


text:
<?php

namespace gymadarasz\minitest;

/**
 *
 * @author Gyula Madarasz <gyula.madarasz at gmail.com>
 */
interface MiniTestInterface {

	public function run();

}


text:
<!DOCTYPE html>

<title>Patient Chart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="chart.css">

  {% for tileRow in tileRows %}

      {% for tile in tileRow %}
        {% set id = tile.item.conceptIds | first %}
        {% set values = tile.points | values %}
        {% set class = values | format_values(tile.item.cssClass) %}
        {% set style = values | format_values(tile.item.cssStyle) %}

{{tile.item.label}}

{{values | format_values(tile.item.format) | line_break_html | raw}}

{{values | format_values(tile.item.captionFormat) | line_break_html | raw}}

      {% endfor %}

  {% endfor %}

        {% set prevColumn = null %}
        {% for column in columns %}
          {% if prevColumn is not null and column.start != prevColumn.stop %}

          {% endif %}

            {{column.headingHtml | raw}}

          {% set prevColumn = column %}
        {% endfor %}

          Observations

        {% for column in columns %}
          {% if prevColumn is not null and column.start != prevColumn.stop %}

          {% endif %}

          {% set prevColumn = column %}
        {% endfor %}

      {% for row in rows %}
      {% set id = row.item.conceptIds | first %}

            {{row.item.label}}

          {% for column in columns %}
            {% set points = get_all_points(row=row, column=column) %}
            {% if points is empty %}
              {% set summaryValue = null %}
            {% elseif row.item.type == 'yes_no' %}
              {% set summaryValue = points | values | max %}
            {% else %}
              {% set summaryValue = (points | last).value %}
            {% endif %}
            {% set class = summaryValue | format_values(row.item.cssClass) %}
            {% set style = summaryValue | format_values(row.item.cssStyle) %}

            {% if points is not empty %}
              {% if row.item.type == 'text_icon' %}

📝

              {% else %}
                {% set output = summaryValue | format_value(row.item.format) %}
                {% if output is empty %}
                  {% set output = summaryValue | format_value(row.item.captionFormat) %}
                {% endif %}
              {{output}}
              {% endif %}
            {% endif %}

          {% endfor %}

      {% endfor %}

          Treatment Plan

        {% for column in columns %}
          {% if prevColumn is not null and column.start != prevColumn.stop %}

          {% endif %}

          {% set prevColumn = column %}
        {% endfor %}

      {% for order in orders %}

{{order.medication}}

{{order.dosage}}

          {% set previousActive = false %}
          {% set future = false %}
          {% for column in columns %}

              {% set active = intervals_overlap(order.interval, column.interval) %}
              {% if order.stop == null and previousActive %}

              {% elseif order.stop != null and previousActive and not active %}

Stop

              {% elseif active %}
                {% if future %}

●

                {% else %}
                  {% set count = get_order_execution_count(order_uuid=order.uuid, column=column) %}

{{count}}

                {% endif %}
              {% endif %}
              {% set previousActive = active %}
              {% set future = future or column.start == nowColumnStart %}

          {% endfor %}

      {% endfor %}

          Add a New Treatment


text:
require "test/unit"
require "coverage"
require "tmpdir"

class TestCoverage < Test::Unit::TestCase
  def test_result_without_start
    assert_raise(RuntimeError) {Coverage.result}
  end

  def test_peek_result_without_start
    assert_raise(RuntimeError) {Coverage.peek_result}
  end

  def test_result_with_nothing
    Coverage.start
    result = Coverage.result
    assert_kind_of(Hash, result)
    result.each do |key, val|
      assert_kind_of(String, key)
      assert_kind_of(Array, val)
    end
  end

  def test_coverage_snapshot
    loaded_features = $".dup

    Dir.mktmpdir {|tmp|
      Dir.chdir(tmp) {
        File.open("test.rb", "w") do |f|
          f.puts <<-EOS
            def coverage_test_method
              :ok
            end
          EOS
        end

        Coverage.start
        require tmp + '/test.rb'
        cov = Coverage.peek_result[tmp + '/test.rb']
        coverage_test_method
        cov2 = Coverage.peek_result[tmp + '/test.rb']
        assert_equal cov[1] + 1, cov2[1]
        assert_equal cov2, Coverage.result[tmp + '/test.rb']
      }
    }
  ensure
    $".replace loaded_features
  end

  def test_restarting_coverage
    loaded_features = $".dup

    Dir.mktmpdir {|tmp|
      Dir.chdir(tmp) {
        File.open("test.rb", "w") do |f|
          f.puts <<-EOS
            def coverage_test_method
              :ok
            end
          EOS
        end

        File.open("test2.rb", "w") do |f|
          f.puts <<-EOS
            def coverage_test_method2
              :ok
              :ok
            end
          EOS
        end

        Coverage.start
        require tmp + '/test.rb'
        assert_equal 3, Coverage.result[tmp + '/test.rb'].size

        # Restart coverage but '/test.rb' is required before restart,
        # so coverage is not recorded.
        Coverage.start
        coverage_test_method
        assert_equal 0, Coverage.result[tmp + '/test.rb'].size

        # Restart coverage and '/test2.rb' is required after restart,
        # so coverage is recorded.
        Coverage.start
        require tmp + '/test2.rb'
        assert_equal 4, Coverage.result[tmp + '/test2.rb'].size
      }
    }
  ensure
    $".replace loaded_features
  end

  def test_big_code
    loaded_features = $".dup

    Dir.mktmpdir {|tmp|
      Dir.chdir(tmp) {
        File.open("test.rb", "w") do |f|
          f.puts "__id__\n" * 10000
          f.puts "def ignore(x); end"
          f.puts "ignore([1"
          f.puts "])"
        end

        Coverage.start
        require tmp + '/test.rb'
        assert_equal 10003, Coverage.result[tmp + '/test.rb'].size
      }
    }
  ensure
    $".replace loaded_features
  end
end unless ENV['COVERAGE']


text:
<?php
// *********************************************************************************************************************************
//
// add.php
//
// This test adds a record with the newAddCommand.
//
// *********************************************************************************************************************************
//
// Copyright (c) 2017 Mark DeNyse
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// *********************************************************************************************************************************

require_once 'startup.inc.php';

$fm = new fmPDA(FM_DATABASE, FM_HOST, FM_USERNAME, FM_PASSWORD, 'PHP_Project');

$addCommand = $fm->newAddCommand('PHP_Project');
$addCommand->setField('Name', 'Project '. rand());
$addCommand->setField('Date_Start', date('m/d/Y'));
$addCommand->setField('Date_End', date('m/d/Y'));
$addCommand->setField('ColorIndex', 999);

$result = $addCommand->execute();

if (fmGetIsValid($result)) {
   fmLogger('Project Name = '. $result->getField('Name'));
   fmLogger($result->dumpRecord());
}
else {
   fmLogger('Error = '. $result->getCode() .' Message = '. $result->getMessage());
}

?>
<!DOCTYPE html>

      <meta charset="utf-8" />
      <title>fmPDA ♥</title>
      <link href="../css/normalize.css" rel="stylesheet" />
      <link href="../css/styles.css" rel="stylesheet" />

         fmPDA ♥

         Add Record - getRecordByID() & newAddCommand()

         Introduction
         Version History
         Examples
         Download

      <?php echo fmGetLog(); ?>


text:
using System;
using Skybrud.Social.Http;
using Skybrud.Social.Json;
using Skybrud.Social.Instagram.Objects;

namespace Skybrud.Social.Instagram.Responses {

    public class InstagramLocationsResponse : InstagramResponse<InstagramLocationsResponseBody> {

        #region Constructors

        private InstagramLocationsResponse(SocialHttpResponse response) : base(response) { }

        #endregion

        #region Static methods

        public static InstagramLocationsResponse ParseResponse(SocialHttpResponse response) {

            // Some input validation
            if (response == null) throw new ArgumentNullException("response");

            // Parse the raw JSON response
            JsonObject obj = response.GetBodyAsJsonObject();
            if (obj == null) return null;

            // Validate the response
            ValidateResponse(response, obj);

            // Initialize the response object
            return new InstagramLocationsResponse(response) {
                Body = InstagramLocationsResponseBody.Parse(obj)
            };

        }

        #endregion

    }

    public class InstagramLocationsResponseBody : InstagramResponseBody<InstagramLocation[]> {

        #region Constructors

        protected InstagramLocationsResponseBody(JsonObject obj) : base(obj) { }

        #endregion

        #region Static methods

        public static InstagramLocationsResponseBody Parse(JsonObject obj) {
            return new InstagramLocationsResponseBody(obj) {
                Data = obj.GetArray("data", InstagramLocation.Parse)
            };
        }

        #endregion

    }

}


text:
package scala.pickling
package generator

// TODO - move these into Pickler/Unpickler and replace the existing macros.
private[pickling] object PicklingMacros {
  import scala.language.experimental.macros
  def genPickler[T]: Pickler[T] with Generated = macro scala.pickling.generator.Compat.genPickler_impl[T]
  def genUnpickler[T]: Unpickler[T] with Generated = macro scala.pickling.generator.Compat.genUnpickler_impl[T]
  def genPicklerUnpickler[T]: AbstractPicklerUnpickler[T] with Generated = macro scala.pickling.generator.Compat.genPicklerUnpickler_impl[T]
}
private[pickling] trait PicklingMacros extends Macro with SourceGenerator with TypeAnalysis {
  import c.universe._
  val symbols = new IrScalaSymbols[c.universe.type, c.type](c.universe, tools)
  // TODO - We should have more customization than this
  val handleCaseClassSubclasses = !configOption(typeOf[IsIgnoreCaseClassSubclasses])
  val generator =
    if(isStaticOnly) {
      // TODO - should we consider externalizable "safe" or "static only" since we know it's externalizable at compile time?
      PicklingAlgorithm.aggregate(Seq(new CaseClassPickling(allowReflection = false, careAboutSubclasses = handleCaseClassSubclasses), AdtPickling, ScalaSingleton))
    } else {
      PicklingAlgorithm.aggregate(Seq(
        new CaseClassPickling(allowReflection = true, careAboutSubclasses = handleCaseClassSubclasses),
        AdtPickling,
        ScalaSingleton,
        new ExternalizablePickling,
        WillRobinsonPickling))
    }

  object logger extends AlgorithmLogger {
    def warn(msg: String): Unit = c.warning(c.enclosingPosition, msg)
    def debug(msg: String): Unit =
    // These are enabled when -verbose is enabled.
      c.info(c.enclosingPosition, msg, force=false)
    def abort(msg: String): Nothing = c.abort(c.enclosingPosition, msg)
    def error(msg: String): Unit = c.error(c.enclosingPosition, msg)
  }

  def checkClassType(tpe: c.Type, isUnpickle: Boolean = true): Unit = {
    import definitions._
    tpe.normalize match {
      case NothingTpe =>
        c.abort(c.enclosingPosition, "cannot generate pickling logic for type Nothing")
      case RefinedType(parents, decls) =>
        c.abort(c.enclosingPosition, "cannot generate pickling logic for refined type")
      case _ if tpe.isEffectivelyPrimitive || tpe.typeSymbol == StringClass =>
        c.abort(c.enclosingPosition, s"cannot generate pickling logic for primitive type: $tpe")
      case tpe1 if tpe1.typeSymbol.isClass =>
        ()  // This case is fine.
      case _ =>
        c.abort(c.enclosingPosition, s"cannot generate pickling logic for non-class type $tpe")
    }
  }

  def genPickler[T: c.WeakTypeTag]: c.Tree = preferringAlternativeImplicits {
    val tpe = computeType[T]
    checkClassType(tpe)
    val sym = symbols.newClass(tpe)
    val impl = PicklingAlgorithm.run(generator)(sym, logger)
    val tree2 = impl map {
      case PickleUnpickleImplementation(alg2, alg) => generatePicklerClass[T](alg2)
    }
    tree2 match {
      case None =>
        c.error(c.enclosingPosition, s"Failed to generate pickler for $tpe")
        ???
      case Some(tree) =>
        //System.err.println(s" --=== $tpe ===--\n$tree\n --=== / $tpe ===--")
        tree
    }
  }
  def genUnPickler[T: c.WeakTypeTag]: c.Tree = preferringAlternativeImplicits {
    val tpe = computeType[T]
    checkClassType(tpe)
    val sym = symbols.newClass(tpe)
    val impl = PicklingAlgorithm.run(generator)(sym, logger)
    val tree2 = impl map {
      case PickleUnpickleImplementation(alg2, alg) => generateUnpicklerClass[T](alg)
    }
    tree2 match {
      case None =>
        c.error(c.enclosingPosition, s"Failed to generate unpickler for $tpe")
        ???
      case Some(tree) =>
        //System.err.println(s" --=== $tpe ===--\n$tree\n --=== / $tpe ===--")
        tree
    }
  }
  def genPicklerUnpickler[T: c.WeakTypeTag]: c.Tree = preferringAlternativeImplicits {
    val tpe = computeType[T]
    checkClassType(tpe)
    val sym = symbols.newClass(tpe)
    val impl = PicklingAlgorithm.run(generator)(sym, logger)
    //System.err.println(impl)
    val tree2 = impl map generatePicklerUnpicklerClass[T]
    tree2 match {
      case None =>
        c.error(c.enclosingPosition, s"Failed to generate pickler/unpickler for $tpe")
        ???
      case Some(tree) =>
        //System.err.println(s" --=== $tpe ===--\n$tree\n --=== / $tpe ===--")
        tree
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>TestSuiteContainer (Gradle API 1.12)</title>
<meta name="date" content="2014-04-29">
<link href="../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../../groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

      Overview

      Package
    Class

      Deprecated
      Index
      Help

Groovy Documentation

  FRAMES
 NO FRAMES

  All Classes

SUMMARY: NESTED | FIELD | METHOD

DETAIL: FIELD | METHOD

org.gradle.nativebinaries.test

[Java] Interface TestSuiteContainer

org.gradle.api.NamedDomainObjectSet
  org.gradle.api.PolymorphicDomainObjectContainer
      org.gradle.api.NamedDomainObjectContainer
          org.gradle.api.ExtensiblePolymorphicDomainObjectContainer
              org.gradle.nativebinaries.test.TestSuiteContainer
                  org.gradle.api.NamedDomainObjectCollection
                      java.lang.Iterable
                          org.gradle.api.DomainObjectCollection
                              org.gradle.util.Configurable
                                  java.util.Collection

All Superinterfaces:

NamedDomainObjectSet, PolymorphicDomainObjectContainer, NamedDomainObjectContainer, ExtensiblePolymorphicDomainObjectContainer, NamedDomainObjectCollection, Iterable, DomainObjectCollection, Configurable, Collection

@Incubating
public interface TestSuiteContainer
extends ExtensiblePolymorphicDomainObjectContainer

 A polymorphic container of TestSuite instances.

                    Method Summary

                Methods inherited from interface ExtensiblePolymorphicDomainObjectContainer

registerBinding, registerFactory, registerFactory

                Methods inherited from interface PolymorphicDomainObjectContainer

create, create, maybeCreate

                Methods inherited from interface NamedDomainObjectContainer

configure, create, create, create, maybeCreate

                Methods inherited from interface NamedDomainObjectSet

findAll, matching, matching, withType

Gradle API 1.12


text:
var playbackUtil = require('./playbackUtil.js');
var PlaybackPoint = require('./PlaybackPoint.js');

function PlaybackTimer(playTime) {
	this._rebase(
		playbackUtil.now(),
		playTime,
		1
	);
}

Object.defineProperty(PlaybackTimer.prototype, 'real', {
	get: function() { return this.getRealTime(); }
});

Object.defineProperty(PlaybackTimer.prototype, 'playback', {
	get: function() { return this.getPlaybackTime(); },
	set: function(v) { this.setPlaybackTime(v); }
});

Object.defineProperty(PlaybackTimer.prototype, 'speed', {
	get: function() { return this._basePoint.speed; },
	set: function(v) { this.setSpeed(v); }
});

PlaybackTimer.prototype.getPoint = function() {
	return PlaybackPoint.currentFromPoint(this._basePoint);
};

PlaybackTimer.prototype.setSpeed = function(speed) {
	var time = playbackUtil.now();
	this._rebase(
		time,
		playbackUtil.realToPlayback(time, this._basePoint),
		speed
	);
	return PlaybackPoint.fromPoint(this._basePoint);
};

PlaybackTimer.prototype.getRealTime = function(playTime) {
	if (!playTime && playTime !== 0) {
		return playbackUtil.now();
	}
	return playbackUtil.playbackToReal(playTime, this._basePoint);
};

PlaybackTimer.prototype.getPlaybackTime = function(realTime) {
	if (!realTime && realTime !== 0) {
		realTime = this.getRealTime();
	}
	return playbackUtil.realToPlayback(realTime, this._basePoint);
};

PlaybackTimer.prototype.setPlaybackTime = function(playTime) {
	this._rebase(
		playbackUtil.now(),
		playTime,
		this._basePoint.speed
	);
	return PlaybackPoint.fromPoint(this._basePoint);
};

PlaybackTimer.prototype._rebase = function(realTime, playTime, speed) {
	this._basePoint = new PlaybackPoint(
		realTime,
		playTime,
		speed
	);
};

module.exports = PlaybackTimer;


text:
/**
Code made by Raizunne as a part of Raizunne's Miscellany
Source code found at github.com/Raizunne
 */
package com.raizunne.miscellany.tileentities;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.Constants;

public class TileEntityTrophyBase extends TileEntity implements IInventory{

	private ItemStack[] items;

	public TileEntityTrophyBase() {
		items = new ItemStack[1];
	}

	@Override
	public int getSizeInventory() {
		return 1;
	}

	@Override
	public ItemStack getStackInSlot(int i) {
		return items[i];
	}

	@Override
	public ItemStack decrStackSize(int p_70298_1_, int p_70298_2_) {
		return null;
	}

	@Override
	public ItemStack getStackInSlotOnClosing(int i) {
		ItemStack item = getStackInSlot(i);
		setInventorySlotContents(i, null);
		return item;

	}

	@Override
	public void setInventorySlotContents(int i, ItemStack itemstack) {
		items[i] = itemstack;
	}

	@Override
	public String getInventoryName() {
		return "Trophy Base";
	}

	@Override
	public boolean hasCustomInventoryName() {
		return false;
	}

	@Override
	public int getInventoryStackLimit() {
		return 64;
	}

	@Override
	public boolean isUseableByPlayer(EntityPlayer player) {
		return player.getDistanceSq(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5) <= 64;
	}

	@Override
	public void openInventory() {
	}

	@Override
	public void closeInventory() {
	}

	@Override
	public boolean isItemValidForSlot(int i, ItemStack itemstack) {
		return true;
	}

	public boolean canInsertItem(int i, ItemStack itemstack, int j){
		return false;
	}

	public boolean canExtractItem(int i, ItemStack itemstack, int j){
		return false;
	}

	@Override
	public void writeToNBT(NBTTagCompound compound) {
		super.writeToNBT(compound);

		NBTTagList items = new NBTTagList();

		for (int i = 0; i < getSizeInventory(); i++) {
			ItemStack stack = getStackInSlot(i);

			if (stack != null) {
				NBTTagCompound item = new NBTTagCompound();
				item.setByte("Slot", (byte)i);
				stack.writeToNBT(item);
				items.appendTag(item);
			}
		}
		compound.setTag("Items", items);
	}

	@Override
	public void readFromNBT(NBTTagCompound compound) {
		super.readFromNBT(compound);
		NBTTagList items = compound.getTagList("Items", 10);

		for (int i = 0; i < items.tagCount(); i++) {
			NBTTagCompound item = (NBTTagCompound)items.getCompoundTagAt(i);
			int slot = item.getByte("Slot");

			if (slot >= 0 && slot < getSizeInventory()) {
				setInventorySlotContents(slot, ItemStack.loadItemStackFromNBT(item));
			}
		}
	}

	@Override
	public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) {
		NBTTagCompound tag = pkt.func_148857_g();
		this.readFromNBT(tag);
	}

	@Override
	public Packet getDescriptionPacket() {
		NBTTagCompound tag = new NBTTagCompound();
		this.writeToNBT(tag);
		return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, this.blockMetadata, tag);
	}
}


text:
export * from './staticMethods/argsToParams.js'
export * from './staticMethods/dom.js'
export * from './staticMethods/fire.js'
export * from './staticMethods/mixin.js'
export * from './staticMethods/showLoading.js'
export * from './staticMethods/timer.js'
export * from './staticMethods/bindClickHandler.js'
export {
  isValidParameter,
  isUpdatableParameter,
  isDeprecatedParameter
} from './utils/params.js'


text:
module("luci.controller.bismark.experiments", package.seeall)

function index()
    entry({"admin", "bismark"}, alias("admin", "bismark", "experiments"), "BISmark", 25).index = true
    entry({"admin", "bismark", "experiments"}, cbi("bismark-experiments-manager/general", {autoapply=true}), "Experiments", 10).leaf = true
end


text:
(function() {
  var Speaker, StreamPlayer, audioOptions, base, base1, events, fs, lame, loadNextSong, request, self,
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;

  Speaker = require('speaker');

  lame = require('lame');

  request = require('request');

  events = require('events');

  fs = require('fs');

  if ((base = String.prototype).startsWith == null) {
    base.startsWith = function(s) {
      return this.slice(0, s.length) === s;
    };
  }

  if ((base1 = String.prototype).endsWith == null) {
    base1.endsWith = function(s) {
      return s === '' || this.slice(-s.length) === s;
    };
  }

  audioOptions = {
    channels: 2,
    bitDepth: 16,
    sampleRate: 44100,
    mode: lame.STEREO
  };

  self = null;

  StreamPlayer = (function(superClass) {
    extend(StreamPlayer, superClass);

    function StreamPlayer() {
      events.EventEmitter.call(this);
      self = this;
      this.queue = [];
      this.trackInfo = [];
      this.currentSong = null;
      this.playing = false;
      this.startTime = 0;
      this.speaker = null;
      this.decoder = null;
    }

    StreamPlayer.prototype.play = function() {
      if (this.currentSong !== null) {
        return this.resume();
      } else if (this.queue.length > 0 && !this.playing) {
        this.getStream(this.queue[0], this.playStream);
        this.playing = true;
        this.queue.shift();
        return this.currentSong = self.trackInfo.shift();
      } else if (this.playing) {
        return new Error('A song is already playing.');
      } else {
        return new Error('The queue is empty.');
      }
    };

    StreamPlayer.prototype.pause = function() {
      this.playing = false;
      this.speaker.removeAllListeners('close');
      return this.speaker.end();
    };

    StreamPlayer.prototype.resume = function() {
      this.speaker = new Speaker(audioOptions);
      this.decoder.pipe(this.speaker);
      this.playing = true;
      return this.speaker.once('close', function() {
        return loadNextSong();
      });
    };

    StreamPlayer.prototype.remove = function(id) {
      var index;
      index = this.trackInfo.map(function(info) {
        return info.id;
      }).indexOf(parseInt(id, 10));
      this.trackInfo.splice(index, 1);
      return this.queue.splice(index, 1);
    };

    StreamPlayer.prototype.add = function(url, track) {
      this.queue.push(url);
      this.trackInfo.push(track);
      return this.emit('song added', url, track);
    };

    StreamPlayer.prototype.nowPlaying = function() {
      if (this.playing) {
        return {
          track: this.currentSong,
          timestamp: this.startTime
        };
      } else {
        throw new Error('No song is currently playing.');
      }
    };

    StreamPlayer.prototype.isPlaying = function() {
      return this.playing;
    };

    StreamPlayer.prototype.getQueue = function() {
      return this.trackInfo;
    };

    StreamPlayer.prototype.getStream = function(url, callback) {
      var stream;
      if (url.startsWith('http')) {
        return request.get(url).on('response', function(res) {
          if (res.headers['content-type'] === 'audio/mpeg') {
            return callback(res);
          } else {
            self.emit('invalid url', url);
            return loadNextSong();
          }
        });
      } else {
        stream = fs.createReadStream(url);
        return callback(stream);
      }
    };

    StreamPlayer.prototype.playStream = function(stream) {
      self.decoder = new lame.Decoder();
      self.speaker = new Speaker(audioOptions);
      return stream.pipe(self.decoder).once('format', function() {
        self.decoder.pipe(self.speaker);
        self.startTime = Date.now();
        self.emit('play start', self.currentSong);
        return self.speaker.once('close', function() {
          return loadNextSong();
        });
      });
    };

    return StreamPlayer;

  })(events.EventEmitter);

  loadNextSong = function() {
    self.emit('play end', self.currentSong);
    self.currentSong = null;
    self.playing = false;
    return self.play();
  };

  module.exports = StreamPlayer;

}).call(this);


text:
var Pacet = function (canvasItem, imgItem) {

    var _this = this,
        isTracking = true;

    this.canvas = document.querySelector(canvasItem);
    this.ctx = this.canvas.getContext('2d');
    this.img = document.querySelector(imgItem);

    this.ctx.drawImage(this.img, 0, 0);

    function getMousePosition(evt) {
        var rect = _this.canvas.getBoundingClientRect();
        return {
            x: evt.clientX - rect.left,
            y: evt.clientY - rect.top
        };
    }

    function rgbToHex(R,G,B) { // http://www.javascripter.net/faq/rgbtohex.htm
        return toHex(R) + toHex(G) + toHex(B);
    }

    function toHex(n) { // http://www.javascripter.net/faq/rgbtohex.htm
        n = parseInt(n,10);
        if (isNaN(n)) {
            return '00';
        }
        n = Math.max(0,Math.min(n,255));
        return '0123456789abcdef'.charAt((n-n%16)/16) + '0123456789abcdef'.charAt(n%16);
    }

    function getColorData(mPos) {
        if (!isTracking) {
            return false;
        }
        var imgData = _this.ctx.getImageData(mPos.x, mPos.y, 1, 1).data,
            RGB = {'R': imgData[0], 'G': imgData[1], 'B': imgData[2]},
            colorOutput = document.querySelector('.colorOutput'),
            rgbOutput = document.querySelector('.rgbOutput'),
            hexOutput = document.querySelector('.hexOutput');

        colorOutput.style.backgroundColor = 'rgb(' + RGB.R + ',' + RGB.G + ',' + RGB.B + ')';
        rgbOutput.value = RGB.R + ',' + RGB.G + ',' + RGB.B;
        hexOutput.value = '#' + rgbToHex(RGB.R, RGB.G, RGB.B);
    }

    function toggleTracking(bool) {
        isTracking = bool;
    }

    this.canvas.addEventListener('mousemove', function (evt) {
        var mousePos = getMousePosition(evt);
        getColorData(mousePos);
    });

    this.canvas.addEventListener('click', function (evt) {
        return !isTracking ? toggleTracking(true) : toggleTracking(false);
    });
};

window.onload = function () {
    var pacet = new Pacet('.pacet_canvas', '.pacet_image');
};


text:
'use strict';

import React from 'react-native';
const {
  StyleSheet,
  ListView,
  RefreshControl,
  ScrollView,
  Text,
  TouchableOpacity,
  PropTypes,
  InteractionManager,
  ProgressBarAndroid,
  Image,
  DrawerLayoutAndroid,
  Dimensions,
  View
  } = React;
import LoadingView from '../components/LoadingView';
import {fetchReddit} from '../actions/reddit';
import CustomTabBar from '../components/CustomTabBar';
import CustomToolbar from '../components/CustomToolbar';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import WebViewContainer from '../containers/WebViewContainer';
import AboutContainer from '../containers/AboutContainer';
import {ToastShort} from '../utils/ToastUtils';
import * as Urls from '../constants/Urls';
import * as Alias from '../constants/Alias';

const propTypes = {
  dispatch: PropTypes.func.isRequired,
  reddit: PropTypes.object.isRequired
};

var canLoadMore;
var _typeIds = new Array();
var loadMoreTime = 0;

class Main extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      })
    };
    this.renderItem = this.renderItem.bind(this);
    this.renderFooter = this.renderFooter.bind(this);
    this.renderNavigationView = this.renderNavigationView.bind(this);
    this.onIconClicked = this.onIconClicked.bind(this);
    this.onScroll = this.onScroll.bind(this);
    canLoadMore = false;
  }

  componentDidMount () {
    const {dispatch} = this.props;
    InteractionManager.runAfterInteractions(() => {
      _typeIds = [1, 2, 3, 4];
      _typeIds.forEach((typeId) => {
        dispatch(fetchReddit(false, true, typeId));
      });
    });

  }

  componentWillReceiveProps (nextProps) {
    const {reddit} = this.props;
    if (reddit.isLoadMore && !nextProps.reddit.isLoadMore && !nextProps.reddit.isRefreshing) {
      if (nextProps.reddit.noMore) {
        ToastShort('没有更多数据了');
      }
    }
  }

  onRefresh (typeId) {
    const {dispatch} = this.props;
    canLoadMore = false;
    dispatch(fetchReddit(true, false, typeId));
  }

  onPress (reddit) {
    const {navigator} = this.props;
    console.error('click:', reddit);
    InteractionManager.runAfterInteractions(() => {
      navigator.push({
        component: WebViewContainer,
        name: 'WebViewPage',
        reddit: reddit
      });
    });
  }

  onPressDrawerItem (index) {
    const {navigator} = this.props;
    this.refs.drawer.closeDrawer();
    switch (index) {
      case 2:
        InteractionManager.runAfterInteractions(() => {
          navigator.push({
            component: AboutContainer,
            name: 'About'
          });
        });
        break;
      default:
        break;
    }
  }

  onIconClicked () {
    this.refs.drawer.openDrawer();
  }

  onScroll () {
    if (!canLoadMore) {
      canLoadMore = true;
    }
  }

  onEndReached (typeId) {
    let time = Date.parse(new Date()) / 1000;
    const {reddit} = this.props;
    if (canLoadMore && time - loadMoreTime > 1) {
      const {dispatch} = this.props;
      dispatch(fetchReddit(false, false, typeId, true, 25, reddit.redditAfter[typeId]));
      canLoadMore = false;
      loadMoreTime = Date.parse(new Date()) / 1000;
    }
  }

  renderFooter () {
    const {reddit} = this.props;
    if (reddit.isLoadMore) {
      return (
        <View style={{flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
          <ProgressBarAndroid styleAttr='Inverse' color='#3e9ce9'/>
          <Text style={{textAlign: 'center', fontSize: 16}}>
            加载中…
          </Text>
        </View>
      );
    }
  }

  renderItem (reddit, sectionID, rowID) {
    const thumbnail = reddit.data.thumbnail.lastIndexOf("http") >= 0 ? reddit.data.thumbnail : 'https://www.redditstatic.com/reddit404b.png';
    console.log('render', reddit.data.thumbnail.lastIndexOf("http"));
    return (
      <TouchableOpacity onPress={this.onPress.bind(this, reddit)}>
        <View style={styles.containerItem}>
          <Image
            style={{width: 88, height: 88, marginRight: 10,borderRadius:44}}
            source={{uri: thumbnail}}
          />
          <View style={{flex: 1, flexDirection: 'column'}}>
            <Text style={styles.title}>
              {reddit.data.title}
            </Text>
            <View style={{flex:1,flexDirection:'row'}}>
              <View style={{flex: 1, flexDirection: 'row'}}>
                <Text style={{fontSize: 14, color: '#aaaaaa', marginTop: 5}}>
                  来自:
                </Text>
                <Text style={{flex: 1, fontSize: 14, color: '#ff0000', marginTop: 5, marginRight: 5}}>
                  {reddit.data.author}
                </Text>
              </View>

              <View style={{flex: 1, flexDirection: 'row'}}>
                <Text style={{fontSize: 14, color: '#aaaaaa', marginTop: 5}}>
                  赞:
                </Text>
                <Text style={{flex: 1, fontSize: 14, color: '#ff0000', marginTop: 5, marginRight: 5}}>
                  {reddit.data.ups}
                </Text>
              </View>
            </View>

          </View>
        </View>
      </TouchableOpacity>
    );
  }

  renderContent (dataSource, typeId) {
    const {reddit} = this.props;
    if (reddit.loading) {
      return <LoadingView/>;
    }
    let isEmpty = reddit.redditList[typeId] == undefined || reddit.redditList[typeId].length == 0;
    if (isEmpty) {
      return (
        <ScrollView
          automaticallyAdjustContentInsets={false}
          horizontal={false}
          contentContainerStyle={styles.no_data}
          style={{flex: 1}}
          refreshControl={
            <RefreshControl
              refreshing={reddit.isRefreshing}
              onRefresh={this.onRefresh.bind(this, typeId)}
              title="Loading..."
              colors={['#ffaa66cc', '#ff00ddff', '#ffffbb33', '#ffff4444']}
            />
          }
        >
          <View style={{alignItems: 'center'}}>
            <Text style={{fontSize: 16}}>
              正在与网络撕扯...
            </Text>
          </View>
        </ScrollView>
      );
    }
    return (
      <ListView
        initialListSize={1}
        dataSource={dataSource}
        renderRow={this.renderItem}
        style={styles.listView}
        onEndReached={this.onEndReached.bind(this, typeId)}
        onEndReachedThreshold={10}
        onScroll={this.onScroll}
        renderFooter={this.renderFooter}
        refreshControl={
          <RefreshControl
            refreshing={reddit.isRefreshing}
            onRefresh={this.onRefresh.bind(this, typeId)}
            title="Loading..."
            colors={['#ff0000', '#ff0000', '#ff0000', '#ff0000']}
          />
        }
      />
    );
  }

  renderNavigationView () {
    return (
      <View style={[styles.container, {backgroundColor: '#fcfcfc'}]}>
        <Image
          style={{width: Dimensions.get('window').width / 5 * 3, height: 120, justifyContent: 'flex-end', paddingBottom: 10}}
          source={require('../img/reddit_bg.png')}
        >
          <Text style={{fontSize: 20, textAlign: 'left', color: '#fcfcfc', marginLeft: 10}}>
            xReddit
          </Text>
        </Image>
        <TouchableOpacity
          style={styles.drawerContent}
          onPress={this.onPressDrawerItem.bind(this, 0)}
        >
          <Image
            style={styles.drawerIcon}
            source={require('../img/reddit_red.png')}
          />
          <Text style={styles.drawerText}>
            首页
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.drawerContent}
          onPress={this.onPressDrawerItem.bind(this,2)}
        >
          <Image
            style={styles.drawerIcon}
            source={require('../img/about.png')}
          />
          <Text style={styles.drawerText}>
            关于
          </Text>
        </TouchableOpacity>
      </View>
    );
  }

  render () {
    const {reddit, navigator} = this.props;
    var lists = [];
    _typeIds.forEach((typeId) => {
      lists.push(
        <View
          key={typeId}
          tabLabel={Alias.CATEGORIES[typeId]}
          style={{flex: 1}}
        >
          {this.renderContent(this.state.dataSource.cloneWithRows(reddit.redditList[typeId] == undefined ? [] : reddit.redditList[typeId]), typeId)}
        </View>);
    });
    return (
      <DrawerLayoutAndroid
        ref='drawer'
        drawerWidth={Dimensions.get('window').width / 5 * 3}
        drawerPosition={DrawerLayoutAndroid.positions.Left}
        renderNavigationView={this.renderNavigationView}
      >
        <View style={styles.container}>
          <CustomToolbar
            title="xReddit"
            navigator={navigator}
            navIcon={require('../img/menu.png')}
            onIconClicked={this.onIconClicked}
          />
          <ScrollableTabView
            renderTabBar={() => <CustomTabBar />}
            tabBarBackgroundColor="#fcfcfc"
            tabBarUnderlineColor="#FF0000"
            tabBarActiveTextColor="#FF0000"
            tabBarInactiveTextColor="#aaaaaa"
          >
            {lists}
          </ScrollableTabView>
        </View>
      </DrawerLayoutAndroid>
    );
  }
}

let styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column'
  },
  containerItem: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fcfcfc',
    padding: 10,
    borderBottomColor: '#ddd',
    borderBottomWidth: 1
  },
  title: {
    flex: 3,
    fontSize: 18,
    textAlign: 'left',
    color: 'black'
  },
  listView: {
    backgroundColor: '#eeeeec'
  },
  no_data: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingBottom: 100
  },
  drawerContent: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#ddd'
  },
  drawerIcon: {
    width: 30,
    height: 30,
    marginLeft: 5
  },
  drawerText: {
    fontSize: 18,
    marginLeft: 15,
    textAlign: 'center',
    color: 'black'
  }
});

Main.propTypes = propTypes;

export default Main;


text:
import logging
import zope
import oz.Fedora
import oz.TDL
import subprocess
import libxml2
import traceback
import ConfigParser
import os
from time import *
from imgfac.ApplicationConfiguration import ApplicationConfiguration
from imgfac.ImageFactoryException import ImageFactoryException
from imgfac.CloudDelegate import CloudDelegate
from imgfac.FactoryUtils import launch_inspect_and_mount, shutdown_and_close, remove_net_persist, create_cloud_info
from novaclient.v1_1 import client
from novaclient.exceptions import NotFound
import oz.Fedora
import pyrax
import pyrax.exceptions
import pyvhd

def subprocess_check_output(*popenargs, **kwargs):
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')

    process = subprocess.Popen(stdout=subprocess.PIPE, stderr=subprocess.STDOUT, *popenargs, **kwargs)
    stdout, stderr = process.communicate()
    retcode = process.poll()
    if retcode:
        cmd = ' '.join(*popenargs)
        raise ImageFactoryException("'%s' failed(%d): %s" % (cmd, retcode, stderr))
    return stdout, stderr, retcode

class Rackspace(object):
    zope.interface.implements(CloudDelegate)

    def activity(self, activity):
        # Simple helper function
        # Activity should be a one line human-readable string indicating the task in progress
        # We log it at DEBUG and also set it as the status_detail on our active image
        self.log.debug(activity)
        if self.active_image:
            self.active_image.status_detail['activity'] = activity

    def __init__(self):
        # Note that we are now missing ( template, target, config_block = None):
        super(Rackspace, self).__init__()
        self.log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__))
        config_obj = ApplicationConfiguration()
        self.app_config = config_obj.configuration
        self.oz_config = ConfigParser.SafeConfigParser()
        self.oz_config.read("/etc/oz/oz.cfg")
        self.oz_config.set('paths', 'output_dir', self.app_config["imgdir"])
        self.active_image = None

        if "rackspace" in config_obj.jeos_images:
            self.rackspace_jeos_amis = config_obj.jeos_images['rackspace']
        else:
            self.log.warning("No JEOS images defined for Rackspace.  Snapshot builds will not be possible.")
            self.rackspace_jeos_amis = {}

    def log_exc(self):
        self.log.debug("Exception caught in ImageFactory")
        self.log.debug(traceback.format_exc())
        self.active_image.status_detail['error'] = traceback.format_exc()

    def wait_for_rackspace_ssh_access(self, guestaddr):
        self.activity("Waiting for SSH access to Rackspace instance")
        for index in range(300):
            if index % 10 == 0:
                self.log.debug("Waiting for Rackspace ssh access: %d/300" % index)

            try:
                self.guest.guest_execute_command(guestaddr, "/bin/true", timeout=10)
                break
            except Exception, e:
                self.log.exception('Caught exception waiting for ssh access: %s' % e)
                #import pdb
                #pdb.set_trace()
                #pass

            sleep(1)

            if index == 299:
                raise ImageFactoryException("Unable to gain ssh access after 300 seconds - aborting")

    def wait_for_rackspace_instance_start(self, instance):
        self.activity("Waiting for Rackspace instance to become active")
        for i in range(600):
            if i % 10 == 0:
                try:
                    instance.get()
                    self.log.debug("Waiting %d more seconds for Rackspace instance to start, %d%% complete..." %
                                   ((600-i), instance.progress))
                except NotFound:
                    # We occasionally get errors when querying an instance that has just started.
                    # Ignore & hope for the best
                    self.log.warning(
                        "NotFound exception encountered when querying Rackspace instance (%s) - trying to continue" % (
                            instance.id), exc_info=True)
                except:
                    self.log.error("Exception encountered when updating status of instance (%s)" % instance.id,
                                   exc_info=True)
                    self.status = "FAILED"
                    try:
                        self.terminate_instance(instance)
                    except:
                        self.log.warning(
                            "WARNING: Instance (%s) failed to start and will not terminate - it may still be running" % (
                                instance.id), exc_info=True)
                        raise ImageFactoryException(
                            "Instance (%s) failed to fully start or terminate - it may still be running" % instance.id)
                    raise ImageFactoryException(
                        "Exception encountered when waiting for instance (%s) to start" % instance.id)
                if instance.status == u'ACTIVE':
                    break
            sleep(1)
        if instance.status != u'ACTIVE':
            self.status = "FAILED"
            try:
                self.terminate_instance(instance)
            except:
                self.log.warning(
                    "WARNING: Instance (%s) failed to start and will not terminate - it may still be running" % (
                        instance.id), exc_info=True)
                raise ImageFactoryException(
                    "Instance (%s) failed to fully start or terminate - it may still be running" % instance.id)
            raise ImageFactoryException("Instance failed to start after 300 seconds - stopping")

    def terminate_instance(self, instance):
        self.activity("Deleting Rackspace instance.")
        try:
            instance.delete()
        except Exception, e:
            self.log.info("Failed to delete Rackspace instance. %s" % e)

    def snapshot_image_on_provider(self, builder, provider, credentials, target, template, parameters):
        self.log.info('snapshot_image_on_provider() called in Rackspace')

        self.builder = builder
        self.active_image = self.builder.provider_image

        # TODO: This is a convenience variable for refactoring - rename
        self.new_image_id = builder.provider_image.identifier
        # TODO: so is this
        self.target = target

        # Template must be defined for snapshots
        self.tdlobj = oz.TDL.TDL(xmlstring=str(template), rootpw_required=True)

        # Create a name combining the TDL name and the UUID for use when tagging Rackspace Images
        self.longname = self.tdlobj.name + "-" + self.new_image_id

        self.log.debug("Being asked to push for provider %s" % provider)
        self.log.debug(
            "distro: %s - update: %s - arch: %s" % (self.tdlobj.distro, self.tdlobj.update, self.tdlobj.arch))
        self.rackspace_decode_credentials(credentials)
        self.log.debug("acting as Rackspace user: %s" % (str(self.rackspace_username)))

        self.status = "PUSHING"
        self.percent_complete = 0

        region = provider

        auth_url = 'https://identity.api.rackspacecloud.com/v2.0/'

        rackspace_client = client.Client(self.rackspace_username, self.rackspace_password,
                                         self.rackspace_account_number, auth_url, service_type="compute",
                                         region_name=region)
        rackspace_client.authenticate()

        mypub = open("/etc/oz/id_rsa-icicle-gen.pub")
        server_files = {"/root/.ssh/authorized_keys": mypub}

        # Now launch it
        self.activity("Launching Rackspace JEOS image")
        rackspace_image_id = self.rackspace_jeos_amis[region][self.tdlobj.distro][self.tdlobj.update][self.tdlobj.arch]['img_id']
        instance_type = '512MB Standard Instance'
        image = rackspace_client.images.find(id=rackspace_image_id)
        small = rackspace_client.flavors.find(name=instance_type)
        self.log.debug("Starting build server %s with instance_type %s" % (rackspace_image_id, instance_type))
        reservation_name = 'imagefactory-snapshot-%s' % self.active_image.identifier
        reservation = rackspace_client.servers.create(reservation_name, image, small, files=server_files)

        if not reservation:
            self.status = "FAILED"
            raise ImageFactoryException("run_instances did not result in the expected single instance - stopping")

        self.instance = reservation

        self.wait_for_rackspace_instance_start(self.instance)

        # From this point on we must be sure to terminate the instance when we are done
        # so wrap in a try/finally
        # Accidentally running a 64 bit instance doing nothing costs 56 USD week
        try:
            while self.instance.accessIPv4 == '':
                self.log.debug("Waiting to get public IP address")
            sleep(1)
            self.instance.get()
            guestaddr = self.instance.accessIPv4
            self.guest = oz.Fedora.FedoraGuest(self.tdlobj, self.oz_config, None, "virtio", True, "virtio", True)

            # Ugly ATM because failed access always triggers an exception
            self.wait_for_rackspace_ssh_access(guestaddr)

            # There are a handful of additional boot tasks after SSH starts running
            # Give them an additional 20 seconds for good measure
            self.log.debug("Waiting 60 seconds for remaining boot tasks")
            sleep(60)

            self.activity("Customizing running Rackspace JEOS instance")
            self.log.debug("Stopping cron and killing any updatedb process that may be running")
            # updatedb interacts poorly with the bundle step - make sure it isn't running
            self.guest.guest_execute_command(guestaddr, "/sbin/service crond stop")
            self.guest.guest_execute_command(guestaddr, "killall -9 updatedb || /bin/true")
            self.log.debug("Done")

            # Not all JEOS images contain this - redoing it if already present is harmless
            self.log.info("Creating cloud-info file indicating target (%s)" % self.target)
            self.guest.guest_execute_command(guestaddr,
                                             'echo CLOUD_TYPE=\\\"%s\\\" > /etc/sysconfig/cloud-info' % self.target)

            self.log.debug("Customizing guest: %s" % guestaddr)
            self.guest.mkdir_p(self.guest.icicle_tmp)
            self.guest.do_customize(guestaddr)
            self.log.debug("Customization step complete")

            self.log.debug("Generating ICICLE from customized guest")
            self.output_descriptor = self.guest.do_icicle(guestaddr)
            self.log.debug("ICICLE generation complete")

            self.log.debug("Re-de-activate firstboot just in case it has been revived during customize")
            self.guest.guest_execute_command(guestaddr,
                                             "[ -f /etc/init.d/firstboot ] && /sbin/chkconfig firstboot off || /bin/true")
            self.log.debug("De-activation complete")

            image_name = str(self.longname)
            #image_desc = "%s - %s" % (asctime(localtime()), self.tdlobj.description)

            self.log.debug("Creating a snapshot of our running Rackspace instance")
            #TODO: give proper name??
            new_image_id = self.instance.create_image(image_name)
            new_image = rackspace_client.images.find(id=new_image_id)
            while True:
                new_image.get()
                self.log.info("Saving image: %d percent complete" % new_image.progress)
                if new_image.progress == 100:
                    break
                else:
                    sleep(20)

            self.builder.provider_image.icicle = self.output_descriptor
            self.builder.provider_image.identifier_on_provider = new_image_id
            self.builder.provider_image.provider_account_identifier = self.rackspace_account_number
        except Exception, e:
            self.log.warning("Exception while executing commands on guest: %s" % e)
        finally:
            self.terminate_instance(self.instance)

    def delete_from_provider(self, builder, provider, credentials, target, parameters):
        self.builder = builder
        self.active_image = self.builder.provider_image
        rackspace_image_id = self.active_image.identifier_on_provider
        try:
            self.log.debug("Deleting Rackspace image (%s)" % self.active_image.identifier_on_provider)
            self.rackspace_decode_credentials(credentials)
            self.log.debug("acting as Rackspace user: %s" % (str(self.rackspace_username)))

            auth_url = 'https://identity.api.rackspacecloud.com/v2.0/'
            rackspace_client = client.Client(self.rackspace_username, self.rackspace_password,
                                             self.rackspace_account_number, auth_url, service_type="compute",
                                             region_name=provider)
            rackspace_client.authenticate()
            image = rackspace_client.images.find(id=rackspace_image_id)
            if image:
                rackspace_client.images.delete(rackspace_image_id)
                self.log.debug('Successfully deleted Rackspace image (%s)' % rackspace_image_id)
        except Exception, e:
            raise ImageFactoryException('Failed to delete Rackspace image (%s) with error (%s)' % (rackspace_image_id,
                                                                                str(e)))

    def push_image_to_provider(self, builder, provider, credentials, target, target_image, parameters):
        # Our target_image is a Rackspace compatible VHD - we need to upload to cloudfiles
        # then register with
        self.builder = builder
        self.active_image = self.builder.provider_image
        self.rackspace_decode_credentials(credentials)

        rackspace_region = provider.upper()
        if rackspace_region not in [ "DFW", "ORD", "SYD" ]:
            raise ImageFactoryException("Unknown Rackspace provider/region specified")

        # This is a module-global setting but I believe setting it here is thread-safe
        # repeating this in multiple invocations should be harmless
        pyrax.set_setting("identity_type", "rackspace")

        if (not self.rackspace_username) or (not self.rackspace_api_key):
            self.status = "FAILED"
            raise ImageFactoryException("You must supply a username and api key to upload images to Rackspace")

        try:
            ctx = pyrax.create_context("rackspace", username=self.rackspace_username,
                                                    api_key=self.rackspace_api_key)
            ctx.authenticate()
        except pyrax.exceptions.AuthenticationFailed:
            self.status = "FAILED"
            raise ImageFactoryException("Authentication into Rackspace API failed")

        cf = ctx.get_client("swift", rackspace_region)
        imgs = ctx.get_client("image", rackspace_region)
        upload_container="factory-images"

        if not upload_container in cf.list_containers():
            self.log.debug("Our default container name (%s) does not exist - creating it" % (upload_container))
            cont = cf.create_container(upload_container)
        else:
            cont = cf.get(upload_container)

        self.log.debug("Uploading target image to Rackspace cloudfiles - this may take some time")
        obj_name = "factory-image-" + str(self.builder.provider_image.identifier)
        cf.upload_file(cont, self.builder.target_image.data, obj_name=obj_name)

        self.log.debug("Rereading container content to verify our new image is there")
        objs = cont.get_objects()

        imgobj = None
        for obj in objs:
            if obj.name == obj_name:
                imgobj = obj
                break
        if not imgobj:
            raise ImageFactoryException("Could not find our new image (%s) in container (%s)" % (obj_name, upload_container))

        self.log.debug("Creating import task")
        task = imgs.import_task(obj, cont, img_format="VHD", img_name=obj_name)

        for i in range(1,360):
            # This gets us the current status - yes, we are just recreating the task object
            task = task.manager.get(task.id)
            if task.status in [ "success", "failure" ]:
                break
            self.log.debug("Waiting for success or failure - %d/3600 - current status (%s)" % (i*10, task.status))
            sleep(10)

        if task.status == "failure":
            raise ImageFactoryException("Rackspace image import failed with reason: %", (task.message))

	if task.status == "success":
	    new_img = imgs.find(name=obj_name)
            self.builder.provider_image.identifier_on_provider = new_img.id
            self.log.debug("Import finished - ID: %s - name: %s - status: %s - size: %s - tags: %s" % (new_img.id, new_img.name, new_img.status, new_img.size, new_img.tags))
        else:
            raise ImageFactoryException("Got to end of push with unexpected status (%s)" % task.status)

    def builder_should_create_target_image(self, builder, target, image_id, template, parameters):
        self.log.info('builder_should_create_target_image() called on Rackspace plugin - returning True')
        return True

    def builder_will_create_target_image(self, builder, target, image_id, template, parameters):
        # Nothing really to do here
        pass

    def builder_did_create_target_image(self, builder, target, image_id, template, parameters):
        self.log.info('builder_did_create_target_image() called in Rackspace plugin')
        self.status="BUILDING"

        # TODO: This is a convenience variable for refactoring - rename
        self.new_image_id = builder.target_image.identifier

        # TODO: More convenience vars - revisit
        self.template = template
        self.target = target
        self.builder = builder
        self.image = builder.target_image.data

        # This lets our logging helper know what image is being operated on
        self.active_image = self.builder.target_image

        # Add the cloud-info file
        self.modify_oz_filesystem()

        self.log.info("Transforming image for use on Rackspace")
        self.rackspace_transform_image()

        self.percent_complete=100
        self.status="COMPLETED"

    def rackspace_transform_image(self):
        # On entry the image points to our generic KVM raw image
        # Convert to a Citrix complatible VHD and then update the image property
        target_image = self.image + ".tmp.vhd"
        self.log.debug("Converting raw kvm image (%s) to Rackspace compatible VHD image (%s)" % (self.image, target_image))
        inimage = open(self.image,"r")
        outimage = open(target_image,"w")
        pyvhd.do_vhd_convert(inimage, outimage)
        inimage.close()
        outimage.close()
        self.log.debug("VHD conversion complete")
        os.unlink(self.image)
        os.rename(target_image, self.image)

    def modify_oz_filesystem(self):
        self.log.debug("Doing further Factory specific modification of Oz image")
        guestfs_handle = launch_inspect_and_mount(self.builder.target_image.data)
        remove_net_persist(guestfs_handle)
        create_cloud_info(guestfs_handle, self.target)
        shutdown_and_close(guestfs_handle)

    def abort(self):
        # TODO: Make this progressively more robust
        # In the near term, the most important thing we can do is terminate any Rackspace instance we may be using
        if self.instance:
            try:
                self.log.debug('Attempting to abort instance: %s' % self.instance)
                self.terminate_instance(self.instance)
            except Exception, e:
                self.log.exception(e)
                self.log.warning("** WARNING ** Instance MAY NOT be terminated ******** ")

    def _rackspace_get_xml_node(self, doc, credtype):
        nodes = doc.xpathEval("//provider_credentials/rackspace_credentials/%s" % credtype)
        if len(nodes) < 1:
            raise ImageFactoryException("No Rackspace %s available" % credtype)

        return nodes[0].content

    def rackspace_decode_credentials(self, credentials):
        self.activity("Preparing Rackspace credentials")
        doc = libxml2.parseDoc(credentials.strip())

        self.rackspace_account_number = self._rackspace_get_xml_node(doc, "account_number")
        self.rackspace_username = self._rackspace_get_xml_node(doc, "username")

        got_pw_or_key = False

        try:
            self.rackspace_password = self._rackspace_get_xml_node(doc, "password")
            got_pw_or_key = True
        except ImageFactoryException:
            self.rackspace_password = None

        try:
            self.rackspace_api_key =  self._rackspace_get_xml_node(doc, "api_key")
            got_pw_or_key = True
        except ImageFactoryException:
            self.rackspace_api_key = None

        if not got_pw_or_key:
            raise ImageFactoryException("You must provide either an api_key or password for Rackspace")

        doc.freeDoc()


text:
ACCEPTED

#### According to
GRIN Taxonomy for Plants

#### Published in
Symb. sin. 7:672. 1933

#### Original name
null

### Remarks
null


text:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const passport = require('passport');

const jwt = require('jsonwebtoken');

const config = require('./config/main');
const cors = require('cors');
const port = 3000;

app.use(cors());

const requireAuth = passport.authenticate('jwt', { session: false });

// Initialize passport for use
app.use(passport.initialize());

// Bring in defined Passport Strategy
require('./config/passport')(passport);

var users = require('./app/routes/users');
var campaigns = require('./app/routes/campaigns');
var brands = require('./app/routes/brands');
var misc = require('./app/routes/misc');

// Use body-parser to get POST requests for API use
app.use(bodyParser.urlencoded({ extended: true, limit: "50mb" }));
app.use(bodyParser.json());
//app.use(multipartyMiddleWare);

// Log requests to console
app.use(morgan('dev'));

// Home route. We'll end up changing this to our main front end index later.
app.get('/', function(req, res) {
  res.json('Relax. We will put the home page here later.');
});

// Connect to database
mongoose.connect(config.database);

app.use('/users', users);
//app.use('/campaigns',requireAuth, campaigns);
app.use('/campaigns', campaigns);

app.use('/brands', brands);
app.use('/misc', misc);

module.exports = app;


text:
<?php
define('PR_MAIL_SUBJECT_1', "SynAPP password restore request for user ");
define('PR_MAIL_SUBJECT_2', ". Do not reply.");
define('PR_MAIL_MIMEALT', "If you are reading this, please update your email-reading-software.");
define('PR_MAIL_TITLE', "SynAPP password reset.");
define('PR_MAIL_TO', "This email was automatically generated and sent from SYNAPP to the address");
define('PR_MAIL_USR_1', "as a result of the reception of a password reset request form for user");
define('PR_MAIL_USR_2', "'s account.");
define('PR_MAIL_NR', "PLEASE DO NOT REPLY TO THIS MESSAGE.");
define('PR_MAIL_IGNORE', "If you have no relation with this account or you don't wish to restore your password please ignore this email.");
define('PR_MAIL_DO', "In order to reset and establish a new password for your account, please follow one of this links by clicking on it or copying it to your browser's url navigation bar:");
define('PR_MAIL_DO_HTTP', "(HTTP connection, non-encrypted, non-authentified, no browser warnings)");
define('PR_MAIL_DO_HTTPS', "(HTTPS connection, encrypted, non-authentified, ignore browser/antivirus warning to proceed)");
define('PR_TITLE_1', "SynAPP Account Recovery Form.");
define('PR_TITLE_3', "SynAPP Account Password Successfuly Changed.");
define('PR_HEADER', "SynAPP Account Recovery Form");
define('PR_HEADER_1', "Please write below your SynAPP username or associated email address.<br />You will receive an email at this address with further instructions on how to recover you account.");
define('PR_INPUT', "User or email:");
define('PR_CAPT', "Captcha:");
define('PR_REFRESH', "Click here to load a different captcha.");
define('PR_SEND', "Send");
define('PR_HOME', "main page");
define('PR_REG', "register");
define('PR_HELP', "help/about");
define('PR_SENT_TITLE_1', "Reset email sent to address");
define('PR_SENT_TITLE_1_B', "Reset email sent to");
define('PR_SENT_1_1', "A restore email has been sent to address ");
define('PR_SENT_1_1_B', "A restore email has been sent to ");
define('PR_SENT_1_2_B', " in case the profile and address were found, and you should see it in your inbox/spam folder in a matter of minutes.");
define('PR_SENT_1_2', "with your username information.");
define('PR_SENT_2', "A restore email has been sent to email address asociated with user");
define('PR_SENT_DO', "Please follow the instructions on it in order to reset your password.");
define('PR_SENT_TITLE_2', "Reset email sent to user");
define('PR_UNSENT_TITLE_1', "Cannot find any user associated to email address");
define('PR_UNSENT_TITLE_2', "Cannot find user");
define('PR_UNSENT_TITLE_3', "Cannot find a valid email address asociated to user");
define('PR_UNSENT_NOMAIL', "Cannot find email address");
define('PR_UNSENT_NOUSR', "Cannot find user");
define('PR_UNSENT_NOMAILTOUSR', "Cannot find a valid email address asociated to user");
define('PR_UNSENT_INSYNAPPDB', "in SYNAPP database.");
define('PR_UNSENT_DO_1', "Please try");
define('PR_UNSENT_DO_2', "again");
define('PR_UNSENT_DO_3', "or");
define('PR_UNSENT_DO_4', "register");
define('PR_UNSENT_DO_5', "to create a new account or");
define('PR_UNSENT_DO_6', "contact");
define('PR_UNSENT_DO_7', "administrator for further information.");
define('PR_GOTO_HOME', "go to SynAPP main page");
define('PR_TITLE_2', "SynAPP password restore form for user");
define('PR_HEADER_2', "New password for user");
define('PR_PASS', "Type new password:");
define('PR_REPASS', "Repeat new password:");
define('PR_ERR_CAPT', "Error, wrong captcha. Please try again.");
define('PR_ERR_EMPTY', "Error: Please write an username/email address.");
define('PR_ERR_EMPTY_2', "Error: Please fill in all requested fields.");
define('PR_ERR_PUMATCH', "Error: User = password. Please choose a diferent password.");
define('PR_ERR_PMATCH', "Error: Password fields do not match.");
define('PR_ERR_NOPASS', "Error: You must select a password.");
define('PR_ERR_PMIN', "Error: Password length < 10 char.");
define('PR_ERR_PMAX', "Error: Password length > 64 char.");
define('PR_ERR_PFORMAT', "Error: Only alphanumeric chains separated by \".\" or \"_\" are allowed in password field.");
define('PR_TITLE_3_1', "Password changed for user");
define('PR_DONE_1', "Password for user");
define('PR_DONE_2', "has been succesfully changed.");


text:
import functools
import json
import logging

import gevent
import six

from kazoo.protocol.states import EventType, KazooState
from kazoo.handlers.gevent import SequentialGeventHandler
from kazoo.exceptions import NoNodeError, KazooException

from .base import BaseServiceRegistry, SERVICE_NAMESPACE
from lymph.exceptions import LookupFailure, RegistrationFailure
from lymph.utils.logging import setup_logger

logger = logging.getLogger(__name__)

DEFAULT_CHROOT = '/lymph'

class ZookeeperServiceRegistry(BaseServiceRegistry):
    def __init__(self, zkclient, pool=None):
        super(ZookeeperServiceRegistry, self).__init__(pool=pool)
        self.client = zkclient
        if not self.client.chroot:
            self.client.chroot = DEFAULT_CHROOT
        self.client.add_listener(self.on_kazoo_state_change)
        self.start_count = 0
        self.registered_names = {}

    @classmethod
    def from_config(cls, config, **kwargs):
        zkclient = config.get_instance('zkclient', handler=SequentialGeventHandler())
        return cls(zkclient=zkclient, **kwargs)

    def on_start(self, timeout=10):
        setup_logger('kazoo')
        self.start_count += 1
        if self.start_count > 1:
            return
        started = self.client.start_async()
        started.wait(timeout=timeout)
        if not self.client.connected:
            raise RuntimeError('could not connect to zookeeper')
        logger.debug('connected to zookeeper (version=%s)', '.'.join(map(str, self.client.server_version())))

    def on_stop(self, **kwargs):
        self.start_count -= 1
        if self.start_count != 0:
            return
        self.client.stop()

    def on_kazoo_state_change(self, state):
        logger.info('kazoo connection state changed to %s', state)
        if state == KazooState.CONNECTED:
            for (namespace, name), instance in self.registered_names.items():
                self.spawn(self.register, name, instance, namespace=namespace)
            for service in six.itervalues(self.cache):
                self.spawn(self.lookup, service, timeout=None)
        elif state == KazooState.LOST:
            logger.warning('zookeeper connection lost')
        elif state == KazooState.SUSPENDED:
            logger.info('zookeeper connection suspended')

    def on_service_name_watch(self, service, event):
        try:
            self.lookup(service)
        except LookupFailure:
            pass
        except Exception:
            logger.exception('error in service type watcher')

    def on_service_watch(self, service, event):
        try:
            prefix, service_name, instance_id = event.path.rsplit('/', 2)
            if event.type == EventType.DELETED:
                service.remove(instance_id)
        except Exception:
            logger.exception('error in service watcher')

    def _get_service_znode(self, service, service_name, instance_id):
        path = self._get_zk_path(SERVICE_NAMESPACE, service_name, instance_id)
        result = self.client.get_async(
            path, watch=functools.partial(self.on_service_watch, service))
        value, znode = result.get()
        items = six.iteritems(json.loads(value.decode('utf-8')))
        return {str(k): v for k, v in items}

    def discover(self):
        result = self.client.get_children_async(path='/%s' % SERVICE_NAMESPACE)
        try:
            return list(result.get())
        except NoNodeError:
            return []

    def lookup(self, service, timeout=1):
        if self.client.state != KazooState.CONNECTED:
            return service
        service_name = service.name
        result = self.client.get_children_async(
            path='/%s/%s' % (SERVICE_NAMESPACE, service_name, ),
            watch=functools.partial(self.on_service_name_watch, service),
        )
        try:
            instance_ids = result.get(timeout=timeout)
        except NoNodeError:
            raise LookupFailure("failed to resolve %s", service.name)
        except KazooException as e:
            logger.warning("zookeeper lookup failure: %s", e)
            return service
        logger.info("lookup %s %r", service_name, instance_ids)
        old_instance_ids = {instance.id for instance in service}
        for instance_id in instance_ids:
            kwargs = self._get_service_znode(service, service_name, instance_id)
            service.update(instance_id, **kwargs)
            try:
                old_instance_ids.remove(instance_id)
            except KeyError:
                pass
        for instance_id in old_instance_ids:
            service.remove(instance_id)
        return service

    def _get_zk_path(self, namespace, service_name, instance_id):
        return '/%s/%s/%s' % (namespace, service_name, instance_id)

    def register(self, service_name, instance, timeout=1, namespace=SERVICE_NAMESPACE):
        path = self._get_zk_path(namespace, service_name, instance.id)
        value = json.dumps(instance.serialize())

        # XXX(Mouad): In case path already exist delete it before registering,
        # this is protecting mechanism for when dev machine go to sleep or service
        # restart too fast (before zookeeper detect service is gone).
        try:
            self.client.delete(path)
        except NoNodeError:
            pass

        result = self.client.create_async(
            path,
            value.encode('utf-8'),
            ephemeral=True, makepath=True)
        # FIXME: result.set_exception(RegistrationFailure())
        try:
            result.get(timeout=timeout)
        except gevent.Timeout:
            logger.exception('registration of %s:%s failed', namespace, service_name)
            raise
        self.registered_names[(namespace, service_name)] = instance

    def unregister(self, service_name, instance, timeout=1, namespace=SERVICE_NAMESPACE):
        path = self._get_zk_path(namespace, service_name, instance.id)
        result = self.client.delete_async(path)
        result.set_exception(RegistrationFailure())
        result.get(timeout=timeout)
        del self.registered_names[(namespace, service_name)]


text:
package com.craftingmobile.util;

import com.craftingmobile.tutorials.simplecamera.BuildConfig;

@SuppressWarnings("unused")
public class Log {
    public static final int LEVEL = android.util.Log.VERBOSE;

    public static void d(String tag, String message) {
        if (LEVEL <= android.util.Log.DEBUG && BuildConfig.DEBUG) {
            android.util.Log.d(tag, message);
        }
    }

    public static void d(String tag, Throwable t, String message) {
        if (LEVEL <= android.util.Log.DEBUG && BuildConfig.DEBUG) {
            android.util.Log.d(tag, message, t);
        }
    }

    public static void e(String tag, String message) {
        if (LEVEL <= android.util.Log.ERROR && BuildConfig.DEBUG) {
            android.util.Log.e(tag, message);
        }
    }

    public static void e(String tag, String message, Throwable e) {
        if (LEVEL <= android.util.Log.ERROR && BuildConfig.DEBUG) {
            android.util.Log.e(tag, message, e);
        }
    }

    public static void i(String tag, String message) {
        if (LEVEL <= android.util.Log.INFO && BuildConfig.DEBUG) {
            android.util.Log.i(tag, message);
        }
    }

    public static void v(String tag, String message) {
        if (LEVEL <= android.util.Log.VERBOSE && BuildConfig.DEBUG) {
            android.util.Log.v(tag, message);
        }
    }

    public static void v(String tag, Throwable t, String message) {
        if (LEVEL <= android.util.Log.VERBOSE && BuildConfig.DEBUG) {
            android.util.Log.v(tag, message, t);
        }
    }

}


text:
This repository contains the source for
[ScottBerrevoets.com](http://scottberrevoets.com). It uses
[Pelican](http://getpelican.com) to generate all content, including file and
directory structures. I'm using a custom Pelican theme. You may use this theme
for your own Pelican installation, but I can't help you out with customizations.

## Installation

```bash
$ pip3 install
```

## Writing

Because I always forget.

- Edit content, then run `$ pelican content` from the root
- To preview: `$ pelican --listen` (with `-r` for continuous regeneration)

## Contributing

Found a mistake, typo, or formatting error? Contributions are welcome!

## License

- Code is published under the [MIT license](https://github.com/sberrevoets/scottberrevoets.com/blob/master/LICENSE)
- Content is published under [CC BY-NC 3.0](https://creativecommons.org/licenses/by-nc/3.0/)


text:
<!DOCTYPE html>

  <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{{app_name}} - {{page_title}}</title>

  <link href="/third_party/bootstrap/css/bootstrap-3.1.0.min.css" rel="stylesheet">
  <link href="/auth/static/css/common.css" rel="stylesheet">

  {% if css_file %}
    <link href="{{css_file}}" rel="stylesheet">
  {% endif %}

  {% if js_file %}

  {% endif %}

{% raw %}

{% endraw %}

        <button type="button" class="navbar-toggle"
                data-toggle="collapse" data-target=".navbar-collapse">
          Toggle navigation

        </button>

          {{app_name}}

          {% for tab_id, title, url in navbar %}

              {{title}}

          {% endfor %}

          {% if not identity.is_anonymous %}
            {{identity.name}}
             |
            Logout
          {% else %}
            Login
          {% endif %}

      {% block content %}
      {% endblock %}

Error

        Version:
          {% if app_revision_url %}
            {{app_version}}
          {% else %}
            {{app_version}}
          {% endif %}


text:
const CGFloat ConservativeSpaceReservation = 1.f;

@implementation NSString(GSParsingHelper)

- (NSMutableArray*) linesWithWidth:(CGFloat)width font:(UIFont*)font firstLineWidth:(CGFloat)firstLineWidth limitLineCount:(int)limitLineCount {

    #ifdef GS_DEBUG_CODE
    GSDebugLog(@"LineBreak - The string: %@, 1st line: %f, other lines: %f", self, firstLineWidth, width);
    #endif

    NSMutableString* firstLineBlocked = [NSMutableString string];
    if (firstLineWidth < width) {
        CGFloat spaceWidth = [@" " sizeWithFont:font].width;
        int spacesToStart = (int)ceilf((width - firstLineWidth) / spaceWidth);
        for (int i=0; i<spacesToStart; i++) {
            [firstLineBlocked appendString:@" "];
        }
        // there will always be 1 or 2 space mismatch..
        while ([firstLineBlocked sizeWithFont:font].width <= width - firstLineWidth + ConservativeSpaceReservation) {
            // about the "<=" (instead of "<") and +2: to be more conservative on space occupation

            [firstLineBlocked appendString:@" "];
        }
    }

    NSMutableArray* lines = [[NSMutableArray alloc] init];
    NSMutableString* currentLine = [[NSMutableString alloc] init];

    CGFloat charWidth = [@"M" sizeWithFont:font].width;

    // estimate the number of characters for each line
    int step = 0;

    for (int i=0; i<self.length; ){  // we control index move in the loop

        // if we are already 1 step reached line count limit, just return the whole thing for the next line
        if (limitLineCount>0 && lines.count == limitLineCount-1) {
            [lines addObject:[self substringFromIndex:i]];
            GSRelease(currentLine);
            return GSAutoreleased(lines);
        }

        // if the rest of the string begins with \n
        BOOL beginsWithBR = [[self substringWithRange:NSMakeRange(i, 1)] isEqualToString:@"\n"];

        // deal with \n first
        if (beginsWithBR){
            #ifdef GS_DEBUG_CODE
            GSDebugLog(@"found \\n at [%d]", i);
            #endif

            if (currentLine.length>0) {
                #ifdef GS_DEBUG_CODE
                GSDebugLog(@"adding line: %@. i=[%d]",currentLine, i);
                #endif
                [lines addObject: [NSString stringWithString:currentLine]];
                [currentLine setString:@""];

                // before adding the next line, we need to check limitLineCount
                if (limitLineCount>0 && lines.count == limitLineCount-1) {
                    [lines addObject:[self substringFromIndex:i]];
                    GSRelease(currentLine);
                    return GSAutoreleased(lines);
                }
            }

            [lines addObject:@""];
            i = i + 1;
            continue;
        }

        // read a range of characters.. try to go reach the end of the line
        CGFloat lineWidth = lines.count? width : firstLineWidth;
        step = (int) (lineWidth / charWidth);
        if (i+step > self.length) {
            step = self.length - i;
        }

        NSString* characters = [self substringWithRange:NSMakeRange(i, step)];

        // if we have a \n in the characters read...
        int brPosition = [characters rangeOfString:@"\n"].location;
        if (brPosition != NSNotFound) {
            characters = [characters substringToIndex:brPosition];
            i = i + brPosition; // set the index to the "\n" position, continue and let the next cycle handle the "\n".
        }
        else {
            i = i + step;
        }
        // the next character to be inserted is at i now

        if (!currentLine.length && lines.count && [[lines lastObject] length]) {
            // if it's not the first line, and this is the first character, and the previous line isn't ended by \n
            // we just skip the leading chars
            [currentLine appendFormat:@"%@", [characters stringByTrimmingLeadingWhitespace]];
        }
        else {
            [currentLine appendFormat:@"%@", characters];
        }

        NSString* lineToCalcWidth = (lines.count || !firstLineBlocked.length) ? currentLine : [NSString stringWithFormat:@"%@%@", firstLineBlocked, currentLine];
        CGSize appleSize = [ lineToCalcWidth
                            sizeWithFont:font
                            constrainedToSize:CGSizeMake(width,1000.f)
                            lineBreakMode:UILineBreakModeWordWrap];

        #ifdef GS_DEBUG_CODE
        GSDebugLog(@"[%d] current line: %@. width to confine: %f, apple width: %f", i, currentLine, width, appleSize.width);
        #endif

        // if we unestimated the number of characters need, add until we exceed the line
        while (appleSize.height <= font.lineHeight) {

            // if the last character is finished. conclude here.
            if (i>=self.length) {
                [lines addObject: [NSString stringWithString:currentLine]];
                GSRelease(currentLine);
                return GSAutoreleased(lines);
            }
            characters = [self substringWithRange:NSMakeRange(i, 1)];

            // if we meet a \n
            if ([characters isEqualToString:@"\n"]) {
                [lines addObject: [NSString stringWithString:currentLine]];
                [currentLine setString:@""]; // let the next cycle handle "\n"
                break;
            }
            [currentLine appendString: characters];
            i++;
            lineToCalcWidth = (lines.count || !firstLineBlocked.length) ? currentLine : [NSString stringWithFormat:@"%@%@", firstLineBlocked, currentLine];
            appleSize = [ lineToCalcWidth
                         sizeWithFont:font
                         constrainedToSize:CGSizeMake(width,1000.f)
                         lineBreakMode:UILineBreakModeWordWrap];
            // #ifdef GS_DEBUG_CODE
            // GSDebugLog(@"advanced to [%d]: %@ (height=%f, targeting:>%f)", i-1, lineToCalcWidth, appleSize.height, font.lineHeight);
            // #endif // this code should be fine, but just in case
        }

        if (appleSize.height > font.lineHeight) {

            CGFloat idealWidth = appleSize.width;

            int minLength = 1; // a line is at least one char
            // special case
            if (!lines.count && firstLineWidth < width) {
                // if it's the first line, and first line width < rest width, we allow zero character just for this line
                minLength = 0;
            }

            NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
            BOOL scanBackForWhitespace = [currentLine rangeOfCharacterFromSet:whitespace].location != NSNotFound;

            // take out characters one by one until the width is idealWidth
            while (currentLine.length > minLength
                   && (
                       [lineToCalcWidth sizeWithFont:font].width > idealWidth
                       || (scanBackForWhitespace && ![whitespace characterIsMember: [currentLine characterAtIndex:(currentLine.length-1)]])
                  )
            ) {
                [currentLine deleteCharactersInRange:NSMakeRange(currentLine.length-1, 1)];
                lineToCalcWidth = (lines.count || !firstLineBlocked.length) ? currentLine : [NSString stringWithFormat:@"%@%@", firstLineBlocked, currentLine];
                i--;
                // #ifdef GS_DEBUG_CODE
                // GSDebugLog(@"retreat to [%d]: %@ (width=%f, targeting:%f)", i-1, lineToCalcWidth, [lineToCalcWidth sizeWithFont:font].width, idealWidth);
                // #endif // this code should be fine, but just in case
            }

            #ifdef GS_DEBUG_CODE
            GSDebugLog(@"adding line: %@. i=[%d]",currentLine, i);
            #endif

            [lines addObject: [NSString stringWithString:currentLine]];
            [currentLine setString:@""];
        }

    }

    GSRelease(currentLine);
    return GSAutoreleased(lines);
}

- (NSMutableArray*) linesWithWidth:(CGFloat)width font:(UIFont*)font {
    return [self linesWithWidth:width font:font firstLineWidth:width limitLineCount:0];
}

-(NSString*)stringByTrimmingLeadingWhitespace {
    if (! GSTrim(self).length) {
        return @"";
    }

    int i = 0;
    while ([[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:[self characterAtIndex:i]]) {
        i++;
    }
    return [self substringFromIndex:i];
}

- (NSString*)stringByTrimmingTrailingWhitespace {
    if (! GSTrim(self).length) {
        return @"";
    }

    int i = self.length - 1;
    while ([[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:[self characterAtIndex:i]]) {
        i--;
    }
    return [self substringToIndex:i+1];
}

- (NSString*)firstNonWhitespaceCharacterSince:(int)location foundAt:(int*)foundLocation {
    if (! GSTrim(self).length) {
        return @"";
    }
    BOOL found = NO;
    int i;
    NSString* character;
    for (i=location; i<self.length; i++) {
        character = [self substringWithRange:NSMakeRange(i, 1)];
        if (GSTrim(character).length) {
            found = YES;
            break;
        }
    }

    if (found) {
        if (foundLocation) {
            *foundLocation = i;
        }
        return character;
    }
    else {
        if (foundLocation) {
            *foundLocation = self.length;
        }
        return @"";
    }
}

- (float)possiblyPercentageNumberWithBase: (float)base {
    NSString* trimmed = GSTrim(self);
    if (!trimmed.length) {
        return 0.f;
    }
    float number = [self floatValue];
    if ([[trimmed substringFromIndex:(trimmed.length-1)] isEqualToString:@"%"]) {
        return number * base /100.f;
    }
    else {
        return number;
    }
}

@end