text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ObjReaderTests.cs" company="Helix Toolkit">
//   Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// <summary>
//   Test for pull request #52.
//   Fix ArgumentOutOfRangeException in MeshBuilder.ComputeNormals.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using HelixToolkit.Wpf.SharpDX.Model;
using NUnit.Framework;
using SharpDX;

namespace HelixToolkit.Wpf.SharpDX.Tests.Importers
{
    [TestFixture]
    class ObjReaderTests
    {
        private ObjReader _objReader;

        [SetUp]
        public void SetUp()
        {
            _objReader = new ObjReader();
            var dir = Path.GetDirectoryName(typeof(ObjReaderTests).Assembly.Location);
            Directory.SetCurrentDirectory(dir);
        }

        /// <summary>
        /// Test for pull request #52.
        /// Fix ArgumentOutOfRangeException in MeshBuilder.ComputeNormals.
        /// </summary>
        [Test]
        public void LoadModelWithoutNormals()
        {
            var objects = _objReader.Read(@"Models\obj\cornell_box.obj");

            Assert.IsNotNull(objects);
            Assert.AreEqual(9, objects.Count);

            var floorGeometry = objects[0].Geometry as MeshGeometry3D;

            Assert.IsNotNull(floorGeometry);
            Assert.AreEqual(4, floorGeometry.Positions.Count);
            Assert.AreEqual(4, floorGeometry.Normals.Count);
        }

        [Test]
        public void CanParseFaceWithRelativeIndices()
        {
            var model = _objReader.Read(@"Models\obj\face_relative_vertices.obj");

            Assert.AreEqual(1, model.Count);
            var geometry = (MeshGeometry3D)model[0].Geometry;
            geometry.Positions.AssertContains(new[] { -1d, 0d, 1d }, new[] { 1d, 0d, 1d }, new[] { -1d, 0d, -1d });
        }

        [Test]
        public void CanParseFaceWithAbsoluteNormals()
        {
            var model = _objReader.Read(@"Models\obj\simple_triangle_with_normals.obj");

            Assert.AreEqual(1, model.Count);
            var geometry = (MeshGeometry3D)model[0].Geometry;
            geometry.Normals.AssertContains(new[] { 0d, 1d, 0d }, new[] { 0d, 1d, 0d }, new[] { 0d, 1d, 0d });
        }

        [Test]
        public void CanParseFaceWithRelativeNormals()
        {
            var model = _objReader.Read(@"Models\obj\face_relative_vertex_normals.obj");

            Assert.AreEqual(1, model.Count);
            var geometry = (MeshGeometry3D)model[0].Geometry;
            geometry.Normals.AssertContains(new[] { 0d, 1d, 0d }, new[] { 0d, 1d, 0d }, new[] { 0d, 1d, 0d });
        }

        [Test]
        public void CanParseFaceWithAbsoluteTextureCoords()
        {
            var model = _objReader.Read(@"Models\obj\simple_triangle_with_texture.obj");

            Assert.AreEqual(1, model.Count);
            var geometry = (MeshGeometry3D)model[0].Geometry;
            geometry.TextureCoordinates.AssertContains(new[] { 0d, 0d }, new[] { 0d, 0d }, new[] { 0d, 0d });
        }

        [Test]
        public void CanParseFaceWithRelativeTextureCoords()
        {
            var model = _objReader.Read(@"Models\obj\face_relative_texture_vertices.obj");

            Assert.AreEqual(1, model.Count);
            var geometry = (MeshGeometry3D)model[0].Geometry;
            geometry.TextureCoordinates.AssertContains(new[] { 0d, 0d }, new[] { 0d, 0d }, new[] { 0d, 0d });
        }

        [Test]
        public void CanParseSimpleTriangle()
        {
            var model = _objReader.Read(@"Models\obj\simple_triangle.obj");

            Assert.AreEqual(1, model.Count);
            model[0].Geometry.Positions.AssertContains(new[] { -1d, 0d, 1d }, new[] { 1d, 0d, 1d }, new[] { -1d, 0d, -1d });
        }

        [Test]
        public void CanParseLineContinuations()
        {
            var model = _objReader.Read(@"Models\obj\line_continuation_single.obj");

            Assert.AreEqual(1, model.Count);
            model[0].Geometry.Positions.AssertContains(new[] { -1d, 0d, 1d }, new[] { 1d, 0d, 1d }, new[] { -1d, 0d, -1d });
        }

        [Test]
        public void CanParseLineContinuationsWithMultipleBreaks()
        {
            var model = _objReader.Read(@"Models\obj\line_continuation_multiple_breaks.obj");

            Assert.AreEqual(1, model.Count);
            model[0].Geometry.Positions.AssertContains(new[] { -1d, 0d, 1d }, new[] { 1d, 0d, 1d }, new[] { -1d, 0d, -1d });
        }

        [Test]
        public void CanParseLineContinuationsWithEmptyContinuations()
        {
            var model = _objReader.Read(@"Models\obj\line_continuation_empty_continuation.obj");

            Assert.AreEqual(1, model.Count);
            model[0].Geometry.Positions.AssertContains(new[] { -1d, 0d, 1d }, new[] { 1d, 0d, 1d }, new[] { -1d, 0d, -1d });
        }

        [Test]
        public void CanParseLineContinuationsWithEmptyLineInMiddle()
        {
            var model = _objReader.Read(@"Models\obj\line_continuation_empty_line.obj");

            Assert.AreEqual(1, model.Count);
            model[0].Geometry.Positions.AssertContains(new[] { -1d, 0d, 1d }, new[] { 1d, 0d, 1d }, new[] { -1d, 0d, -1d });
        }

        [Test]
        public void CanParseLineContinuationsInComments()
        {
            var model = _objReader.Read(@"Models\obj\line_continuation_comment.obj");

            Assert.AreEqual(1, model.Count);
            model[0].Geometry.Positions.AssertContains(new[] { -1d, 0d, 1d }, new[] { 1d, 0d, 1d }, new[] { -1d, 0d, -1d });
        }

        [Test]
        public void BuildModel_SmoothingOff_Valid()
        {
            string content = @"
s off

v 0 0 0
v 1 0 0
v 0 1 0
v 1 1 0

vt 0.0 0.0
vt 0.5 0.0
vt 0.0 0.5
vt 1.0 1.0
vt 0.0 1.0
vt 1.0 0.0

f 1/1 2/2 3/3
f 4/4 3/5 2/6
";

            var expectedPositions = new Vector3[]
            {
                new Vector3(0.0f, 0.0f, 0.0f),
                new Vector3(1.0f, 0.0f, 0.0f),
                new Vector3(0.0f, 1.0f, 0.0f),
                new Vector3(1.0f, 1.0f, 0.0f),
                new Vector3(0.0f, 1.0f, 0.0f),
                new Vector3(1.0f, 0.0f, 0.0f)
            };

            var expectedTextureCoordinates = new Vector2[]
            {
                new Vector2(0.0f, 1.0f),
                new Vector2(0.5f, 1.0f),
                new Vector2(0.0f, 0.5f),
                new Vector2(1.0f, 0.0f),
                new Vector2(0.0f, 0.0f),
                new Vector2(1.0f, 1.0f)
            };

            var buffer = Encoding.UTF8.GetBytes(content);

            using (var stream = new MemoryStream(buffer, false))
            {
                var model = _objReader.Read(stream);
                var mesh = (MeshGeometry3D)model[0].Geometry;

                Assert.AreEqual(6, mesh.Indices.Count);
                Assert.AreEqual(6, mesh.Positions.Count);
                Assert.AreEqual(6, mesh.TextureCoordinates.Count);

                CollectionAssert.AreEqual(expectedPositions, mesh.Positions);
                CollectionAssert.AreEqual(expectedTextureCoordinates, mesh.TextureCoordinates);
            }
        }

        [Test]
        public void BuildModel_SmoothingOn_Valid()
        {
            string content = @"
s 1

v 0 0 0
v 1 0 0
v 0 1 0
v 1 1 0

vt 0.0 0.0
vt 0.5 0.0
vt 0.0 0.5
vt 1.0 1.0
vt 0.0 1.0
vt 1.0 0.0

f 1/1 2/2 3/3
f 4/4 3/5 2/6
";

            var expectedPositions = new Vector3[]
            {
                new Vector3(0.0f, 0.0f, 0.0f),
                new Vector3(1.0f, 0.0f, 0.0f),
                new Vector3(0.0f, 1.0f, 0.0f),
                new Vector3(1.0f, 1.0f, 0.0f),
                new Vector3(0.0f, 1.0f, 0.0f),
                new Vector3(1.0f, 0.0f, 0.0f)
            };

            var expectedTextureCoordinates = new Vector2[]
            {
                new Vector2(0.0f, 1.0f),
                new Vector2(0.5f, 1.0f),
                new Vector2(0.0f, 0.5f),
                new Vector2(1.0f, 0.0f),
                new Vector2(0.0f, 0.0f),
                new Vector2(1.0f, 1.0f)
            };

            var buffer = Encoding.UTF8.GetBytes(content);

            using (var stream = new MemoryStream(buffer, false))
            {
                var model = _objReader.Read(stream);
                var mesh = (MeshGeometry3D)model[0].Geometry;

                Assert.AreEqual(6, mesh.Indices.Count);
                Assert.AreEqual(6, mesh.Positions.Count);
                Assert.AreEqual(6, mesh.TextureCoordinates.Count);

                CollectionAssert.AreEqual(expectedPositions, mesh.Positions);
                CollectionAssert.AreEqual(expectedTextureCoordinates, mesh.TextureCoordinates);
            }
        }

        [TestCase("")]
        [TestCase("/")]
        [TestCase("./")]
        public void TexturePath_AbsoluteOrRelative_Valid(string prefix)
        {
            var tempObj = Path.GetTempFileName();
            var tempMtl = Path.GetTempFileName();
            var tempTexDiffuse = Path.GetTempFileName();
            var tempTexBump = Path.GetTempFileName();

            try
            {
                File.WriteAllText(tempObj, @"
mtllib " + prefix + Path.GetFileName(tempMtl) + @"
v -0.5 0 0.5
v 0.5 0 0.5
v -0.5 0 -0.5
vt 0 1
usemtl TestMaterial
f 1/1 2/1 3/1
");

                File.WriteAllText(tempMtl, @"
newmtl TestMaterial
map_Kd " + prefix + Path.GetFileName(tempTexDiffuse) + @"
map_bump " + prefix + Path.GetFileName(tempTexBump) + @"
");

                using (var image = new System.Drawing.Bitmap(1, 1))
                {
                    image.Save(tempTexDiffuse);
                    image.Save(tempTexBump);
                }

                var model = _objReader.Read(tempObj);
                var material = (PhongMaterialCore)model[0].Material;
                using(var fs = new FileStream(tempTexDiffuse, FileMode.Open))
                {
                    Compare(fs, material.DiffuseMap);
                }
                using (var fs = new FileStream(tempTexBump, FileMode.Open))
                {
                    Compare(fs, material.NormalMap);
                }
            }
            finally
            {
                File.Delete(tempObj);
                File.Delete(tempMtl);
                //File.Delete(tempTexDiffuse);
                //File.Delete(tempTexBump);
            }
        }

        public void Compare(Stream s1, Stream s2)
        {
            Assert.AreEqual(s1.Length, s2.Length);
            s2.Position = 0;
            s1.Position = 0;
            for(int i=0; i<s1.Length; ++i)
            {
                Assert.AreEqual(s1.ReadByte(), s2.ReadByte());
            }
        }

        [Test]
        public void MaterialLib_LoadMultipleTimes_Valid()
        {
            var tempObj = Path.GetTempFileName();
            var tempMtl = Path.GetTempFileName();

            try
            {
                File.WriteAllText(tempObj, @"
mtllib " + Path.GetFileName(tempMtl) + @"
mtllib " + Path.GetFileName(tempMtl) + @"
v -0.5 0 0.5
v 0.5 0 0.5
v -0.5 0 -0.5
vt 0 1
usemtl TestMaterial
f 1/1 2/1 3/1
");

                File.WriteAllText(tempMtl, @"
newmtl TestMaterial
Kd 1 1 1
newmtl TestMaterial
Kd 0 0 0
");

                var model = _objReader.Read(tempObj);
                Assert.AreEqual(new Color4(1, 1, 1, 1), _objReader.Materials["TestMaterial"].Diffuse);
            }
            finally
            {
                File.Delete(tempObj);
                File.Delete(tempMtl);
            }
        }
    }

    public static class TestExtensions
    {
        public static void AssertContains(this Core.Vector2Collection collection, params double[][] points)
        {
            Assert.AreEqual(points.Length, collection.Count, "Expected to find {0} points in collection", points.Length);
            foreach (var point in points)
                Assert.IsTrue(collection.Contains(point), "Expected collection to contain point [{0},{1}]", point[0], point[1]);
        }

        public static void AssertContains(this Core.Vector3Collection collection, params double[][] points)
        {
            Assert.AreEqual(points.Length, collection.Count, "Expected to find {0} points in collection", points.Length);
            foreach (var point in points)
                Assert.IsTrue(collection.Contains(point), "Expected collection to contain point [{0},{1},{2}]", point[0], point[1], point[2]);
        }

        public static bool Contains(this Core.Vector3Collection vectors, double[] expectedVector)
        {
            return vectors.Any(vector => Math.Abs((float) expectedVector[0] - vector.X) < float.Epsilon &&
                                         Math.Abs((float) expectedVector[1] - vector.Y) < float.Epsilon &&
                                         Math.Abs((float) expectedVector[2] - vector.Z) < float.Epsilon);
        }

        public static bool Contains(this Core.Vector2Collection vectors, double[] expectedVector)
        {
            return vectors.Any(vector => Math.Abs((float) expectedVector[0] - vector.X) < float.Epsilon &&
                                         Math.Abs((float) expectedVector[1] - vector.Y) < float.Epsilon);
        }
     }
}


text:
import { b as useStore } from './index-c9ec5590.js';

var nodesSelector = function nodesSelector(state) {
  return Array.from(state.nodeInternals.values());
};

function useNodes() {
  var nodes = useStore(nodesSelector);
  return nodes;
}

export { useNodes as u };
//# sourceMappingURL=useNodes-b7453306.js.map

redpajama_set_name: RedPajamaGithub


text:
var geocoder = new google.maps.Geocoder();

function geocodePosition(pos) {
  geocoder.geocode({
    latLng: pos
  }, function(responses) {
    if (responses && responses.length > 0) {
      updateMarkerAddress(responses[0].formatted_address);
    } else {
      updateMarkerAddress('Cannot determine address at this location.');
    }
  });
}

function updateMarkerStatus(str) {
  document.getElementById('markerStatus').innerHTML = str;
}

function updateMarkerPosition(latLng) {
  document.getElementById('info').value = [
    latLng.lat(),
    latLng.lng()
  ].join(', ');
}

function updateMarkerAddress(str) {
  document.getElementById('address').innerHTML = str;
}

function initialize() {
  var latLng = new google.maps.LatLng(-22.905119425426758, -43.13168442726135);
  var map = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 8,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var marker = new google.maps.Marker({
    position: latLng,
    title: 'Point A',
    map: map,
    draggable: true
  });

  // Update current position info.
  updateMarkerPosition(latLng);
  geocodePosition(latLng);

  // Add dragging event listeners.
  google.maps.event.addListener(marker, 'dragstart', function() {
    updateMarkerAddress('Dragging...');
  });

  google.maps.event.addListener(marker, 'drag', function() {
    updateMarkerStatus('Dragging...');
    updateMarkerPosition(marker.getPosition());
  });

  google.maps.event.addListener(marker, 'dragend', function() {
    updateMarkerStatus('Drag ended');
    geocodePosition(marker.getPosition());
  });
}

// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Commodity extends Model
{
    protected $table = 'commodities';

    protected $primaryKey = 'id';

    protected $fillable = ['id','name', 'type','category','"numin','numout','avgin','avgout','lesswarn','morewarn','alarm'];

    public function scopeSoldMost($query){
        return $query->orderBy('numout','desc');
    }

    public function scopeSoldLeast($query){
        return $query->orderBy('numout','asc');
    }
}


text:
One-click popup extension to access popular ASCII/Unicode faces from your Google Chrome browser to your clipboard.

There are other extensions in the Chrome web store that perform the same function... _but none has a name so irrelevant!_

Jokes aside, why did I write this? I have vague trust issues with the other extensions in the store. They don't seem to be updated very often. And, frankly, I just thought it would be a fun little diversion. I wanted an implementation of this kind of extension to be available with full source code available to anyone, free of any kind of 'hanky panky', like ads or worse.

About the name... I'm sorry. _(Not sorry!)_

* http://bytestemplar.com/web/greensmile

<img src="http://i.imgur.com/eAozVGd.jpg"/>


text:
'''
Defines the interface to the Z3 solver.
'''
# TODO: Define UnsatException and SolverException
# TODO: Count things about the model that we want to record.
import z3

class Z3:
  def __init__(self):
    self.solver = z3.Solver()

  # TODO: Is this the place to do this?
  #def __del__(self):
  #  z3.delete()

  # Defining variables.
  def getIntVar(self, name):
    return z3.Int(name)

  def getBoolVar(self, name):
    return z3.Bool(name)

  def check(self):
    return self.solver.check()

  def isSatisfiable(self):
    r = self.solver.check()
    if r == z3.sat:
      return True
    elif r == z3.unsat:
      return False
    else:
      raise ValueError("got neither sat nor unsat from solver")

  def evaluate(self, t):
    s = self.solver.model().eval(t.z3Node())
    assert z3.is_true(s) or z3.is_false(s)
    return z3.is_true(s)

  def solverAssert(self, constraint):
    return self.solver.add(constraint)

  def boolExprAssert(self, constraint):
    return self.solver.add(constraint.z3Node())

  def push(self):
    self.solver.push()

  def pop(self):
    self.solver.pop()

  def reset(self):
    self.solver.reset_memory()


text:
package org.ayo.notify;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

public class LocalDisplay {
    public static int SCREEN_WIDTH_PIXELS;
    public static int SCREEN_HEIGHT_PIXELS;
    public static float SCREEN_DENSITY;
    public static int SCREEN_WIDTH_DP;
    public static int SCREEN_HEIGHT_DP;
    private static boolean sInitialed;

    public LocalDisplay() {
    }
    public static float sp2px(Context context, float value) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return value * metrics.scaledDensity;
    }
    public static void init(Context context) {
        if(!sInitialed && context != null) {
            sInitialed = true;
            DisplayMetrics dm = new DisplayMetrics();
            WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
            wm.getDefaultDisplay().getMetrics(dm);
            SCREEN_WIDTH_PIXELS = dm.widthPixels;
            SCREEN_HEIGHT_PIXELS = dm.heightPixels;
            SCREEN_DENSITY = dm.density;
            SCREEN_WIDTH_DP = (int)((float)SCREEN_WIDTH_PIXELS / dm.density);
            SCREEN_HEIGHT_DP = (int)((float)SCREEN_HEIGHT_PIXELS / dm.density);
        }
    }

    public static int dp2px(float dp) {
        float scale = SCREEN_DENSITY;
        return (int)(dp * scale + 0.5F);
    }

    public static int designedDP2px(float designedDp) {
        if(SCREEN_WIDTH_DP != 320) {
            designedDp = designedDp * (float)SCREEN_WIDTH_DP / 320.0F;
        }

        return dp2px(designedDp);
    }

    public static void setPadding(View view, float left, float top, float right, float bottom) {
        view.setPadding(designedDP2px(left), dp2px(top), designedDP2px(right), dp2px(bottom));
    }
}


text:
@protocol UserSearchDelegate;

@interface UserSearchViewController : UIViewController

@property (strong, nonatomic) FirefeedSearch* firefeedSearch;
@property (weak, nonatomic) id<UserSearchDelegate> delegate;

@end

@protocol UserSearchDelegate

- (void) userWasSelected:(NSString *)userId;
- (void) searchWasCancelled;

@end


text:
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Kooboo.CMS.Sites.Models;
using System.IO;

namespace Kooboo.CMS.Sites.Tests.Models
{
    /// <summary>
    /// Summary description for SiteTests
    /// </summary>
    [TestClass]
    public class SiteTests
    {

        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        [TestMethod]
        public void TestPhysicalPath()
        {
            Site site = new Site("site1");
            string expected = Path.Combine(Kooboo.Settings.BaseDirectory, "Cms_Data", "sites", "site1");
            Assert.AreEqual(expected, site.PhysicalPath, true);
        }
        [TestMethod]
        public void TestVirtualPath()
        {
            Site site = new Site("site1");
            string expected = Kooboo.Web.Url.UrlUtility.Combine("~/","Cms_Data", "sites", "site1");
            Assert.AreEqual(expected, site.VirtualPath, true);
        }
        [TestMethod]
        public void TestParseFromPhysicalPath()
        {
            string siteName = "site1";
            string physicalPath = Path.Combine(Kooboo.Settings.BaseDirectory, "sites", siteName);
            Site site = Site.ParseSiteFromPhysicalPath(physicalPath);
            Assert.AreEqual(siteName, site.Name);
        }

        [TestMethod]
        public void TestParseFromRelativePath()
        {
            string siteName = "site1";
            Site site = Site.ParseSiteFromRelativePath(new string[] { siteName });
            Assert.AreEqual(siteName, site.Name);
        }

        [TestMethod]
        public void TestParseWithParentSite()
        {
            string parent = "parent";
            string siteName = "subSite";

            string physicalPath = Path.Combine(Kooboo.Settings.BaseDirectory, "sites", parent, Site.PATH_NAME, siteName);
            Site site = Site.ParseSiteFromPhysicalPath(physicalPath);
            Assert.AreEqual(siteName, site.Name);
            Assert.IsNotNull(site.Parent);
            Assert.AreEqual(parent, site.Parent.Name);
        }

        [TestMethod]
        public void TestPhysicalPathWithParentSite()
        {
            Site parent = new Site("parent");
            Site sub = new Site(parent, "sub");
            string expected = Path.Combine(Kooboo.Settings.BaseDirectory, "Cms_Data", "sites", "parent", Site.PATH_NAME, "sub");
            Assert.AreEqual(expected, sub.PhysicalPath, true);
        }
        [TestMethod]
        public void TestRelativePaths()
        {
            Site parent = new Site("parent");

            Assert.AreEqual("parent", parent.RelativePaths.First());
        }
        [TestMethod]
        public void TestRelativePathsWithParentSite()
        {
            Site parent = new Site("parent");
            Site child = new Site(parent, "child");
            Assert.AreEqual(2, child.RelativePaths.Count());
            Assert.AreEqual("parent", child.RelativePaths.First());
            Assert.AreEqual("child", child.RelativePaths.Last());
        }
    }
}


text:
from distutils.core import setup

setup(name='llap_fdw',
      version='0.1.0',
      description='LLAP FDW',
      author='Gopal V',
      author_email='gopalv@apache.org',
      url='https://github.com/t3rmin4t0r/llap_fdw',
      py_modules=['llap_fdw'])


text:
- [ ] I made sure that the site looks great and functions perfectly live
- [ ] I ran splell check
- [ ] I'm ready for these changes to be made live

## For the Reviewer

### General Review

- [ ] All changes/updates requested were intentionally changed or added (no extraneous file or partial updates)
- [ ] The live rendered page behaves and looks like intended.
- [ ] All links work as intended. (click every link to make sure that it takes the user to the expected place).
- [ ] The markdown was rendered to HTML as intended. (Tables look right, code samples are gated properly).
- [ ] Any style or CSS changes are tested on multiple different pages to ensure nothing unexpected broke or changed.
- [ ] I proof-read the live site (`gitbook serve`) and there are no oblivious splelling or grammer misteaks.

### Gitbook Specific

- [ ] Any new documentation pages have been added to the `SUMMARY.md` file so they are rendered to HTML.
- [ ] Any links to other pages within this documentation use relative links (`[read more about ...](guides/voice/voicemail.md)`).
- [ ] Gitbook can install and build the documentation (`gitbook install` & `gitbook build`)

### Code Specific

- [ ] All code has been tested against the live API.
- [ ] All code can be run without throwing errors or **new** warnings.
- [ ] All code is formatted correctly and consistently (spaces, tabs).
- [ ] All code is legible and idiomatic to the language.
- [ ] All code uses sensical method, function, and variable names.
- [ ] All code samples use the appropriate syntax highlighting.
- [ ] Any examples re-use same phone numbers, uuids, variable names, etc... throughout (IE don't have something like `{from: '+19191231234', to: '+19191231234'}` unless it's meant to show the same phone number calling/texting itself ).

## TL;DR

- [ ] I did these things
- [ ] I'm ready for these changes to be made live


text:
package uk.co.autotrader.tingle.core;

import javax.inject.Inject;

import org.eclipse.equinox.log.Logger;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryMigrator;

public class MingleRepositoryMigrator extends AbstractRepositoryMigrator
{
	@Inject
	Logger logger;

	public MingleRepositoryMigrator() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public String getConnectorKind() {
		// TODO Auto-generated method stub
		return null;
	}
}


text:
require('../Token');
require("../Tokenizable");
require("../../Test/ConsoleUnitTest");
describeConsoleUnitTest('Consoloid.Interpreter.Tokenizable', function() {
  describe('#_tokenize()', function() {
    it('should return argument value places of the given text', function() {
      var tokenizable = env.create(Consoloid.Interpreter.Tokenizable, {})
      tokenizable._tokenize('rename <from> to <to>');

      var tokens = tokenizable.getTokens();
      tokens.should.have.lengthOf(4);
      tokens[0].should.have.property('type', Consoloid.Interpreter.Token.LITERAL);
      tokens[0].should.have.property('text', 'rename');
      tokens[1].should.have.property('type', Consoloid.Interpreter.Token.ARGUMENT_VALUE);
      tokens[1].should.have.property('text', 'from');
      tokens[2].should.have.property('type', Consoloid.Interpreter.Token.LITERAL);
      tokens[2].should.have.property('text', 'to');
      tokens[3].should.have.property('type', Consoloid.Interpreter.Token.ARGUMENT_VALUE);
      tokens[3].should.have.property('text', 'to');
    });

    it('should return expression with argument value of the text', function() {
      env.setTokenMocks({'rename "<from> to <to>"': ['rename', '<from> to <to>']});

      var tokenizable = env.create(Consoloid.Interpreter.Tokenizable, {})
      tokenizable._tokenize('rename "<from> to <to>"');

      var tokens = tokenizable.getTokens();
      tokens.should.have.lengthOf(2);
      tokens[0].should.have.property('type', Consoloid.Interpreter.Token.LITERAL);
      tokens[0].should.have.property('text', 'rename');
      tokens[1].should.have.property('type', Consoloid.Interpreter.Token.LITERAL);
      tokens[1].should.have.property('text', '<from> to <to>');
    });
  });
});


text:
<?php
namespace Procure\Application\Reporting\GR;

use Application\Service\AbstractService;
use Procure\Application\Reporting\GR\Output\SaveAsExcel;
use Procure\Application\Reporting\GR\Output\SaveAsOpenOffice;
use Procure\Application\Reporting\GR\Output\Header\Spreadsheet\ExcelBuilder;
use Procure\Application\Service\Output\Contract\HeadersSaveAsSupportedType;
use Procure\Application\Service\Output\Formatter\Header\DefaultHeaderFormatter;
use Procure\Application\Service\Output\Header\HeadersSaveAsArray;
use Procure\Infrastructure\Contract\SqlFilterInterface;
use Procure\Infrastructure\Persistence\GrReportRepositoryInterface;

/**
 * GR Reporter
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class GrReporter extends AbstractService
{

    /**
     *
     * @var GrReportRepositoryInterface $reporterRespository;
     */
    protected $reporterRespository;

    public function getList($filter, $sort_by, $sort, $limit, $offset, $file_type)
    {
        if ($file_type == HeadersSaveAsSupportedType::OUTPUT_IN_EXCEL || $file_type == HeadersSaveAsSupportedType::OUTPUT_IN_OPEN_OFFICE) {
            $limit = null;
            $offset = null;
        }

        $results = $this->getReporterRespository()->getList($filter, $sort_by, $sort, $limit, $offset);

        $factory = null;
        $formatter = null;

        switch ($file_type) {
            case HeadersSaveAsSupportedType::OUTPUT_IN_ARRAY:
                $formatter = new DefaultHeaderFormatter();
                $factory = new HeadersSaveAsArray();
                break;
            case HeadersSaveAsSupportedType::OUTPUT_IN_EXCEL:

                $builder = new ExcelBuilder();
                $formatter = new DefaultHeaderFormatter();
                $factory = new SaveAsExcel($builder);
                break;

            case HeadersSaveAsSupportedType::OUTPUT_IN_OPEN_OFFICE:

                $builder = new ExcelBuilder();
                $formatter = new DefaultHeaderFormatter();
                $factory = new SaveAsOpenOffice($builder);
                break;

            default:
                $formatter = new DefaultHeaderFormatter();
                $factory = new HeadersSaveAsArray();
                break;
        }

        return $factory->saveAs($results, $formatter);
    }

    public function getListTotal(SqlFilterInterface $filter)
    {
        $key = \sprintf("total_list_%s", $filter->__toString());

        $resultCache = $this->getCache()->getItem($key);
        if (! $resultCache->isHit()) {
            $total = $this->getReporterRespository()->getListTotal($filter);
            $resultCache->set($total);
            $this->getCache()->save($resultCache);
        } else {
            $total = $this->getCache()
                ->getItem($key)
                ->get();
        }

        return $total;
    }

    /**
     *
     * @param GrReportRepositoryInterface $reporterRespository
     */
    public function setReporterRespository(GrReportRepositoryInterface $reporterRespository)
    {
        $this->reporterRespository = $reporterRespository;
    }

    /**
     *
     * @return \Procure\Infrastructure\Persistence\GrReportRepositoryInterface
     */
    public function getReporterRespository()
    {
        return $this->reporterRespository;
    }
}


text:
#include "Srl/Srl.h"
#include "Srl/Lib.h"
extern "C" {
#include "fpconv/fpconv.h"
}

#include <limits>
#include <cmath>

using namespace std;
using namespace Srl;
using namespace Lib;
using namespace Tools;

namespace {

    const char str_true[]  = "true";
    const char str_false[] = "false";
    const char str_null[]  = "null";

    tuple<double, bool> str_to_double(const uint8_t* str, size_t str_len)
    {
        const size_t buffer_size = 64;
        char buffer[buffer_size];

        double val;

        const auto apply = [&val, str, str_len](char* ptr_mem) -> bool {
            char* end = nullptr;
            memcpy(ptr_mem, str, str_len);
            ptr_mem[str_len] = '\0';
            val = strtod(ptr_mem, &end);

            return end == ptr_mem + str_len;
        };

        if(str_len + 1 < buffer_size) {
            return make_tuple(val, apply(buffer));

        } else {
            vector<char> vec_buffer(str_len + 1);
            return make_tuple(val, apply(vec_buffer.data()));
        }
    }

    tuple<uint64_t, bool, bool> str_to_int(const uint8_t* str, size_t str_len)
    {
        size_t   idx = 0;
        uint64_t val = 0;
        bool is_signed = false;

        if(str_len > 0 && *str == '-') {
            if(str_len < 2) {
                /* invalid string */
                return make_tuple(val, false, false);
            }
            is_signed = true;
            idx = 1;
        }

        uint64_t tmp = 0;
        for(char c = '\0'; idx < str_len; idx++) {
            c = str[idx];

            if(c < '0' || c > '9') {
                break;
            }

            tmp = val * 10 + c - '0';
            if(tmp < val) {
                /* overflow */
                break;
            }
            val = tmp;
        }

        bool success = idx >= str_len && (!is_signed || val <= numeric_limits<int64_t>::max());

        return make_tuple(val, is_signed, success);
    }

    template<typename TCharAr>
    bool cmp_str(const uint8_t* str, size_t str_len, const TCharAr& to_compare, size_t offset = 0)
    {
        assert(str_len >= offset);

        return str_len == sizeof(TCharAr) - 1 &&
               memcmp(to_compare + offset, str + offset, str_len - offset) == 0;
    }

    template<Type TP>
    typename enable_if<TpTools::is_num(TP) && !TpTools::is_fp(TP), size_t>::type
    conv_type(const Value& value, vector<uint8_t>& out)
    {
        typedef typename TpTools::Real<TP>::type T;
        const auto buffer_size = size_t(numeric_limits<T>::digits10) + 1 + TpTools::is_signed(TP);

        uint8_t buffer[buffer_size];

        bool negative = TpTools::is_signed(TP) && value.pblock().i64 < 0;

        uint64_t val = negative ? -value.pblock().i64 : value.pblock().ui64;

        if(val == 0) {
            if(out.size() < 1) out.resize(1);
            out[0] = '0';
            return 1;
        }

        size_t str_len = 0;
        auto* ptr = buffer + buffer_size - 1;

        for(; val > 0U;
            val /= 10U, ptr--, str_len++) {

            *ptr = '0' + val % 10;
        }

        if(negative) {
            *(ptr) = '-';
            str_len++;
        } else {
            ptr++;
        }

        Aux::copy_to_vec(out, ptr, str_len);

        return str_len;
    }

    template<Type type> typename enable_if<TpTools::is_fp(type), size_t>::type
    conv_type(const Value& value, vector<uint8_t>& out)
    {
        double val = type == Type::FP64 ? value.pblock().fp64 : value.pblock().fp32;

        if(floor(val) == val && val <= numeric_limits<int64_t>::max() && val >= numeric_limits<int64_t>::min()) {

            return conv_type<Type::I64>((int64_t)val, out);
        }

        if(out.size() < 24) {
            out.resize(24);
        }

        return fpconv_dtoa(val, (char*)out.data());
    }

    template<Type type> typename enable_if<type == Type::Bool, size_t>::type
    conv_type(const Value& value, vector<uint8_t>& out)
    {
        const char* str = value.pblock().ui64 ? str_true : str_false;
        size_t size = (value.pblock().ui64 ? sizeof(str_true) : sizeof(str_false)) - 1;

        Aux::copy_to_vec(out, (const uint8_t*)str, size);

        return size;
    }

    template<Type type>
    typename enable_if<type == Type::Null, size_t>::type
    conv_type(const Value&, vector<uint8_t>& out)
    {
        Aux::copy_to_vec(out, (const uint8_t*)str_null, sizeof(str_null) - 1);
        return sizeof(str_null) - 1;
    }
}

void Tools::trim_space(Lib::MemBlock& block)
{
    return trim_space(block.ptr, block.size);
}

void Tools::trim_space(const uint8_t*& str, size_t& str_len)
{
    if(str == nullptr) {
        return;
    }

    while(str_len > 0 && is_space(*str)) {
        str++;
        str_len--;
    }

    while(str_len > 0 && is_space(*(str + str_len - 1))) {
        str_len--;
    }
}

pair<bool, Value> Tools::str_to_type(const uint8_t* str, size_t str_len, Type hint)
{
    Tools::trim_space(str, str_len);

    if(str_len < 1) {
        return { false, Value(Type::Null) };
    }

    if(str_len >= 4 && str[0] >= 'f') {

        if((str[0] == 't' || str[0] == 'T') && cmp_str(str, str_len, str_true, 1)) {
            return { true, true };
        }

        if((str[0] == 'f' || str[0] == 'F') && cmp_str(str, str_len, str_false, 1)) {
            return { true, false };
        }

        if((str[0] == 'n' || str[0] == 'N') && cmp_str(str, str_len, str_null, 1)) {
            return { true, Value(Type::Null) };
        }
    }

    bool success = false;

    if(!TpTools::is_fp(hint)) {
        bool is_signed;
        uint64_t i;

        tie(i, is_signed, success) = str_to_int(str, str_len);

        if(success) {
            return is_signed ? make_pair(true, Value(-(int64_t)i)) : make_pair(true, Value(i));
        }
    }

    double fp;
    tie(fp, success) = str_to_double(str, str_len);

    return success ? make_pair(true, Value(fp)) : make_pair(false, Value(Type::Null));
}

pair<bool, Value> Tools::str_to_type(const String& string_wrap, Type hint)
{
    if(string_wrap.encoding() == Encoding::UTF8) {
        return str_to_type(string_wrap.data(), string_wrap.size(), hint);

    } else {
        auto vec = Tools::conv_charset(Encoding::UTF8, string_wrap, false);
        if(vec.size() < 1) {
            return make_pair(false, Value(Type::Null));
        }

        return str_to_type(vec.data(), vec.size(), hint);
    }
}

#define SRL_TYPE_TO_STR(id, idx, real, size) \
    case Type::id : return conv_type<Type::id>(value, out);

size_t Tools::type_to_str(const Value& value, vector<uint8_t>& out)
{
    switch(value.type()) {
        /* defined in Type.h */
        SRL_TYPES_SCALAR(SRL_TYPE_TO_STR)

        default : return 0;
    }
}

#undef SRL_TYPE_TO_STR

string Tools::type_to_str(const Value& value)
{
    vector<uint8_t> buffer;
    auto size = Tools::type_to_str(value, buffer);

    return size > 0 ? string((const char*)buffer.data(), size) : string();
}

vector<uint8_t> Tools::conv_charset(Encoding target_encoding, const String& string_wrap, bool throw_error)
{
    vector<uint8_t> buffer;
    auto converted_total = conv_charset(target_encoding, string_wrap, buffer, throw_error);
    buffer.resize(converted_total);

    return buffer;
}

/* At time of writing standard code conversion facets aren't implemented in libstdc++, so:
 * TODO convert with codecvt */
#include <iconv.h>
namespace {

    const char* get_charset_string(Encoding encoding)
    {
        static const char str_utf8[] = "UTF-8", str_utf16[] = "UTF-16LE", str_utf32[] = "UTF-32LE";

        const char* rslt = nullptr;

        switch(encoding) {
            case Encoding::UTF8    : rslt = str_utf8;  break;
            case Encoding::UTF16   : rslt = str_utf16; break;
            case Encoding::UTF32   : rslt = str_utf32; break;
            case Encoding::Unknown : rslt = nullptr;   break;
        }

        return rslt;
    }
}

size_t Tools::conv_charset(Encoding target_encoding, const String& str_wrap,
                           vector<uint8_t>& buffer,  bool throw_error, size_t buffer_index)
{
    if(str_wrap.size() < 1) {
        return 0;
    }

    auto src_encoding = str_wrap.encoding();

    auto* cs_from = get_charset_string(src_encoding);
    auto* cs_to   = get_charset_string(target_encoding);

    if(cs_from == cs_to) {
        auto seg = str_wrap.size() + buffer_index;
        if(buffer.size() < seg) {
            buffer.resize(seg);
        }
        memcpy(&buffer[buffer_index], str_wrap.data(), str_wrap.size());

        return str_wrap.size();
    }

    if(cs_from == nullptr || cs_to == nullptr) {
        if(throw_error) {
            throw Exception("Unable to convert charset. Unknown encoding.");
        }
        return 0;
    }

    iconv_t desc = iconv_open(cs_to, cs_from);

    if(desc == (iconv_t)(-1)) {
        if(throw_error) {
            throw Exception("Unable to convert charset. Failed to open iconv descriptor.");
        }
        return 0;
    }

    size_t left_in = str_wrap.size();
    size_t reserve = left_in * (
        target_encoding < src_encoding ? 1 : src_encoding == Encoding::UTF16 ? 2 : 4
    );

    if(buffer_index + reserve > buffer.size()) {
        buffer.resize(buffer_index + reserve);
    }
    size_t left_out = buffer.size() - buffer_index;

    auto* src = (char*)str_wrap.data();
    size_t converted = 0;

    while(true) {
        auto* dst = (char*)&buffer[buffer_index + converted];
        converted = iconv(desc, &src, &left_in, &dst, &left_out);

        if(converted == 0) {
            /* all characters converted */
            break;
        }

        if(errno == EINVAL) {
            iconv_close(desc);
            if(throw_error) {
                throw Exception("Unable to convert charset. Incomplete byte sequence.");
            }
            return 0;
        }

        if(errno == EILSEQ) {
            iconv_close(desc);
            if(throw_error) {
                throw Exception("Unable to convert charset. Invalid byte sequence.");
            }
            return 0;
        }

        if (errno == E2BIG) {
            /* output buffer not big enough */
            auto current = buffer.size();
            auto new_size = buffer.size() + left_in * 4;
            buffer.resize(new_size);
            converted = current - left_out;
            left_out = new_size - converted;
        }
    }

    iconv_close(desc);

    return buffer.size() - buffer_index - left_out;
}


text:
import os
import cv2

# First check how many faces are detected per frame; report when value is different than one

def save_image(image, dest_path, filename):
	cv2.imwrite(os.path.join(dest_path, filename), image)

def check_number_faces_detected(face, faces_to_detect, filename):
	if len(face) != faces_to_detect:
		print "Faces found: " + str(len(face)) + " on file " + filename
		return True
	return False

def show_image(image, header="faces"):
	cv2.imshow(header, image)
	cv2.waitKey(0)

def crop_image(face, image):
	for (x, y, w, h) in face:
		crop_image = image[y:y+h, x:x+w]
	return crop_image

def draw_rectangle(face, image):
	for (x, y, w, h) in face:
		cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
	return image

def get_face(filename, face_cascade):
	image = cv2.imread(filename)
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	face = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=2, minSize=(70, 70))
	return face, image

def get_images(path, face_cascade, dest_path, faces_to_detect):
	erros = 0
	for root, dirs, files in os.walk(path, True):
		for name in files:
			face = get_face(os.path.join(root, name), face_cascade)
			check = check_number_faces_detected(face[0], faces_to_detect, os.path.join(root, name))
			if check is True:
				erros = erros + 1
			else:
				image = crop_image(face[0], face[1])
				save_image(image, dest_path, name)
	print erros

def main(argv=None):  # pylint: disable=unused-argument
	face_cascade = cv2.CascadeClassifier("/home/neo/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_default.xml")
	#image_path = "/home/neo/projects/deepLearning/data/image_exp2/"
	#image_path = "/home/neo/projects/deepLearning/data/ck_image_seq_10"
	image_path = "/home/neo/projects/deepLearning/data/amfed/happy"
	#dest_path = "/home/neo/projects/deepLearning/data/crop_faces_seq_10/"
	dest_path = "/home/neo/projects/deepLearning/data/amfed_faces"
	faces_to_detect = 1
	get_images(image_path, face_cascade, dest_path, faces_to_detect)

if __name__ == '__main__':
	main()


text:
namespace v8 {
namespace internal {

class ExtrasUtilsBuiltinsFromDSLAssembler {
 public:
  explicit ExtrasUtilsBuiltinsFromDSLAssembler(compiler::CodeAssemblerState* state) : state_(state), ca_(state) { USE(state_, ca_); }
 private:
  compiler::CodeAssemblerState* const state_;
  compiler::CodeAssembler ca_;
};

}  // namespace internal
}  // namespace v8

#endif  // V8_TORQUE_EXTRAS_UTILS_FROM_DSL_BASE_H__


text:
package net.sf.openmm.frontend2;

import java.util.Arrays;

import net.sf.openmm.frontend2.BaseDynamicActivity.ViewType;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;

import com.intirix.openmm.server.api.MoviePrefixListResponse;
import com.intirix.openmm.server.api.beans.MoviePrefixCounts;

public class MoviePrefixListActivity extends BaseDynamicActivity< MoviePrefixCounts, MoviePrefixListResponse >
{

	@Override
	protected void onCreate( Bundle savedInstanceState )
	{
		super.onCreate( savedInstanceState );
		setTitle( "Movies" );

		GridView gridView = (GridView)findViewById( R.id.grid );
		gridView.setNumColumns( 5 );
	}

	@Override
	protected ViewType getViewType()
	{
		return ViewType.GRID;
	}

	@Override
	protected String getDataUrl()
	{
		return OpenMMUtil.getServerUrl( this ) + "/api/get/movies/prefix/list/all.xml";
	}

	@Override
	protected int getRowLayout()
	{
		return R.layout.movie_prefix_list_row;
	}

	@Override
	protected void applyDataToRow( MoviePrefixCounts obj, View view, Object tag )
	{
		final TextView label = (TextView)view.findViewById( R.id.movie_prefix_list_label );
		//label.setHeight( getTextViewHeight() );
		label.setText( obj.getPrefix() );
		label.setTextSize( TypedValue.COMPLEX_UNIT_PX, getTextMaxHeight() * 2f );
		//label.setGravity( Gravity.CENTER_VERTICAL );

		//final TextView count = (TextView)view.findViewById( R.id.movie_prefix_list_count );
		//count.setText( obj.getNumMoviesAvailable() + "/" + obj.getNumMovies() );
	}

	@Override
	protected Class< MoviePrefixListResponse > getResponseClass()
	{
		return MoviePrefixListResponse.class;
	}

	@Override
	protected void handleResponse( MoviePrefixListResponse response )
	{
		listItems.clear();
		listItems.addAll( Arrays.asList( response.getPrefixes() ) );
	}

	@Override
	protected void onListItemClick( MoviePrefixCounts item, int position )
	{
		final Intent i = new Intent( this, MovieListActivity.class );
		i.putExtra( "PREFIX", item.getPrefix() );
		i.putExtra( "TITLE", "Movies - " + item.getPrefix() );
		startActivity( i );
		overridePendingTransition( android.R.anim.slide_in_left, android.R.anim.slide_out_right );
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<title>Add an Event</title>

<?php // Script 7.9 - event.php
/* This script handle the event form. */

// Address error management, if you want.

// Print the text:
print "
You want to add an event called {$_POST['name']} which takes place on:
";

// Print each weekday:
if (isset($_POST['days']) AND is_array($_POST['days'])) {

	foreach ($_POST['days'] as $day) {
		print "$day
\n";
	}

} else {
	print 'Please select at least one weekday for this event!';
}

// Complete the paragraph:
print '
';
?>


text:
#ifndef SINGLE_STATE_QUEUE_H
#define SINGLE_STATE_QUEUE_H

// Non-blocking single element state queue, or
// Non-blocking single-reader / single-writer multi-word atomic load / store

#include <stdint.h>
#include <cutils/atomic.h>

namespace android {

template<typename T> class SingleStateQueue {

public:

    class Mutator;
    class Observer;

    enum SSQ_STATUS {
        SSQ_PENDING, /* = 0 */
        SSQ_READ,
        SSQ_DONE,
    };

    struct Shared {
        // needs to be part of a union so don't define constructor or destructor

        friend class Mutator;
        friend class Observer;

private:
        void                init() { mAck = 0; mSequence = 0; }

        volatile int32_t    mAck;
        volatile int32_t    mSequence;
        T                   mValue;
    };

    class Mutator {
    public:
        Mutator(Shared *shared)
            : mSequence(0), mShared(shared)
        {
            // exactly one of Mutator and Observer must initialize, currently it is Observer
            // shared->init();
        }

        // push new value onto state queue, overwriting previous value;
        // returns a sequence number which can be used with ack()
        int32_t push(const T& value)
        {
            Shared *shared = mShared;
            int32_t sequence = mSequence;
            sequence++;
            android_atomic_acquire_store(sequence, &shared->mSequence);
            shared->mValue = value;
            sequence++;
            android_atomic_release_store(sequence, &shared->mSequence);
            mSequence = sequence;
            // consider signalling a futex here, if we know that observer is waiting
            return sequence;
        }

        // returns the status of the last state push.  This may be a stale value.
        //
        // SSQ_PENDING, or 0, means it has not been observed
        // SSQ_READ means it has been read
        // SSQ_DONE means it has been acted upon, after Observer::done() is called
        enum SSQ_STATUS ack() const
        {
            // in the case of SSQ_DONE, prevent any subtle data-races of subsequent reads
            // being performed (out-of-order) before the ack read, should the caller be
            // depending on sequentiality of reads.
            const int32_t ack = android_atomic_acquire_load(&mShared->mAck);
            return ack - mSequence & ~1 ? SSQ_PENDING /* seq differ */ :
                    ack & 1 ? SSQ_DONE : SSQ_READ;
        }

        // return true if a push with specified sequence number or later has been observed
        bool ack(int32_t sequence) const
        {
            // this relies on 2's complement rollover to detect an ancient sequence number
            return mShared->mAck - sequence >= 0;
        }

    private:
        int32_t     mSequence;
        Shared * const mShared;
    };

    class Observer {
    public:
        Observer(Shared *shared)
            : mSequence(0), mSeed(1), mShared(shared)
        {
            // exactly one of Mutator and Observer must initialize, currently it is Observer
            shared->init();
        }

        // return true if value has changed
        bool poll(T& value)
        {
            Shared *shared = mShared;
            int32_t before = shared->mSequence;
            if (before == mSequence) {
                return false;
            }
            for (int tries = 0; ; ) {
                const int MAX_TRIES = 5;
                if (before & 1) {
                    if (++tries >= MAX_TRIES) {
                        return false;
                    }
                    before = shared->mSequence;
                } else {
                    android_memory_barrier();
                    T temp = shared->mValue;
                    int32_t after = android_atomic_release_load(&shared->mSequence);
                    if (after == before) {
                        value = temp;
                        shared->mAck = before;
                        mSequence = before; // mSequence is even after poll success
                        return true;
                    }
                    if (++tries >= MAX_TRIES) {
                        return false;
                    }
                    before = after;
                }
            }
        }

        // (optional) used to indicate to the Mutator that the state that has been polled
        // has also been acted upon.
        void done()
        {
            const int32_t ack = mShared->mAck + 1;
            // ensure all previous writes have been performed.
            android_atomic_release_store(ack, &mShared->mAck); // mSequence is odd after "done"
        }

    private:
        int32_t     mSequence;
        int         mSeed;  // for PRNG
        Shared * const mShared;
    };

#if 0
    SingleStateQueue(void /*Shared*/ *shared);
    /*virtual*/ ~SingleStateQueue() { }

    static size_t size() { return sizeof(Shared); }
#endif

};

}   // namespace android

#endif  // SINGLE_STATE_QUEUE_H


text:
function usage {

	local file="icon-generator.sh"
	echo "$file - create images for iOS"
	echo " ++++ inkscape must be in \$PATH ++++"
	echo "$file [options]"
	echo "options:"
	echo -e "-h, --help""\t\t\t""show help data"
	echo -e "-i, --image FILE""\t\t""(Obligatory)""\t""specify image input directory"
	echo -e "-o, --output-directory DIR""\t""(Optional Default 'image-directory"\\\\"icons_DATETIME')""\t""specify image output directory (must exist)"
	echo " "
	echo "Example: ./$file -i ../svg-images/app-icon.svg"
	echo "Example: ./$file -i ../svg-images/app-icon.svg -o ../app-icons"
	exit 0
}

function noArgument {

	echo "You need to pass some arguments."
	usage
}

# Check if argument is passed.
if [ -z "$1" ]; then
	noArgument
	exit 1
fi

# Default values
exportsFolderName="icons_"`date "+%F_%T"`

# Input
inputDirectory=""
inputExtension=""
inputFileNameWithoutExtension=""
# Output
outputDirectory=""
outputDirectoryUpdated=1
outputExtension="png"
outputSizesArray=( 512 1024 120 180 76 152 40 80 120 29 58 87 57 114 50 100 72 144 ) #All

function checkInputImagePath {

	if [ -f "$1" ]; then
		local inputImagePath=$1
		inputDirectory=$(dirname ${inputImagePath})
		inputExtension="${inputImagePath##*.}"
		local inputFileWithExtension=$(basename "$inputImagePath")
		local lengthWithoutExension=$((${#inputFileWithExtension} - ${#inputExtension} - 1))
		inputFileNameWithoutExtension=${inputFileWithExtension:0:$lengthWithoutExension}

		if [[ $outputDirectoryUpdated == 1 ]]; then
			outputDirectory=$(dirname ${inputImagePath})
		fi
		echo "Input image: OK"
	else
		echo "Input image: ERROR"
		echo "Image not found: $inputImagePath"
		exit 1
	fi
}

function checkOutputDirectory {

	if [ -d "$1" ]; then
		outputDirectoryUpdated=0
		outputDirectory=$1
		echo "Output directory: OK"
	else
		echo "Ouput directory: ERROR"
		echo "Directory not found: $outputDirectory"
		exit 1
	fi
}

function generateOutputData {

	if [[ $outputDirectoryUpdated == 1 ]]; then
		# Directory opcion not found
		local exportFolderPath=$outputDirectory"/"$exportsFolderName
		if [ ! -d "$exportFolderPath" ]; then
			echo "Creating exports folder."
			`mkdir $exportFolderPath`
		fi
		# Update output dir
		outputDirectory=$exportFolderPath
	fi
	# If the directory is different do nothing

	# Get all sizes and create images
	for (( x = 0; x < "${#outputSizesArray[@]}"; x++ )); do
		local exportFileName=$inputFileNameWithoutExtension
		local exportSize=${outputSizesArray[$x]}

		exportFileName=$exportFileName"-"$exportSize"x"$exportSize
		echo $exportFileName
		createOutputFile $exportFileName $exportSize
	done
}

function createOutputFile {

	# Output data
	local mOutputFileNameWithoutExtension=$1
	local mOutputSize=$2

	# Create images in output.sh for better image management
	sh ./output.sh $outputDirectory $mOutputFileNameWithoutExtension $outputExtension $mOutputSize $inputDirectory $inputFileNameWithoutExtension $inputExtension
}

function showDebugData {

	exportsFolderName="icons_"`date "+%F_%T"`

	echo "========================== DEBUG - START =========================="
	echo "inputDirectory: $inputDirectory"
	echo "inputExtension: $inputExtension"
	echo "inputFileNameWithoutExtension: $inputFileNameWithoutExtension"

	echo "exportsFolderName: $exportsFolderName"
	echo "outputDirectory: $outputDirectory"
	echo "outputExtension: $outputExtension"
	echo "outputSizesArray:"

	# Index in 'i'
	# Removing '!' value in 'i'
	for i in "${!outputSizesArray[@]}"
	do
		echo "     $i -> ${outputSizesArray[i]}"
	done
	echo "========================== DEBUG - END =========================="
}

while true $# -gt 0; do
	case "$1" in
		-h|--help)
			usage
			;;
		-i|--image)
			checkInputImagePath $2
			shift 2
			;;
		-o|--output-directory)
			checkOutputDirectory $2
			shift 2
			;;
		*)
		echo #"Error: $0 $1 $2 $3 $4 $5"
		break
		;;
	esac
done

#showDebugData
# TODO: Check valid input image
generateOutputData
exit 0


text:
package pourmaster;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Files;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pourmaster.exceptions.ConflictingFieldTypesException;
import pourmaster.fields.Field;
import pourmaster.fields.FieldData;
import pourmaster.postings.Postings;
import pourmaster.search.Query;
import pourmaster.search.RankedDocument;
import pourmaster.search.RankedDocumentId;
import pourmaster.terms.Term;
import pourmaster.terms.TermOccurrence;
import pourmaster.util.Tuple;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * The main class for the inverted index used for lookup.
 */
public class InvertedIndex {

    // TODO: Fuzzy queries
    // TODO: Scoring class
    // TODO: Index compression
    // TODO: Query parser (see https://github.com/jparsec/jparsec )

    private final static Logger LOGGER = LogManager.getLogger(InvertedIndex.class);

    // Number of documents per index iteration
    private final static int DOCS_PER_ITERATION = 10000;

    private final DocumentTypeStore docTypeStore;
    private final TermDictionary dictionary;
    private final DocumentIndex docIndex;
    private FieldNormsStore fieldNormsStore;
    private final Postings postings;
    private final IndexConfig config;

    public InvertedIndex(IndexConfig conf) throws IOException, ReflectiveOperationException {
        this.config = conf;
        new File(conf.getBaseDirectory()).mkdirs();
        this.docIndex = conf.getDocumentIndex().newInstance();
        this.docIndex.init(conf);
        this.dictionary = conf.getTermDictionary().newInstance();
        this.dictionary.init(conf);
        this.docTypeStore = new DocumentTypeStore(conf.getDocumentTypeFilePath());
        this.postings = conf.getPostings().newInstance();
        this.postings.init(conf);
        this.fieldNormsStore = new FieldNormsStore(conf.getFieldNormsFilePath(),
                this.docIndex.getFieldDataStore().getFieldCount(),
                this.docIndex.getDocumentCount());
    }

    public List<RankedDocument> search(Query query) throws IOException, ReflectiveOperationException {
        return search(query, -1);
    }

    public List<RankedDocument> search(Query query, int count) throws IOException, ReflectiveOperationException {
        Iterator<RankedDocumentId> result = query.search(this);
        // Convert documents to original document format
        ArrayList<RankedDocument> docs = new ArrayList<RankedDocument>();
        while (result.hasNext() && (count == -1 || docs.size() < count)) {
            RankedDocumentId dId = result.next();
            Document d = getDocIndex().getDocument(dId.getDocument());
            // Create result object
            Class docType = this.docTypeStore.getDocumentType(d.getDocumentType());
            Object doc = docType.newInstance();
            // Set object fields
            for (FieldData fieldData : d.getFields()) {
                if (fieldData.getField().isStored()) {
                    docType.getField(fieldData.getField().getFieldName()).set(doc, fieldData.getValue());
                }
            }
            docs.add(new RankedDocument(doc, dId.getScore()));
        }
        return docs;
    }

    public void indexDocuments(Iterable<Object> docStream) throws IOException, ReflectiveOperationException {
        this.indexDocuments(docStream.iterator());
    }

    public void indexDocuments(Iterator<Object> docStream) throws IOException, ReflectiveOperationException {
        // Clear index
        deleteAll();

        String tmpDir = config.getTmpDir();
        ArrayList<String> tmpFiles = new ArrayList<>();
        PartialIndexData partialIndex = new PartialIndexData();
        ArrayList<String> partialFiles = new ArrayList<String>(); // Partial files paths
        // Term indices in (per partial file)
        ArrayList<ArrayList<Tuple<Term, Long>>> termIndices = new ArrayList<ArrayList<Tuple<Term, Long>>>();
        final HashMap<Term, TermDictionary.TermData> tempTermData = new HashMap<Term, TermDictionary.TermData>();
        // Mapping from term to document frequencies (per partial file)
        HashMap<Term, List<Integer>> docFrequencies = new HashMap<Term, List<Integer>>(DOCS_PER_ITERATION);
        ArrayList<FieldNormsStore> fieldNormsStores = new ArrayList<FieldNormsStore>();
        // Create first field normalization store
        FieldNormsStore normsStore = createPartialNormsStore(tmpDir, fieldNormsStores.size());
        fieldNormsStores.add(normsStore);
        tmpFiles.add(normsStore.getFile());

        HashMap<String, Field> fieldIds = new HashMap<String, Field>();
        long docId = 0;
        while (docStream.hasNext()) {
            Object document = docStream.next();
            ArrayList<FieldData> fields = new ArrayList<FieldData>();
            HashSet<Term> termsInDoc = new HashSet<Term>();
            for (java.lang.reflect.Field f : document.getClass().getFields()) {
                pourmaster.annotations.Field field = f.getAnnotation(pourmaster.annotations.Field.class);
                if (field != null) {
                    // Check if field already exists - if not, create it
                    if (!fieldIds.containsKey(f.getName())) {
                        Field fieldInfo = new Field();
                        fieldInfo.setFieldName(f.getName());
                        fieldInfo.setFieldId(fieldIds.size());
                        fieldInfo.setFieldType(field.type().newInstance());
                        fieldInfo.setIsIndexed(field.indexed());
                        fieldInfo.setIsStored(field.stored());
                        fieldIds.put(f.getName(), fieldInfo);
                    } else {
                        Field fieldInfo = fieldIds.get(f.getName());
                        if (!field.type().equals(fieldInfo.getFieldType().getClass())) {
                            throw new ConflictingFieldTypesException(
                                    String.format("Conflicting field types for %s: %s and %s",
                                            fieldInfo.getFieldName(), field.type(), fieldInfo.getFieldType().getClass()));
                        }
                    }
                    Field fieldInfo = fieldIds.get(f.getName());
                    if (field.indexed()) {
                        int numTokens = 0;
                        Iterator<Token> tokens = field.indexAnalyzer().newInstance().analyze(f.get(document));
                        while (tokens.hasNext()) {
                            numTokens++;
                            // Index document
                            Token t = tokens.next();
                            partialIndex.addPositionForTerm(t, docId, fieldInfo.getFieldId());

                            // Update document frequency mapping if not already added (only add once per unique term)
                            if (!termsInDoc.contains(t.getValue())) {
                                termsInDoc.add(t.getValue());

                                // Update document frequency
                                if (!docFrequencies.containsKey(t.getValue())) {
                                    docFrequencies.put(t.getValue(), new ArrayList<Integer>(
                                            Collections.nCopies(partialFiles.size() + 1, Integer.valueOf(0))));
                                } else if (docFrequencies.get(t.getValue()).size() <= partialFiles.size()) {
                                    List<Integer> termList = docFrequencies.get(t.getValue());
                                    while (termList.size() <= partialFiles.size()) {
                                        termList.add(0);
                                    }
                                }

                                // Add new doc frequency
                                int oldFreq = docFrequencies.get(t.getValue()).get(partialFiles.size());
                                docFrequencies.get(t.getValue()).set(partialFiles.size(), oldFreq + 1);
                            }
                        }

                        // Set field length
                        normsStore.setFieldNorm(fieldInfo.getFieldId(), docId % DOCS_PER_ITERATION, 1.0f / (float) numTokens);
                    }
                    FieldData fieldData = new FieldData();
                    fieldData.setField(fieldInfo);
                    fieldData.setValue(f.get(document));
                    fields.add(fieldData);
                }

            }
            if ((docId + 1) % DOCS_PER_ITERATION == 0) {
                // Write to disk
                LOGGER.info("Indexed {} documents", docId + 1);
                LOGGER.info("Writing partial file...");
                // Create new partial index and stores
                String outputFile = new File(tmpDir, String.format("postings_%d.part", partialFiles.size())).getAbsolutePath();
                termIndices.add(writePartialPostings(outputFile, partialIndex, tempTermData));
                partialFiles.add(outputFile);
                tmpFiles.add(outputFile);
                partialIndex.clear();

                normsStore = createPartialNormsStore(tmpDir, fieldNormsStores.size());
                fieldNormsStores.add(normsStore);
                tmpFiles.add(normsStore.getFile());
                LOGGER.info("Partial write successful.");
                // Log memory usage
                Runtime runtime = Runtime.getRuntime();
                long memUsage = runtime.totalMemory() - runtime.freeMemory();
                LOGGER.debug("Memory usage {} bytes", memUsage);
            }

            // Add document to document index and field store
            int docType = this.docTypeStore.getOrCreateDocumentType(document.getClass());
            Document doc = new Document(docId, docType, fields);
            docIndex.addDocument(doc);
            docId++;
        }
        // Write remaining postings
        if (partialIndex.size() > 0) {
            String outputFile = new File(tmpDir, String.format("postings_%d.part", partialFiles.size())).getAbsolutePath();
            termIndices.add(writePartialPostings(outputFile, partialIndex, tempTermData));
            partialFiles.add(outputFile);
            tmpFiles.add(outputFile);
        }

        LOGGER.info("Merging partial files...");
        // Merge partial files
        final HashMap<Term, Long> indices = postings.mergePartialPostingsFiles(partialFiles, termIndices, docFrequencies);

        // Insert into dictionary
        this.dictionary.bulkInsertData(
                ImmutableList.copyOf(Collections2.transform(tempTermData.entrySet(),
                        new Function<Map.Entry<Term, TermDictionary.TermData>, Tuple<Term, TermDictionary.TermData>>() {
            public Tuple<Term, TermDictionary.TermData> apply(Map.Entry<Term, TermDictionary.TermData> termEntry) {
                termEntry.getValue().setPostingsIndex(indices.get(termEntry.getKey()));
                return new Tuple<>(termEntry.getKey(), termEntry.getValue());
            }
        })));

        // Merge norms stores
        fieldNormsStore = new FieldNormsStore(config.getFieldNormsFilePath(), fieldIds.size(), docId);
        for (long i = 0; i < docId; i++) {
            FieldNormsStore partial = fieldNormsStores.get((int) (i / DOCS_PER_ITERATION));
            for (Field f : fieldIds.values()) {
                fieldNormsStore.setFieldNorm(f.getFieldId(), i, partial.getFieldNorm(f.getFieldId(), i % DOCS_PER_ITERATION));
            }
        }

        deleteTmpFiles(tmpDir, tmpFiles);
        LOGGER.info("Indexed {} documents", docId + 1);
        LOGGER.info("Indexing completed.");
    }

    private void deleteTmpFiles(String tmpDir, List<String> files) {
        for (String tmpFileName : files) {
            File f = new File(tmpFileName);
            if (f.exists()) {
                f.delete();
            }
        }
        // Delete tmp dir if empty
        try {
            new File(tmpDir).delete();
        } catch (SecurityException e) {
            LOGGER.warn("Could not delete tmp directory", e);
        }
    }

    private FieldNormsStore createPartialNormsStore(String tmpDir, int index) throws IOException {
        return new FieldNormsStore(tmpDir + "/fns_" + index, 256, DOCS_PER_ITERATION);
    }

    private ArrayList<Tuple<Term, Long>> writePartialPostings(String outputFile, PartialIndexData partialIndex, HashMap<Term,
            TermDictionary.TermData> tempTermData) throws IOException {
        ArrayList<Tuple<Term, Long>> termIndices = this.postings.writePartialPostingsToFile(outputFile, partialIndex);
        for (Tuple<Term, Long> term : termIndices) {
            // Aggregate document frequency and term frequency
            int docFreq = 0;
            HashMap<Integer, Integer> fieldDocFreq = new HashMap<Integer, Integer>();
            for (Long docId : partialIndex.getDocsForTerm(term.getFirst())) {
                docFreq += 1;
                // Update per-field doc frequency
                for (TermOccurrence occurrence : partialIndex.getPositionsForDoc(term.getFirst(), docId)) {
                    if (!fieldDocFreq.containsKey(occurrence.getFieldId())) {
                        fieldDocFreq.put(occurrence.getFieldId(), 1);
                    } else {
                        int newFreq = fieldDocFreq.get(occurrence.getFieldId()) + 1;
                        fieldDocFreq.put(occurrence.getFieldId(), newFreq);
                    }
                }
            }
            // Update dictionary
            if (!tempTermData.containsKey(term.getFirst())) {
                tempTermData.put(term.getFirst(), new TermDictionary.TermData(docFreq, fieldDocFreq, term.getSecond()));
            } else {
                // Term already exists: Increase existing docFreq and fieldDocFreq
                TermDictionary.TermData existingData = tempTermData.get(term.getFirst());
                existingData.setDocFrequency(existingData.getDocFrequency() + docFreq);
                for (Map.Entry<Integer, Integer> entry : fieldDocFreq.entrySet()) {
                    if (!existingData.getFieldDocFrequency().containsKey(entry.getKey())) {
                        existingData.getFieldDocFrequency().put(entry.getKey(), entry.getValue());
                    } else {
                        int newVal = existingData.getFieldDocFrequency().get(entry.getKey()) + entry.getValue();
                        existingData.getFieldDocFrequency().put(entry.getKey(), newVal);
                    }
                }
            }
        }

        return termIndices;
    }

    public void deleteAll() throws IOException {
        docTypeStore.deleteAll();
        dictionary.deleteAll();
        docIndex.deleteAll();
        postings.deleteAll();
        fieldNormsStore.deleteAll();
    }

    public void close() {
        dictionary.close();
    }

    public DocumentIndex getDocIndex() {
        return docIndex;
    }

    public Postings getPostings() {
        return postings;
    }

    public TermDictionary getDictionary() {
        return dictionary;
    }

    public IndexConfig getConfig() {
        return config;
    }

    public FieldNormsStore getFieldNormsStore() {
        return fieldNormsStore;
    }

}


text:
namespace msa {
namespace physics {

template <typename T>
struct ParamsT {
    float   timeStep, timeStep2;
    float	drag;

    int		numIterations;
    bool	isCollisionEnabled;

    bool	doGravity;
    T		gravity;

    // do world boundaries
    bool	doWorldEdges;
    T		worldMin;					// use for sectors
    T		worldMax;
    T		worldSize;                  // cache these
    //    T		worldSizeInv;
    T		sectorCount;				// number of sectors in each axis
};

}
}


text:
@interface ChromeIcon : NSObject

// Commonly used icons. Icons that flip in RTL already have their
// flipsForRightToLeftLayoutDirection
// property set accordingly.
+ (UIImage*)backIcon;
+ (UIImage*)closeIcon;
+ (UIImage*)infoIcon;
+ (UIImage*)searchIcon;
+ (UIImage*)chevronIcon;

// Returns a "template" UIBarButtonItem initialized with the given image.
// The returned bar button item will have its image rendering mode set to
// UIImageRenderingModeAlwaysTemplate and will thus take on the tint color of
// its container.
+ (UIBarButtonItem*)templateBarButtonItemWithImage:(UIImage*)image
                                            target:(id)target
                                            action:(SEL)action;

@end

#endif  // IOS_CHROME_BROWSER_UI_ICONS_CHROME_ICON_H_


text:
public class UnresolvedSuperClass {
  public void superMethod() {
    System.out.println("UnresolvedClass.superMethod()");
  }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package org.red5.server.adapter (Red5 :: Server 1.0.7-SNAPSHOT API)</title>
<meta name="date" content="2016-02-18">
<link rel="stylesheet" type="text/css" href="../../../../javadoc.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
org.red5.server.adapter

Packages that use org.red5.server.adapter

Package
Description

org.red5.server.adapter

org.red5.server.api.plugin

org.red5.server.plugin

Classes in org.red5.server.adapter used by org.red5.server.adapter

Class and Description

MultiThreadedApplicationAdapter

ApplicationAdapter class serves as a base class for your Red5 applications.

Classes in org.red5.server.adapter used by org.red5.server.api.plugin

Class and Description

MultiThreadedApplicationAdapter

ApplicationAdapter class serves as a base class for your Red5 applications.

Classes in org.red5.server.adapter used by org.red5.server.plugin

Class and Description

MultiThreadedApplicationAdapter

ApplicationAdapter class serves as a base class for your Red5 applications.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2005–2016 Red5. All rights reserved.


text:
<?php

/**
 * Image transformation to apply rounded corners to the image
 *
 * @package    sfImageTransformExtraPlugin
 * @subpackage transforms
 * @author     Christian Schaefer <caefer@ical.ly>
 */
class sfImageRoundedCornersGD extends sfImageAlphaMaskGD
{

  protected $radius = 5;

  public function __construct($radius, $color = false)
  {
    $this->setRadius($radius);
    $this->setColor($color);
  }

  protected function transform(sfImage $image)
  {
    $this->setMask($this->createMask($image, $image->getWidth(), $image->getHeight()));

    return parent::transform($image);
  }

  public function setRadius($radius)
  {
    if(is_numeric($radius) && $radius > 0)
    {
      $this->radius = $radius;

      return true;
    }

    return false;
  }

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

  protected function createMask(sfImage $image, $w, $h)
  {
    // Create a mask png image of the area you want in the circle/ellipse (a 'magicpink' image with a black shape on it, with black set to the colour of alpha transparency) - $mask
    $mask = $image->getAdapter()->getTransparentImage($w, $h);

    // Set the masking colours
    if (false === $this->getColor() ||'image/png' == $image->getMIMEType())
    {
      $mask_black = imagecolorallocate($mask, 0, 0, 0);
    }
    else
    {
      $mask_black = $image->getAdapter()->getColorByHex($mask, $this->getColor());
    }

    // Cannot use white as transparent mask if color is set to white
    if($this->getColor() === '#FFFFFF' || $this->getColor() === false)
    {
      $mask_transparent = imagecolorallocate($mask, 255, 0, 0);
    }

    else
    {
      $mask_color = imagecolorsforindex($mask, imagecolorat($image->getAdapter()->getHolder(), 0, 0));
      $mask_transparent = imagecolorallocate($mask, $mask_color['red'], $mask_color['green'], $mask_color['blue']);
    }

    imagecolortransparent($mask, $mask_transparent);
    imagefill($mask, 0, 0, $mask_black);

    // Draw the rounded rectangle for the mask
    $this->imagefillroundedrect($mask, 0, 0, $w, $h, $this->getRadius(), $mask_transparent);

    $mask_image = clone $image;
    $mask_image->getAdapter()->setHolder($mask);

    return $mask_image;
  }

  protected function imagefillroundedrect($im, $x, $y, $cx, $cy, $rad, $col)
  {
    // Draw the middle cross shape of the rectangle
    imagefilledrectangle($im, $x, $y + $rad, $cx, $cy - $rad, $col);
    imagefilledrectangle($im, $x + $rad, $y, $cx - $rad, $cy, $col);

    $dia = $rad * 2;

    // Now fill in the rounded corners
    imagefilledellipse($im, $x + $rad, $y + $rad, $rad * 2, $dia, $col);
    imagefilledellipse($im, $x + $rad, $cy - $rad, $rad * 2, $dia, $col);
    imagefilledellipse($im, $cx - $rad, $cy - $rad, $rad * 2, $dia, $col);
    imagefilledellipse($im, $cx - $rad, $y + $rad, $rad * 2, $dia, $col);
  }
}


text:
var app = angular.module('eventmanagerApp', ['angularMoment']);

// http://stackoverflow.com/a/1714899/205832
var serializeObject = function(obj) {
    var str = [];
    for(var p in obj)
      if (obj.hasOwnProperty(p)) {
          str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      }
    return str.join("&");
};

function escapeRegExp(string){
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

// We already have a limitTo filter built-in to angular,
// let's make a startFrom filter
app.filter('startFrom', function() {
    return function(input, start) {
        start = +start; //parse to int
        return input.slice(start);
    };
});

app.controller('EventManagerController',
['$scope', '$http', '$interval', '$timeout',
function EventManagerController($scope, $http, $interval, $timeout) {
    'use strict';

    $scope.first_loading = true;
    $scope.second_loading = true;
    function fetchEvents(params) {
        var url = location.pathname + 'data/';
        url += '?' + serializeObject(params);
        return $http.get(url);
    }
    $scope.events = [];
    $scope.currentPage = 0;
    $scope.sorting = 'modified';
    $scope.sorting_reverse = true;

    $scope.$watch('sorting', function(value) {
        if (value === 'modified') {
            $scope.sorting_reverse = true;
        } else {
            $scope.sorting_reverse = false;
        }
    });

    $scope.toggleSortingReverse = function() {
        $scope.sorting_reverse = !$scope.sorting_reverse;
    };

    $scope.setSorting = function(key) {
        if ($scope.sorting == key) {
            $scope.toggleSortingReverse();
        }
        $scope.sorting = key;
    };

    var pageSize = 10;  // default
    $scope.pageSizeOptions = [10, 25, 50];
    // attempt to load a different number from localStorage
    var pageSizeStorageKey = 'pageSize' + window.location.pathname;
    if (window.localStorage) {
        var localpageSize = window.localStorage.getItem(pageSizeStorageKey);
        if (localpageSize) {
            pageSize = +localpageSize;
        }
    }
    $scope.pageSize = pageSize;
    $scope.$watch('pageSize', function(value) {
        if (window.localStorage) {
            window.localStorage.setItem(pageSizeStorageKey, value);
        }
    });

    $scope.numberOfPages = function(items){
        if (typeof items === 'undefined') return 0;
        return Math.ceil(items.length / $scope.pageSize);
    };
    $scope.formatDate = function(date) {
        return moment(date).format('ddd, MMM D, YYYY, h:mma UTCZZ');
    };

    $scope.resetCurrentPage = function() {
        $scope.currentPage = 0;
    };
    $scope.resetFilter = function(key) {
        $scope[key] = '';
    };

    /* Filtering */
    $scope.hasFilter = function() {
        return ($scope.search_title ||
                $scope.search_location ||
                $scope.search_cat_chan ||
                $scope.search_archived ||
                $scope.search_status ||
                $scope.search_start_time ||
                $scope.search_privacy ||
                $scope.search_only);
    };
    $scope.clearFilter = function() {
        $scope.search_title = '';
        $scope.search_location = '';
        $scope.search_archived = '';
        $scope.search_cat_chan = '';
        $scope.search_status = '';
        $scope.search_privacy = '';
        $scope.search_start_time = '';
        $scope.search_only = '';
    };

    $scope.search_title = '';
    var search_title_regexes = [];
    var search_slug_regex = null;
    $scope.$watch('search_title', function(value) {
        search_title_regexes = [];
        angular.forEach(value.trim().split(' '), function(part) {
            search_title_regexes.push(new RegExp('\\b' + escapeRegExp(part), 'i'));
        });
        if (value.trim()) {
            search_slug_regex = new RegExp('^' + escapeRegExp(value.trim()), 'i');
        }
        $scope.currentPage = 0;
    });

    $scope.search_location = '';
    var search_location_regex = null;
    $scope.$watch('search_location', function(value) {
        search_location_regex = new RegExp(escapeRegExp(value), 'i');
        $scope.currentPage = 0;
    });

    $scope.search_cat_chan = '';
    var search_cat_chan_regex = null;
    $scope.$watch('search_cat_chan', function(value) {
        search_cat_chan_regex = new RegExp(escapeRegExp(value), 'i');
        $scope.currentPage = 0;
    });

    $scope.search_status = '';
    $scope.search_privacy = '';
    $scope.search_start_time = '';
    $scope.search_archived = '';
    $scope.search_only = '';

    $scope.$watch('search_status', function() {
        $scope.currentPage = 0;
    });
    $scope.$watch('search_privacy', function() {
        $scope.currentPage = 0;
    });
    $scope.$watch('search_start_time', function() {
        $scope.currentPage = 0;
    });
    $scope.$watch('search_archived', function() {
        $scope.currentPage = 0;
    });
    $scope.$watch('search_only', function() {
        $scope.currentPage = 0;
    });

    $scope.filterBySearch = function(event) {
        if (!$scope.hasFilter()) return true;

        // gimme a reason NOT to include this
        if ($scope.search_title) {
            var unmatched = false;
            angular.forEach(search_title_regexes, function(regex) {
                if (!unmatched && !regex.test(event.title)) {
                    unmatched = true;
                }
            });
            if (unmatched && search_slug_regex && search_slug_regex.test(event.slug)) {
                unmatched = false;
            }
            // at least one regex said no
            if (unmatched) return false;
        }
        if ($scope.search_location) {
            if (['blank', 'empty', 'pre-recorded'].indexOf($scope.search_location) > -1) {
                // then strangely match those with no location
                if (event.location) {
                    return false;
                }
            } else if (!search_location_regex.test(event.location)) {
                return false;
            }
        }
        if ($scope.search_cat_chan) {
            // it must match either the category or one of the channels
            var something = false;
            if (search_cat_chan_regex.test(event.category)) {
                something = true;
            } else {
                angular.forEach(event.channels, function(channel) {
                    if (!something && search_cat_chan_regex.test(channel)) {
                        something = true;
                    }
                });
            }
            //if (!something) return false;
            return something;
        }
        if ($scope.search_status && $scope.search_status !== event.status) {
            return false;
        }
        if ($scope.search_privacy && $scope.search_privacy !== event.privacy) {
            return false;
        }
        if ($scope.search_start_time && !in_search_start_time_range(moment(event.start_time_iso))) {
            return false;
        }
        if ($scope.search_archived) {
            if ($scope.search_archived === 'archived') {
                if (!event.archive_time) {
                    return false;
                }
            } else {
                if (event.archive_time) {
                    return false;
                }
            }
        }
        if ($scope.search_only) {
            if ($scope.search_only === 'upcoming') {
                return !!event.is_upcoming;
            } else if ($scope.search_only === 'needs_approval') {
                return !!event.needs_approval;
            } else if ($scope.search_only === 'live') {
                return !!event.is_live;
            } else if ($scope.search_only === 'pictureless') {
                return !!event.pictureless;
            } else {
                console.warn('Unrecognized option', $scope.search_only);
            }
        }
        return true;
    };
    var search_start_times = [];
    $scope.$watch('search_start_time', function(value) {
        if (value) {
            value = moment.utc(value);
            search_start_times = [value, value.clone().add('days', 1)];
            $scope.sorting = 'start_time_iso';
            $scope.sorting_reverse = true;
        }
    });
    function in_search_start_time_range(date) {
        return date > search_start_times[0];
    }

    $scope.selectSearchStatus = function(status) {
        $scope.search_status = status;
    };
    $scope.selectSearchPrivacy = function(privacy) {
        $scope.search_privacy = privacy;
    };
    $scope.selectSearchOnly = function(only) {
        if (only === $scope.search_only) {
            $scope.search_only = '';
        } else {
            $scope.search_only = only;
        }
    };
    /* End filtering */

    $scope.urls = {};
    $scope.url = function(viewname, item) {
        if (!$scope.urls[viewname]) {
            console.warn('No known URL view by that name', viewname);
        }
        return $scope.urls[viewname].replace('0', item);
    };

    $scope.modified_events = [];

    $scope.replaceModifiedEvents = function() {
        var modified = {};
        $scope.modified_events.forEach(function(event) {
            modified[event.id] = event;
        });
        $scope.events.forEach(function(event, i) {
            if (modified[event.id]) {
                $scope.events[i] = modified[event.id];
                delete modified[event.id];
            }
        });
        // add what's left
        for (var id in modified) {
            $scope.events.push(modified[id]);
        }
        $scope.max_modified = $scope.next_max_modified;
        $scope.modified_events = [];
    };

    function lookForModifiedEvents() {
        /* This function is repeatedly called in an interval timer */
        fetchEvents({since: $scope.max_modified})
        .success(function(response) {
            if (response.max_modified) {
                $scope.modified_events = response.events;
                $scope.next_max_modified = response.max_modified;
            }
        })
        .error(function() {
            console.error.apply(console, arguments);
        });
    }

    $scope.load_error = null;

    function loadAll() {
        fetchEvents({})
          .success(function(data) {
              $scope.load_error = null;
              localStorage.setItem('eventmanager', JSON.stringify(data));
              $scope.events = data.events;
              $scope.max_modified = data.max_modified;

              // This update looking for modified events doesn't need
              // to be initialized immediately. It can wait a little bit.
              $timeout(function() {
                  var reloadInterval = 10; // seconds
                  if (typeof window.Fanout !== 'undefined') {
                      window.Fanout.subscribe('/events', function(data) {
                          $scope.$apply(lookForModifiedEvents);
                      });
                      reloadInterval = 60;
                  }
                  // every 10 seconds, look for for changed events
                  $interval(lookForModifiedEvents, reloadInterval * 1000);
              }, 2 * 1000);

          }).error(function(data, status) {
              console.log(data, status);
              $scope.load_error = 'Failed to fetch ALL events (' + status + ')';
          }).finally(function() {
              $scope.second_loading = false;
          });
    }

    $scope.retryLoadAll = loadAll;

    function loadSome() {
        fetchEvents({limit: $scope.pageSize})
          .success(function(data) {
              $scope.urls = data.urls;
              $scope.events = data.events;
              loadAll();
          }).error(function(data, status) {
              console.warn('Failed to fetch events', status);
          }).finally(function() {
              $scope.first_loading = false;
          });
    }
    loadSome();

    // A legacy fix. We used to store ALL cached events in localStorage
    // under the key `eventmanager`. This is often a HUGE JSON string.
    // We're no longer depending on that and we can remove it now.
    // This whole code segment can be deleted around the end of 2016.
    setTimeout(function() {
        // Reason for using setTimeout instead of angular $timeout is
        // because, this will never modify the scope.
        localStorage.removeItem('eventmanager');
    }, 5000);
    // -end legacy fixup.

}]);


text:
<?php
namespace canis\broadcaster\handlers\configuration;
class WebClientConfiguration extends Configuration
{
	public function getDescriptor()
	{
		return null;
	}

	public function rules()
	{
		return [];
	}

	public function getAttributeConfig()
	{
		return [];
	}

	/**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [];
    }
}


text:
package uk.ac.ebi.eva.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Scanner;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Estimate the number of lines in a file.
 */
public class FileWithHeaderNumberOfLinesEstimator {
    private static final Logger logger = LoggerFactory.getLogger(FileWithHeaderNumberOfLinesEstimator.class);

    private static final int MAX_NUMBER_OF_LINES = 10000;

    private static final String HEADER_PREFIX = "#";

    private File bodyFile;

    private File headFile;

    /**
     * Given that a file with header could be VERY big then we estimate the number of lines using the following steps:
     * 1) retrieve the size in bytes of the whole zipped file (fileSize)
     * 2) retrieve the size in bytes of the head of the file in a zipped file (headFileSize)
     * 3) retrieve the size in bytes of the first MAX_NUMBER_OF_LINES lines of the file in a zipped file and divide the
     * value by MAX_NUMBER_OF_LINES to obtain the size of a single line (singleLineSize)
     * 4) calculate the (fileSize - headFileSize) / singleLineSize to estimate the total number of line in the file.
     *

     * Why MAX_NUMBER_OF_LINES in point 3?
     * Tested on a file with 157049 lines, MAX_NUMBER_OF_LINES is the best and minimum number of lines to compress. This
     * should generate an estimated total number of lines similar to the real one.
     *

     * In case of small files the MAX_NUMBER_OF_LINES will be the actual number of lines.
     *
     * @param filePath location of the file
     * @return the approximated number of lines in the file
     */
    public long estimateNumberOfLines(String filePath) {
        logger.debug("Estimating the number of lines in file {}", filePath);

        long linesInBody = copyHeadAndBody(filePath);

        long estimatedTotalNumberOfLines;
        if (skipEstimation(linesInBody)) {
            estimatedTotalNumberOfLines = linesInBody;
            logger.info("Number of lines in file {}: {} lines", filePath, estimatedTotalNumberOfLines);
        } else {
            estimatedTotalNumberOfLines = getEstimatedTotalNumberOfLines(filePath);
            logger.info("Estimated number of lines in file {}: {} lines", filePath, estimatedTotalNumberOfLines);
        }

        return estimatedTotalNumberOfLines;
    }

    private boolean skipEstimation(long linesReadInBody) {
        return linesReadInBody < MAX_NUMBER_OF_LINES;
    }

    /**
     * @return lines in the body. It will be min(MAX_NUMBER_OF_LINES, actualLinesInTheBody)
     */
    private long copyHeadAndBody(String filePath) {
        long linesInBody = 0;
        try {
            headFile = File.createTempFile("headFile", ".gz");
            bodyFile = File.createTempFile("bodyFile", ".gz");
        } catch (IOException e) {
            throw new RuntimeException("Error creating file", e);
        }

        try (Writer head = getOutputStreamWriter(headFile); Writer body = getOutputStreamWriter(bodyFile);
             Scanner scanner = new Scanner(new GZIPInputStream(new FileInputStream(filePath)))) {
            while (scanner.hasNextLine() && linesInBody < MAX_NUMBER_OF_LINES) {
                String line = scanner.nextLine();
                if (line.startsWith(HEADER_PREFIX)) {
                    head.write(line);
                    head.write("\n");
                } else {
                    linesInBody++;
                    body.write(line);
                    body.write("\n");
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Error writing to file", e);
        }
        return linesInBody;
    }

    private OutputStreamWriter getOutputStreamWriter(File file) throws IOException {
        return new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(file)), "UTF-8");
    }

    private long getEstimatedTotalNumberOfLines(String filePath) {
        long fileSize = new File(filePath).length();
        long singleLineSize = bodyFile.length() / MAX_NUMBER_OF_LINES;
        long headFileSize = headFile.length();

        headFile.deleteOnExit();
        bodyFile.deleteOnExit();

        long estimatedTotalNumberOfLines = ((fileSize - headFileSize) / singleLineSize);
        return estimatedTotalNumberOfLines;
    }

}


text:
const path = require('path')
const changeCase = require('change-case')

module.exports = (plop, config) => {
  plop.setGenerator(`${config.prefix}component`, {
    description: 'Generate Component',
    prompts: [{
      type: 'input',
      message: 'Component name',
      name: 'componentName',
      validate: (value) => {
        if (!value.length) return 'A component name is required.'
        if (!value.match(/^[a-zA-Z]+$/)) return 'A component name can only contain letters.'
        if (changeCase.pascalCase(value) !== value) return 'A component name must be written in PascalCase.'
        return true
      }
    }],
    actions: (answers) => {
      const actions = [{
        type: 'add',
        path: path.resolve(config.basePath, 'components', answers.componentName, 'index.js'),
        templateFile: path.resolve(__dirname, 'component.hbs')
      }, {
        type: 'add',
        path: path.resolve(config.basePath, 'components', answers.componentName, 'style.scss'),
        templateFile: path.resolve(__dirname, 'component.scss.hbs')
      }]

      return actions
    }
  })
}


text:
<BroadcastMonitor>
  <updated>2015-08-02T17:38:59</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-02T17:38:57</startTime>
    <itemId>1000080497:0</itemId>
    <titleId>216135453</titleId>
    <itemCode>10144</itemCode>
    <itemReference></itemReference>
    <titleName>Don't Worry (Feat Ray Dalton)</titleName>
    <artistName>Madcon</artistName>
    <albumName></albumName>
    <CategoryCode>874</CategoryCode>
    <CategoryName>ZATERDAG</CategoryName>
    <itemDuration>215</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-02T17:42:25</startTime>
    <itemId>1000080497:1240783</itemId>
    <titleId>190148121</titleId>
    <itemCode>HDX2574-0032</itemCode>
    <itemReference>HDX2574-0032</itemReference>
    <titleName>The Best Is Yet To Come</titleName>
    <artistName>Frank Sinatra & Count Basie & His Orchestra </artistName>
    <albumName></albumName>
    <CategoryCode>737</CategoryCode>
    <CategoryName>JAZZ</CategoryName>
    <itemDuration>173</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>