text:
package de.javagl.jgltf.model.io.v1;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

import de.javagl.jgltf.impl.v1.Buffer;
import de.javagl.jgltf.impl.v1.GlTF;
import de.javagl.jgltf.impl.v1.Image;
import de.javagl.jgltf.impl.v1.Shader;
import de.javagl.jgltf.model.Optionals;
import de.javagl.jgltf.model.io.Buffers;
import de.javagl.jgltf.model.io.GltfAsset;
import de.javagl.jgltf.model.io.GltfReference;
import de.javagl.jgltf.model.io.IO;
import de.javagl.jgltf.model.v1.BinaryGltfV1;

/**
 * Implementation of the {@link GltfAsset} interface for glTF 1.0.
 */
public final class GltfAssetV1 implements GltfAsset
{
    /**
     * The {@link GlTF}
     */
    private final GlTF gltf;

    /**
     * The optional binary data
     */
    private final ByteBuffer binaryData;

    /**
     * The mapping from (relative) URI strings to the associated external data
     */
    private final Map<String, ByteBuffer> referenceDatas;

    /**
     * Creates a new instance
     *
     * @param gltf The {@link GlTF}
     * @param binaryData The optional binary data
     */
    public GltfAssetV1(GlTF gltf, ByteBuffer binaryData)
    {
        this.gltf = Objects.requireNonNull(gltf, "The gltf may not be null");
        this.binaryData = binaryData;
        this.referenceDatas = new ConcurrentHashMap<String, ByteBuffer>();
    }

    /**
     * Store the given byte buffer under the given (relative) URI string
     *
     * @param uriString The URI string
     * @param byteBuffer The byte buffer
     */
    void putReferenceData(String uriString, ByteBuffer byteBuffer)
    {
        if (byteBuffer == null)
        {
            referenceDatas.remove(uriString);
        }
        else
        {
            referenceDatas.put(uriString, byteBuffer);
        }
    }

    @Override
    public GlTF getGltf()
    {
        return gltf;
    }

    @Override
    public ByteBuffer getBinaryData()
    {
        return Buffers.createSlice(binaryData);
    }

    @Override
    public List<GltfReference> getReferences()
    {
        List<GltfReference> references = new ArrayList<GltfReference>();
        references.addAll(getBufferReferences());
        references.addAll(getImageReferences());
        references.addAll(getShaderReferences());
        return references;
    }

    /**
     * Create a list containing all {@link GltfReference} objects for the
     * buffers that are contained in this model.
     *
     * @return The references
     */
    public List<GltfReference> getBufferReferences()
    {
        List<GltfReference> references = new ArrayList<GltfReference>();
        Map<String, Buffer> buffers = Optionals.of(gltf.getBuffers());
        for (Entry<String, Buffer> entry : buffers.entrySet())
        {
            String bufferId = entry.getKey();
            if (BinaryGltfV1.isBinaryGltfBufferId(bufferId))
            {
                continue;
            }
            Buffer buffer = buffers.get(bufferId);
            String uri = buffer.getUri();
            if (!IO.isDataUriString(uri))
            {
                Consumer<ByteBuffer> target =
                    byteBuffer -> putReferenceData(uri, byteBuffer);
                GltfReference reference =
                    new GltfReference(bufferId, uri, target);
                references.add(reference);
            }
        }
        return references;
    }

    /**
     * Create a list containing all {@link GltfReference} objects for the
     * images that are contained in this model.
     *
     * @return The references
     */
    public List<GltfReference> getImageReferences()
    {
        List<GltfReference> references = new ArrayList<GltfReference>();
        Map<String, Image> images = Optionals.of(gltf.getImages());
        for (Entry<String, Image> entry : images.entrySet())
        {
            String imageId = entry.getKey();
            Image image = entry.getValue();
            if (BinaryGltfV1.hasBinaryGltfExtension(image))
            {
                continue;
            }
            String uri = image.getUri();
            if (!IO.isDataUriString(uri))
            {
                Consumer<ByteBuffer> target =
                    byteBuffer -> putReferenceData(uri, byteBuffer);
                GltfReference reference =
                    new GltfReference(imageId, uri, target);
                references.add(reference);
            }
        }
        return references;
    }

    /**
     * Create a list containing all {@link GltfReference} objects for the
     * shaders that are contained in this model.
     *
     * @return The references
     */
    public List<GltfReference> getShaderReferences()
    {
        List<GltfReference> references = new ArrayList<GltfReference>();
        Map<String, Shader> shaders = Optionals.of(gltf.getShaders());
        for (Entry<String, Shader> entry : shaders.entrySet())
        {
            String shaderId = entry.getKey();
            Shader shader = entry.getValue();
            if (BinaryGltfV1.hasBinaryGltfExtension(shader))
            {
                continue;
            }
            String uri = shader.getUri();
            if (!IO.isDataUriString(uri))
            {
                Consumer<ByteBuffer> target =
                    byteBuffer -> putReferenceData(uri, byteBuffer);
                GltfReference reference =
                    new GltfReference(shaderId, uri, target);
                references.add(reference);
            }
        }
        return references;
    }

    @Override
    public ByteBuffer getReferenceData(String uriString)
    {
        return Buffers.createSlice(referenceDatas.get(uriString));
    }

    @Override
    public Map<String, ByteBuffer> getReferenceDatas()
    {
        return Collections.unmodifiableMap(referenceDatas);
    }

}


text:
import { HttpClient } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { I18n, I18nInjectionToken } from 'app/i18n/i18n';
import { I18nMeta } from 'app/i18n/i18n-meta';
import { isDevServer } from 'app/shared/helper';
import { BehaviorSubject, Observable, Subscription } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';

/**
 * Handles loading of translation keys
 */
@Injectable({
  providedIn: 'root',
})
export class I18nLoadingService {
  locales = I18nMeta.locales();

  isStatic = false;
  i18nRoot: string;
  private resourceCacheKey: string;
  private locale$ = new BehaviorSubject<string>(null);

  constructor(
    @Inject(I18nInjectionToken) private i18n: I18n,
    private http: HttpClient) {
  }

  /**
   * Called just after the application setup. Basically checks for a static locale
   */
  initialize(i18nRoot: string, params: { resourceCacheKey?: string, locale?: string; }) {
    this.i18nRoot = i18nRoot;
    this.resourceCacheKey = params.resourceCacheKey;
    // If running in development mode, read the default translations first
    if (isDevServer()) {
      const hash = I18nMeta.contentHash('en');
      return this.http.get(`${i18nRoot}/i18n.json?h=${hash}`).pipe(
        switchMap((defaultValues) => {
          this.i18n.$defaults(defaultValues);
          return this.load(params.locale);
        }));
    } else {
      return this.load(params.locale);
    }
  }

  /**
   * Loads the translation for the given locale
   */
  private load(localeParam = 'en'): Observable<I18n> {
    // Figure out the locale to use, according to the available ones
    let locale: string;
    if (this.locales.includes(localeParam)) {
      locale = localeParam;
    } else {
      const parts = localeParam.split(/_/g);
      if (this.locales.includes(parts[0])) {
        locale = parts[0];
      } else {
        locale = 'en';
      }
    }

    const url = `${this.i18nRoot}/i18n${locale === 'en' ? '' : '.' + locale}.json?_k=${this.resourceCacheKey}`;
    return this.http.get(url).pipe(
      map(values => {
        this.setLocale(locale, values);
        return this.i18n;
      }),
    );
  }

  /**
   * Adds a new observer subscription for locale change events.
   * The event is only triggered when the translations are fetched
   */
  subscribeForLocale(next?: (locale: string) => void, error?: (error: any) => void, complete?: () => void): Subscription {
    return this.locale$.subscribe(next, error, complete);
  }

  /**
   * Sets the locale and translation values.
   * Shouldn't be called by regular components, only by initializations.
   */
  private setLocale(locale: string, translationValues: any) {
    this.i18n.$initialize(translationValues);
    if (this.locale$.value !== locale) {
      this.locale$.next(locale);
    }
    document.documentElement.lang = locale.toLowerCase();
  }
}

redpajama_set_name: RedPajamaGithub


text:
package nvimutil

import (
	"fmt"
	"go/token"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/neovim/go-client/nvim"

	"github.com/zchee/nvim-go/pkg/config"
)

// SetLoclist set the error results data to current buffer's locationlist.
func SetLoclist(v *nvim.Nvim, loclist []*nvim.QuickfixError) error {
	// setloclist({nr}, {list} [, {action}])
	// v.Call(fname string, result interface{}, args ...interface{})
	if len(loclist) > 0 {
		v.Call("setloclist", nil, 0, loclist)
	} else {
		v.Command("lexpr ''")
	}

	return nil
}

var (
	listtype     ErrorListType
	openlistCmd  func() error
	closelistCmd func() error
	clearlistCmd func() error
	setlistCmd   func(errlist []*nvim.QuickfixError) error
)

// ErrorListType represents a neovim error list type.
type ErrorListType string

const (
	// Quickfix quickfix error list type.
	Quickfix ErrorListType = "quickfix"
	// LocationList locationlist error list type.
	LocationList = "locationlist"
)

func getListCmd(v *nvim.Nvim) {
	listtype = ErrorListType(config.ErrorListType)
	switch listtype {
	case Quickfix:
		openlistCmd = func() error { return v.Command("copen") }
		closelistCmd = func() error { return v.Command("cclose") }
		clearlistCmd = func() error { return v.Command("cgetexpr ''") }
		setlistCmd = func(errlist []*nvim.QuickfixError) error { return v.Call("setqflist", nil, errlist, "r") }
	case LocationList:
		openlistCmd = func() error { return v.Command("lopen") }
		closelistCmd = func() error { return v.Command("lclose") }
		clearlistCmd = func() error { return v.Command("lgetexpr ''") }
		setlistCmd = func(errlist []*nvim.QuickfixError) error { return v.Call("setloclist", nil, 0, errlist, "r") }
	}
}

// ErrorList merges the errlist map items and open the locationlist window.
func ErrorList(v *nvim.Nvim, errors map[string][]*nvim.QuickfixError, keep bool) error {
	if listtype == "" {
		getListCmd(v)
	}

	if errors == nil || len(errors) == 0 {
		defer clearlistCmd()
		return closelistCmd()
	}

	var errlist []*nvim.QuickfixError
	for _, err := range errors {
		errlist = append(errlist, err...)
	}
	if err := SetErrorlist(v, errlist); err != nil {
		return err
	}

	if keep {
		w, err := v.CurrentWindow()
		if err != nil {
			return err
		}
		defer v.SetCurrentWindow(w)
	}
	return openlistCmd()
}

// SetErrorlist set the error results data to Neovim error list.
func SetErrorlist(v *nvim.Nvim, errlist []*nvim.QuickfixError) error {
	if setlistCmd == nil {
		getListCmd(v)
	}

	return setlistCmd(errlist)
}

// ClearErrorlist clear the Neovim error list.
func ClearErrorlist(v *nvim.Nvim, close bool) error {
	if clearlistCmd == nil {
		getListCmd(v)
	}

	if close {
		defer closelistCmd()
	}
	return clearlistCmd()
}

// OpenLoclist open or close the current buffer's locationlist window.
func OpenLoclist(v *nvim.Nvim, w nvim.Window, loclist []*nvim.QuickfixError, keep bool) error {
	if len(loclist) == 0 {
		return v.Command("lclose")
	}

	v.Command("lopen")
	if keep {
		return v.SetCurrentWindow(w)
	}
	return nil
}

// CloseLoclist close the current buffer's locationlist window.
func CloseLoclist(v *nvim.Nvim) error {
	return v.Command("lclose")
}

// SetQuickfix set the error results data to quickfix list.
func SetQuickfix(b *nvim.Batch, qflist []*nvim.QuickfixError) error {
	b.Call("setqflist", nil, qflist)

	return nil
}

// OpenOuickfix open the quickfix list window.
func OpenOuickfix(b *nvim.Batch, w nvim.Window, keep bool) error {
	b.Command("copen")
	if keep {
		b.SetCurrentWindow(w)
	}
	if err := b.Execute(); err != nil {
		return err
	}

	return nil
}

// CloseQuickfix close the quickfix list window.
func CloseQuickfix(v *nvim.Nvim) error {
	return v.Command("cclose")
}

// GotoPos change current buffer from the pos position with 'zz' normal behavior.
func GotoPos(v *nvim.Nvim, w nvim.Window, pos token.Position, cwd string) error {
	fname, line, col := SplitPos(pos.String(), cwd)

	v.Command(fmt.Sprintf("edit %s", fname))
	v.SetWindowCursor(w, [2]int{line, col - 1})
	defer v.Command(`lclose`)

	return v.Command(`normal zz`)
}

// SplitPos parses a string of form 'token.Pos', and return the relative
// filepath from the current working directory path.
func SplitPos(pos string, cwd string) (string, int, int) {
	position := strings.Split(pos, ":")

	fname := position[0]
	line, err := strconv.ParseInt(position[1], 10, 64)
	if err != nil {
		line = 0
	}
	col, err := strconv.ParseInt(position[2], 10, 64)
	if err != nil {
		col = 0
	}

	if strings.HasPrefix(fname, cwd) {
		frel := strings.TrimPrefix(fname, cwd+string(filepath.Separator))
		if fname != frel {
			return frel, int(line), int(col)
		}
	}

	return fname, int(line), int(col)
}


text:
base_dir=$(dirname $0)/..

for file in $base_dir/project/boot/scala-2.8.0/lib/*.jar;
do
  CLASSPATH=$CLASSPATH:$file
done
for file in $base_dir/core/lib_managed/scala_2.8.0/compile/*.jar;
do
  CLASSPATH=$CLASSPATH:$file
done
for file in $base_dir/core/target/scala_2.8.0/*.jar;
do
  CLASSPATH=$CLASSPATH:$file
done
for file in $base_dir/perf/target/scala_2.8.0/*.jar;
do
  CLASSPATH=$CLASSPATH:$file
done

echo $CLASSPATH

if [ -z "$KAFKA_PERF_OPTS" ]; then
  KAFKA_OPTS="-Xmx512M -server -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=3333 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
fi

if [ -z "$JAVA_HOME" ]; then
  JAVA="java"
else
  JAVA="$JAVA_HOME/bin/java"
fi

$JAVA $KAFKA_OPTS -cp $CLASSPATH kafka.perf.KafkaPerfSimulator $@


text:
require('newrelic');

var express = require('express');
    routes = require('./routes');
    app = express();

app.use('/', routes);
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
  console.log('Keg server on port ' + server.address().port);
});

module.exports = app;


text:
local NodeRankingGansnerKNV1993 = {}

-- Imports

local Edge           = require "pgf.gd.deprecated.Edge"
local Node           = require "pgf.gd.deprecated.Node"

local NetworkSimplex = require "pgf.gd.layered.NetworkSimplex"

function NodeRankingGansnerKNV1993:run()

  local simplex = NetworkSimplex.new(self.graph, NetworkSimplex.BALANCE_TOP_BOTTOM)
  simplex:run()
  self.ranking = simplex.ranking

  return simplex.ranking
end

function NodeRankingGansnerKNV1993:mergeClusters()

  self.cluster_nodes = {}
  self.cluster_node = {}
  self.cluster_edges = {}

  self.original_nodes = {}
  self.original_edges = {}

  for _,cluster in ipairs(self.graph.clusters) do

    local cluster_node = Node.new{
      name = 'cluster@' .. cluster.name,
    }
    table.insert(self.cluster_nodes, cluster_node)

    for _,node in ipairs(cluster.nodes) do
      self.cluster_node[node] = cluster_node
      table.insert(self.original_nodes, node)
    end

    self.graph:addNode(cluster_node)
  end

  for _,edge in ipairs(self.graph.edges) do
    local tail = edge:getTail()
    local head = edge:getHead()

    if self.cluster_node[tail] or self.cluster_node[head] then
      table.insert(self.original_edges, edge)

      local cluster_edge = Edge.new{
        direction = Edge.RIGHT,
        weight = edge.weight,
        minimum_levels = edge.minimum_levels,
      }
      table.insert(self.cluster_edges, cluster_edge)

      if self.cluster_node[tail] then
        cluster_edge:addNode(self.cluster_node[tail])
      else
        cluster_edge:addNode(tail)
      end

      if self.cluster_node[head] then
        cluster_edge:addNode(self.cluster_node[head])
      else
        cluster_edge:addNode(head)
      end

    end
  end

  for _,edge in ipairs(self.cluster_edges) do
    self.graph:addEdge(edge)
  end

  for _,edge in ipairs(self.original_edges) do
    self.graph:deleteEdge(edge)
  end

  for _,node in ipairs(self.original_nodes) do
    self.graph:deleteNode(node)
  end
end

function NodeRankingGansnerKNV1993:createClusterEdges()
  for n = 1, #self.cluster_nodes-1 do
    local first_cluster = self.cluster_nodes[n]
    local second_cluster = self.cluster_nodes[n+1]

    local edge = Edge.new{
      direction = Edge.RIGHT,
      weight = 1,
      minimum_levels = 1,
    }

    edge:addNode(first_cluster)
    edge:addNode(second_cluster)

    self.graph:addEdge(edge)

    table.insert(self.cluster_edges, edge)
  end
end

function NodeRankingGansnerKNV1993:removeClusterEdges()
end

function NodeRankingGansnerKNV1993:expandClusters()

  for _,node in ipairs(self.original_nodes) do
    assert(self.ranking:getRank(self.cluster_node[node]))
    self.ranking:setRank(node, self.ranking:getRank(self.cluster_node[node]))
    self.graph:addNode(node)
  end

  for _,edge in ipairs(self.original_edges) do
    for _,node in ipairs(edge.nodes) do
      node:addEdge(edge)
    end
    self.graph:addEdge(edge)
  end

  for _,node in ipairs(self.cluster_nodes) do
    self.ranking:setRank(node, nil)
    self.graph:deleteNode(node)
  end

  for _,edge in ipairs(self.cluster_edges) do
    self.graph:deleteEdge(edge)
  end
end

-- done

return NodeRankingGansnerKNV1993


text:
require 'rubygems'
require 'test/unit/notification'
require 'test/unit'
# require 'active_support'
#require 'action_pack/actioncontroller'

require 'action_controller'
require 'action_controller/integration'
require 'action_controller/test_case'
require 'action_controller/test_process'

require File.join(File.expand_path(File.dirname(__FILE__)), 'mock_mongrel_response')

unless defined?(RAILS_ROOT)
 RAILS_ROOT = ENV["RAILS_ROOT"] || File.dirname(__FILE__)
end

require File.join(File.dirname(__FILE__), "..", "init")

MOCK_CONTROLLER_DIR = File.join(File.expand_path(File.dirname(__FILE__)), 'test_controllers')
require File.join(MOCK_CONTROLLER_DIR, 'application')

ActionController::Routing::Routes.clear!
ActionController::Routing.controller_paths= [ MOCK_CONTROLLER_DIR ]
ActionController::Routing::Routes.draw {|m| m.connect ':controller/:action/:id' }

class MongrelStreamingTest < ActionController::TestCase

  def setup
    @controller = ApplicationController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
  end

  def test_setup
    get 'test'
    assert_equal("test", @response.body)
  end

  def test_render_mongrel_stream_proc
    thing_to_stream = "Hello World"

    get 'test_render_mongrel_stream_proc', :thing_to_stream => thing_to_stream

    response_body = MockMongrelResponse.new.get_body(@response.body)

    assert_equal(thing_to_stream, response_body)
  end

  def test_render_mongrel_stream_proc_with_translation_proc
    thing_to_stream = "Hello World"

    get 'test_render_mongrel_stream_with_custom_translation_proc', :thing_to_stream => thing_to_stream

    response_body = MockMongrelResponse.new.get_body(@response.body)

    assert_equal(thing_to_stream + " and " + thing_to_stream, response_body)
  end

end


text:
layout: docs.hbs
title: Hotswap
---
```csharp
public class GreetingActor : UntypedActor
{
    protected override void OnReceive(object message)
    {
        Pattern.Match(message)
            .With<Greet>(m => {
                Console.WriteLine("Hello {0}", m.Who);
                //this could also be a lambda
                Become(OtherReceive);
            });
    }

    void OtherReceive(object message)
    {
        Pattern.Match(message)
            .With<Greet>(m => {
                Console.WriteLine("You already said hello!");
                //Unbecome() to revert to old behavior
            });
    }
}
```


text:
package misc;

import one.util.streamex.StreamEx;

public class HeadTail {
  public static void main(String[] args) {
    // Breakpoint!
    final long count = StreamEx.of(1, 2, 3, 4).headTail((head, tail) -> tail, () -> StreamEx.of(0)).count();
    System.out.println(count);
  }
}


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

    Modules.prototype.add('halfedge', function (instance) {
        Math.HalfEdgeMesh = HalfEdgeMesh;
    });

    var HalfEdgeMesh = function () {
        this.bounds = new Math.Octree();
        this.halfEdges = [];
        this.vertices = [];
        this.faces = [];
    };

    HalfEdgeMesh.prototype.addVertices = function (vertices) {
        if (arguments.length > 1) this.addVertices.apply(this, arguments);
        if (!Array.isArray(vertices)) return;
        this.bounds.addItems(vertices);
        for (var i = 0; i < vertices.length; i++) {
            var vertex = vertices[i];
            var index = this.vertices.indexOf(vertex);
            if (index < 0) {
                var _halfEdge = null;
                if (!vertex._halfEdge) {
                    _halfEdge = {};
                    _halfEdge.computeNormal = VertexComputeNormal;
                    _halfEdge.getFaces = VertexGetFaces;
                    _halfEdge.outEdges = [];
                    vertex._halfEdge = _halfEdge;
                } else _halfEdge = vertex._halfEdge;
                _halfEdge.ownIndex = this.vertices.length;
                this.vertices.push(vertex);
            } else {
                console.error('addVertices: Adding vertex twice!', vertex);
            }
        }
    };

    HalfEdgeMesh.prototype.addFace = function (vertices) {
        if (arguments.length > 1) return this.addFace.apply(this, arguments);
        if (!Array.isArray(vertices)) return null;
        if (vertices.length >= 3) {
            var he1 = buildEdge(vertices[0], vertices[1]);
            var he2 = buildEdge(vertices[1], vertices[2], he1.face);
            he1.next = he2;
            this.halfEdges.push(he1, he2);

            var last, prev = he2;
            for (var i = 2; i < vertices.length - 1; i++) {
                last = buildEdge(vertices[i], vertices[i + 1], he1.face);
                prev.next = last;
                this.halfEdges.push(last);
                prev = last;
            }
            last = buildEdge(vertices[i], vertices[0], he1.face);
            last.next = he1;
            this.halfEdges.push(last);
            prev.next = last;

            this.faces.push(he1.face);
            return he1.face;
        } else {
            console.error('addFace: 3 or more vertices needed to form a face!');
        }
        return null;
    };

    HalfEdgeMesh.prototype.onVerticesChange = function (vertex) {
        if (this.cache && this.cache.onVerticesChange)
            this.cache.onVerticesChange(vertex);
        this.bounds.onVerticesMove(vertex);
    };

    HalfEdgeMesh.prototype.clear = function () {
        this.halfEdges = [];
        this.vertices = [];
        this.faces = [];
    };

    function buildEdge (start, end, face) {
        var edge = {};
        edge.vertex = end;
        edge.face = face ? face : new HalfEdgeFace(edge);
        edge.opposite = findOppositeEdge(start, end, edge);
        start._halfEdge.outEdges.push(edge);
        edge.next = null;
        return edge;
    }

    function findOppositeEdge(start, end, he) {
        var opposites = end._halfEdge.outEdges.filter(function (he) {
            return he.vertex === start;
        });
        if (opposites.length > 0) {
            var opposite = opposites[0];
            opposite.opposite = he;
            return opposite;
        } else return null;
    }

    function VertexGetFaces () {
        return this.outEdges.map(function (edge) {
            return edge.face;
        });
    }

    function VertexComputeNormal () {
        var normal = [0, 0, 0];
        this.getFaces().forEach(function (face) {
            vec3.add(normal, normal, face.computeRawNormal());
        });
        vec3.normalize(normal, normal);
        return normal;
    }

    var HalfEdgeFace = function (halfEdge) {
        this.halfEdge = halfEdge;
    };

    HalfEdgeFace.prototype.getEdges = function () {
        var output = [];
        var he = this.halfEdge;
        while (he.next !== this.halfEdge) {
            output.push(he);
            he = he.next;
            if (he === null) {
                var a = 0;
            }
        }
        output.push(he);
        return output;
    };

    HalfEdgeFace.prototype.getVertices = function () {
        return this.getEdges().map(function (edge) {
            return edge.vertex;
        });
    };

    HalfEdgeFace.prototype.getVerticesTriangulated = function () {
        var triangulated = [];
        var vertices = this.getVertices();
        for (var i = 0; i < vertices.length - 2; i++) {
            triangulated.push([vertices[0], vertices[i + 1], vertices[i + 2]]);
        }
        return triangulated;
    };

    HalfEdgeFace.prototype.computeRawNormal = function () {
        var normal = [0, 0, 0];
        this.getVerticesTriangulated().forEach(function (triplet) {
            var triangleNormal = computeNormal(triplet[0], triplet[1], triplet[2]);
            vec3.add(normal, normal, triangleNormal);
        });
        return normal;
    };

    HalfEdgeFace.prototype.computeNormal = function () {
        var normal = this.computeRawNormal();
        vec3.normalize(normal, normal);
        return normal;
    };

    HalfEdgeFace.prototype.computeCenter = function () {
        return Math.geo.computePointsCenter(this.getVertices());
    };

    function computeNormal (v1, v2, v3) {
        var tmp1 = vec3.create();
        var tmp2 = vec3.create();
        vec3.sub(tmp1, v2, v1);
        vec3.sub(tmp2, v3, v1);
        vec3.cross(tmp1, tmp1, tmp2);
        return tmp1;
    }
})());


text:
* * *

De: "Hadi Partovi (Code.org) Gracias por registrarse para patrocinar la Hora de Código Usted está haciendo posible que estudiantes a lo largo de Latinoamérica aprendan una Hora de Código que puede cambiar el resto de sus vidas, de octubre 5 al 11, Usted está haciendo posible que estudiantes alrededor del mundo aprendan una Hora de Código que puede cambiar el resto de sus vidas, de Diciembre 7 al 13

* * *

<% hostname = CDO.canonical_hostname('hourofcode.com') %>

# ¡Gracias por inscribirte para ser anfitrión de una Hora de Código!

Usted está haciendo posible para que los estudiantes de todo el mundo aprendan una Hora de Código que puede cambiar el resto de sus vidas, durante los días del 7 al 13 de Diciembre.

*Every* Hour of Code organizer worldwide will receive a gift card to Amazon, iTunes, or Windows Store as a thank-you gift while supplies last. [And there are more awesome prizes](https://<%= hostname %>/prizes).

#### Estaremos en contacto sobre nuevos tutoriales y otras noticias interesantes. ¿Qué puede usted hacer ahora?

## 1. Find a local volunteer to help you with your event.

[Search our volunteer map](https://code.org/volunteer/local) for volunteers who can visit your classroom or video chat remotely to inspire your students about the breadth of possibilities with computer science.

## 1. Corre la voz

We need your help to reach organizers worldwide. Tell your friends about the #HourOfCode. [Use these helpful resources](https://<%= hostname %>/promote/resources) to promote your event.

## 3. Recruit your whole school for the Hour of Code

[Send this email](https://<%= hostname %>/promote/resources#sample-emails) to your principal or [share these handouts](https://<%= hostname %>/promote/resources).

## 4. Pídele a tu compañía que se involucre

[Envia este correo electrónico](https://<%= hostname %>/promover/recursos #muestra-mensajes de correo electrónico) a tu gerente o director general.

## 5. Promote the Hour of Code in your community

Recluta a un grupo local o incluso algunos amigos. [Enviar este correo electrónico](https://<%= hostname %>/recursos #muestra-mensajes de correo electrónico).

Gracias por dirigir el movimiento para dar a cada estudiante la oportunidad de aprender habilidades informáticas fundacionales.

Hadi Partovi
Fundador, Code.org

* * *

 Estás recibiendo este correo electrónico porque usted se registro para la Hora de Código, apoyado por más de 200 socios y organizado por Code.org. Code.org es una 501c3 sin fines de lucro. Nuestra dirección es 1301 5th Ave, Suite 1225, Seattle, WA, 98101. ¿No quieres estos correos? Darse de baja.

![](<%= tracking_pixel %>)


text:
app.controller("myProfileCtrl", function($scope,$rootScope,user, $firebaseArray) {

		/*initialzation and checking*/
		var userAccount = firebase.database().ref("UserAccount");
		$scope.userAccount = $firebaseArray(userAccount);

		$scope.updateRole=function()
		{
			$scope.email=user.email;
			$scope.role=user.role;
			$scope.userName=user.userName;
			$scope.key=user.key;
		}

		$rootScope.$on("updateRole", function(){
			$scope.updateRole();
		    $scope.loadUserData();
		    $scope.initTagList();
		});

		$scope.currUser;
		$scope.password;
		$scope.userIcon;
		$scope.defaultTags=[];
		$scope.addedTags;

		File.prototype.convertToBase64 = function(callback){		//function of  convert uploaded image to base64 image
			var reader = new FileReader();
			reader.onload = function(e) {
				 callback(e.target.result)
			};
			reader.onerror = function(e) {
				 callback(null);
			};
			reader.readAsDataURL(this);
		};

		$scope.fileNameChanged = function (ele) // trigger when user upload a file
		{
		  var file = ele.files[0];
		  if(file.type.length>0&&file.type.substr(0,5)=="image")  // check for the format type of the chose file
		  {
				file.convertToBase64(function(base64)
				{
					$scope.userIcon=base64;
					$scope.$apply();
				//	$('#removeURL').show();
					$('#profilePic').val('');
				});
		  }
		  else
		  {
			  alert("invliad file format");
			  $('#profilePic').val('');
		  }

		}

		$scope.removeImg=function()
		{
			//$('#removeURL').hide();
			$scope.userIcon='image/usericon.png';
			$scope.$apply();

		}

		$scope.removeElementFromArrayByValue=function(value,array)
		{
			array.splice(array.indexOf(value), 1);
		}

		$scope.removeTag=function(tag)
		{
			$scope.removeElementFromArrayByValue(tag,$scope.addedTags);
		}

		$scope.addTag=function()
		{

			var tmpTag=$('#autoComplete').val();

			if(typeof(tmpTag)=="undefined"||tmpTag.trim()=="")
			{
				alert("you should enter a valid tag");
				return;
			}

			if(typeof($scope.addedTags)=="undefined")
			{
				$scope.addedTags=[];
				$scope.addedTags.push(tmpTag);
			}
			else
			{
				if($scope.addedTags.indexOf(tmpTag.trim())>-1)
				{
					alert("you have adde this tag already");
						return;
				}
				else
				{
					$scope.addedTags.push(tmpTag);
				}
			}
			$('#autoComplete').val('');
			//$('#autoComplete').focus();
		}

		$scope.initTagList=function ()
		{
			$.getJSON('tags.json', function(data) {

				$scope.defaultTags=data.data;
				for(var i=0;i<$scope.defaultTags.length;i++)
				{

					$scope.defaultTags[i]=$scope.defaultTags[i]+" ";
				}
				$scope.initAutoComplete();
			});

		}
		$scope.initAutoComplete=function ()
		{
			$( "#autoComplete" ).autocomplete({

				source: function(request, response) {
					var results = $.ui.autocomplete.filter($scope.defaultTags, request.term);
					for(var i=0;i<results.length;i++)
					{
						results[i]=results[i].trim();
					}
					response(results.slice(0, 10));
				}

			}).focus(function() {

				$(this).autocomplete("search"," ");
				$(this).autocomplete( "option", "minLength", 0 );
			});;
		}

		$scope.loadUserData=function()
		{
			firebase.database().ref("UserAccount/"+$scope.key).once('value', function(data)
			{
				$scope.currUser=data.val();
				$scope.addedTags=data.val().tags;
				if(typeof(data.val().icon)!="undefined")
				{
					$scope.userIcon=data.val().icon;
				}
				else
				{
					$scope.userIcon='image/usericon.png';
				}

			});

		}

		$scope.validInputForEditProfile=function()
		{

			if(typeof($scope.currUser.userName)=="undefined"||$scope.currUser.userName.trim()=="")
			{
				alert("some data missed");
				return;

			}
			if(typeof($scope.password)!="undefined"&&$scope.password!="")
			{
				var user = firebase.auth().currentUser;
				user.updatePassword($scope.password).then(function()
				{
					$scope.updateProfileData();
				},
				function(error)
				{
					alert(error);

				});
			}
			else
			{
				$scope.updateProfileData();
			}

		}

		$scope.contactInfoHandler=function(inputData,userData,key)
		{

			if(typeof(inputData)=="undefined"||inputData.trim()=="")
			{
				if(typeof(userData[key])!="undefined")
				{
					delete userData[key];
				}
			}
			else
			{
				userData[key]=inputData;
			}

		}

		$scope.updateProfileData=function()
		{
			firebase.database().ref("UserAccount/"+$scope.key).once('value', function(data)
			{
				var newUserData=data.val();
				newUserData.userName=$scope.currUser.userName;
				if(typeof($scope.addedTags)!="undefined")
				{
					newUserData.tags=$scope.addedTags;
					console.log($scope.addedTags);
				}
				else
				{
					if(newUserData.hasOwnProperty['tags'])
					{
						delete newUserData['tags'];
					}
				}

			$scope.contactInfoHandler($scope.currUser.contactEmail,newUserData,'contactEmail');
			$scope.contactInfoHandler($scope.currUser.contactSkype,newUserData,'contactSkype');
			$scope.contactInfoHandler($scope.currUser.contactPhone,newUserData,'contactPhone');
			$scope.contactInfoHandler($scope.currUser.contactFb,newUserData,'contactFb');
			$scope.contactInfoHandler($scope.currUser.contactTwitter,newUserData,'contactTwitter');
			$scope.contactInfoHandler($scope.currUser.contactGoogle,newUserData,'contactGoogle');
			newUserData.icon=$scope.userIcon;

				firebase.database().ref("UserAccount/"+$scope.key).set(newUserData).then(function(){
					user.userName=$scope.currUser.userName;

					$rootScope.$emit("updataEmailCall", {});
					alert("success");

				});
			});

		}

	});


text:
static inline void OnMainThread(dispatch_block_t block)
{
    // If this is the main thread, then just execute the block; otherwise, dispatch the block.
    if ([NSThread isMainThread])
    {
        block();
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), block);
    }
}

// Executes the specified block off the main thread.
static inline void OffMainThread(dispatch_block_t block)
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block);
}

// Executes the specified block on the main thread after the specified delay.
static inline void OnMainThreadAfterTimeInterval(NSTimeInterval timeInterval, dispatch_block_t block)
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
}

// Executes the specified block on the main thread after the specified delay.
static inline void OffMainThreadAfterTimeInterval(NSTimeInterval timeInterval, dispatch_block_t block)
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInterval * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block);
}

// Executes the specified block on the specified queue.
static inline void OnQueue(dispatch_queue_t queue, dispatch_block_t block)
{
    dispatch_async(queue, block);
}

// Executes the specified block on the specified queue.
static inline void OnQueueAfterTimeInterval(NSTimeInterval timeInterval, dispatch_queue_t queue, dispatch_block_t block)
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInterval * NSEC_PER_SEC)), queue, block);
}

#endif


text:
<?php
declare(strict_types=1);

namespace T3v\T3vContent\ViewHelpers;

use T3v\T3vCore\ViewHelpers\AbstractTagBasedViewHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3Fluid\Fluid\Core\ViewHelper\TagBuilder;

/**
 * The subheadline link view helper class.
 *
 * @package T3v\T3vContent\ViewHelpers
 * @deprecated Use standard view helpers instead, will be removed in a next major version.
 */
class SubheadlineLinkViewHelper extends AbstractTagBasedViewHelper
{
    /**
     * The tag name.
     *
     * @var string
     */
    protected $tagName = 'h2';

    /**
     * Initializes the arguments.
     */
    public function initializeArguments(): void
    {
        parent::initializeArguments();

        $this->registerArgument(
            'content',
            'string',
            'The content of the subheadline'
        );
        $this->registerArgument(
            'layout',
            'int',
            'The optional layout of the subheadline, defaults to `100`',
            false,
            100
        );
        $this->registerArgument(
            'cssClass',
            'string',
            'The optional CSS class of the subheadline, defaults to `ce__subtitle`',
            false,
            'ce__subtitle'
        );
    }

    /**
     * The view helper render function.
     *
     * @return string The rendered subheadline
     */
    public function render(): string
    {
        $subheadline = '';
        $content = (string)$this->arguments['content'];
        $layout = (int)$this->arguments['layout'];
        $cssClass = (string)$this->arguments['cssClass'];

        if (empty($content)) {
            $content = $this->renderChildren();
        }

        if (!empty($content) && $layout !== 0 && $layout !== 100) {
            $layout++;

            $this->tag->setTagName("h$layout");
            $this->tag->addAttribute('class', $cssClass);
            $this->tag->setContent($this->createLink($content)->render());

            $subheadline = $this->tag->render();
        }

        return $subheadline;
    }

    /**
     * Creates a link.
     *
     * @param string $content The content of the link
     * @param string $href The optional href attribute of the link, defaults to `#`
     * @param string|null $title The optional title attribute of the link
     * @return TagBuilder The link
     */
    protected function createLink(string $content, string $href = '#', string $title = null): TagBuilder
    {
        if (empty($title)) {
            $title = $content;
        }

        $link = GeneralUtility::makeInstance(TagBuilder::class);
        $link->setTagName('a');
        $link->addAttribute('href', $href);
        $link->addAttribute('title', $title);
        $link->setContent($content);

        return $link;
    }
}


text:
// Copyright 2004-present Facebook. All Rights Reserved.

#pragma once

#include <atomic>
#include <functional>
#include <iostream>
#include <memory>

#include "yarpl/Refcounted.h"
#include "yarpl/observable/Subscription.h"

namespace yarpl {
namespace observable {

/**
* Implementation that gets a callback when cancellation occurs.
*/
class CallbackSubscription : public Subscription {
 public:
  explicit CallbackSubscription(std::function<void()> onCancel);
  void cancel() override;

 private:
  std::function<void()> onCancel_;
};

class Subscriptions {
 public:
  static std::shared_ptr<Subscription> create(std::function<void()> onCancel);
  static std::shared_ptr<Subscription> create(std::atomic_bool& cancelled);
  static std::shared_ptr<Subscription> create();
};

} // observable namespace
} // yarpl namespace


text:
@implementation AFHTTPRequestOperationManager (AutoRetry)

SYNTHESIZE_ASC_OBJ(__operationsDict, setOperationsDict);
SYNTHESIZE_ASC_OBJ(__retryDelayCalcBlock, setRetryDelayCalcBlock);

- (void)createOperationsDict {
    [self setOperationsDict:[[NSDictionary alloc] init]];
}

- (void)createDelayRetryCalcBlock {
    RetryDelayCalcBlock block = ^int(int totalRetries, int currentRetry, int delayInSecondsSpecified) {
        return delayInSecondsSpecified;
    };
    [self setRetryDelayCalcBlock:block];
}

- (id)retryDelayCalcBlock {
    if (!self.__retryDelayCalcBlock) {
        [self createDelayRetryCalcBlock];
    }
    return self.__retryDelayCalcBlock;
}

- (id)operationsDict {
    if (!self.__operationsDict) {
        [self createOperationsDict];
    }
    return self.__operationsDict;
}

- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
                                                    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                                    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                                                autoRetryOf:(int)retriesRemaining retryInterval:(int)intervalInSeconds {

    void (^retryBlock)(AFHTTPRequestOperation *, NSError *) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        NSMutableDictionary *retryOperationDict = self.operationsDict[request];
        int originalRetryCount = [retryOperationDict[@"originalRetryCount"] intValue];
        int retriesRemainingCount = [retryOperationDict[@"retriesRemainingCount"] intValue];
        if (retriesRemainingCount > 0) {
            NSLog(@"AutoRetry: Request failed: %@, retry %d out of %d begining...",
                    error.localizedDescription, originalRetryCount - retriesRemainingCount + 1, originalRetryCount);
            AFHTTPRequestOperation *retryOperation = [self HTTPRequestOperationWithRequest:request
                                                                                success:success
                                                                                failure:failure
                                                                               autoRetryOf:retriesRemainingCount - 1
                                                                             retryInterval:intervalInSeconds];
            void (^addRetryOperation)() = ^{
                [self.operationQueue addOperation:retryOperation];
            };
            RetryDelayCalcBlock delayCalc = self.retryDelayCalcBlock;
            int intervalToWait = delayCalc(originalRetryCount, retriesRemainingCount, intervalInSeconds);
            if (intervalToWait > 0) {
                NSLog(@"AutoRetry: Delaying retry for %d seconds...", intervalToWait);
                dispatch_time_t delay = dispatch_time(0, (int64_t) (intervalToWait * NSEC_PER_SEC));
                dispatch_after(delay, dispatch_get_main_queue(), ^(void) {
                    addRetryOperation();
                });
            } else {
                addRetryOperation();
            }
        } else {
            NSLog(@"AutoRetry: Request failed %d times: %@", originalRetryCount, error.localizedDescription);
            NSLog(@"AutoRetry: No more retries allowed! executing supplied failure block...");
            failure(operation, error);
            NSLog(@"AutoRetry: done.");
        }
    };
    NSMutableDictionary *operationDict = self.operationsDict[request];
    if (!operationDict) {
        operationDict = [NSMutableDictionary new];
        operationDict[@"originalRetryCount"] = [NSNumber numberWithInt:retriesRemaining];
    }
    operationDict[@"retriesRemainingCount"] = [NSNumber numberWithInt:retriesRemaining];
    NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:self.operationsDict];
    newDict[request] = operationDict;
    self.operationsDict = newDict;
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request
                                                                      success:^(AFHTTPRequestOperation *operation, id responseObj) {
                                                                          NSMutableDictionary *successOperationDict = self.operationsDict[request];
                                                                          int originalRetryCount = [successOperationDict[@"originalRetryCount"] intValue];
                                                                          int retriesRemainingCount = [successOperationDict[@"retriesRemainingCount"] intValue];
                                                                          NSLog(@"AutoRetry: success with %d retries, running success block...", originalRetryCount - retriesRemainingCount);
                                                                          success(operation, responseObj);
                                                                          NSLog(@"AutoRetry: done.");

                                                                      } failure:retryBlock];

    return operation;
}

- (AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure autoRetry:(int)timesToRetry {
    return [self POST:URLString parameters:parameters success:success failure:failure autoRetry:timesToRetry retryInterval:0];
}

- (AFHTTPRequestOperation *)GET:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure autoRetry:(int)timesToRetry {
    return [self GET:URLString parameters:parameters success:success failure:failure autoRetry:timesToRetry retryInterval:0];
}

- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *operation))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure autoRetry:(int)timesToRetry {
    return [self HEAD:URLString parameters:parameters success:success failure:failure autoRetry:timesToRetry retryInterval:0];
}

- (AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure autoRetry:(int)timesToRetry {
    return [self POST:URLString parameters:parameters constructingBodyWithBlock:block success:success failure:failure autoRetry:timesToRetry retryInterval:0];
}

- (AFHTTPRequestOperation *)PUT:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure autoRetry:(int)timesToRetry {
    return [self PUT:URLString parameters:parameters success:success failure:failure autoRetry:timesToRetry retryInterval:0];
}

- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure autoRetry:(int)timesToRetry {
    return [self PATCH:URLString parameters:parameters success:success failure:failure autoRetry:timesToRetry retryInterval:0];
}

- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure autoRetry:(int)timesToRetry {
    return [self DELETE:URLString parameters:parameters success:success failure:failure autoRetry:timesToRetry retryInterval:0];
}

- (AFHTTPRequestOperation *)POST:(NSString *)URLString
                      parameters:(NSDictionary *)parameters
                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                       autoRetry:(int)timesToRetry
                   retryInterval:(int)intervalInSeconds {
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure autoRetryOf:timesToRetry retryInterval:intervalInSeconds];
    [self.operationQueue addOperation:operation];

    return operation;
}

- (AFHTTPRequestOperation *)GET:(NSString *)URLString
                     parameters:(NSDictionary *)parameters
                        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                      autoRetry:(int)timesToRetry
                  retryInterval:(int)intervalInSeconds {
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure autoRetryOf:timesToRetry retryInterval:intervalInSeconds];
    [self.operationQueue addOperation:operation];

    return operation;
}

- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString
                      parameters:(NSDictionary *)parameters
                         success:(void (^)(AFHTTPRequestOperation *operation))success
                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                       autoRetry:(int)timesToRetry
                   retryInterval:(int)intervalInSeconds {
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"HEAD" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *requestOperation, __unused id responseObject) {
        if (success) {
            success(requestOperation);
        }
    }                                                                 failure:failure autoRetryOf:timesToRetry retryInterval:intervalInSeconds];
    [self.operationQueue addOperation:operation];

    return operation;
}

- (AFHTTPRequestOperation *)POST:(NSString *)URLString
                      parameters:(NSDictionary *)parameters
       constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                       autoRetry:(int)timesToRetry
                   retryInterval:(int)intervalInSeconds {
    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:nil];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure autoRetryOf:timesToRetry retryInterval:intervalInSeconds];
    [self.operationQueue addOperation:operation];

    return operation;
}

- (AFHTTPRequestOperation *)PUT:(NSString *)URLString
                     parameters:(NSDictionary *)parameters
                        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                      autoRetry:(int)timesToRetry
                  retryInterval:(int)intervalInSeconds {
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PUT" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure autoRetryOf:timesToRetry retryInterval:intervalInSeconds];
    [self.operationQueue addOperation:operation];

    return operation;
}

- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString
                       parameters:(NSDictionary *)parameters
                          success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                          failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                        autoRetry:(int)timesToRetry
                    retryInterval:(int)intervalInSeconds {
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PATCH" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure autoRetryOf:timesToRetry retryInterval:intervalInSeconds];
    [self.operationQueue addOperation:operation];

    return operation;
}

- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString
                        parameters:(NSDictionary *)parameters
                           success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                           failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                         autoRetry:(int)timesToRetry
                     retryInterval:(int)intervalInSeconds {
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"DELETE" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure autoRetryOf:timesToRetry retryInterval:intervalInSeconds];
    [self.operationQueue addOperation:operation];

    return operation;
}

@end

#pragma clang diagnostic pop


text:
using System;

namespace _3.InvalidRangeException
{
    public class InvalidRangeException<T> : Exception
        where T : struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
    {
       //Properties
        public T StartRange { get; private set; }
        public T EndRange { get; private set; }

        // Constructor
        public InvalidRangeException(T startRange, T endRange)
        {
            this.StartRange = startRange;
            this.EndRange = endRange;
        }
        public InvalidRangeException(T startRange, T endRange, string message)
            : base(message)
        {
            this.StartRange = startRange;
            this.EndRange = endRange;
        }
        public InvalidRangeException(T startRange, T endRange, string message, Exception innerException)
            : base(message, innerException)
        {
            this.StartRange = startRange;
            this.EndRange = endRange;
        }

    }
}


text:
import numpy as np
import cv2
import matplotlib.pyplot as plt

from ivf.batch.batch import DatasetBatch
from ivf.io_util.image import loadNormal, saveNormal
from ivf.core.sfs import amg_constraints
from ivf.core.solver import amg_solver
from ivf.core.sfs.lumo import computeNz
from ivf.cv.normal import normalizeImage
from ivf.np.norm import normalizeVectors

class InitialNormalBatch(DatasetBatch):
    def __init__(self, name="InitialNormal", dataset_name="3dmodel"):
        super(InitialNormalBatch, self).__init__(name, dataset_name)

    def _runImp(self):
        normal_data = loadNormal(self._data_file)

        if normal_data is None:
            return

        N0_32F, A_8U = normal_data

        h, w = A_8U.shape[:2]
        A_c, b_c = amg_constraints.silhouetteConstraints(A_8U, is_flat=True)

        A_L = amg_constraints.laplacianMatrix((h, w), num_elements=3)
        A = A_c + A_L
        b = b_c

        N = amg_solver.solve(A, b).reshape(-1, 3)
        N = computeNz(N)
        N = normalizeVectors(N)
        N_32F = N.reshape(h, w, 3)

        file_path = self.resultFile(self._data_file_name)
        saveNormal(file_path, N_32F, A_8U)

if __name__ == '__main__':
    InitialNormalBatch().run()


text:
package cn.fuyoushuo.fqbb.view.flagment;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.jakewharton.rxbinding.view.RxView;
import com.trello.rxlifecycle.components.support.RxDialogFragment;
import com.umeng.analytics.MobclickAgent;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.fuyoushuo.fqbb.MyApplication;
import cn.fuyoushuo.fqbb.R;
import cn.fuyoushuo.fqbb.commonlib.utils.DateUtils;
import cn.fuyoushuo.fqbb.commonlib.utils.EventIdConstants;
import cn.fuyoushuo.fqbb.commonlib.utils.LocalStatisticConstants;
import cn.fuyoushuo.fqbb.commonlib.utils.PageSession;
import cn.fuyoushuo.fqbb.ext.LocalStatisticInfo;
import cn.fuyoushuo.fqbb.presenter.impl.JdGoodDetailPresenter;
import cn.fuyoushuo.fqbb.presenter.impl.LocalLoginPresent;
import cn.fuyoushuo.fqbb.view.activity.UserLoginActivity;
import cn.fuyoushuo.fqbb.view.view.JdGoodDetailView;
import rx.functions.Action1;

/**
 * 处理京东详情页的相关逻辑
 * Created by QA on 2016/11/3.
 */
public class JdWebviewDialogFragment extends RxDialogFragment implements JdGoodDetailView {

    private String initUrl = "";

    private String currentLoadGoodUrl = "";

    private String currentItemId = "";

    @Bind(R.id.jd_wv)
    WebView myJdWebView;

    LocalLoginPresent localLoginPresent;

    JdGoodDetailPresenter jdGoodDetailPresenter;

    @Bind(R.id.wv_back_area)
    RelativeLayout backView;

    @Bind(R.id.fq_jd_tip_area)
    FrameLayout fanliTipLayout;

    @Bind(R.id.jd_left_tip_text)
    TextView leftTipText;

    @Bind(R.id.jd_right_tip_text)
    TextView rightTipText;

    @Bind(R.id.jd_hide_tip)
    TextView hideTipText;

    @Bind(R.id.show_fanli)
    FrameLayout showFanliLayout;

    @Bind(R.id.jd_wv_close)
    RelativeLayout closeArea;

    private String fromWhere = "main";

    /**
     * 0 默认情况 1 去登陆 2 重新获取CPS链接  3 重新获取商品CPS跳转
     */
    private int leftTipBiz = 0;

    /**
     * 是否登录
     */
    private boolean isLocalLogin = false;

    /**
     * 是否进入返利
     */
    private boolean isHasFanli = false;

    private boolean isFanliState = false;

    private PageSession pageSession;

    @Override
    public void show(FragmentManager manager, String tag) {
        try{
            super.show(manager, tag);
        }catch (Exception e){
            // to do nothing
        }
    }

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

        if (!TextUtils.isEmpty(getArguments().getString("initUrl", ""))) {
            this.initUrl = getArguments().getString("initUrl", "");
            this.currentLoadGoodUrl = "";
            this.currentItemId = "";
        }
        pageSession = new PageSession(LocalStatisticConstants.JD);
        fromWhere = getArguments().getString("fromWhere","main");
        setStyle(DialogFragment.STYLE_NORMAL, R.style.fullScreenDialog);
        localLoginPresent = new LocalLoginPresent();
        jdGoodDetailPresenter = new JdGoodDetailPresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.flagment_jd_webview, container);
        ButterKnife.bind(this, inflate);
        // TODO: 2016/11/3  初始化VIEW
        myJdWebView.getSettings().setJavaScriptEnabled(true);
        //myWebView.getSettings().setBuiltInZoomControls(true);//是否显示缩放按钮,默认false
        myJdWebView.getSettings().setSupportZoom(true);//是否可以缩放,默认true
        myJdWebView.getSettings().setDomStorageEnabled(true);

        myJdWebView.getSettings().setUseWideViewPort(true);// 设置此属性,可任意比例缩放。大视图模式
        myJdWebView.getSettings().setLoadWithOverviewMode(true);// 和setUseWideViewPort(true)一起解决网页自适应问题

        myJdWebView.requestFocusFromTouch();
        myJdWebView.setWebChromeClient(new WebChromeClient());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            myJdWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(myJdWebView, true);
        }

        if(Build.VERSION.SDK_INT <= 18){
            myJdWebView.getSettings().setSavePassword(false);
        }

        myJdWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                 if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("www://")) {
                    String replaceUrl = url.replace("https://", "").replace("http://", "");
                    //http://item.m.jd.com/ware/view.action?wareId=3332179
                    if (isPageGoodDetail(url) && url.indexOf("jd_pop") == -1) {
                        if (!url.contains("#ns")) {
                            String itemId = getJdItemId(replaceUrl);
                            loadGoodPage(itemId);
                        }
                    }
                }
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (jdGoodDetailPresenter.isUserFanqianMode(url)) {
                    MobclickAgent.onEvent(MyApplication.getContext(),EventIdConstants.NUMBER_OF_FANLI_FOR_JD);
                    leftTipText.setText("返钱模式");
                    leftTipText.setClickable(false);
                    fanliTipLayout.setVisibility(View.VISIBLE);
                    return false;
                }
                if (isPageGoodDetail(url) && url.indexOf("jd_pop") > -1){
                    isFanliState = true;
                }
                if(isPageGoodDetail(url) && url.contains("#ns")){
                    Log.d("jdGoodDetail",url);
                    return false;
                }
                if(url.replace("http://","").replace("https://","").startsWith("pay.m.jd.com/cpay/finish.html")){
                     MobclickAgent.onEvent(MyApplication.getContext(),EventIdConstants.SUCCESS_BUY_FOR_JD);
                }

                //http://p.m.jd.com/norder/order.action?wareId=1750531&wareNum=1&enterOrder=true&sid=13c72c6665914925103c4af7aff54ebe
                //付款的时候拦截
                if(url.replace("http://","").replace("https://","").startsWith("p.m.jd.com/norder/order.action") && url.indexOf("wareNum=1") > -1 && url.indexOf("enterOrder") > -1){
                     if(!isHasFanli){
                         return false;
                     }else{
                         if(!isLocalLogin){
                             showFanliLoginDialog();
                             return true;
                         }
                     }
                }
                //购物车结算时拦截
                //http://p.m.jd.com/norder/order.action?sid=b13ffb9032fbd3a26dc0471717cb454f&flowType=&page_param=
                else if(url.replace("http://","").replace("https://","").startsWith("p.m.jd.com/norder/order.action") && url.indexOf("wareNum=1") == -1 && url.indexOf("enterOrder") > -1){
                    myJdWebView.post(new Runnable() {
                        @Override
                        public void run() {
                            showFanliTipDialogWhenClickBalance();
                        }
                    });
                }
                return false;
            }

            //兼容 android 5.0 以上
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public WebResourceResponse shouldInterceptRequest(final WebView webView, WebResourceRequest webResourceRequest) {
                String url = webResourceRequest.getUrl().toString();
                if(isHasFanli && !isFanliState && !TextUtils.isEmpty(url) && url.replace("http://","").replace("https://","").startsWith("p.m.jd.com/cart/add.json")){
                    myJdWebView.post(new Runnable() {
                        @Override
                        public void run() {
                            showFanliTipDialogWhenClickCart();
                        }
                    });
                     String result = "{}";
                     InputStream resultInputStream = null;
                    try {
                        resultInputStream = new ByteArrayInputStream(result.getBytes("utf-8"));
                        WebResourceResponse webResourceResponse = new WebResourceResponse("application/json","utf-8",resultInputStream);
                        return webResourceResponse;
                    } catch (UnsupportedEncodingException e) {
                        return null;
                    }finally {
                        if(resultInputStream != null){
                            try {
                                resultInputStream.close();
                            } catch (IOException e) {

                            }
                        }
                    }
                }
                return null;
            }

            //兼容 android 4.4 及以上
            @Override
            public WebResourceResponse shouldInterceptRequest(final WebView view, final String url) {//也能拦截iframe的链接,图片,css,js等
                if(isHasFanli && !isFanliState && !TextUtils.isEmpty(url) && url.replace("http://","").replace("https://","").startsWith("p.m.jd.com/cart/add.json")){
                    myJdWebView.post(new Runnable() {
                        @Override
                        public void run() {
                            showFanliTipDialogWhenClickCart();
                        }
                    });
                    String result = "{}";
                    InputStream resultInputStream = null;
                    try {
                        resultInputStream = new ByteArrayInputStream(result.getBytes("utf-8"));
                        WebResourceResponse webResourceResponse = new WebResourceResponse("application/json","utf-8",resultInputStream);
                        return webResourceResponse;
                    } catch (UnsupportedEncodingException e) {
                        return null;
                    }finally {
                        if(resultInputStream != null){
                            try {
                                resultInputStream.close();
                            } catch (IOException e) {

                            }
                        }
                    }
                }
                return super.shouldInterceptRequest(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                //统计页面跳转
                try {
                    LocalStatisticInfo.getIntance().appWvLoad(URLEncoder.encode(url,"utf-8"),"");
                } catch (Exception e) {
                }
                if (jdGoodDetailPresenter.isUserFanqianMode(url)) {
                    fanliTipLayout.setVisibility(View.VISIBLE);
                } else if (isPageGoodDetail(url)) {
                    fanliTipLayout.setVisibility(View.VISIBLE);
                } else {
                    fanliTipLayout.setVisibility(View.GONE);
                    showFanliLayout.setVisibility(View.GONE);
                }
                String js = "var rmadjs = document.createElement(\"script\");";
                js += "rmadjs.src=\"//www.fanqianbb.com/static/mobile/rmadjd.js\";";
                js += "document.body.appendChild(rmadjs);";
                view.loadUrl("javascript:" + js);
                super.onPageFinished(view, url);
            }
        });
        return inflate;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        RxView.clicks(backView).compose(this.<Void>bindToLifecycle()).throttleFirst(1000, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        goback();
                    }
                });

        RxView.clicks(leftTipText).compose(this.<Void>bindToLifecycle()).throttleFirst(1000, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (leftTipBiz == 0) return;
                        else if (leftTipBiz == 1) {
                            Intent intent = new Intent(getActivity(), UserLoginActivity.class);
                            if("main".equals(fromWhere)){
                                intent.putExtra("biz", "MainToJdWv");
                            }
                            else if("search".equals(fromWhere)){
                                intent.putExtra("biz","SearchToJdWv");
                            }
                            startActivity(intent);
                        }
                        else if (leftTipBiz == 2) {

                        }
                    }
                });

        RxView.clicks(hideTipText).compose(this.<Void>bindToLifecycle()).throttleFirst(1000, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if(fanliTipLayout.isShown()){
                             fanliTipLayout.setVisibility(View.GONE);
                             showFanliLayout.setVisibility(View.VISIBLE);
                        }
                    }
                });

        RxView.clicks(showFanliLayout).compose(this.<Void>bindToLifecycle()).throttleFirst(1000,TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                         if(!(fanliTipLayout.isShown())){
                             showFanliLayout.setVisibility(View.GONE);
                             fanliTipLayout.setVisibility(View.VISIBLE);
                         }
                    }
                });

        RxView.clicks(closeArea).compose(this.<Void>bindToLifecycle()).throttleFirst(1000,TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        dismissAllowingStateLoss();
                    }
                });

        if (myJdWebView != null) {
            myJdWebView.loadUrl(initUrl);
        }
    }

    @Override
    public void onDestroy() {
        if (myJdWebView != null) {
            ViewGroup viewGroup = (ViewGroup) myJdWebView.getParent();
            if(viewGroup!=null){
                viewGroup.removeView(myJdWebView);
            }
            myJdWebView.removeAllViews();
            myJdWebView.destroy();
        }
        localLoginPresent.onDestroy();
        jdGoodDetailPresenter.onDestroy();
        ButterKnife.unbind(this);
        super.onDestroy();
    }

    //http://mitem.jd.hk/product/3336062.html?sid=6891dd56029cece0e25bbf3a7ea56e69
    //http://mitem.jd.hk/ware/view.action?wareId=2457625&cachekey=3114863cc00f80
    private boolean isPageGoodDetail(String url) {
        if (TextUtils.isEmpty(url)) return false;
        String replaceUrl = url.replace("http://", "").replace("https://", "");
        if (replaceUrl.startsWith("item.m.jd.com/ware/view.action")) {
            return true;
        } else if (replaceUrl.startsWith("item.m.jd.com/product/")) {
            return true;
        } else if (replaceUrl.startsWith("mitem.jd.hk/product/")){
            return true;
        } else if(replaceUrl.startsWith("mitem.jd.hk/ware/view.action")){
            return true;
        }
        return false;
    }

    //获取商品的id
    private String getJdItemId(String url) {
        String result = "";
        if (TextUtils.isEmpty(url)) return result;
        //http://item.m.jd.com/ware/view.action?wareId=3332179
        if (url.startsWith("item.m.jd.com/ware/view.action") || url.startsWith("mitem.jd.hk/ware/view.action")) {
            String groupResult = "";
            Pattern pattern = Pattern.compile("wareId=([0-9]*)");
            Matcher matcher = pattern.matcher(url);
            if (matcher.find()) {
                groupResult = matcher.group(1);
            }
            if (!TextUtils.isEmpty(groupResult)) result = groupResult;
        }
        //http://item.m.jd.com/product/10076124548.html?sid=dbfc3c8a253faf33265f643e30780ebf
        if (url.startsWith("item.m.jd.com/product/") || url.startsWith("mitem.jd.hk/product/")) {
            String groupResult = "";
            Pattern pattern = Pattern.compile("/product/([0-9]*)\\.html");
            Matcher matcher = pattern.matcher(url);
            if (matcher.find()) {
                groupResult = matcher.group(1);
            }
            if (!TextUtils.isEmpty(groupResult)) result = groupResult;
        }
        return result;
    }

    private void showFanliLoginDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("登录到返利模式才会获得返利!");

        builder.setCancelable(false);
        builder.setPositiveButton("返利登录", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(getActivity(), UserLoginActivity.class);
                if("main".equals(fromWhere)){
                   intent.putExtra("biz", "MainToJdWv");
                }
                else if("search".equals(fromWhere)){
                   intent.putExtra("biz","SearchToJdWv");
                }
                startActivity(intent);
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    //加入购物车的时候进行提示
    private void showFanliTipDialogWhenClickCart() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("在返利模式下加入购物车的商品才能获得返利,亲!");
        builder.setCancelable(false);
        builder.setPositiveButton("去登录", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(getActivity(), UserLoginActivity.class);
                if("main".equals(fromWhere)){
                    intent.putExtra("biz", "MainToJdWv");
                }
                else if("search".equals(fromWhere)){
                    intent.putExtra("biz","SearchToJdWv");
                }
                startActivity(intent);
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    //点击加入购物车结算进行拦截
    private void showFanliTipDialogWhenClickBalance(){
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("只有在返利模式下加入购物车的商品才能返还返利,亲!");
        builder.setCancelable(false);
        builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    //获取当前商品的页面
    private void loadGoodPage(final String itemId) {
        if (TextUtils.isEmpty(itemId)) return;
        MobclickAgent.onEvent(MyApplication.getContext(), EventIdConstants.BROWSE_JD_GOODS_NUM);
        final String loadUrl = "http://item.m.jd.com/product/" + itemId + ".html";
        isFanliState = false;
        currentLoadGoodUrl = loadUrl;
        currentItemId = itemId;
        fanliTipLayout.setVisibility(View.VISIBLE);
        localLoginPresent.isFqbbLocalLogin(new LocalLoginPresent.LoginCallBack() {
            @Override
            public void localLoginSuccess() {
                leftTipText.setText("处理中");
                leftTipText.setClickable(false);
                isLocalLogin = true;
                jdGoodDetailPresenter.getJdFanliInfo(itemId, loadUrl);
            }

            @Override
            public void localLoginFail() {
                // TODO: 2016/11/3 提示登录
                isLocalLogin = false;
                leftTipText.setText("去登录");
                leftTipText.setClickable(true);
                leftTipBiz = 1;
                jdGoodDetailPresenter.getJdFanliInfo(itemId,"");
            }
        });
    }

    public void reloadGoodPage() {
        if(TextUtils.isEmpty(currentItemId) || TextUtils.isEmpty(currentLoadGoodUrl)){
            return;
        }else{
            isLocalLogin = true;
            jdGoodDetailPresenter.getJdCpsUrl(currentLoadGoodUrl);
        }
    }

    /**
     * webview 倒退
     */
    private void goback(){
         if(myJdWebView != null && myJdWebView.canGoBack()){
             String url = myJdWebView.getUrl();
             if(!TextUtils.isEmpty(url) && jdGoodDetailPresenter.isUserFanqianMode(url) && "main".equals(fromWhere)){
                  //返回首页
                  myJdWebView.loadUrl("http://m.jd.com");
             }else{
                if("search".equals(fromWhere)){
                   dismissAllowingStateLoss();
                }else{
                  myJdWebView.goBack();
                }
             }
         }else{
             dismissAllowingStateLoss();
         }
    }

    //初始化fragment
    public static JdWebviewDialogFragment newInstance(String initUrl,String fromWhere) {
        Bundle args = new Bundle();
        args.putString("initUrl",initUrl);
        args.putString("fromWhere",fromWhere);
        JdWebviewDialogFragment fragment = new JdWebviewDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        LocalStatisticInfo.getIntance().onPageStart(this.pageSession);
        MobclickAgent.onPageStart("jdHomeH5Page");
    }

    @Override
    public void onPause() {
        super.onPause();
        LocalStatisticInfo.getIntance().onPageEnd(this.pageSession);
        MobclickAgent.onPageEnd("jdHomeH5Page");
    }

    //-----------------------------------------回调VIEW的接口------------------------------------------

    @Override
    public void onGetJdFanliFail() {
        isHasFanli = false;
        leftTipText.setText("");
        rightTipText.setText("当前商品没有返利");
    }

    @Override
    public void onGetJdFanliSucc(JSONObject result,String loadUrl) {
       isHasFanli = true;
       float percent = 0.00f;
       float sumPrice = 0.00f;
       if(result != null && !result.isEmpty()){
           if(result.containsKey("rateWl")){
               percent = result.getFloatValue("rateWl");
           }
           if(result.containsKey("itemPriceWl")){
               sumPrice = result.getFloatValue("itemPriceWl");
           }
       }
       String percentString = String.valueOf(DateUtils.getFormatFloat(percent*100));
       String savePoints = String.valueOf(DateUtils.floatToInt(sumPrice*percent*100));
       rightTipText.setText("返"+percentString+"%|"+"约"+savePoints+"积分");
       if(jdGoodDetailPresenter != null && !TextUtils.isEmpty(loadUrl)){
          jdGoodDetailPresenter.getJdCpsUrl(loadUrl);
       }
    }

    @Override
    public void onGetCpsSucc(String cpsUrl) {
        if(myJdWebView != null){
            myJdWebView.loadUrl(cpsUrl);
        }
    }

    @Override
    public void onGetCpsFail() {
        Toast.makeText(MyApplication.getContext(),"获取CPS链接失败,请重试",Toast.LENGTH_SHORT);
        leftTipText.setText("CPS链接获取");
        leftTipText.setClickable(true);
        leftTipBiz = 2;
    }
}


text:
package com.siyeh.igtest.classlayout.class_initializer;

public class Simple {

  <warning descr="Non-'static' initializer">{</warning>}

  Simple() {}
}


text:
// -------------------------------------------------------------------------------------------------

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

#ifndef WIDGET_H
#define WIDGET_H

// ----- general includes --------------------------------------------------------------------------
#include <QMainWindow>
#include <QStringList>

// ----- local includes ----------------------------------------------------------------------------
// ----- pre defines -------------------------------------------------------------------------------

// ----- class definition --------------------------------------------------------------------------
/**
 *  @short
 *
 *  The usage is fairly easy. Derive your own MainWindow class from DocumentWindow instead of QMainWindow
 *  and implement the pure virtual function openFiles.
 *
 *  @code
    MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :
        DocumentWindow(parent, flags)
    {
        ...

        setWindowTitle(tr("MDI"));
        setUnifiedTitleAndToolBarOnMac(true);
    }
    @endcode
 *
 *  Aditionally, the openFiles must be implermented:
 *
 *  @code
        bool MyClass::openFiles(const QStringList& pathList)
        {
            bool success = true;
            for (int i = 0; i < pathList.size() && i < 32; ++i)
            {
                MdiChild *child = createMdiChild();
                if (child->loadFile(pathList.at(i)))
                {
                    statusBar()->showMessage(tr("File loaded"), 2000);
                    child->show();
                }
                else
                {
                    child->close();
                }
            }
            return success;
        }
    @endcode
 *
 */
class DocumentWindow : public QMainWindow
{
    Q_OBJECT
public:
    // ----- enums ---------------------------------------------------------------------------------
    // ----- construction --------------------------------------------------------------------------
    /**
     *  Constructor.
     *
     *  Creates a DocumentWindow with a given @arg parent and @arg flags.
     */
    explicit DocumentWindow(QWidget* parent = 0, Qt::WindowFlags flags = 0);

    /**
     *  Destructor
     */
    ~DocumentWindow();

    // ----- operators -----------------------------------------------------------------------------
    // ----- methods -------------------------------------------------------------------------------
    // ----- accessors -----------------------------------------------------------------------------
    // ----- members -------------------------------------------------------------------------------

protected:
    // ----- events --------------------------------------------------------------------------------
    /**
     *  this event is called when the mouse enters the widgets area during a drag/drop operation
     */
    void dragEnterEvent(QDragEnterEvent* event);

    /**
     *  this event is called when the mouse moves inside the widgets area during a drag/drop operation
     */
    void dragMoveEvent(QDragMoveEvent* event);

    /**
     *  this event is called when the mouse leaves the widgets area during a drag/drop operation
     */
    void dragLeaveEvent(QDragLeaveEvent* event);

    /**
     *  this event is called when the drop operation is initiated at the widget
     */
    void dropEvent(QDropEvent* event);

    // ----- helpers -------------------------------------------------------------------------------
    /**
     *  This method must be implemented by the client. It is used to opened the dropped files.
     *
     *  @param pathList list of urls given by the drop event
     *  @retval true if successfull otherwise false
     *
     *  Here is an example implementation:
     *
     *  @code
        bool MyClass::openFiles(const QStringList& pathList)
        {
            bool success = true;
            for (int i = 0; i < pathList.size() && i < 32; ++i)
            {
                MdiChild *child = createMdiChild();
                if (child->loadFile(pathList.at(i)))
                {
                    statusBar()->showMessage(tr("File loaded"), 2000);
                    child->show();
                }
                else
                {
                    child->close();
                }
            }
            return success;
        }
        @endcode
     */
    virtual bool openFiles(const QStringList& pathList) = 0;

private:
    // ----- privat helpers ------------------------------------------------------------------------
    // ----- members -------------------------------------------------------------------------------
    // ----- not allowed members -------------------------------------------------------------------
};

#endif // WIDGET_H


text:
#!/usr/bin/env node

var path = require('path');
var fs = require('fs');
var appRoot = process.cwd();
var isWin = /^win/.test(process.platform);

var prosFile = path.resolve(appRoot, 'sonar-project.properties');
var pjson = require(path.resolve(appRoot, 'package.json'));

var sonarProps = pjson.sonar;

/**
 * Execute the sonar-scanner command.
 * @param command an Array containing the sonar-scanner command and props.
 */
function execSonarScanner(command) {

    var sonarScannerFile = isWin? 'sonar-scanner.bat' : 'sonar-scanner';
    var sonarCommand = path.resolve(__dirname, './../lib/sonar-scanner/bin/' + sonarScannerFile);
    var projectBaseDir = '-Dsonar.projectBaseDir=' + appRoot;

    command.unshift(projectBaseDir);
    command.unshift(sonarCommand);

    var sys = require('sys');
    var exec = require('child_process').exec;

    exec(command.join(' '), function (error, stdout, stderr) {
        sys.print('stdout: ' + stdout);
        sys.print('stderr: ' + stderr);
        if (error !== null) {
            console.log('exec error: ' + error);
        }
    });
}

//Execute the sonar-scanner command specifying the location of the props file.
if (fs.existsSync(prosFile)) {
    execSonarScanner(['-Dproject.settings=' + path.resolve(appRoot, 'sonar-project.properties')])

} else {

    //Execute the sonar-scanner command specifying the props as command line args.
    if (sonarProps !== null || sonarProps !== undefined) {

        var acceptedParams = [
            'host.url',
            'projectKey',
            'sources',
            'projectName',
            'projectVersion',
            'login',
            'password',
            'ws.timeout',
            'projectDescription',
            'links.homepage',
            'links.ci',
            'links.issue',
            'links.scm',
            'links.scm_dev',
            'tests',
            'language',
            'sourceEncoding',
            'projectDate',
            'branch',
            'profile',
            'projectBaseDir',
            'working.directory',
            'scm.provider',
            'scm.forceReloadAll',
            'inclusions',
            'exclusions',
            'coverage.exclusions',
            'test.exclusions',
            'test.inclusions',
            'issue.ignore.allfile',
            'import_unknown_files',
            'cpd.exclusions',
            'cpd.exclusions',
            'cpd.${language}.minimumtokens',
            'cpd.${language}.minimumLines',
            'log.level',
            'verbose',
            'showProfiling',
            'scanner.dumpToFile',
            'analysis.mode'
        ];

        /**
         * Check whether the acceptedParams array contains the provided param.
         * @param param
         * @returns {boolean}
         */
        function paramIsValid(param) {
            for (var i = 0; i < acceptedParams.length; i++) {
                if (acceptedParams[i] === param) {
                    return true;
                }
            }
            return false;
        }

        var cmdProps = [];

        for (var param in sonarProps) {
            if (sonarProps.hasOwnProperty(param) && paramIsValid(param)) {
                cmdProps.push('-Dsonar.' + param + '=' + sonarProps[param]);
            }
        }

        execSonarScanner(cmdProps);
    }
}