text:
@implementation UIImage (Addition)
+ (UIImage *)wg_resizedImageWithName:(NSString *)name {
    UIImage *normal = [UIImage imageNamed:name];
    return [normal wg_resizedImage];
//    UIImage *image = [normal stretchableImageWithLeftCapWidth:imageW topCapHeight:imageH];
}
- (UIImage *)wg_resizedImage {
    CGFloat imageW = self.size.width * 0.5;
    CGFloat imageH = self.size.height * 0.5;
    return [self wg_resizedImageWithCapInsets:UIEdgeInsetsMake(imageH, imageW, imageH, imageW)];
}
- (UIImage *)wg_resizedImageWithCapInsets:(UIEdgeInsets)capInsets {
    return [self resizableImageWithCapInsets:capInsets];
}
- (UIImage *)wg_resizedImageWithNewSize:(CGSize)newSize {

    UIGraphicsBeginImageContextWithOptions(newSize, NO, [UIScreen mainScreen].scale);
    [self drawInRect:(CGRect){0,0,newSize}];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
@end

@implementation UIImage (Color)

+ (UIImage *)wg_imageWithColor:(UIColor *)color {
    CGSize imageSize = CGSizeMake(1.0, 1.0);
    return [self wg_imageWithColor:color size:imageSize];
}
+ (UIImage *)wg_imageWithColor:(UIColor *)color size:(CGSize)size {

    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
- (UIImage *)wg_circleImage {
    CGSize size = self.size;
    float corner = MIN(size.width, size.height);
    return [self wg_imageWithCornerRadius:corner];
}
- (UIImage *)wg_imageWithCornerRadius:(CGFloat)cornerRadius {
    return [self wg_imageWithCornerRadius:cornerRadius borderWidth:0 borderColor:nil];
}
- (UIImage *)wg_imageWithCornerRadius:(CGFloat)cornerRadius borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor {

    CGRect rect = (CGRect){0, 0, self.size};
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);

    CGContextRef context = UIGraphicsGetCurrentContext();

    if (cornerRadius > 0) {
        rect = CGRectMake(borderWidth/2, borderWidth/2, self.size.width-borderWidth, self.size.height-borderWidth);
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
        CGContextAddPath(context, path.CGPath);
        if (borderWidth > 0) {
            CGContextSetLineWidth(context, borderWidth);
            CGContextSetStrokeColorWithColor(context, borderColor.CGColor);
            CGContextDrawPath(context, kCGPathFillStroke);
        } else {

        }
        [path addClip];
    } else {
        if (borderWidth > 0) {
            rect = CGRectMake(borderWidth/2, borderWidth/2, self.size.width-borderWidth, self.size.height-borderWidth);
            CGContextSetLineWidth(context, borderWidth);
            CGContextSetStrokeColorWithColor(context, borderColor.CGColor);
            CGContextStrokeRect(context, rect);
        } else {

        }
    }

    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end


text:
<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model backend\models\TrainingSubjectTrainerRecommendation */

$this->title = 'Update : #'.$model->id;
$this->params['breadcrumbs'][] = ['label'=>'Training','url'=>['training3/index']];
$this->params['breadcrumbs'][] = ['label'=>\yii\helpers\Inflector::camel2words('Subject : '.$model->training->name),'url'=>['training-subject3/index','tb_training_id'=>(int)$model->tb_training_id]];
$this->params['breadcrumbs'][] = ['label' => $model->programSubject->name, 'url' => ['index','tb_training_id'=>(int)$model->tb_training_id,'tb_program_subject_id'=>(int)$model->tb_program_subject_id]];
$this->params['breadcrumbs'][] = $this->title;
$controller = $this->context;
$menus = $controller->module->getMenuItems();
$this->params['sideMenu'][$controller->module->uniqueId]=$menus;

echo \kartik\widgets\AlertBlock::widget([
    'useSessionFlash' => true,
    'type' => \kartik\widgets\AlertBlock::TYPE_ALERT
]);
?>
<div class="training-subject-trainer-recommendation-update">

    <?= $this->render('_form', [
        'model' => $model,
		'tb_training_id'=>(int)$model->tb_training_id,
		'tb_program_subject_id'=>(int)$model->tb_program_subject_id
    ]) ?>

</div>

redpajama_set_name: RedPajamaGithub


text:
namespace GameController
{
    partial class FormGameController
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.groupBoxRender = new System.Windows.Forms.GroupBox();
            this.comboBoxRenderers = new System.Windows.Forms.ComboBox();
            this.groupBoxMap = new System.Windows.Forms.GroupBox();
            this.buttonSaveMap = new System.Windows.Forms.Button();
            this.buttonLoadMap = new System.Windows.Forms.Button();
            this.groupBoxRender.SuspendLayout();
            this.groupBoxMap.SuspendLayout();
            this.SuspendLayout();
            //
            // groupBoxRender
            //
            this.groupBoxRender.Controls.Add(this.comboBoxRenderers);
            this.groupBoxRender.Location = new System.Drawing.Point(12, 12);
            this.groupBoxRender.Name = "groupBoxRender";
            this.groupBoxRender.Size = new System.Drawing.Size(172, 82);
            this.groupBoxRender.TabIndex = 0;
            this.groupBoxRender.TabStop = false;
            this.groupBoxRender.Text = "Render";
            //
            // comboBoxRenderers
            //
            this.comboBoxRenderers.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.comboBoxRenderers.FormattingEnabled = true;
            this.comboBoxRenderers.Location = new System.Drawing.Point(7, 20);
            this.comboBoxRenderers.Name = "comboBoxRenderers";
            this.comboBoxRenderers.Size = new System.Drawing.Size(159, 21);
            this.comboBoxRenderers.TabIndex = 0;
            //
            // groupBoxMap
            //
            this.groupBoxMap.Controls.Add(this.buttonLoadMap);
            this.groupBoxMap.Controls.Add(this.buttonSaveMap);
            this.groupBoxMap.Location = new System.Drawing.Point(12, 101);
            this.groupBoxMap.Name = "groupBoxMap";
            this.groupBoxMap.Size = new System.Drawing.Size(172, 100);
            this.groupBoxMap.TabIndex = 1;
            this.groupBoxMap.TabStop = false;
            this.groupBoxMap.Text = "Map";
            //
            // buttonSaveMap
            //
            this.buttonSaveMap.Location = new System.Drawing.Point(7, 20);
            this.buttonSaveMap.Name = "buttonSaveMap";
            this.buttonSaveMap.Size = new System.Drawing.Size(91, 23);
            this.buttonSaveMap.TabIndex = 0;
            this.buttonSaveMap.Text = "Save Map";
            this.buttonSaveMap.UseVisualStyleBackColor = true;
            this.buttonSaveMap.Click += new System.EventHandler(this.buttonSaveMap_Click);
            //
            // buttonLoadMap
            //
            this.buttonLoadMap.Location = new System.Drawing.Point(7, 50);
            this.buttonLoadMap.Name = "buttonLoadMap";
            this.buttonLoadMap.Size = new System.Drawing.Size(91, 23);
            this.buttonLoadMap.TabIndex = 1;
            this.buttonLoadMap.Text = "Load Map";
            this.buttonLoadMap.UseVisualStyleBackColor = true;
            this.buttonLoadMap.Click += new System.EventHandler(this.buttonLoadMap_Click);
            //
            // FormGameController
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.groupBoxMap);
            this.Controls.Add(this.groupBoxRender);
            this.Name = "FormGameController";
            this.Text = "Form1";
            this.groupBoxRender.ResumeLayout(false);
            this.groupBoxMap.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.GroupBox groupBoxRender;
        private System.Windows.Forms.ComboBox comboBoxRenderers;
        private System.Windows.Forms.GroupBox groupBoxMap;
        private System.Windows.Forms.Button buttonSaveMap;
        private System.Windows.Forms.Button buttonLoadMap;
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace ImplementNotifyPropertyChangedCS
{
    internal static class ExpansionChecker
    {
        internal static IEnumerable<ExpandablePropertyInfo> GetExpandableProperties(TextSpan span, SyntaxNode root, SemanticModel model)
        {
            var propertiesInTypes = root.DescendantNodes(span)
                       .OfType<PropertyDeclarationSyntax>()
                       .Select(p => GetExpandablePropertyInfo(p, model))
                       .Where(p => p != null)
                       .GroupBy(p => p.PropertyDeclaration.FirstAncestorOrSelf<TypeDeclarationSyntax>());

            return propertiesInTypes.Any()
                ? propertiesInTypes.First()
                : Enumerable.Empty<ExpandablePropertyInfo>();
        }

        /// <summary>
        /// Returns true if the specified <see cref="PropertyDeclarationSyntax"/> can be expanded to include
        /// support for <see cref="INotifyPropertyChanged"/>.
        /// </summary>
        internal static ExpandablePropertyInfo GetExpandablePropertyInfo(PropertyDeclarationSyntax property, SemanticModel model)
        {
            // Don't expand properties with parse errors.
            if (property.ContainsDiagnostics)
            {
                return null;
            }

            if (property.Modifiers.Any(SyntaxKind.StaticKeyword) || property.Modifiers.Any(SyntaxKind.AbstractKeyword))
            {
                return null;
            }

            AccessorDeclarationSyntax getter, setter;
            if (!TryGetAccessors(property, out getter, out setter))
            {
                return null;
            }

            if (getter.Body == null && setter.Body == null)
            {
                return new ExpandablePropertyInfo
                {
                    PropertyDeclaration = property,
                    BackingFieldName = GenerateFieldName(property, model),
                    NeedsBackingField = true,
                    Type = model.GetDeclaredSymbol(property).Type
                };
            }

            IFieldSymbol backingField;
            return (TryGetBackingFieldFromExpandableGetter(getter, model, out backingField)
                && IsExpandableSetter(setter, model, backingField))
                ? new ExpandablePropertyInfo { PropertyDeclaration = property, BackingFieldName = backingField.Name }
                : null;
        }

        /// <summary>
        /// Retrieves the get and set accessor declarations of the specified property.
        /// Returns true if both get and set accessors exist; otherwise false.
        /// </summary>
        internal static bool TryGetAccessors(
            PropertyDeclarationSyntax property,
            out AccessorDeclarationSyntax getter,
            out AccessorDeclarationSyntax setter)
        {
            var accessors = property.AccessorList.Accessors;
            getter = accessors.FirstOrDefault(ad => ad.Kind() == SyntaxKind.GetAccessorDeclaration);
            setter = accessors.FirstOrDefault(ad => ad.Kind() == SyntaxKind.SetAccessorDeclaration);

            return accessors.Count == 2 && getter != null && setter != null;
        }

        private static string GenerateFieldName(PropertyDeclarationSyntax property, SemanticModel semanticModel)
        {
            var baseName = property.Identifier.ValueText;
            baseName = char.ToLower(baseName[0]).ToString() + baseName.Substring(1);

            var propertySymbol = semanticModel.GetDeclaredSymbol(property);
            if (propertySymbol == null ||
                propertySymbol.ContainingType == null)
            {
                return baseName;
            }

            var index = 0;
            var name = baseName;
            while (propertySymbol.ContainingType.MemberNames.Contains(name))
            {
                name = baseName + (++index).ToString();
            }

            return name;
        }

        private static IFieldSymbol GetBackingFieldFromGetter(
            AccessorDeclarationSyntax getter,
            SemanticModel semanticModel)
        {
            // The getter should have a body containing a single return of a backing field.

            if (getter.Body == null)
            {
                return null;
            }

            var statements = getter.Body.Statements;
            if (statements.Count != 1)
            {
                return null;
            }

            var returnStatement = statements.Single() as ReturnStatementSyntax;
            if (returnStatement == null || returnStatement.Expression == null)
            {
                return null;
            }

            return semanticModel.GetSymbolInfo(returnStatement.Expression).Symbol as IFieldSymbol;
        }

        private static bool TryGetBackingFieldFromExpandableGetter(
            AccessorDeclarationSyntax getter,
            SemanticModel semanticModel,
            out IFieldSymbol backingField)
        {
            backingField = GetBackingFieldFromGetter(getter, semanticModel);
            return backingField != null;
        }

        private static bool IsBackingField(ExpressionSyntax expression, IFieldSymbol backingField, SemanticModel semanticModel)
        {
            return semanticModel
                .GetSymbolInfo(expression).Symbol
                .Equals(backingField);
        }

        private static bool IsPropertyValueParameter(ExpressionSyntax expression, SemanticModel semanticModel)
        {
            var parameterSymbol = semanticModel.GetSymbolInfo(expression).Symbol as IParameterSymbol;

            return parameterSymbol != null
                && parameterSymbol.IsImplicitlyDeclared
                && parameterSymbol.Name == "value";
        }

        private static bool IsAssignmentOfPropertyValueParameterToBackingField(
            ExpressionSyntax expression,
            IFieldSymbol backingField,
            SemanticModel semanticModel)
        {
            if (expression.Kind() != SyntaxKind.SimpleAssignmentExpression)
            {
                return false;
            }

            var assignment = (AssignmentExpressionSyntax)expression;

            return IsBackingField(assignment.Left, backingField, semanticModel)
                && IsPropertyValueParameter(assignment.Right, semanticModel);
        }

        private static bool ComparesPropertyValueParameterAndBackingField(
            BinaryExpressionSyntax expression,
            IFieldSymbol backingField,
            SemanticModel semanticModel)
        {
            return (IsPropertyValueParameter(expression.Right, semanticModel) && IsBackingField(expression.Left, backingField, semanticModel))
                || (IsPropertyValueParameter(expression.Left, semanticModel) && IsBackingField(expression.Right, backingField, semanticModel));
        }

        private static bool IsExpandableSetter(AccessorDeclarationSyntax setter, SemanticModel semanticModel, IFieldSymbol backingField)
        {
            // The setter should have a body containing one of the following heuristic patterns or
            // no body at all.
            //
            // Patterns:
            //    field = value;
            //    if (field != value) field = value;
            //    if (field == value) return; field = value;

            if (setter.Body == null)
            {
                return false;
            }

            return IsExpandableSetterPattern1(setter, backingField, semanticModel)
                || IsExpandableSetterPattern2(setter, backingField, semanticModel)
                || IsExpandableSetterPattern3(setter, backingField, semanticModel);
        }

        private static bool IsExpandableSetterPattern1(
            AccessorDeclarationSyntax setter,
            IFieldSymbol backingField,
            SemanticModel semanticModel)
        {
            // Pattern: field = value
            Debug.Assert(setter.Body != null);

            var statements = setter.Body.Statements;
            if (statements.Count != 1)
            {
                return false;
            }

            var expressionStatement = statements[0] as ExpressionStatementSyntax;
            return expressionStatement != null
                && IsAssignmentOfPropertyValueParameterToBackingField(expressionStatement.Expression, backingField, semanticModel);
        }

        private static bool IsExpandableSetterPattern2(
            AccessorDeclarationSyntax setter,
            IFieldSymbol backingField,
            SemanticModel semanticModel)
        {
            // Pattern: if (field != value) field = value;
            Debug.Assert(setter.Body != null);

            var statements = setter.Body.Statements;
            if (statements.Count != 1)
            {
                return false;
            }

            var ifStatement = statements[0] as IfStatementSyntax;
            if (ifStatement == null)
            {
                return false;
            }

            var statement = ifStatement.Statement;
            if (statement is BlockSyntax)
            {
                var blockStatements = ((BlockSyntax)statement).Statements;
                if (blockStatements.Count != 1)
                {
                    return false;
                }

                statement = blockStatements[0];
            }

            var expressionStatement = statement as ExpressionStatementSyntax;
            if (expressionStatement == null)
            {
                return false;
            }

            if (!IsAssignmentOfPropertyValueParameterToBackingField(expressionStatement.Expression, backingField, semanticModel))
            {
                return false;
            }

            var condition = ifStatement.Condition as BinaryExpressionSyntax;
            if (condition == null ||
                condition.Kind() != SyntaxKind.NotEqualsExpression)
            {
                return false;
            }

            return ComparesPropertyValueParameterAndBackingField(condition, backingField, semanticModel);
        }

        private static bool IsExpandableSetterPattern3(
            AccessorDeclarationSyntax setter,
            IFieldSymbol backingField,
            SemanticModel semanticModel)
        {
            // Pattern: if (field == value) return; field = value;

            Debug.Assert(setter.Body != null);

            var statements = setter.Body.Statements;
            if (statements.Count != 2)
            {
                return false;
            }

            var ifStatement = statements[0] as IfStatementSyntax;
            if (ifStatement == null)
            {
                return false;
            }

            var statement = ifStatement.Statement;
            if (statement is BlockSyntax)
            {
                var blockStatements = ((BlockSyntax)statement).Statements;
                if (blockStatements.Count != 1)
                {
                    return false;
                }

                statement = blockStatements[0];
            }

            var returnStatement = statement as ReturnStatementSyntax;
            if (returnStatement == null ||
                returnStatement.Expression != null)
            {
                return false;
            }

            var expressionStatement = statements[1] as ExpressionStatementSyntax;
            if (expressionStatement == null)
            {
                return false;
            }

            if (!IsAssignmentOfPropertyValueParameterToBackingField(expressionStatement.Expression, backingField, semanticModel))
            {
                return false;
            }

            var condition = ifStatement.Condition as BinaryExpressionSyntax;
            if (condition == null ||
                condition.Kind() != SyntaxKind.EqualsExpression)
            {
                return false;
            }

            return ComparesPropertyValueParameterAndBackingField(condition, backingField, semanticModel);
        }
    }
}


text:
from zurllib import urlopen, quote
from btformats import check_peers
from bencode import bdecode
from threading import Thread, Lock
from socket import error
from time import time
from random import randrange
from binascii import b2a_hex

class Rerequester:
    def __init__(self, url, interval, sched, howmany, minpeers,
            connect, externalsched, amount_left, up, down,
            port, ip, myid, infohash, timeout, errorfunc, maxpeers, doneflag,
            upratefunc, downratefunc, ever_got_incoming):
        self.url = ('%s?info_hash=%s&peer_id=%s&port=%s&key=%s' %
            (url, quote(infohash), quote(myid), str(port),
            b2a_hex(''.join([chr(randrange(256)) for i in xrange(4)]))))
        if ip != '':
            self.url += '&ip=' + quote(ip)
        self.interval = interval
        self.last = None
        self.trackerid = None
        self.announce_interval = 30 * 60
        self.sched = sched
        self.howmany = howmany
        self.minpeers = minpeers
        self.connect = connect
        self.externalsched = externalsched
        self.amount_left = amount_left
        self.up = up
        self.down = down
        self.timeout = timeout
        self.errorfunc = errorfunc
        self.maxpeers = maxpeers
        self.doneflag = doneflag
        self.upratefunc = upratefunc
        self.downratefunc = downratefunc
        self.ever_got_incoming = ever_got_incoming
        self.last_failed = True
        self.last_time = 0

    def c(self):
        self.sched(self.c, self.interval)
        if self.ever_got_incoming():
            getmore = self.howmany() <= self.minpeers / 3
        else:
            getmore = self.howmany() < self.minpeers
        if getmore or time() - self.last_time > self.announce_interval:
            self.announce()

    def begin(self):
        self.sched(self.c, self.interval)
        self.announce(0)

    def announce(self, event = None):
        self.last_time = time()
        s = ('%s&uploaded=%s&downloaded=%s&left=%s' %
            (self.url, str(self.up()), str(self.down()),
            str(self.amount_left())))
        if self.last is not None:
            s += '&last=' + quote(str(self.last))
        if self.trackerid is not None:
            s += '&trackerid=' + quote(str(self.trackerid))
        if self.howmany() >= self.maxpeers:
            s += '&numwant=0'
        else:
            s += '&compact=1'
        if event != None:
            s += '&event=' + ['started', 'completed', 'stopped'][event]
        set = SetOnce().set
        def checkfail(self = self, set = set):
            if set():
                if self.last_failed and self.upratefunc() < 100 and self.downratefunc() < 100:
                    self.errorfunc('Problem connecting to tracker - timeout exceeded')
                self.last_failed = True
        self.sched(checkfail, self.timeout)
        Thread(target = self.rerequest, args = [s, set]).start()

    def rerequest(self, url, set):
        try:
            h = urlopen(url)
            r = h.read()
            h.close()
            if set():
                def add(self = self, r = r):
                    self.last_failed = False
                    self.postrequest(r)
                self.externalsched(add, 0)
        except (IOError, error), e:
            if set():
                def fail(self = self, r = 'Problem connecting to tracker - ' + str(e)):
                    if self.last_failed:
                        self.errorfunc(r)
                    self.last_failed = True
                self.externalsched(fail, 0)

    def postrequest(self, data):
        try:
            r = bdecode(data)
            check_peers(r)
            if r.has_key('failure reason'):
                self.errorfunc('rejected by tracker - ' + r['failure reason'])
            else:
                if r.has_key('warning message'):
                    self.errorfunc('warning from tracker - ' + r['warning message'])
                self.announce_interval = r.get('interval', self.announce_interval)
                self.interval = r.get('min interval', self.interval)
                self.trackerid = r.get('tracker id', self.trackerid)
                self.last = r.get('last')
                p = r['peers']
                peers = []
                if type(p) == type(''):
                    for x in xrange(0, len(p), 6):
                        ip = '.'.join([str(ord(i)) for i in p[x:x+4]])
                        port = (ord(p[x+4]) << 8) | ord(p[x+5])
                        peers.append((ip, port, None))
                else:
                    for x in p:
                        peers.append((x['ip'], x['port'], x.get('peer id')))
                ps = len(peers) + self.howmany()
                if ps < self.maxpeers:
                    if self.doneflag.isSet():
                        if r.get('num peers', 1000) - r.get('done peers', 0) > ps * 1.2:
                            self.last = None
                    else:
                        if r.get('num peers', 1000) > ps * 1.2:
                            self.last = None
                for x in peers:
                    self.connect((x[0], x[1]), x[2])
        except ValueError, e:
            if data != '':
                self.errorfunc('bad data from tracker - ' + str(e))

class SetOnce:
    def __init__(self):
        self.lock = Lock()
        self.first = True

    def set(self):
        try:
            self.lock.acquire()
            r = self.first
            self.first = False
            return r
        finally:
            self.lock.release()


text:
---
layout: post
title: TextView的巧用
---
一、需求展示
有时会需要,像社交网站评论一样的效果。因为Android的所有控件其实都是矩形的,导致如果使用两个或者以上的TextView控件来做的话会导致类似一下的排版:

	用户:我是评论我是评论我是评论我是评论我是评论
		  我是评论我是评论我是评论我是评论我是评论
		  我是评论我是评论我是评论我是评论我是评论

以上的排版有个很不好的地方,就是没法自然的换行,因为左右分别是一个控件,而我们想达到的效果是:

	用户:我是评论我是评论我是评论我是评论我是评论
	我是评论我是评论我是评论我是评论我是评论是评论
	我是评论我是评论我是评论我是评论我是评论是评论

而且,我们希望用户可以点击跳转。这样的排版显然用一个TextView比较容易实现,那么要想用户二字单独分离出来就需要用到一个属性:`android:autoLink` 。这其实不是什么新东西,就是在TextView中链接网址,电话或者其他什么链接的属性。

那么,首先先看效果吧:
![点击前.png](http://upload-images.jianshu.io/upload_images/3792480-dbaf7b32ea23b1d3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
点击李四后,会跳转到另一个activity,并把李四传过去,当然,你可以随便传数据,比如整个实体类什么的,也可以uri拼接的时候把这个拼接到uri里,参数传其他的都可以,随你。
那么点击后,跳转后的展示如下:
![点击后.png](http://upload-images.jianshu.io/upload_images/3792480-85e85d2fac455fb4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
二、代码及原理
1.新建一个android项目
2.修改代码
代码一共新增/修改了6个文件,包括manifest。
①steings.xml
只是一些字符串常量,存在里面(里面两个冒号是为了验证是否只匹配其中第一个真正的用户名):

	<?xml version="1.0" encoding="utf-8"?>
	<resources>

		<string name="app_name">TextViewLink</string>
		<string name="hello_world">李四:我是评论我是评:论我是评论我是评论我是评论我是评论我是评论我是评论我是评论我是评论我是评论我是评论我是评论我是评论我是评论我是评论我是评论我是评论我是评论我是评论</string>
		<string name="action_settings">Settings</string>
		<string name="waiting">加载中</string>

	</resources>

②activity_main.xml

	<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
		xmlns:tools="http://schemas.android.com/tools"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:paddingBottom="@dimen/activity_vertical_margin"
		android:paddingLeft="@dimen/activity_horizontal_margin"
		android:paddingRight="@dimen/activity_horizontal_margin"
		android:paddingTop="@dimen/activity_vertical_margin"
		tools:context="com.BigBoom.textviewlink.MainActivity" >

		<!-- 只加了android:autoLink属性和id -->
		<TextView
			android:id="@+id/tv_link"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="@string/hello_world"
			android:autoLink="web|phone|email" />

	</RelativeLayout>

③activity_user.xml 跳转后activity的布局文件,同样很简单,只有一个控件,为了展示,传值的效果

	<?xml version="1.0" encoding="utf-8"?>
	<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:orientation="vertical" >

		<TextView
			android:id="@+id/tv_user"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="@string/waiting"/>

	</LinearLayout>

④MainActivity.java
本功能最重要的修改,通过修改uri来实现activity之间的跳转和传值

	package com.BigBoom.textviewlink;

	import java.util.regex.Matcher;
	import java.util.regex.Pattern;

	import android.app.Activity;
	import android.os.Bundle;
	import android.text.util.Linkify;
	import android.text.util.Linkify.MatchFilter;
	import android.text.util.Linkify.TransformFilter;
	import android.widget.TextView;

	public class MainActivity extends Activity {

		private TextView tvLink;

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_main);

			tvLink = (TextView) findViewById(R.id.tv_link);
			extractMention2Link(tvLink);
		}
		/**
		* 实现单TextView同时展示用户和评论并实现传值跳转
		* @param v 展示用TextView
		*/
		private void extractMention2Link(TextView v){
			v.setAutoLinkMask(0);
			//匹配规则
			Pattern pattern = Pattern.compile("(.*?):");
			//用于跳转
			String scheme = "bigboom://bigboom";
			Linkify.addLinks(v, pattern, scheme, new MatchFilter() {

				@Override
				public boolean acceptMatch(CharSequence s, int start, int end) {
					//只有第一个进行匹配
					return start == 0;
				}
			}, new TransformFilter() {

				@Override
				public String transformUrl(Matcher match, String url) {
					//传值
					return "?username="+match.group(1);
				}
			});
		}
	}

⑤UserActivity.java
跳转后取值,并展示

	package com.BigBoom.textviewlink;

	import android.app.Activity;
	import android.content.Intent;
	import android.net.Uri;
	import android.os.Bundle;
	import android.widget.TextView;

	public class UserActivity extends Activity {

		private TextView tvUser;
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_user);
			tvUser = (TextView) findViewById(R.id.tv_user);

			Intent intent = getIntent();
			if(intent != null){
				Uri uri = intent.getData();
				if(uri == null){
					return;
				}
				String username = uri.getQueryParameter("username");
				tvUser.setText(username);
			}
		}
	}

⑥最后manifest文件

	<?xml version="1.0" encoding="utf-8"?>
	<manifest xmlns:android="http://schemas.android.com/apk/res/android"
		package="com.BigBoom.textviewlink"
		android:versionCode="1"
		android:versionName="1.0" >

		<uses-sdk
			android:minSdkVersion="19"
			android:targetSdkVersion="19" />

		<application
			android:allowBackup="true"
			android:icon="@drawable/ic_launcher"
			android:label="@string/app_name"
			android:theme="@style/AppTheme" >
			<activity
				android:name=".MainActivity"
				android:label="@string/app_name" >
				<intent-filter>
					<action android:name="android.intent.action.MAIN" />

					<category android:name="android.intent.category.LAUNCHER" />
				</intent-filter>
			</activity>
			<activity android:name=".UserActivity">
				<intent-filter>
					<action android:name="android.intent.action.VIEW"/>
					<category android:name="android.intent.category.DEFAULT"/>
					<category android:name="android.intent.category.BROWSABLE"/>
					<data android:scheme="bigboom" android:host="bigboom"/>
				</intent-filter>
			</activity>

		</application>

	</manifest>

三、总结
其实这是一个非常简单又实用的功能,其最核心的东西只有`android:autoLink`和类`Linkify`而已。可以做很多延伸,不如微博@人的功能和##话题功能。


text:
require 'tempfile'

module Cargo
  # CargoFile is an Active Record model that is associated to the model that
  # calls <tt>cargo</tt> via Active Record's <tt>has_one</tt> association.
  #
  # For example, the following class definition will attach two CargoFiles
  # to each Image object.
  #
  #   class Image < ActiveRecord::Base
  #     cargo :original
  #     cargo :thumbnail
  #   end
  #
  # Now you can access <tt>original</tt> and <tt>thumbnail</tt> just like any
  # other <tt>has_one</tt> association.
  #
  #   @image = Image.find(:first)
  #   @image.original                 # => #<Cargo::CargoFile>
  #   @image.original.filename        # => "00_02_bz_myk25s.jpg"
  #
  #   # All the usual has_one methods work too.
  #   @image.thumbnail.destroy
  #
  class CargoFile < ActiveRecord::Base
    belongs_to :parent, :polymorphic => true

    validate_on_create :file_data_exists

    before_save :assign_key

    after_save :save_file_if_new_data

    before_destroy :remove_file_and_empty_directories

    # Combines <tt>dirname</tt> and <tt>filename</tt> to return the full path to
    # this file. If new data has been assigned but not saved, returns the path
    # to the temporary file.
    #
    # ==== Example
    #
    #   @image = Image.find(:first)
    #   @image.original.path
    #   # => "/var/files/images/00/00/00_00_01_4b2xu3.jpg"
    #
    def path
      if new_data?
        @tempfile.path
      else
        permanent_path
      end
    end

    # Returns the directory of this file on disk
    #
    # ==== Example
    #
    #   @image = Image.find(:first)
    #   @image.original.dirname
    #   # => "/var/files/images/00/00"
    #
    def dirname
      File.join(Cargo.config.file_path, subdir)
    end

    # Returns the filename for this file. Filenames are generated automatically
    # based on the model's <tt>id</tt>, <tt>key</tt>, and <tt>extension</tt>
    # fields.
    #
    # The <tt>filename</tt> has three parts:
    #
    # * <tt>id</tt> converted to base 36
    # * <tt>key</tt>
    # * <tt>extension</tt>
    #
    # The model's <tt>id</tt> is converted to base 36, zero-padded to six
    # places, and split into three parts of two characters each. This has the
    # following consequences:
    #
    # * Base 36 keeps directory names and filenames short
    # * Max of "zz" for each part limits each directory to 1295 files
    # * A depth of three directories allows for two billion files
    # * Zero-padding keeps directory listings in numerical order by model's
    #   <tt>id</tt>
    #
    # ==== Example
    #
    #   @image = Image.find(3023)
    #   @image.original.id                 # => 3023
    #   @image.original.key                # => "myk25s"
    #   @image.original.extension          # => "jpg"
    #
    #   # 3023 in base 36 is "2bz"
    #   # zero-padded and split gives 00 02 bz
    #   # the first two parts are used as subdirectories
    #
    #   @image.original.filename           # => "00_02_bz_myk25s.jpg"
    #   @image.original.subdir             # => "images/00/02"
    #   @image.original.path
    #   # => "/var/files/images/00/02/00_02_bz_myk25s.jpg"
    #
    def filename
      suffix = extension.blank? ? '' : ".#{extension}"
      suffix = key.blank? ? suffix : "_#{key}#{suffix}"
      "#{base_filename}#{suffix}"
    end

    # Boolean value indicating whether model has unsaved file data
    #
    def new_data?
      @tempfile ? @tempfile.size > 0 : false
    end

    # Generates a relative url for this file based on <tt>config.url_subdir</tt>
    #
    # ==== Example
    #
    #   Cargo.config.url_subdir = '/files'
    #
    #   @image = Image.find(:first)
    #   @image.original.relative_url
    #   # => "/files/images/00/00/00_00_01_4b2xu3.jpg"
    #
    def relative_url
      mtime = File.exist?(path) ? File.mtime(path).to_i.to_s : nil
      name = mtime ? "#{filename}?#{mtime}" : filename
      url = []
      url << Cargo.config.url_subdir
      url << subdir.split(File::SEPARATOR)
      url << name
      url.flatten.map do |s|
        s.ends_with?('/') ? s.chop : s
      end.join('/')
    end

    # Sets the file that will be saved during the Active Record after_save
    # callback. Automatically parses and sets the file extension.
    #
    # ==== Example
    #
    #   @image = Image.new
    #   @image.original                             # => nil
    #   @image.build_original
    #   @image.original.set('path/to/image.jpg')    # => true
    #
    #   # You can use a shortcut for the above to build and set the object in
    #   # one step:
    #   #
    #   # @image.set_original('path/to/image.jpg')
    #
    #   @image.original.extension                   # => "jpg"
    #
    #   file = File.open('path/to/image.png')
    #   @image.original.set(file)                   # => true
    #   @image.original.extension                   # => "png"
    #
    # ==== Parameters
    #
    # [filename_or_file]
    #   Either a string to specify the filename or a file object. This
    #   parameter can also be an ActionController::UploadedStringIO or
    #   ActionController::UploadedTempfile from a Rails form post.
    #
    def set(filename_or_file)
      @tempfile.close! if @tempfile
      @tempfile = Tempfile.new(self.class.name.demodulize.underscore)
      @tempfile.binmode
      filename = nil
      case filename_or_file
      when String
        filename = filename_or_file
        File.open(filename, 'rb') do |f|
          write_tempfile(f)
        end
      when File
        filename = filename_or_file.path
        write_tempfile(filename_or_file)
      else
        upload = filename_or_file
        if upload.respond_to?(:original_path) && upload.respond_to?(:read)
          filename = upload.original_path
          write_tempfile(upload)
        end
      end
      set_metadata(filename) if new_data?
      return new_data?
    end

    # Returns the subdirectory under <tt>config.file_path</tt> for this file
    #
    # ==== Example
    #
    #   @image = Image.find(:first)
    #   @image.original.subdir
    #   # => "images/00/00"
    #
    def subdir
      id_parts = id_in_base_36_parts
      level1 = id_parts[0]
      level2 = id_parts[1]
      File.join(parent_type.tableize, level1, level2)
    end

    private

    def assign_key
      self.key ||= random_key
    end

    def base_filename
      id_in_base_36_parts.join('_')
    end

    def create_directory
      FileUtils.mkdir_p(dirname)
    end

    def file_data_exists
      errors.add(:base, 'File must be set') unless new_data?
    end

    # Returns a 3-part array of this object's id in base 36 which is used in
    # the subdir method to organize files such that each directory has a maximum
    # of 1295, or "zz", files.
    #
    # For example, an id of 1947 is "1i3" is base 36 and gives us the result
    # => ["00", "01", "i3"]
    #
    def id_in_base_36_parts
      raise(Errors::CannotGenerateFilename) if id.blank?
      base_36 = id.to_s(36).rjust(6, '0')
      parts = []
      # taking the rightmost two digits first allows for numbers larger than
      # "zzzzzz" by storing extra places in the first element of the array
      parts.unshift(base_36[-2, 2])
      parts.unshift(base_36[-4, 2])
      parts.unshift(base_36[0, base_36.length - 4])
    end

    def permanent_path
      File.join(dirname, filename)
    end

    def random_key(length = 6)
      # letters and numbers except 0, 1, l, O, and vowels
      a = 'bcdfghjkmnpqrstvwxyz23456789'.split(//)
      Array.new(length) { a[rand(a.length)] }.join
    end

    def remove_empty_directories
      dirs = dirname.split(File::SEPARATOR)
      subdir.split(File::SEPARATOR).length.times do
        begin
          FileUtils.rmdir(dirs.join(File::SEPARATOR))
          dirs.pop
        rescue Errno::ENOTEMPTY, Errno::ENOENT
          break
        end
      end
    end

    # Look for and delete a file matching this record's id. The key or extension
    # may have changed since this file was originally created, so we use the
    # base_filename to identify the file.
    #
    def remove_existing_file
      existing = Dir[File.join(dirname, "#{base_filename}*")].first
      FileUtils.rm_f(existing) unless existing.nil?
    end

    # Deletes the file and removes any empty directories that were created when
    # the file was created
    #
    def remove_file_and_empty_directories
      FileUtils.rm_f(path)
      remove_empty_directories
    end

    def save_file_if_new_data
      if new_data?
        create_directory
        remove_existing_file
        File.open(permanent_path, 'wb+') do |f|
          f.write(@tempfile.read)
        end
        @tempfile.close!
        @tempfile = nil
      end
    end

    def set_metadata(filename)
      orig = nil
      if filename =~ /^(?:.*[:\\\/])?(.*)/m
        orig = $1
      else
        orig = File.basename(filename) unless filename.nil?
      end
      self.original_filename = orig
      ext = File.extname(filename)
      ext = ext.reverse.chop.reverse if ext.starts_with?('.')
      self.extension = ext
      self.original_filename_will_change!
      self.extension_will_change!
    end

    def write_tempfile(source)
      bytes = 8192
      buffer = ''
      source.rewind
      while source.read(bytes, buffer) do
        @tempfile.write(buffer)
      end
      @tempfile.rewind
    end
  end
end


text:
// <copyright file="RaceManager.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>

using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi.Multiplayer;
using System.Collections.Generic;

public class RaceManager : RealTimeMultiplayerListener
{
    const string RaceTrackName = "RaceTrack";
    string[] CarNames = new string[] { "Car-Orange", "Car-Lime", "Car-Red", "Car-Cyan" };
    const int QuickGameOpponents = 1;
    const int GameVariant = 0;
    static RaceManager sInstance = null;
    const int MinOpponents = 1;
    const int MaxOpponents = 3;

    // points required to finish race. Must be < 255 because it has to fit in a byte
    const int PointsToFinish = 100;

    public enum RaceState
    {
        SettingUp,
        Playing,
        Finished,
        SetupFailed,
        Aborted}

    ;

    private RaceState mRaceState = RaceState.SettingUp;

    // how many points each of our fellow racers has
    private Dictionary<string,int> mRacerScore = new Dictionary<string,int>();

    // whether or not we received the final score for each participant id
    private HashSet<string> mGotFinalScore = new HashSet<string>();

    // my participant ID
    private string mMyParticipantId = "";

    // my rank (1st, 2nd, 3rd, 4th, or 0 to mean 'no rank yet')
    // This is updated every time we get a finish notification from a peer
    private int mFinishRank = 0;

    // room setup progress
    private float mRoomSetupProgress = 0.0f;

    // speed of the "fake progress" (to keep the player happy)
    // during room setup
    const float FakeProgressSpeed = 1.0f;
    const float MaxFakeProgress = 30.0f;
    float mRoomSetupStartTime = 0.0f;

    private RaceManager()
    {
        mRoomSetupStartTime = Time.time;
    }

    public static void CreateQuickGame()
    {
        sInstance = new RaceManager();
        PlayGamesPlatform.Instance.RealTime.CreateQuickGame(QuickGameOpponents,
            QuickGameOpponents,
            GameVariant,
            sInstance);
    }

    public static void CreateWithInvitationScreen()
    {
        sInstance = new RaceManager();
        PlayGamesPlatform.Instance.RealTime.CreateWithInvitationScreen(
            MinOpponents,
            MaxOpponents,
            GameVariant,
            sInstance);
    }

    public static void AcceptFromInbox()
    {
        sInstance = new RaceManager();
        PlayGamesPlatform.Instance.RealTime.AcceptFromInbox(sInstance);
    }

    public static void AcceptInvitation(string invitationId)
    {
        sInstance = new RaceManager();
        PlayGamesPlatform.Instance.RealTime.AcceptInvitation(invitationId, sInstance);
    }

    public RaceState State
    {
        get
        {
            return mRaceState;
        }
    }

    public static RaceManager Instance
    {
        get
        {
            return sInstance;
        }
    }

    public int FinishRank
    {
        get
        {
            return mFinishRank;
        }
    }

    public float RoomSetupProgress
    {
        get
        {
            float fakeProgress = (Time.time - mRoomSetupStartTime) * FakeProgressSpeed;
            if (fakeProgress > MaxFakeProgress)
            {
                fakeProgress = MaxFakeProgress;
            }
            float progress = mRoomSetupProgress + fakeProgress;
            return progress < 99.0f ? progress : 99.0f;
        }
    }

    private void SetupTrack()
    {
        BehaviorUtils.MakeVisible(GameObject.Find(RaceTrackName), true);
        Debug.Log("About to get self");
        Participant self = GetSelf();
        Debug.Log("Self is " + self);
        Debug.Log("About to get a list of connected participants");
        List<Participant> racers = GetRacers();
        Debug.Log("Racers is  " + racers + " with count of " + racers.Count);
        int i;
        for (i = 0; i < CarNames.Length; i++)
        {
            Debug.Log("Looking at i value of " + i);
            GameObject car = GameObject.Find(CarNames[i]);
            Debug.Log("Looking for car name " + CarNames[i]);
            Participant racer = i < racers.Count ? racers[i] : null;
            Debug.Log("Racer is " + racer);

            bool isSelf = racer != null && racer.ParticipantId.Equals(self.ParticipantId);
            if (racer != null)
            {
                Debug.Log("Racer is not null!");
                BehaviorUtils.MakeVisible(car, true);
                CarController controller = car.GetComponent<CarController>();
                controller.SetParticipantId(racer.ParticipantId);
                controller.SetBlinking(isSelf);
            }
            else
            {
                Debug.Log("Hiding racer");
                BehaviorUtils.MakeVisible(car, false);
            }
        }
    }

    private void TearDownTrack()
    {
        BehaviorUtils.MakeVisible(GameObject.Find(RaceTrackName), false);
        foreach (string name in CarNames)
        {
            GameObject car = GameObject.Find(name);
            car.GetComponent<CarController>().Reset();
            BehaviorUtils.MakeVisible(car, false);
        }
    }

    public void OnRoomConnected(bool success)
    {
        if (success)
        {
            mRaceState = RaceState.Playing;
            mMyParticipantId = GetSelf().ParticipantId;
            SetupTrack();
        }
        else
        {
            mRaceState = RaceState.SetupFailed;
        }
    }

    public void OnLeftRoom()
    {
        if (mRaceState != RaceState.Finished)
        {
            mRaceState = RaceState.Aborted;
        }
    }

    public void OnParticipantLeft(Participant participant)
    {
    }

    public void OnPeersConnected(string[] peers)
    {
    }

    public void OnPeersDisconnected(string[] peers)
    {
        foreach (string peer in peers)
        {
            // if this peer has left and hasn't finished the race,
            // consider them to have abandoned the race (0 score!)
            mGotFinalScore.Add(peer);
            mRacerScore[peer] = 0;
            RemoveCarFor(peer);
        }

        // if, as a result, we are the only player in the race, it's over
        List<Participant> racers = GetRacers();
        if (mRaceState == RaceState.Playing && (racers == null || racers.Count < 2))
        {
            mRaceState = RaceState.Aborted;
        }
    }

    private void RemoveCarFor(string participantId)
    {
        foreach (string name in CarNames)
        {
            GameObject obj = GameObject.Find(name);
            CarController cc = obj.GetComponent<CarController>();
            if (participantId.Equals(cc.ParticipantId))
            {
                BehaviorUtils.MakeVisible(obj, false);
            }
        }
    }

    public void OnRoomSetupProgress(float percent)
    {
        mRoomSetupProgress = percent;
    }

    public void OnRealTimeMessageReceived(bool isReliable, string senderId, byte[] data)
    {
        int score = (int)data[1];

        if (data[0] == (byte)'I')
        {
            // interim score update
            mRacerScore[senderId] = score;
        }
        else if (data[0] == (byte)'F')
        {
            // finish notification
            if (!mGotFinalScore.Contains(senderId))
            {
                // record final score
                mRacerScore[senderId] = score;
                mGotFinalScore.Add(senderId);
                UpdateMyRank();

                // finish race too, if we haven't yet
                if (mRaceState == RaceState.Playing)
                {
                    FinishRace();
                }
            }
            else
            {
                Debug.LogWarning("Received duplicate finish notification for " + senderId);
            }
        }
    }

    public void CleanUp()
    {
        PlayGamesPlatform.Instance.RealTime.LeaveRoom();
        TearDownTrack();
        mRaceState = RaceState.Aborted;
        sInstance = null;
    }

    public float GetRacerProgress(string participantId)
    {
        return GetRacerPosition(participantId) / (float)PointsToFinish;
    }

    public int GetRacerPosition(string participantId)
    {
        if (mRacerScore.ContainsKey(participantId))
        {
            return mRacerScore[participantId];
        }
        else
        {
            return 0;
        }
    }

    private Participant GetSelf()
    {
        return PlayGamesPlatform.Instance.RealTime.GetSelf();
    }

    private List<Participant> GetRacers()
    {
        return PlayGamesPlatform.Instance.RealTime.GetConnectedParticipants();
    }

    private Participant GetParticipant(string participantId)
    {
        return PlayGamesPlatform.Instance.RealTime.GetParticipant(participantId);
    }

    public void UpdateSelf(float deltaT, int pointsToAdd)
    {
        int pos = GetRacerPosition(mMyParticipantId);

        if (pos >= PointsToFinish)
        {
            // already finished
            return;
        }

        pos += pointsToAdd;
        pos = pos < 0 ? 0 : pos >= PointsToFinish ? PointsToFinish : pos;
        mRacerScore[mMyParticipantId] = pos;

        if (pos >= PointsToFinish)
        {
            // we finished the race!
            FinishRace();
        }
        else if (pointsToAdd > 0)
        {
            // broadcast position update to peers
            BroadCastPosition(pos);
        }
    }

    byte[] mPosPacket = new byte[2];

    private void BroadCastPosition(int pos)
    {
        mPosPacket[0] = (byte)'I'; // interim update
        mPosPacket[1] = (byte)pos;
        PlayGamesPlatform.Instance.RealTime.SendMessageToAll(false, mPosPacket);
    }

    byte[] mFinalPacket = new byte[2];

    private void FinishRace()
    {
        mGotFinalScore.Add(mMyParticipantId);
        mRaceState = RaceState.Finished;
        UpdateMyRank();

        // send final score packet to peers
        mFinalPacket[0] = (byte)'F'; // final update
        mFinalPacket[1] = (byte)mRacerScore[mMyParticipantId];
        PlayGamesPlatform.Instance.RealTime.SendMessageToAll(true, mFinalPacket);
    }

    private void UpdateMyRank()
    {
        int numRacers = GetRacers().Count;
        if (mGotFinalScore.Count < numRacers)
        {
            mFinishRank = 0; // undefined for now
        }
        int myScore = mRacerScore[mMyParticipantId];
        int rank = 1;
        foreach (string participantId in mRacerScore.Keys)
        {
            if (mRacerScore[participantId] > myScore)
            {
                ++rank;
            }
        }
        mFinishRank = rank;
    }
}


text:
require 'formula'

class Opam < Formula
  homepage 'https://opam.ocaml.org'
  url 'https://github.com/ocaml/opam/archive/1.1.1.tar.gz'
  sha1 'f1a8291eb888bfae4476ee59984c9a30106cd483'

  head 'https://github.com/ocaml/opam.git'

  depends_on "objective-caml"
  depends_on "aspcud" => :recommended

  if build.with? "aspcud"
    needs :cxx11
  end

  def install
    ENV.deparallelize
    # Set TERM to workaround bug in ocp-build (ocaml/opam#1038)
    ENV["TERM"] = "dumb"
    system "./configure", "--prefix=#{prefix}"
    system "make"
    system "make", "install"

    bash_completion.install "shell/opam_completion.sh"
    zsh_completion.install "shell/opam_completion_zsh.sh"
  end

  test do
    system "#{bin}/opam", "--help"
  end

  def caveats; <<-EOS.undent
    OPAM uses ~/.opam by default for its package database, so you need to
    initialize it first by running (as a normal user):

    $  opam init

    Run the following to initialize your environment variables:

    $  eval `opam config env`

    To export the needed variables every time, add them to your dotfiles.
      * On Bash, add them to `~/.bash_profile`.
      * On Zsh, add them to `~/.zprofile` instead.

    Documentation and tutorials are available at http://opam.ocaml.org, or
    via 'man opam' and 'opam --help'.
    EOS
  end
end


text:
import React from 'react';

export default () => (
hello universe
);


text:
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.ui;

import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

/**
 * Utility functions for common Android UI tasks.
 * This class is not supposed to be instantiated.
 */
public class UiUtils {
    /**
     * Guards this class from being instantiated.
     */
    private UiUtils() {
    }

    /** The minimum size of the bottom margin below the app to detect a keyboard. */
    private static float KEYBOARD_DETECT_BOTTOM_THRESHOLD_DP = 100;

    /**
     * Shows the software keyboard if necessary.
     * @param view The currently focused {@link View}, which would receive soft keyboard input.
     */
    public static void showKeyboard(View view) {
        InputMethodManager imm =
                (InputMethodManager) view.getContext().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
        // Only shows soft keyboard if there isn't an open physical keyboard.
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * Hides the keyboard.
     * @param view The {@link View} that is currently accepting input.
     * @return Whether the keyboard was visible before.
     */
    public static boolean hideKeyboard(View view) {
        InputMethodManager imm =
                (InputMethodManager) view.getContext().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
        return imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static boolean isKeyboardShowing(Context context, View view) {
        View rootView = view.getRootView();
        if (rootView == null) return false;
        Rect appRect = new Rect();
        rootView.getWindowVisibleDisplayFrame(appRect);
        final float screenHeight = context.getResources().getDisplayMetrics().heightPixels;
        final float bottomMargin = Math.abs(appRect.bottom - screenHeight);
        final float density = context.getResources().getDisplayMetrics().density;
        return bottomMargin > KEYBOARD_DETECT_BOTTOM_THRESHOLD_DP * density;
    }

    /**
     * Inserts a {@link View} into a {@link ViewGroup} after directly before a given {@View}.
     * @param container The {@link View} to add newView to.
     * @param newView The new {@link View} to add.
     * @param existingView The {@link View} to insert the newView before.
     * @return The index where newView was inserted, or -1 if it was not inserted.
     */
    public static int insertBefore(ViewGroup container, View newView, View existingView) {
        return insertView(container, newView, existingView, false);
    }

    /**
     * Inserts a {@link View} into a {@link ViewGroup} after directly after a given {@View}.
     * @param container The {@link View} to add newView to.
     * @param newView The new {@link View} to add.
     * @param existingView The {@link View} to insert the newView after.
     * @return The index where newView was inserted, or -1 if it was not inserted.
     */
    public static int insertAfter(ViewGroup container, View newView, View existingView) {
        return insertView(container, newView, existingView, true);
    }

    private static int insertView(
            ViewGroup container, View newView, View existingView, boolean after) {
        // See if the view has already been added.
        int index = container.indexOfChild(newView);
        if (index >= 0) return index;

        // Find the location of the existing view.
        index = container.indexOfChild(existingView);
        if (index < 0) return -1;

        // Add the view.
        if (after) index++;
        container.addView(newView, index);
        return index;
    }
}


text:
<?php
namespace Mason\Task;

use Mason\Attrs\EmptyAttrs;

class CallableTask implements Task
{
    private $callable;
    private $attrs;

    public function __construct(callable $callable)
    {
        $this->callable = $callable;
        $this->attrs = new EmptyAttrs();
    }

    public function run()
    {
        call_user_func($this->callable);
    }

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


text:
"use strict";

let ValidationErrorCodes =
  require("../../../lib/braintree/validation_error_codes").ValidationErrorCodes;

let braintree = specHelper.braintree;

describe("MerchantGateway", function () {
  describe("create", () =>
    it("creates a merchant", function (done) {
      let gateway = new braintree.BraintreeGateway({
        clientId: "client_id$development$integration_client_id",
        clientSecret: "client_secret$development$integration_client_secret",
      });

      return gateway.merchant.create(
        {
          email: "name@email.com",
          countryCodeAlpha3: "USA",
          paymentMethods: ["credit_card", "paypal"],
        },
        function (err, response) {
          assert.isNull(err);
          assert.isTrue(response.success);

          let merchant = response.merchant;

          assert.isNotNull(merchant.id);
          assert.equal(merchant.email, "name@email.com");
          assert.equal(merchant.companyName, "name@email.com");
          assert.equal(merchant.countryCodeAlpha3, "USA");
          assert.equal(merchant.countryCodeAlpha2, "US");
          assert.equal(merchant.countryCodeNumeric, "840");
          assert.equal(merchant.countryName, "United States of America");

          let credentials = response.credentials;

          assert.isNotNull(credentials.accessToken);
          assert.equal(credentials.accessToken.indexOf("access_token"), 0);
          assert.isNotNull(credentials.refreshToken);
          assert.isNotNull(credentials.expiresAt);
          assert.equal(credentials.tokenType, "bearer");

          done();
        }
      );
    }));

  it("returns an error when using invalid payment methods", function (done) {
    let gateway = new braintree.BraintreeGateway({
      clientId: "client_id$development$integration_client_id",
      clientSecret: "client_secret$development$integration_client_secret",
    });

    return gateway.merchant.create(
      {
        email: "name@email.com",
        countryCodeAlpha3: "USA",
        paymentMethods: ["fake_money"],
      },
      function (err, response) {
        assert.isNotNull(response.errors);
        assert.isFalse(response.success);

        assert.equal(
          response.errors.for("merchant").on("paymentMethods")[0].code,
          ValidationErrorCodes.Merchant.PaymentMethodsAreInvalid
        );

        done();
      }
    );
  });

  describe("create_multi_currency", function () {
    it("creates a multi-currency merchant", function (done) {
      let gateway = new braintree.BraintreeGateway({
        clientId: "client_id$development$signup_client_id",
        clientSecret: "client_secret$development$signup_client_secret",
      });

      return gateway.merchant.create(
        {
          email: "name@email.com",
          countryCodeAlpha3: "USA",
          paymentMethods: ["credit_card", "paypal"],
          currencies: ["GBP", "USD"],
        },
        function (err, response) {
          assert.isNull(err);
          assert.isTrue(response.success);

          let merchant = response.merchant;

          assert.isNotNull(merchant.id);
          assert.equal(merchant.email, "name@email.com");
          assert.equal(merchant.companyName, "name@email.com");
          assert.equal(merchant.countryCodeAlpha3, "USA");
          assert.equal(merchant.countryCodeAlpha2, "US");
          assert.equal(merchant.countryCodeNumeric, "840");
          assert.equal(merchant.countryName, "United States of America");

          let credentials = response.credentials;

          assert.isNotNull(credentials.accessToken);
          assert.equal(credentials.accessToken.indexOf("access_token"), 0);
          assert.isNotNull(credentials.refreshToken);
          assert.isNotNull(credentials.expiresAt);
          assert.equal(credentials.tokenType, "bearer");

          let merchantAccounts = merchant.merchantAccounts;

          assert.equal(merchantAccounts.length, 2);

          let usdMerchantAccount = merchantAccounts.filter(
            (x) => x.id === "USD"
          )[0];

          assert.isNotNull(usdMerchantAccount);
          assert.equal(usdMerchantAccount.default, true);
          assert.equal(usdMerchantAccount.currencyIsoCode, "USD");

          let gbpMerchantAccount = merchantAccounts.filter(
            (x) => x.id === "GBP"
          )[0];

          assert.isNotNull(gbpMerchantAccount);
          assert.equal(gbpMerchantAccount.default, false);
          assert.equal(gbpMerchantAccount.currencyIsoCode, "GBP");

          done();
        }
      );
    });

    it("creates a paypal-only merchant", function (done) {
      let gateway = new braintree.BraintreeGateway({
        clientId: "client_id$development$signup_client_id",
        clientSecret: "client_secret$development$signup_client_secret",
      });

      return gateway.merchant.create(
        {
          email: "name@email.com",
          countryCodeAlpha3: "USA",
          paymentMethods: ["paypal"],
          currencies: ["GBP", "USD"],
          paypalAccount: {
            clientId: "fake_client_id",
            clientSecret: "fake_client_secret",
          },
        },
        function (err, response) {
          assert.isNull(err);
          assert.isTrue(response.success);

          let merchant = response.merchant;

          assert.isNotNull(merchant.id);
          assert.equal(merchant.email, "name@email.com");
          assert.equal(merchant.companyName, "name@email.com");
          assert.equal(merchant.countryCodeAlpha3, "USA");
          assert.equal(merchant.countryCodeAlpha2, "US");
          assert.equal(merchant.countryCodeNumeric, "840");
          assert.equal(merchant.countryName, "United States of America");

          let credentials = response.credentials;

          assert.isNotNull(credentials.accessToken);
          assert.equal(credentials.accessToken.indexOf("access_token"), 0);
          assert.isNotNull(credentials.refreshToken);
          assert.isNotNull(credentials.expiresAt);
          assert.equal(credentials.tokenType, "bearer");

          let merchantAccounts = merchant.merchantAccounts;

          assert.equal(merchantAccounts.length, 2);

          let usdMerchantAccount = merchantAccounts.filter(
            (x) => x.id === "USD"
          )[0];

          assert.isNotNull(usdMerchantAccount);
          assert.equal(usdMerchantAccount.default, true);
          assert.equal(usdMerchantAccount.currencyIsoCode, "USD");

          let gbpMerchantAccount = merchantAccounts.filter(
            (x) => x.id === "GBP"
          )[0];

          assert.isNotNull(gbpMerchantAccount);
          assert.equal(gbpMerchantAccount.default, false);
          assert.equal(gbpMerchantAccount.currencyIsoCode, "GBP");

          done();
        }
      );
    });

    it("allows creation of non-US merchant if onboarding application is internal", function (done) {
      let gateway = new braintree.BraintreeGateway({
        clientId: "client_id$development$signup_client_id",
        clientSecret: "client_secret$development$signup_client_secret",
      });

      return gateway.merchant.create(
        {
          email: "name@email.com",
          countryCodeAlpha3: "JPN",
          paymentMethods: ["paypal"],
          paypalAccount: {
            clientId: "fake_client_id",
            clientSecret: "fake_client_secret",
          },
        },
        function (err, response) {
          assert.isNull(err);
          assert.isTrue(response.success);

          let merchant = response.merchant;

          assert.isNotNull(merchant.id);
          assert.equal(merchant.email, "name@email.com");
          assert.equal(merchant.companyName, "name@email.com");
          assert.equal(merchant.countryCodeAlpha3, "JPN");
          assert.equal(merchant.countryCodeAlpha2, "JP");
          assert.equal(merchant.countryCodeNumeric, "392");
          assert.equal(merchant.countryName, "Japan");

          let credentials = response.credentials;

          assert.isNotNull(credentials.accessToken);
          assert.equal(credentials.accessToken.indexOf("access_token"), 0);
          assert.isNotNull(credentials.refreshToken);
          assert.isNotNull(credentials.expiresAt);
          assert.equal(credentials.tokenType, "bearer");

          let merchantAccounts = merchant.merchantAccounts;

          assert.equal(merchantAccounts.length, 1);

          let merchantAccount = merchantAccounts[0];

          assert.equal(merchantAccount.default, true);
          assert.equal(merchantAccount.currencyIsoCode, "JPY");

          done();
        }
      );
    });

    it("defaults to USD for non-US merchant if onboarding application is internal and country currency not supported", function (done) {
      let gateway = new braintree.BraintreeGateway({
        clientId: "client_id$development$signup_client_id",
        clientSecret: "client_secret$development$signup_client_secret",
      });

      return gateway.merchant.create(
        {
          email: "name@email.com",
          countryCodeAlpha3: "YEM",
          paymentMethods: ["paypal"],
          paypalAccount: {
            clientId: "fake_client_id",
            clientSecret: "fake_client_secret",
          },
        },
        function (err, response) {
          assert.isNull(err);
          assert.isTrue(response.success);

          let merchant = response.merchant;

          assert.isNotNull(merchant.id);
          assert.equal(merchant.email, "name@email.com");
          assert.equal(merchant.companyName, "name@email.com");
          assert.equal(merchant.countryCodeAlpha3, "YEM");
          assert.equal(merchant.countryCodeAlpha2, "YE");
          assert.equal(merchant.countryCodeNumeric, "887");
          assert.equal(merchant.countryName, "Yemen");

          let credentials = response.credentials;

          assert.isNotNull(credentials.accessToken);
          assert.equal(credentials.accessToken.indexOf("access_token"), 0);
          assert.isNotNull(credentials.refreshToken);
          assert.isNotNull(credentials.expiresAt);
          assert.equal(credentials.tokenType, "bearer");

          let merchantAccounts = merchant.merchantAccounts;

          assert.equal(merchantAccounts.length, 1);

          let merchantAccount = merchantAccounts[0];

          assert.equal(merchantAccount.default, true);
          assert.equal(merchantAccount.currencyIsoCode, "USD");

          done();
        }
      );
    });

    it("returns error if invalid currency is passed", function (done) {
      let gateway = new braintree.BraintreeGateway({
        clientId: "client_id$development$signup_client_id",
        clientSecret: "client_secret$development$signup_client_secret",
      });

      return gateway.merchant.create(
        {
          email: "name@email.com",
          countryCodeAlpha3: "USA",
          paymentMethods: ["paypal"],
          currencies: ["FAKE", "USD"],
          paypalAccount: {
            clientId: "fake_client_id",
            clientSecret: "fake_client_secret",
          },
        },
        function (err, response) {
          assert.isNotNull(response.errors);
          assert.isFalse(response.success);

          assert.equal(
            response.errors.for("merchant").on("currencies")[0].code,
            ValidationErrorCodes.Merchant.CurrenciesAreInvalid
          );

          done();
        }
      );
    });
  });
});


text:
(function(global) {
	var app = global.app = global.app || {};

	app.changeStatusService = {
		createItem: function(jobId, pStatus) {
			//var newStatus = Status;
			var that = app.jobService.viewModel;
			//console.debug("gotoAccept context: " + e.context);
			var JBs = app.jobService.viewModel.get("jobDataSource");
			var selectProblemC = app.jobService.viewModel.get("selectProblemC");
			var selectProblemCM = app.jobService.viewModel.get("selectProblemCM");
			var selectProblemS = app.jobService.viewModel.get("selectProblemS");

			var itemList = [];
			JBs.filter({
				field: "jobId",
				operator: "eq",
				value: jobId
			});

			JBs.fetch(function() {
                      //console.log("#### JBs Fetch ##### ");
				var view = JBs.view();
				var selectItem
				if (view[0] == undefined){
					selectItem = app.jobService.viewModel.get("selectItem");
				}else{
                	 selectItem = view[0];
				}
				var jobId = selectItem.jobId;
				var statusId = pStatus;
				var newStatus = pStatus;
				var oldStatus = selectItem.statusId;
				var report = selectItem.report;
				var reasonOverdue = "";
				var reportTypeId = "";
				var reportType = "";

				var ttId = selectItem.ttId;
				var trId = selectItem.trId;
				var jbLat = selectItem.latitude;
				var jbLong = selectItem.longtitude;
				var updateDate = moment().unix()*1000;

                      var aamShow;
                      if(selectItem.aamShow == undefined){
                        aamShow = null;
                      }else{
                        aamShow = selectItem.aamShow;
                      }

				var faultAlarmNumber = selectItem.faultAlarmNumber;

				var problemCause = null;
				var problemSolve = null;
				var problemSolveProcess = null;
				var problemCauseMulti = null;

				if (pStatus == "05" && selectItem.statusId != "10") {

					var reasonOverdue = selectItem.reasonOverdueId;
					var reportTypeId = app.jobService.viewModel.get("jobReportType");

					if (selectItem.reportType == "01") {

						if (selectProblemC.data().length == 0) {
							navigator.notification.alert("Please select Problem Cause",
								function() {}, "Change Status : incomplete", 'OK');
							return false;
						}

						selectProblemC.fetch(function() {
							problemCause = [];
							var PC = selectProblemC.view();

							for (var i = 0; i < PC.length; i++) {
								var str = PC[i].problemCauseMainId + "|" + PC[i].problemCauseSubId;

								problemCause.push(str);
							}
						});

						selectProblemS.fetch(function() {
							problemSolve = [];
							problemSolveProcess = [];
							var PS = selectProblemS.view();

							for (var i = 0; i < PS.length; i++) {
								var str = PS[i].problemSolveId + "|" + PS[i].process + "|N|" + PS[i].subProblemCauseId;

								problemSolve.push(str);

								if (PS[i].processDesc != null && PS[i].processDesc != undefined && PS[i].processDesc != "") {

									str = PS[i].problemSolveId + "|" + PS[i].processDesc;

									problemSolveProcess.push(str);
								}
							}
						});

					} else if (selectItem.reportType == "02") {

						if (selectProblemCM.data().length == 0) {
							navigator.notification.alert("Please select Problem Cause",
								function() {}, "Change Status : incomplete", 'OK');
							return false;
						}

						selectProblemCM.fetch(function() {
							problemCauseMulti = [];
							var PCM = selectProblemCM.view();

							for (var i = 0; i < PCM.length; i++) {

								var arrMulti = PCM[i].multiCauseIds.split("|");
								var result = [];
								for (var j = 0; j < arrMulti.length; j++) {
									var str = arrMulti[j] + "#" + (j + 1);

									result.push(str);
								}

								var str = result.join("|");

								problemCauseMulti.push(str);
							}
						});

						selectProblemS.fetch(function() {
							problemSolve = [];
							var PS = selectProblemS.view();

							for (var i = 0; i < PS.length; i++) {
								var str = PS[i].problemSolveId + "|" + PS[i].process + "|N|" + PS[i].subProblemCauseId;

								problemSolve.push(str);
							}
						});
					}
				}

				// >>>> JB
				var jbList = [];
				var itemsAttr = {};
				itemsAttr.jobId = jobId;
				itemsAttr.statusId = statusId; //newstatus

				itemsAttr.newStatus = newStatus;
				itemsAttr.oldStatus = oldStatus;

				itemsAttr.report = report;

				itemsAttr.reasonOverdue = reasonOverdue;
				itemsAttr.reportTypeId = reportTypeId;
				itemsAttr.reportType = reportType;

				itemsAttr.trId = trId;
				itemsAttr.faultAlarmNumber = faultAlarmNumber;
				itemsAttr.jbLat = jbLat;
				itemsAttr.jbLong = jbLong;
				itemsAttr.aamShow = aamShow;

				itemsAttr.updateDate = updateDate;

				jbList.push(itemsAttr);
				// <<<<

				// >>>> TT
				var ttList = [];
				var itemsAttr = {};
				itemsAttr.ttId = ttId;
				ttList.push(itemsAttr);
				// <<<<

				// >>>> problemSolve
				var problemSolveList = [];
				var itemsAttr = {};
				itemsAttr.problemSolve = problemSolve;
				problemSolveList.push(itemsAttr);
				// <<<<

				// >>>> problemCause
				var problemCauseList = [];
				var itemsAttr = {};
				itemsAttr.problemCause = problemCause;
				problemCauseList.push(itemsAttr);
				// <<<<

				// >>>> equipment
				var equipmentList = [];
				var itemsAttr = {};
				equipmentList.push(itemsAttr);
				// <<<<

				// >>>> problemCauseMulti
				var problemCauseMultiList = [];
				var itemsAttr = {};
				itemsAttr.problemCauseMulti = problemCauseMulti;
				problemCauseMultiList.push(itemsAttr);
				// <<<<

				// >>>> problemCauseMulti
				var problemSolveProcessList = [];
				var itemsAttr = {};
				itemsAttr.problemSolveProcess = problemSolveProcess;
				problemSolveProcessList.push(itemsAttr);
				// <<<<

				// >>>> paramList (all parameter from page)
				var paramList = [];
				var itemsAttr = {};
				paramList.push(itemsAttr);
				// <<<<

				var dataValue = {};
				dataValue.token = localStorage.getItem("token");
				dataValue.version = '2';
				dataValue.userId = JSON.parse(localStorage.getItem("profileData")).userId;

				itemList = {};
				itemList.paramList = paramList;
				itemList.jbList = jbList;
				itemList.ttList = ttList;
				itemList.problemCauseList = problemCauseList;
				itemList.problemSolveList = problemSolveList;
				itemList.equipmentList = equipmentList;
				itemList.problemCauseMultiList = problemCauseMultiList;
				itemList.problemSolveProcessList = problemSolveProcessList;
			});
			console.log('create itemList complete');
			return itemList;

		},
		createItemMulti: function(jobId, pStatus) {
			//var newStatus = Status;
			var that = app.jobService.viewModel;
			//console.debug("gotoAccept context: " + e.context);
			var JBs = app.multiService.viewModel.get("jobMultiDataSource");
			var selectProblemC = [];//app.jobService.viewModel.get("selectProblemC");
			var selectProblemCM = [];//app.jobService.viewModel.get("selectProblemCM");
			var selectProblemS = [];//app.jobService.viewModel.get("selectProblemS");

			var itemList = [];
			JBs.filter({
				field: "jobId",
				operator: "eq",
				value: jobId
			});

			JBs.fetch(function() {
				var view = JBs.view();

				var selectItem = view[0];
				var jobId = selectItem.jobId;
				var statusId = pStatus;
				var newStatus = pStatus;
				var oldStatus = selectItem.statusId;
				var report = selectItem.report;
				var reasonOverdue = "";
				var reportTypeId = "";
				var reportType = "";

				var ttId = selectItem.ttId;
				var trId = selectItem.trId;
				var jbLat = selectItem.latitude;
				var jbLong = selectItem.longtitude;
				var aamShow = selectItem.aamShow;

				var updateDate =  moment().unix()*1000;

				var faultAlarmNumber = selectItem.faultAlarmNumber;

				var problemCause = null;
				var problemSolve = null;
				var problemSolveProcess = null;
				var problemCauseMulti = null;

				// >>>> JB
				var jbList = [];
				var itemsAttr = {};
				itemsAttr.jobId = jobId;
				itemsAttr.statusId = statusId; //newstatus

				itemsAttr.newStatus = newStatus;
				itemsAttr.oldStatus = oldStatus;

				itemsAttr.report = report;

				itemsAttr.reasonOverdue = reasonOverdue;
				itemsAttr.reportTypeId = reportTypeId;
				itemsAttr.reportType = reportType;

				itemsAttr.trId = trId;
				itemsAttr.jbLat = jbLat;
				itemsAttr.jbLong = jbLong;
				itemsAttr.aamShow = aamShow;

				itemsAttr.updateDate = updateDate;

				jbList.push(itemsAttr);
				// <<<<

				// >>>> TT
				var ttList = [];
				var itemsAttr = {};
				itemsAttr.ttId = ttId;
				ttList.push(itemsAttr);
				// <<<<

				// >>>> problemSolve
				var problemSolveList = [];
				var itemsAttr = {};
				itemsAttr.problemSolve = problemSolve;
				problemSolveList.push(itemsAttr);
				// <<<<

				// >>>> problemCause
				var problemCauseList = [];
				var itemsAttr = {};
				itemsAttr.problemCause = problemCause;
				problemCauseList.push(itemsAttr);
				// <<<<

				// >>>> equipment
				var equipmentList = [];
				var itemsAttr = {};
				equipmentList.push(itemsAttr);
				// <<<<

				// >>>> problemCauseMulti
				var problemCauseMultiList = [];
				var itemsAttr = {};
				itemsAttr.problemCauseMulti = problemCauseMulti;
				problemCauseMultiList.push(itemsAttr);
				// <<<<

				// >>>> problemCauseMulti
				var problemSolveProcessList = [];
				var itemsAttr = {};
				itemsAttr.problemSolveProcess = problemSolveProcess;
				problemSolveProcessList.push(itemsAttr);
				// <<<<

				// >>>> paramList (all parameter from page)
				var paramList = [];
				var itemsAttr = {};
				paramList.push(itemsAttr);
				// <<<<

				var dataValue = {};
				dataValue.token = localStorage.getItem("token");
				dataValue.version = '2';
				dataValue.userId = JSON.parse(localStorage.getItem("profileData")).userId;

				itemList = {};
				itemList.paramList = paramList;
				itemList.jbList = jbList;
				itemList.ttList = ttList;
				itemList.problemCauseList = problemCauseList;
				itemList.problemSolveList = problemSolveList;
				itemList.equipmentList = equipmentList;
				itemList.problemCauseMultiList = problemCauseMultiList;
				itemList.problemSolveProcessList = problemSolveProcessList;
			});

			return itemList;

		},
		checkReq: function(pStatus) {
         console.log("###### checkReq #########");
			var that = app.jobService.viewModel;
			var selectItem = that.get("selectItem");
			var loadReportType = that.get("loadReportType");
			if(pStatus == "05" && selectItem.statusId == "10"){

				if (selectItem.report == undefined || selectItem.report == null || selectItem.report == "") {
					navigator.notification.alert("Please fill Report Detail",
						function() {}, "Change Status Job : Save incomplete!", 'OK');
					console.log("Report Detail Require!");
					return false;
				}else{
					return true;
				}

			}
			else if (pStatus == "05") {
				console.log("###### checkReq Job Report Type#########");
				if (jobReportType == undefined || jobReportType == null || jobReportType == "") {
					navigator.notification.alert("Please select Job Report Type",
						function() {}, "Change Status Job : Save incomplete!", 'OK');

					console.log("Job Report Type Require!");
					return false;
				}

				console.log("###### checkReq Job Report Type 1#########");
				if (selectItem.reportType == "01") {
					var selectProblemC = that.get("selectProblemC");
					console.log("###### checkReq selectProblemC#########");
					var flag = true;
					selectProblemC.fetch(function() {
						var view = selectProblemC.view();
						if (view.length == 0) {
							navigator.notification.alert("Please select Problem Cause.",
								function() {}, "Change Status Job : Save incomplete!", 'OK');

							flag = false;
						}
					});

					if (!flag) {
						return false;
					}
					console.log("###### checkReq selectProblem Solve#########");
					if (!app.changeStatusService.checkProblemSolve()) {
						navigator.notification.alert("Please select problem solve.",
							function() {
								return false;
							}, "Change Status Job : Save incomplete!", 'OK');
						return false;
					}
				} else {
//                  console.log("###### check problemCm #########");
//					var selectProblemCM = that.get("selectProblemCM");
//
//					selectProblemCM.fetch(function() {
//						var view = selectProblemCM.view();
//						if (view.length == 0) {
//							navigator.notification.alert("Please select Problem Cause.",
//								function() {}, "Change Status Job : Save incomplete!", 'OK');
//							console.log("#### Problem Cause Multi Require! 4");
//							return false;
//						}
//					});

					//if (!app.changeStatusService.checkProblemSolve()) {
					//	return false;
					//}
				}

				var isReason;

				//var that = app.jobService.viewModel;

				//var selectItem = that.get("selectItem");
				var selectedStatus = that.get("selectedStatus");

				if (selectItem.statusId < "05" && selectedStatus == "05") {
					if ((selectItem.finishDate / 1000) < moment().unix()) {
						isReason = true;
					}
				} else if (selectItem.statusId == "05") {
					isReason = true;
				} else {
					isReason = false;
				}

				console.log("###### checkReq Reason#########");
				if (isReason) {
					if (selectItem.reasonOverdueDesc == undefined || selectItem.reasonOverdueDesc == null || selectItem.reasonOverdueDesc == "") {
						navigator.notification.alert("Please select Reason over Due",
							function() {}, "Change Status Job : Save incomplete!", 'OK');
						////console.log("Reason over Due Require!");
						return false;
					}
				}

				console.log("###### checkReq report#########");
				if (selectItem.report == undefined || selectItem.report == null || selectItem.report == "") {
					navigator.notification.alert("Please fill Report Detail",
						function() {}, "Change Status Job : Save incomplete!", 'OK');
					////console.log("Report Detail Require!");
					return false;
				}
			}
			console.log("###### checkReq pass#########");
			return true;
		},
		checkProblemSolve: function() {
			var that = app.jobService.viewModel;
			var flag = false;

			var selectProblemC = that.get("selectProblemC");
			var selectProblemCM = that.get("selectProblemCM");

			var selectProblemS = that.get("selectProblemS");

			var problemSolveData = new kendo.data.DataSource({
				transport: {
					read: function(operation) {
						operation.success(JSON.parse(localStorage.getItem("problemSolveData")));
					}
				},
				filter: {
					logic: "and",
					filters: [{
						field: "description",
						operator: function(left, fieldExpression) {
							return left.indexOf(fieldExpression()) < 0;
						},
						value: function(a) {
							return "Permanent";
						}
					}, {
						field: "description",
						operator: function(left, fieldExpression) {
							return left.indexOf(fieldExpression()) < 0;
						},
						value: function(a) {
							return "Temporary";
						}
					}]

				},
				schema: {
					data: "problemSolves"
				}
			});

			problemSolveData.fetch(function() {
				problemSolveFilter = new kendo.data.DataSource({
					data: problemSolveData.view()
				});

				var filter = {
					logic: "or",
					filters: []
				}

				if (selectProblemC != undefined && selectProblemC != null) {

					var data = selectProblemC.data();
					for (var i = 0; i < data.length; i++) {
						var filters = {
							field: "subproblemCauseId",
							operator: "eq",
							value: data[i].problemCauseSubId
						};
						filter.filters.push(filters);
					}
				}

				if (selectProblemCM != undefined && selectProblemCM != null) {

					var data = selectProblemCM.data();
					for (var i = 0; i < data.length; i++) {
						var filters = {
							field: "subproblemCauseId",
							operator: "eq",
							value: data[i].problemCauseSubId
						};
						filter.filters.push(filters);
					}

				}

				if ((selectProblemC != undefined && selectProblemC != null) || (selectProblemCM != undefined && selectProblemCM != null)) {

					problemSolveFilter.filter(filter);
					problemSolveFilter.group({
						field: "subproblemCauseId",
						aggregates: [{
							field: "subproblemCauseId",
							aggregate: "count"
						}]
					});

					////console.log(JSON.stringify(problemSolveFilter));

					problemSolveFilter.fetch(function() {
						var temp = problemSolveFilter.view();

						if (temp.length == 0) {
							flag = true;
						}
						if (!flag) {
							var selectS;
							var ds;
							selectProblemS.fetch(function() {
								selectS = selectProblemS.data();
								ds = new kendo.data.DataSource({
									data: selectS
								});

							});

							var arr = [];
							for (var i = 0; i < temp.length; i++) {

								if (temp[i].aggregates.subproblemCauseId.count > 0) {
									ds.filter({
										logic: "and",
										filters: [{
											field: "problemSolveDesc",
											operator: function(left, fieldExpression) {
												return left.indexOf(fieldExpression()) < 0;
											},
											value: function(a) {
												return "Permanent";
											}
										}, {
											field: "problemSolveDesc",
											operator: function(left, fieldExpression) {
												return left.indexOf(fieldExpression()) < 0;
											},
											value: function(a) {
												return "Temporary";
											}
										}, {
											field: "subProblemCauseId",
											operator: "eq",
											value: temp[i].value
										}]
									});

									ds.fetch(function() {
										var view = ds.view();

										arr.push(view.length)
									});
								}
							}

							flag = true;

							for (var j = 0, l = arr.length; j < l; j++) {
								if (arr[j] == 0) {
									flag = false;
								}
							};
						}
						return flag;
					});
				}

				////console.log("checkProblemSolve fail!");
			});
			return flag;
		}
	}
})(window);


text:
package term

import "syscall"

const (
	getTermios = syscall.TIOCGETA
	setTermios = syscall.TIOCSETA
)


text:
.. _units:

Units system used
=================

The package makes use of the :mod:`astropy.units` package to handle units and
unit conversions. Several of the options that need to be specified in the
functions described below require :class:`~astropy.units.quantity.Quantity`
instances. Defining quantities is straightforward::

    from astropy import units as u

    # Define scalar quantity
    q1 = 3. * u.kpc

    # Define array quantity using a list
    q2 = [1., 2., 3.] * u.arcsec

    # Define array quantity using a Numpy array
    q3 = np.array([1., 2., 3.]) * u.cm ** 2 / u.g


text:
import primes, lists

num = 600851475143
primeFactors = []
currNum = num/primes.findPrimeFactor(num)
primeFactors.append(primes.findPrimeFactor(num))
while primes.isComposite(currNum):
	currNum = currNum/primes.findPrimeFactor(currNum)
	primeFactors.append(primes.findPrimeFactor(currNum))

print primeFactors

print "The largest prime factor is:\n%s" % (primeFactors[len(primeFactors) - 1])


text:
<?php

namespace tutoria\helloBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class tutoriahelloBundle extends Bundle
{
}


text:
package impl

import (
	"encoding/json"
	"errors"
	"github.com/vaporz/turbo/test/testservice/gen/proto"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

// RegisterServer registers a service struct to a server
func RegisterServer(s *grpc.Server) { // todo move to main.go
	proto.RegisterTestServiceServer(s, &TestService{})
	proto.RegisterMinionsServiceServer(s, &MinionsService{})
}

// TestService is the struct which implements generated interface
type TestService struct {
}

// SayHello is an example entry point
func (s *TestService) SayHello(ctx context.Context, req *proto.SayHelloRequest) (*proto.SayHelloResponse, error) {
	if req.BoolValue {
		bytes, err := json.Marshal(req)
		if err != nil {
			return &proto.SayHelloResponse{}, err
		}
		return &proto.SayHelloResponse{Message: string(bytes)}, nil
	}
	if req.YourName == "error" {
		return &proto.SayHelloResponse{}, errors.New("grpc error")
	}
	trailer := metadata.Pairs("trailer-key", "trailerval")
	grpc.SetTrailer(ctx, trailer)
	header := metadata.Pairs("header-key", "headerval")
	grpc.SetHeader(ctx, header)
	return &proto.SayHelloResponse{Message: "[grpc server]Hello, " + req.YourName}, nil
}

func (s *TestService) TestJson(ctx context.Context, req *proto.TestJsonRequest) (*proto.TestJsonResponse, error) {
	return &proto.TestJsonResponse{}, nil
}


text:
id: 67
title: Amor I
date: 2007-06-08T02:28:00+00:00
author: Alvar
layout: post
guid: http://www.acercadelaeducacion.com.ar/?p=67
disqus: true
subclass: 'post'
cover: false
navigation: True
logo: 'assets/images/lain.gif'
cover: 'assets/images/cover1.jpg'
permalink: /2007/06/amor-i-2/
blogger_blog:
  - acercadelaeducacion.blogspot.com
  - acercadelaeducacion.blogspot.com
blogger_permalink:
  - /2007/06/amor-i.html
  - /2007/06/amor-i.html
aktt_tweeted:
  - "1"
podPressPostSpecific:
  - 'a:6:{s:15:"itunes:subtitle";s:15:"##PostExcerpt##";s:14:"itunes:summary";s:15:"##PostExcerpt##";s:15:"itunes:keywords";s:17:"##WordPressCats##";s:13:"itunes:author";s:10:"##Global##";s:15:"itunes:explicit";s:7:"Default";s:12:"itunes:block";s:7:"Default";}'
dsq_thread_id:
  - "2448970172"
bitly_url:
  - http://bit.ly/1ZujoTJ
bitly_hash:
  - 1ZujoTJ
bitly_long_url:
  - http://www.acercadelaeducacion.com.ar/2007/06/amor-i-2/
categories:
  - Alvar
tags:
  - poesía
  - silvio
  - Para Eva y Sol
---
En días de entregas y de parcial, de desilusión electoral.
pienso confirmo y entrego

Soy ciudadano del amor,
llevo dogal de belleza
entre la hombrera y la cabeza,
entre rodilla y cinturón.
Haciendo crítica social
me perfumé de valiente,
creyeron que era disidente
y no era más que natural.

Martí me habló de la    amistad
y creo en él cada día,
aunque la cruda economía
ha dado luz a otra verdad.

El mundo tiene la razón
puesta en el pan, en el diario,
ese señor rudimentario
que nos dará la absolución.

Ciega,
la vida nueva es
como un verso al revés,
como un amor por descifrar,
como un Dios en edad de jugar.
Trino,
vete al destino, al punto que será final,
juega a lo que no jugué
y canta que aunque sin rey mago
sigo en pie.

Seguro estoy requete mal,
debo sufrir algo extraño,
pues ni la hiel ni el desengaño
me dan canción de funeral.

El fin de siglo trae la sien
cebada de pudredumbre,
como invitándome a una lumbre
que prenderá quien ame bien.

Bendito el tiempo que me dio
una canción sin permiso.
Bendito sea el paraíso
algo infernal que me parió.

El día del Armagedón
no quiero estar tras la puerta,
sino soñando bien alerta,
donde esté a salvo de perdón.

Ciega,
la vida nueva es
como un verso al revés,
como un amor por descifrar,
como un Dios en edad de jugar.
Trino,
vete al destino, al punto que será final,
juega a lo que no jugué
y canta que aunque sin rey mago
sigo en pie.

Cuenta Silvio: «Cuando yo estaba en el tercer grado, mi maestra pensaba que yo era anormal. Oí como se lo decía a los padres de una niña, fuera del aula, aunque me esncontraba esperando a que terminara la clase de catecísmo. A mi no me metían en aquella lección porque mi padre lo había prohibido, con la amenaza de ponerme en otra escuela. La hija de auqellos padres que me miraban con arrobada piedad, se llamaba Lupe. Era muy buena y aplicada, era la excelencia anual del colegio y aquel año sus padres estaban preocupados porque sus notas habían bajado un poquito. Ni sus padres ni la maestra podían saber que Lupe, a quien yo amaba como un condenado, nos enredábamos en extensas discuciones espirituales cuyo meollo era la existencia de los tres reyes magos. Ella afirmaba que no existían, que eran nuestros padres, y yo, que no iba a la clase de religión, lo contrario. Un buen ejemplo de cómo el hábito no hace al monje.»

Gracias silvio por tus palabras
gracias flickr por tu imagen de amor


text:
package sun.jvm.hotspot.debugger;

/** This interface specifies how a page is fetched by the PageCache. */

public interface PageFetcher {
  public Page fetchPage(long pageBaseAddress, long numBytes);
}


text:
2.0.0

### Installation

`pip install -r requirements.txt`

### Usage
Open your favorite Terminal and run these commands:

```sh
$ export FLASK_APP=app.py
$ flask run
```

Open a web browser and navigate to: `http://localhost:5000`.


text:
Flying autonomous Parrot AR Drone 2 with Python

# Basic level

- [Lesson 1 - before you takeoff ...](lesson1.md)
- [Lesson 2 - manual control, takeoff, hover, land](lesson2.md)
- [Lesson 3 - logging](lesson3.md)
- [Lesson 4 - fly forward](lesson4.md)
- [Lesson 5 - fly at given height](lesson5.md)
- [Lesson 6 - video recording](lesson6.md)

# Advanced level (cv2)
- flying 8 figure
- simple road detection

# C-extensions
- navigation in the field


text:
<!doctype html>

        <meta charset="utf-8">
        <?php
            $headerItems = Event::fire('html.master.header.start', array());
        ?>
        @foreach($headerItems as $headerItem)
            {!!$headerItem!!}
        @endforeach
        <meta name="viewport" content="width=device-width, initial-scale=1">

        @section('main-head')
            <title>{{@$application->name}}</title>
        @show

        <link rel="stylesheet" href="/vendor/bootleg/cms/css/application.css" />
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,400,600,700,300&subset=latin" rel="stylesheet" type="text/css">

        <?php
            $headerItems = Event::fire('html.master.header.end', array());
        ?>
        @foreach($headerItems as $headerItem)
            {!! $headerItem !!}
        @endforeach

        <?php
            $headerItems = Event::fire('html.body.start', array());
        ?>
        @foreach($headerItems as $headerItem)
            {{$headerItem}}
        @endforeach
        @include('cms::layouts.nav')

                @include('cms::layouts.main_menu')

                    @yield('main-content')

        <?php
            $headerItems = Event::fire('html.body.end', array());
        ?>
        @foreach($headerItems as $headerItem)
            {{$headerItem}}
        @endforeach


text:
import {
  NOT_AUTHENTICATED,
  SIGN_IN,
  AUTH_SUCCESS,
  AUTH_FAILURE,
} from './actionTypes';
import { createActions } from 'redux-actions';

/**
 * Authentication related actions.
 */
const authActions = createActions(
  NOT_AUTHENTICATED,
  SIGN_IN,
  AUTH_SUCCESS,
  AUTH_FAILURE,
);

module.exports = authActions;