text:
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using OpenMetaverse;

namespace OpenSim.Services.Connectors
{
    public class GridServicesConnector : IGridService
    {
        private static readonly ILog m_log =
                LogManager.GetLogger(
                MethodBase.GetCurrentMethod().DeclaringType);

        private string m_ServerURI = String.Empty;

        public GridServicesConnector()
        {
        }

        public GridServicesConnector(string serverURI)
        {
            m_ServerURI = serverURI.TrimEnd('/');
        }

        public GridServicesConnector(IConfigSource source)
        {
            Initialise(source);
        }

        public virtual void Initialise(IConfigSource source)
        {
            IConfig gridConfig = source.Configs["GridService"];
            if (gridConfig == null)
            {
                m_log.Error("[GRID CONNECTOR]: GridService missing from OpenSim.ini");
                throw new Exception("Grid connector init error");
            }

            string serviceURI = gridConfig.GetString("GridServerURI",
                    String.Empty);

            if (serviceURI == String.Empty)
            {
                m_log.Error("[GRID CONNECTOR]: No Server URI named in section GridService");
                throw new Exception("Grid connector init error");
            }
            m_ServerURI = serviceURI;
        }

        #region IGridService

        public virtual string RegisterRegion(UUID scopeID, GridRegion regionInfo)
        {
            Dictionary<string, object> rinfo = regionInfo.ToKeyValuePairs();
            Dictionary<string, object> sendData = new Dictionary<string,object>();
            foreach (KeyValuePair<string, object> kvp in rinfo)
                sendData[kvp.Key] = (string)kvp.Value;

            sendData["SCOPEID"] = scopeID.ToString();
            sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
            sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
            sendData["METHOD"] = "register";

            string reqString = ServerUtils.BuildQueryString(sendData);
            // m_log.DebugFormat("[GRID CONNECTOR]: queryString = {0}", reqString);
            try
            {
                string reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/grid",
                        reqString);
                if (reply != string.Empty)
                {
                    Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                    if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "success"))
                    {
                        return String.Empty;
                    }
                    else if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "failure"))
                    {
                        m_log.DebugFormat("[GRID CONNECTOR]: Registration failed: {0}", replyData["Message"].ToString());
                        return replyData["Message"].ToString();
                    }
                    else if (!replyData.ContainsKey("Result"))
                    {
                        m_log.DebugFormat("[GRID CONNECTOR]: reply data does not contain result field");
                    }
                    else
                    {
                        m_log.DebugFormat("[GRID CONNECTOR]: unexpected result {0}", replyData["Result"].ToString());
                        return "Unexpected result "+replyData["Result"].ToString();
                    }

                }
                else
                    m_log.DebugFormat("[GRID CONNECTOR]: RegisterRegion received null reply");
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
            }

            return "Error communicating with grid service";
        }

        public virtual bool DeregisterRegion(UUID regionID)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();

            sendData["REGIONID"] = regionID.ToString();

            sendData["METHOD"] = "deregister";

            try
            {
                string reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/grid",
                        ServerUtils.BuildQueryString(sendData));

                if (reply != string.Empty)
                {
                    Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                    if ((replyData["Result"] != null) && (replyData["Result"].ToString().ToLower() == "success"))
                        return true;
                }
                else
                    m_log.DebugFormat("[GRID CONNECTOR]: DeregisterRegion received null reply");
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
            }

            return false;
        }

        public virtual List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();

            sendData["SCOPEID"] = scopeID.ToString();
            sendData["REGIONID"] = regionID.ToString();

            sendData["METHOD"] = "get_neighbours";

            List<GridRegion> rinfos = new List<GridRegion>();

            string reqString = ServerUtils.BuildQueryString(sendData);
            string reply = string.Empty;
            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/grid",
                        reqString);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
                return rinfos;
            }

            Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);

            if (replyData != null)
            {
                Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
                //m_log.DebugFormat("[GRID CONNECTOR]: get neighbours returned {0} elements", rinfosList.Count);
                foreach (object r in rinfosList)
                {
                    if (r is Dictionary<string, object>)
                    {
                        GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
                        rinfos.Add(rinfo);
                    }
                    else
                        m_log.DebugFormat("[GRID CONNECTOR]: GetNeighbours {0}, {1} received invalid response type {2}",
                            scopeID, regionID, r.GetType());
                }
            }
            else
                m_log.DebugFormat("[GRID CONNECTOR]: GetNeighbours {0}, {1} received null response",
                    scopeID, regionID);

            return rinfos;
        }

        public virtual GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();

            sendData["SCOPEID"] = scopeID.ToString();
            sendData["REGIONID"] = regionID.ToString();

            sendData["METHOD"] = "get_region_by_uuid";

            string reply = string.Empty;
            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/grid",
                        ServerUtils.BuildQueryString(sendData));
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
                return null;
            }

            GridRegion rinfo = null;

            if (reply != string.Empty)
            {
                Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                if ((replyData != null) && (replyData["result"] != null))
                {
                    if (replyData["result"] is Dictionary<string, object>)
                        rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
                    //else
                    //    m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response",
                    //        scopeID, regionID);
                }
                else
                    m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response",
                        scopeID, regionID);
            }
            else
                m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID received null reply");

            return rinfo;
        }

        public virtual GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();

            sendData["SCOPEID"] = scopeID.ToString();
            sendData["X"] = x.ToString();
            sendData["Y"] = y.ToString();

            sendData["METHOD"] = "get_region_by_position";
            string reply = string.Empty;
            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/grid",
                        ServerUtils.BuildQueryString(sendData));
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
                return null;
            }

            GridRegion rinfo = null;
            if (reply != string.Empty)
            {
                Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                if ((replyData != null) && (replyData["result"] != null))
                {
                    if (replyData["result"] is Dictionary<string, object>)
                        rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
                    else
                        m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received invalid response",
                            scopeID, x, y);
                }
                else
                    m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received null response",
                        scopeID, x, y);
            }
            else
                m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition received null reply");

            return rinfo;
        }

        public virtual GridRegion GetRegionByName(UUID scopeID, string regionName)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();

            sendData["SCOPEID"] = scopeID.ToString();
            sendData["NAME"] = regionName;

            sendData["METHOD"] = "get_region_by_name";
            string reply = string.Empty;
            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/grid",
                        ServerUtils.BuildQueryString(sendData));
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
                return null;
            }

            GridRegion rinfo = null;
            if (reply != string.Empty)
            {
                Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                if ((replyData != null) && (replyData["result"] != null))
                {
                    if (replyData["result"] is Dictionary<string, object>)
                        rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
                }
                else
                    m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1} received null response",
                        scopeID, regionName);
            }
            else
                m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByName received null reply");

            return rinfo;
        }

        public virtual List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();

            sendData["SCOPEID"] = scopeID.ToString();
            sendData["NAME"] = name;
            sendData["MAX"] = maxNumber.ToString();

            sendData["METHOD"] = "get_regions_by_name";
            List<GridRegion> rinfos = new List<GridRegion>();
            string reply = string.Empty;
            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/grid",
                        ServerUtils.BuildQueryString(sendData));
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
                return rinfos;
            }

            if (reply != string.Empty)
            {
                Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                if (replyData != null)
                {
                    Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
                    foreach (object r in rinfosList)
                    {
                        if (r is Dictionary<string, object>)
                        {
                            GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
                            rinfos.Add(rinfo);
                        }
                        else
                            m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName {0}, {1}, {2} received invalid response",
                                scopeID, name, maxNumber);
                    }
                }
                else
                    m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName {0}, {1}, {2} received null response",
                        scopeID, name, maxNumber);
            }
            else
                m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName received null reply");

            return rinfos;
        }

        public virtual List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();

            sendData["SCOPEID"] = scopeID.ToString();
            sendData["XMIN"] = xmin.ToString();
            sendData["XMAX"] = xmax.ToString();
            sendData["YMIN"] = ymin.ToString();
            sendData["YMAX"] = ymax.ToString();

            sendData["METHOD"] = "get_region_range";

            List<GridRegion> rinfos = new List<GridRegion>();
            string reply = string.Empty;
            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/grid",
                        ServerUtils.BuildQueryString(sendData));

                //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
                return rinfos;
            }

            if (reply != string.Empty)
            {
                Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                if (replyData != null)
                {
                    Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
                    foreach (object r in rinfosList)
                    {
                        if (r is Dictionary<string, object>)
                        {
                            GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
                            rinfos.Add(rinfo);
                        }
                    }
                }
                else
                    m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange {0}, {1}-{2} {3}-{4} received null response",
                        scopeID, xmin, xmax, ymin, ymax);
            }
            else
                m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange received null reply");

            return rinfos;
        }

        #endregion

    }
}


text:
<?php
include('header.php');
$page_id=$_GET['page'];
?>

		  	  <?php include('sidebar.php');?>

Project Details

  			<?php $pros=$zoom->select('projects',"id='$page_id'",'*');
                foreach ($pros as $pro) {

            ?>

<?php echo $pro['name'];?>

<?php echo $pro['title'];?>
posted by: zac on <?php echo date('M-d',strtotime($pro['date']));?>

<?php echo $pro['description'];?>

Comments

  <?php
   $project_id= $pro['project_id'];
  $comments =$zoom->select('comments',"project_id='$project_id'  order by id DESC","*");
foreach ($comments as $comment) {
  ?>

<?php echo $comment['author_name'];?>
posted on <?php echo date('M-d',strtotime($comment['date']));?>

<?php echo $comment['description'];?>

<?php if($zoom->is_admin()){?>

<form  class="update_form">
 <input type="hidden" name="id" value="<?Php echo $comment['id'] ;?>">
 <input type="hidden" name="table" value="comments">
 <input type="hidden" name="action" value="astatus">
<input type="checkbox" <?php if($comment['status']==1){echo 'checked';}else{echo 'unchecked';} ?> data-toggle="toggle" data-on="Activated" data-off="Not Activated" data-onstyle="success" data-offstyle="danger" class="supdate" name="status">
</form>

   <form action="delete.php" method="post">
 <input type="hidden" name="id" value="<?Php echo $comment['id'] ;?>">
 <input type="hidden" name="table" value="comments">

<input type="submit" value="Delete" name="Delete" class="btn  btn-danger glyphicon-trash">
   </form>
   <?php }?>
<?php }?>

<button class="btn btn-warning btn-lg" id="adcom"> Add Comment</button>

     <form action="comment.php"  id="ajaxform">
      <input type="hidden" name="action" value="comment">
      <input type="hidden" name="pro_id" value="<?Php echo $project_id;?>">

   <textarea id="tinymce_full" name="posts"></textarea>

<input type="submit" value="Add Comment" name="submit" class="btn btn-warning btn-lg" id="adcoms">

       </form>

Project Related documents

         <?php $types= $pro['attachements'];
 $type=explode(".",$types);
?>

  <a href="<?php echo $pro['attachements'];?>" target="blank"><img src="images/<?php echo $type['1'] ;?>.jpg" width='25%'/>    <?php echo $pro['file_description'];?>

  		<?php }?>

               Copyright 2014 Website

    <link href="https://gitcdn.github.io/bootstrap-toggle/2.0.0/css/bootstrap-toggle.min.css" rel="stylesheet">

redpajama_set_name: RedPajamaGithub


text:
Reports calls to .equals() where the target and argument are
of incompatible types. While such a call might theoretically be useful, most likely it represents
a bug.


text:
object Test extends App {
  def expectUnit(): Unit = {
    Macros.foo(true)
  }
}


text:
require "securerandom"
require "yaml"
require "time"
require "uri"
require "forwardable"

# External gems
require "rbnacl/libsodium"
require "macaroons"

require "boulangerie/version"

# Boulangerie Classes
require "boulangerie/identifier"
require "boulangerie/keyring"
require "boulangerie/macaroon"
require "boulangerie/predicate"
require "boulangerie/schema"
require "boulangerie/type"
require "boulangerie/verifier"

# Boulangerie Predicate Matchers
require "boulangerie/matcher/expires"
require "boulangerie/matcher/not_before"

# Boulangerie Types
require "boulangerie/type/list"

require "boulangerie/type/atom"
require "boulangerie/type/binary"
require "boulangerie/type/boolean"
require "boulangerie/type/date_time"
require "boulangerie/type/decimal"
require "boulangerie/type/uri"

# An opinionated library for creating and verifying Macaroons in Ruby
class Boulangerie
  attr_reader :schema

  # Version of the format used
  FORMAT_VERSION = 0

  # Raised if Boulangerie's global maker hasn't been configured
  NotConfiguredError = Class.new(StandardError)

  # Caveats are invalid
  InvalidCaveatError = Class.new(StandardError)

  # Problems with serialization/deserialization
  SerializationError = Class.new(StandardError)

  # Default Boulangerie
  @default = nil

  def self.setup(**args)
    @default = new(**args)
  end

  def self.default
    fail NotConfiguredError, "not configured yet, call #{self}.setup" unless @default
    @default
  end

  def self.bake(**args)
    default.bake(**args)
  end

  def initialize(schema: nil, keyring: nil, location: nil, matchers: {})
    @schema =
      case schema
      when Schema           then schema
      when String, Pathname then Schema.from_yaml(File.read(schema.to_s))
      else fail TypeError,  "bad schema type: #{schema.class}"
      end.freeze

    @location = location || fail(ArgumentError, "no location given")
    @keyring  = keyring  || fail(ArgumentError, "no keyring given")

    matchers  = Hash[matchers.map { |k, v| [caveat_id(k), v] }]
    @verifier = Verifier.new(schema: @schema, matchers: matchers).freeze
  end

  # Creates a "golden macaroon" with no caveats
  # WARNING: This bypasses the security benefits Boulangerie ordinarily
  # provides. Make sure you know what you're doing!
  #
  # @return [Boulangerie::Macaroon] a new golden Macaroon object with no caveats
  def golden_macaroon!
    identifier = Identifier.new(
      schema_id:      @schema.schema_id,
      schema_version: @schema.schema_version,
      key_id:         @keyring.default_key_id
    )

    Boulangerie::Macaroon.new(
      key:        @keyring.default_key,
      identifier: identifier,
      location:   @location
    )
  end

  # Creates a new Macaroon object from the given caveats
  #
  # @param [Hash] :caveats to include in the generated Macaroon
  #
  # @return [Macaroon] a new Macaroon object from the macaroons gem
  def create_macaroon(caveats: {})
    caveat_keys = caveats.keys.map { |id| caveat_id(id) }
    unspecified_predicates = @schema.predicates.keys - caveat_keys

    unless unspecified_predicates.empty?
      fail InvalidCaveatError, "no caveat specified for #{unspecified_predicates.first}"
    end

    golden_macaroon!.tap do |macaroon|
      caveat_keys.zip(caveats.values).each do |id, caveat|
        predicate = @schema.predicates[id]
        fail InvalidCaveatError, "no predicate in schema for: #{id.inspect}" unless predicate

        macaroon.add_first_party_caveat(id, predicate.serialize(caveat))
      end
    end
  end

  # Creates a serialized macaroon as a String for use in a cookie
  #
  # @param [Hash] :caveats to pass to #create_macaroon
  #
  # @return [String] a serialized Macaroon that can be used as a cookie
  def bake(**args)
    create_macaroon(**args).serialize
  end

  # Parse a Macaroon and verify it against the registered predicate matchers
  def parse_and_verify(serialized_token)
    macaroon  = Boulangerie::Macaroon.from_binary(serialized_token)
    schema_id = macaroon.identifier.schema_id

    unless schema_id == @schema.schema_id
      fail SerializationError, "bad schema ID: #{schema_id} (expected #{@schema.schema_id})"
    end

    @verifier.verify(
      key: @keyring.fetch(macaroon.identifier.key_id),
      macaroon: macaroon,
      discharge_macaroons: []
    )

    macaroon
  end

  def caveat_id(id)
    id.to_s.tr("_", "-")
  end
end


text:
@interface DoneTableVC : UIViewController <UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UITableView *DoneTable;
@property (nonatomic) NSInteger numberofrows;      //number of rows

@end


text:
FROM alpine:3.15

# dependencies required for running "phpize"
# these get automatically installed and removed by "docker-php-ext-*" (unless they're already installed)
ENV PHPIZE_DEPS \
		autoconf \
		dpkg-dev dpkg \
		file \
		g++ \
		gcc \
		libc-dev \
		make \
		pkgconf \
		re2c

# persistent / runtime deps
RUN apk add --no-cache \
		ca-certificates \
		curl \
		tar \
		xz \
# https://github.com/docker-library/php/issues/494
		openssl

# ensure www-data user exists
RUN set -eux; \
	adduser -u 82 -D -S -G www-data www-data
# 82 is the standard uid/gid for "www-data" in Alpine
# https://git.alpinelinux.org/aports/tree/main/apache2/apache2.pre-install?h=3.14-stable
# https://git.alpinelinux.org/aports/tree/main/lighttpd/lighttpd.pre-install?h=3.14-stable
# https://git.alpinelinux.org/aports/tree/main/nginx/nginx.pre-install?h=3.14-stable

ENV PHP_INI_DIR /usr/local/etc/php
RUN set -eux; \
	mkdir -p "$PHP_INI_DIR/conf.d"; \
# allow running as an arbitrary user (https://github.com/docker-library/php/issues/743)
	[ ! -d /var/www/html ]; \
	mkdir -p /var/www/html; \
	chown www-data:www-data /var/www/html; \
	chmod 777 /var/www/html

# Apply stack smash protection to functions using local buffers and alloca()
# Make PHP's main executable position-independent (improves ASLR security mechanism, and has no performance impact on x86_64)
# Enable optimization (-O2)
# Enable linker optimization (this sorts the hash buckets to improve cache locality, and is non-default)
# https://github.com/docker-library/php/issues/272
# -D_LARGEFILE_SOURCE and -D_FILE_OFFSET_BITS=64 (https://www.php.net/manual/en/intro.filesystem.php)
ENV PHP_CFLAGS="-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64"
ENV PHP_CPPFLAGS="$PHP_CFLAGS"
ENV PHP_LDFLAGS="-Wl,-O1 -pie"

ENV GPG_KEYS 1729F83938DA44E27BA0F4D3DBDB397470D12172 BFDDD28642824F8118EF77909B67A5C12229118F 2C16C765DBE54A088130F1BC4B9B5F600B55F3B4

ENV PHP_VERSION 8.0.26RC1
ENV PHP_URL="https://downloads.php.net/~pollita/php-8.0.26RC1.tar.xz" PHP_ASC_URL="https://downloads.php.net/~pollita/php-8.0.26RC1.tar.xz.asc"
ENV PHP_SHA256="42ed42933d850a99e3afab0927524e199b3e3aaf2536ac3abfb7fca24c1635ad"

RUN set -eux; \
	\
	apk add --no-cache --virtual .fetch-deps gnupg; \
	\
	mkdir -p /usr/src; \
	cd /usr/src; \
	\
	curl -fsSL -o php.tar.xz "$PHP_URL"; \
	\
	if [ -n "$PHP_SHA256" ]; then \
		echo "$PHP_SHA256 *php.tar.xz" | sha256sum -c -; \
	fi; \
	\
	if [ -n "$PHP_ASC_URL" ]; then \
		curl -fsSL -o php.tar.xz.asc "$PHP_ASC_URL"; \
		export GNUPGHOME="$(mktemp -d)"; \
		for key in $GPG_KEYS; do \
			gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key"; \
		done; \
		gpg --batch --verify php.tar.xz.asc php.tar.xz; \
		gpgconf --kill all; \
		rm -rf "$GNUPGHOME"; \
	fi; \
	\
	apk del --no-network .fetch-deps

COPY docker-php-source /usr/local/bin/

RUN set -eux; \
	apk add --no-cache --virtual .build-deps \
		$PHPIZE_DEPS \
		argon2-dev \
		coreutils \
		curl-dev \
		gnu-libiconv-dev \
		libsodium-dev \
		libxml2-dev \
		linux-headers \
		oniguruma-dev \
		openssl-dev \
		readline-dev \
		sqlite-dev \
	; \
	\
# make sure musl's iconv doesn't get used (https://www.php.net/manual/en/intro.iconv.php)
	rm -vf /usr/include/iconv.h; \
	\
	export \
		CFLAGS="$PHP_CFLAGS" \
		CPPFLAGS="$PHP_CPPFLAGS" \
		LDFLAGS="$PHP_LDFLAGS" \
	; \
	docker-php-source extract; \
	cd /usr/src/php; \
	gnuArch="$(dpkg-architecture --query DEB_BUILD_GNU_TYPE)"; \
	./configure \
		--build="$gnuArch" \
		--with-config-file-path="$PHP_INI_DIR" \
		--with-config-file-scan-dir="$PHP_INI_DIR/conf.d" \
		\
# make sure invalid --configure-flags are fatal errors instead of just warnings
		--enable-option-checking=fatal \
		\
# https://github.com/docker-library/php/issues/439
		--with-mhash \
		\
# https://github.com/docker-library/php/issues/822
		--with-pic \
		\
# --enable-ftp is included here because ftp_ssl_connect() needs ftp to be compiled statically (see https://github.com/docker-library/php/issues/236)
		--enable-ftp \
# --enable-mbstring is included here because otherwise there's no way to get pecl to use it properly (see https://github.com/docker-library/php/issues/195)
		--enable-mbstring \
# --enable-mysqlnd is included here because it's harder to compile after the fact than extensions are (since it's a plugin for several extensions, not an extension in itself)
		--enable-mysqlnd \
# https://wiki.php.net/rfc/argon2_password_hash
		--with-password-argon2 \
# https://wiki.php.net/rfc/libsodium
		--with-sodium=shared \
# always build against system sqlite3 (https://github.com/php/php-src/commit/6083a387a81dbbd66d6316a3a12a63f06d5f7109)
		--with-pdo-sqlite=/usr \
		--with-sqlite3=/usr \
		\
		--with-curl \
		--with-iconv=/usr \
		--with-openssl \
		--with-readline \
		--with-zlib \
		\
# https://github.com/bwoebi/phpdbg-docs/issues/1#issuecomment-163872806 ("phpdbg is primarily a CLI debugger, and is not suitable for debugging an fpm stack.")
		--disable-phpdbg \
		\
# in PHP 7.4+, the pecl/pear installers are officially deprecated (requiring an explicit "--with-pear")
		--with-pear \
		\
# bundled pcre does not support JIT on s390x
# https://manpages.debian.org/bullseye/libpcre3-dev/pcrejit.3.en.html#AVAILABILITY_OF_JIT_SUPPORT
		$(test "$gnuArch" = 's390x-linux-musl' && echo '--without-pcre-jit') \
		\
		--disable-cgi \
		\
		--enable-fpm \
		--with-fpm-user=www-data \
		--with-fpm-group=www-data \
	; \
	make -j "$(nproc)"; \
	find -type f -name '*.a' -delete; \
	make install; \
	find \
		/usr/local \
		-type f \
		-perm '/0111' \
		-exec sh -euxc ' \
			strip --strip-all "$@" || : \
		' -- '{}' + \
	; \
	make clean; \
	\
# https://github.com/docker-library/php/issues/692 (copy default example "php.ini" files somewhere easily discoverable)
	cp -v php.ini-* "$PHP_INI_DIR/"; \
	\
	cd /; \
	docker-php-source delete; \
	\
	runDeps="$( \
		scanelf --needed --nobanner --format '%n#p' --recursive /usr/local \
			| tr ',' '\n' \
			| sort -u \
			| awk 'system("[ -e /usr/local/lib/" $1 " ]") == 0 { next } { print "so:" $1 }' \
	)"; \
	apk add --no-cache $runDeps; \
	\
	apk del --no-network .build-deps; \
	\
# update pecl channel definitions https://github.com/docker-library/php/issues/443
	pecl update-channels; \
	rm -rf /tmp/pear ~/.pearrc; \
	\
# smoke test
	php --version

COPY docker-php-ext-* docker-php-entrypoint /usr/local/bin/

# sodium was built as a shared module (so that it can be replaced later if so desired), so let's enable it too (https://github.com/docker-library/php/issues/598)
RUN docker-php-ext-enable sodium

ENTRYPOINT ["docker-php-entrypoint"]
WORKDIR /var/www/html

RUN set -eux; \
	cd /usr/local/etc; \
	if [ -d php-fpm.d ]; then \
		# for some reason, upstream's php-fpm.conf.default has "include=NONE/etc/php-fpm.d/*.conf"
		sed 's!=NONE/!=!g' php-fpm.conf.default | tee php-fpm.conf > /dev/null; \
		cp php-fpm.d/www.conf.default php-fpm.d/www.conf; \
	else \
		# PHP 5.x doesn't use "include=" by default, so we'll create our own simple config that mimics PHP 7+ for consistency
		mkdir php-fpm.d; \
		cp php-fpm.conf.default php-fpm.d/www.conf; \
		{ \
			echo '[global]'; \
			echo 'include=etc/php-fpm.d/*.conf'; \
		} | tee php-fpm.conf; \
	fi; \
	{ \
		echo '[global]'; \
		echo 'error_log = /proc/self/fd/2'; \
		echo; echo '; https://github.com/docker-library/php/pull/725#issuecomment-443540114'; echo 'log_limit = 8192'; \
		echo; \
		echo '[www]'; \
		echo '; if we send this to /proc/self/fd/1, it never appears'; \
		echo 'access.log = /proc/self/fd/2'; \
		echo; \
		echo 'clear_env = no'; \
		echo; \
		echo '; Ensure worker stdout and stderr are sent to the main error log.'; \
		echo 'catch_workers_output = yes'; \
		echo 'decorate_workers_output = no'; \
	} | tee php-fpm.d/docker.conf; \
	{ \
		echo '[global]'; \
		echo 'daemonize = no'; \
		echo; \
		echo '[www]'; \
		echo 'listen = 9000'; \
	} | tee php-fpm.d/zz-docker.conf

# Override stop signal to stop process gracefully
# https://github.com/php/php-src/blob/17baa87faddc2550def3ae7314236826bc1b1398/sapi/fpm/php-fpm.8.in#L163
STOPSIGNAL SIGQUIT

EXPOSE 9000
CMD ["php-fpm"]


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Sydowia 7: 43 (1973)

#### Original name
Mycena melandeta Singer

### Remarks
null


text:
export default {
  locales: ["en"],

  messages: {

    "meta": {
      "title": "isomorphic500",
      "description": "Demo application made with React and Fluxible",
      "loadingTitle": "Loading…",
      "errorTitle": "Error displaying this page",
      "notFoundTitle": "Page not found"
    },

    // "features": {
    //   "popular": "Most Popular",
    //   "highest_rated": "Highest Rated",
    //   "upcoming": "Upcoming",
    //   "editors": "Editors picks",
    //   "fresh_today": "Fresh Today",
    //   "fresh_yesterday": "Fresh Yesterday",
    //   "fresh_week": "Fresh This Week"
    // },

    // "featured": {
    //   "documentTitle": "{feature} on 500px"
    // },

    // "home": {
    //   "welcome": "Welcome to isomorphic500. Now explore some photo..."
    // },

    // "photo": {

    //   "documentTitle": "{name} – by {user}",
    //   "documentDescription": "{name} is a photo by {user} published on 500px",

    //   "attribution": "Photo by {userLink}",
    //   "rating": "Rating {rating}"
    // }
  }
};


text:
namespace remoting {

// Number of frames to be captured per second.
const int kFramesPerSec = 10;

WebrtcVideoCapturerAdapter::WebrtcVideoCapturerAdapter(
    scoped_ptr<webrtc::DesktopCapturer> capturer)
    : desktop_capturer_(capturer.Pass()) {
  DCHECK(desktop_capturer_);

  thread_checker_.DetachFromThread();

  // Disable video adaptation since we don't intend to use it.
  set_enable_video_adapter(false);
}

WebrtcVideoCapturerAdapter::~WebrtcVideoCapturerAdapter() {
  DCHECK(!capture_timer_);
}

webrtc::SharedMemory* WebrtcVideoCapturerAdapter::CreateSharedMemory(
    size_t size) {
  return nullptr;
}

void WebrtcVideoCapturerAdapter::OnCaptureCompleted(
    webrtc::DesktopFrame* frame) {
  scoped_ptr<webrtc::DesktopFrame> owned_frame(frame);

  // Drop the owned_frame if there were no changes.
  if (!owned_frame || owned_frame->updated_region().is_empty()) {
    owned_frame.reset();
    return;
  }

  // Convert the webrtc::DesktopFrame to a cricket::CapturedFrame.
  cricket::CapturedFrame captured_frame;
  captured_frame.width = owned_frame->size().width();
  captured_frame.height = owned_frame->size().height();
  base::TimeTicks current_time = base::TimeTicks::Now();
  captured_frame.time_stamp =
      current_time.ToInternalValue() * base::Time::kNanosecondsPerMicrosecond;
  captured_frame.data = owned_frame->data();

  // The data_size attribute must be set. If multiple formats are supported,
  // this should be set appropriately for each one.
  captured_frame.data_size =
      (captured_frame.width * webrtc::DesktopFrame::kBytesPerPixel * 8 + 7) /
      8 * captured_frame.height;
  captured_frame.fourcc = cricket::FOURCC_ARGB;

  SignalFrameCaptured(this, &captured_frame);
}

bool WebrtcVideoCapturerAdapter::GetBestCaptureFormat(
    const cricket::VideoFormat& desired,
    cricket::VideoFormat* best_format) {
  DCHECK(thread_checker_.CalledOnValidThread());

  // For now, just used the desired width and height.
  best_format->width = desired.width;
  best_format->height = desired.height;
  best_format->fourcc = cricket::FOURCC_ARGB;
  best_format->interval = FPS_TO_INTERVAL(kFramesPerSec);
  return true;
}

cricket::CaptureState WebrtcVideoCapturerAdapter::Start(
    const cricket::VideoFormat& capture_format) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(!capture_timer_);
  DCHECK_EQ(capture_format.fourcc, (static_cast<uint32>(cricket::FOURCC_ARGB)));

  if (!desktop_capturer_) {
    VLOG(1) << "WebrtcVideoCapturerAdapter failed to start.";
    return cricket::CS_FAILED;
  }

  // This is required to tell the cricket::VideoCapturer base class what the
  // capture format will be.
  SetCaptureFormat(&capture_format);

  desktop_capturer_->Start(this);

  capture_timer_.reset(new base::RepeatingTimer());
  capture_timer_->Start(FROM_HERE,
                        base::TimeDelta::FromMicroseconds(
                            GetCaptureFormat()->interval /
                            (base::Time::kNanosecondsPerMicrosecond)),
                        this,
                        &WebrtcVideoCapturerAdapter::CaptureNextFrame);

  return cricket::CS_RUNNING;
}

// Similar to the base class implementation with some important differences:
// 1. Does not call either Stop() or Start(), as those would affect the state of
// |desktop_capturer_|.
// 2. Does not support unpausing after stopping the capturer. It is unclear
// if that flow needs to be supported.
bool WebrtcVideoCapturerAdapter::Pause(bool pause) {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (pause) {
    if (capture_state() == cricket::CS_PAUSED)
      return true;

    bool running = capture_state() == cricket::CS_STARTING ||
                   capture_state() == cricket::CS_RUNNING;

    DCHECK_EQ(running, IsRunning());

    if (!running) {
      LOG(ERROR)
          << "Cannot pause WebrtcVideoCapturerAdapter.";
      return false;
    }

    // Stop |capture_timer_| and set capture state to cricket::CS_PAUSED.
    capture_timer_->Stop();
    SetCaptureState(cricket::CS_PAUSED);

    VLOG(1) << "WebrtcVideoCapturerAdapter paused.";

    return true;
  } else {  // Unpausing.
    if (capture_state() != cricket::CS_PAUSED || !GetCaptureFormat() ||
        !capture_timer_) {
      LOG(ERROR) << "Cannot unpause WebrtcVideoCapturerAdapter.";
      return false;
    }

    // Restart |capture_timer_| and set capture state to cricket::CS_RUNNING;
    capture_timer_->Start(FROM_HERE,
                          base::TimeDelta::FromMicroseconds(
                              GetCaptureFormat()->interval /
                              (base::Time::kNanosecondsPerMicrosecond)),
                          this,
                          &WebrtcVideoCapturerAdapter::CaptureNextFrame);
    SetCaptureState(cricket::CS_RUNNING);

    VLOG(1) << "WebrtcVideoCapturerAdapter unpaused.";
  }
  return true;
}

void WebrtcVideoCapturerAdapter::Stop() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK_NE(capture_state(), cricket::CS_STOPPED);

  capture_timer_.reset();

  SetCaptureFormat(nullptr);
  SetCaptureState(cricket::CS_STOPPED);

  VLOG(1) << "WebrtcVideoCapturerAdapter stopped.";
}

bool WebrtcVideoCapturerAdapter::IsRunning() {
  DCHECK(thread_checker_.CalledOnValidThread());

  return capture_timer_->IsRunning();
}

bool WebrtcVideoCapturerAdapter::IsScreencast() const {
  return true;
}

bool WebrtcVideoCapturerAdapter::GetPreferredFourccs(
    std::vector<uint32>* fourccs) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!fourccs)
    return false;
  fourccs->push_back(cricket::FOURCC_ARGB);
  return true;
}

void WebrtcVideoCapturerAdapter::CaptureNextFrame() {
  // If we are paused, then don't capture.
  if (!IsRunning())
    return;

  desktop_capturer_->Capture(webrtc::DesktopRegion());
}

}  // namespace remoting


text:
import request from "request";
import URI     from "urijs";
import merge   from "merge";

const uri = process.env.WEBHOOK_URI;

let color = 0x77CBD1;

function esc(str)
{
   return str.replace(/([*#/()[\]_`\\])/g, "\\$&");
}

function sendMessage(content, embeds)
{
   request.post({ uri: uri, json: { content: content, embeds: embeds } },
   function(error, response, body)
   {
      if(error || response.statusCode < 200 || response.statusCode >= 300)
      {
         if(body != undefined)
            console.log("ERROR: \n", body);
         else
            console.log("<error>");
      }
   });
}

function struri(str)
{
   return new URI(str).unicode().toString();
}

function uristr(name, uri)
{
   return "[" + name + "](" + struri(uri) + ")";
}

function clipstr(str, amt)
{
   if(str == null) return str;
   if(str.length > amt)
      str = str.substring(0, amt - 3) + "...";
   return str;
}

function author(name, url, icon_url)
{
   return {
      color: color,
      author: {
         name: name,
         url: url,
         icon_url: icon_url
      }
   };
}

function embed(title, description, url)
{
   return {
      color: color,
      title: title,
      description: description,
      url: url
   };
}

function field(name, value)
{
   return {
      color: color,
      fields: [{
         name: name,
         value: value,
         inline: true
      }]
   };
}

function footer(text, icon_url)
{
   return {
      color: color,
      footer: {
         text: text,
         icon_url: icon_url
      }
   };
}

function prsCommInfo(info)
{
   return {
      id:     info.comment.commit_id.substring(0, 7),
      idLong: info.comment.commit_id,
      uri:    info.comment.html_url,
      body:   esc(info.comment.body)
   };
}

function prsTracInfo(info)
{
   return {
      title:  info.title,
      body:   info.body,
      uristr: uristr("#" + info.number, info.html_url),
      uri:    info.html_url
   };
}

function prsIssuInfo(info)
{
   return prsTracInfo(info.issue);
}

function prsPullInfo(info)
{
   return prsTracInfo(info.pull_request);
}

function prsRepoInfo(info)
{
   return {
      shortname: info.repository.name,
      name:   info.repository.full_name,
      avatar: info.repository.owner.avatar_url,
      uri:    info.repository.html_url,
      uristr: uristr(info.repository.full_name, info.repository.html_url),
      mai:    "**" +
              uristr(info.repository.full_name, info.repository.html_url) +
              "**:"
   };
}

function prsUserInfo(info)
{
   return {
      user:    info.login,
      userUri: info.html_url,
      avatar:  info.avatar_url,
      uristr:  uristr(info.login, info.html_url)
   };
}

function prsSendInfo(info)
{
   return prsUserInfo(info.sender);
}

function issueInfo(info, issu)
{
   const repo = prsRepoInfo(info);
   const send = prsSendInfo(info);

   let outp = null;

   switch(info.action)
   {
   case "opened":
      const body = clipstr(issu.body, 128);
      outp = merge(true,
         author(send.user, send.uri, send.avatar),
         field(esc(issu.title), body ? body : "<no description>")
      );
      break;
   case "labeled": case "unlabeled":
      const tmp = color;
      const uri = struri(`${repo.uri}/labels/${info.label.name}`);
      const tag = info.action[0].toUpperCase() + info.action.substring(1);

      color = parseInt(info.label.color, 16);
      outp = embed(`${tag} **${info.label.name}**`, null, uri);
      color = tmp;
      break;
   case "assigned": case "unassigned":
      let user = prsUserInfo(info.assignee);
      outp =
         author(`${user.user} was ${info.action}`, user.uri, user.avatar);
      break;
   }
   return outp;
}

function commitMsg(repo, commit)
{
   const shorthash = commit.id.substring(0, 7);
   const uri  = struri(`${repo.uri}/commit/${commit.id}`);
   const msg  = esc(clipstr(commit.message.split(/\r?\n/)[0], 64));
   const name = esc(commit.author.name);
   return uristr("`" + shorthash + "`", uri) + ` ${msg} - *${name}*\n`;
}

export default class Events
{
   static commit_comment(info)
   {
      const comm = prsCommInfo(info);
      const repo = prsRepoInfo(info);
      const send = prsSendInfo(info);

      const comment = uristr("comment", comm.uri);
      const commit  = uristr(comm.id, `${repo.uri}/commit/${comm.idLong}`);

      sendMessage(`${repo.mai} New ${comment} on commit **${commit}**`,
         [merge(true,
            author(send.user, send.uri, send.avatar),
            footer(clipstr(comm.body, 80))
         )]);
   }

   static create(info)
   {
      const repo = prsRepoInfo(info);
      const send = prsSendInfo(info);

      const type   = info.ref_type;
      const ref    = info.ref;
      const refmsg = (ref != null) ? (": **" + ref + "**") : "";

      sendMessage(
         `${send.uristr} created a new ${type} on ${repo.uristr}${refmsg}`);
   }

   static delete(info)
   {
      const repo = prsRepoInfo(info);
      const send = prsSendInfo(info);

      const type   = info.ref_type;
      const ref    = info.ref;
      const refmsg = (ref != null) ? (": **" + ref + "**") : "";

      sendMessage(
         `${send.uristr} deleted a ${type} on ${repo.uristr}${refmsg}`);
   }

   static fork(info)
   {
      const repo = prsRepoInfo(info);
      const send = prsSendInfo(info);

      const fork = uristr(info.forkee.full_name, info.forkee.html_url);

      sendMessage(`**${send.uristr}** forked ${repo.uristr} into **${fork}**`);
   }

   static issue_comment(info)
   {
      const repo = prsRepoInfo(info);
      const send = prsSendInfo(info);
      const user = prsUserInfo(info.comment.user);
      const issu = prsIssuInfo(info);

      let outp = null;
      let msg = null;

      switch(info.action)
      {
      case "created":
      {
         const comment = uristr("comment", info.comment.html_url);
         msg = `New ${comment} on issue **${issu.uristr}**`;
         outp = merge(true,
            author(user.user, user.uri, user.avatar),
            footer(clipstr(info.comment.body, 80))
         );
         break;
      }
      case "edited":
      {
         const comm = uristr("Comment", info.comment.html_url);
         msg = `${comm} on issue **${issu.uristr}** edited by ${send.uristr}`;
         break;
      }
      case "deleted":
         msg = `Comment on issue **${issu.uristr}** deleted by ${send.uristr}`;
         break;
      }

      sendMessage(`${repo.mai} ${msg}`, outp ? [outp] : null);
   }

   static issues(info)
   {
      const repo = prsRepoInfo(info);
      const send = prsSendInfo(info);
      const issu = prsIssuInfo(info);
      const outp = issueInfo(info, issu);

      sendMessage(
         `${repo.mai} Issue **${issu.uristr}** ` +
         `${info.action} by ${send.uristr}`,
         outp ? [outp] : null);
   }

   static member(info)
   {
      const repo = prsRepoInfo(info);
      const user = prsUserInfo(info.member);
      sendMessage(`${user.uristr} was added to ${repo.uristr}`);
   }

   static milestone(info)
   {
      const repo = prsRepoInfo(info);
      const send = prsSendInfo(info);

      const mstone = uristr(info.milestone.title, info.milestone.html_url);
      const action = info.action;

      sendMessage(
         `${repo.mai} Milestone ${mstone} ${action} by ${send.uristr}`);
   }

   static public(info)
   {
      sendMessage(`${prsRepoInfo(info).uristr} has been made public`);
   }

   static pull_request_review(info)
   {
      const repo = prsRepoInfo(info);
      const send = prsSendInfo(info);
      const pull = prsPullInfo(info);

      let statename = info.review.state;
      if(statename == "changes_requested") statename = "denied";

      const state = uristr(statename, info.review.html_url);
      const body = clipstr(info.review.body, 80);

      sendMessage(
         `${repo.mai} Pull request **${pull.uristr}** ${state}`,
         [merge(true,
            author(send.user, send.uri, send.avatar),
            footer(clipstr(body ? body : "<no description>", 80))
         )]);
   }

   static pull_request(info)
   {
      const repo = prsRepoInfo(info);
      const send = prsSendInfo(info);
      const pull = prsPullInfo(info);

      let outp = null;
      let msg =
         `Pull request **${pull.uristr}** ${info.action} by ${send.uristr}`;

      if(info.pull_request.merged && info.action == "closed")
         msg = `Pull request **${pull.uristr}** merged by ${send.uristr}`;
      else
         outp = issueInfo(info, pull);

      sendMessage(`${repo.mai} ${msg}`, outp ? [outp] : null);
   }

   static push(info)
   {
      if(info.created || info.deleted)
         return;

      const repo = prsRepoInfo(info);
      const send = prsSendInfo(info);
      const name = `${repo.shortname}/${info.ref.split("/")[2]}`;
      const s = info.commits.length != 1 ? "s" : "";
      const parm = "";

      if(info.forced)
         parm = "(force pushed)";

      let commits = "";
      if(info.commits.length >= 10)
      {
         let omitted = info.commits.length - 8;

         for(let i = 0; i < 4; i++)
            commits += commitMsg(repo, info.commits[i]);

         commits += `(*${omitted} more commits*)\n`;

         for(let i = omitted + 4; i < info.commits.length; i++)
            commits += commitMsg(repo, info.commits[i]);
      }
      else for(let i = 0; i < info.commits.length; i++)
         commits += commitMsg(repo, info.commits[i]);

      const uri = info.compare;

      sendMessage(null, [merge(true,
         author(send.user, send.uri, send.avatar),
         embed(`[${name}] ${info.commits.length} new commit${s} ${parm}`,
            commits, uri)
      )]);
   }

   static release(info)
   {
      const repo = prsRepoInfo(info);
      const tag = uristr(info.release.tag_name, info.release.html_url);
      sendMessage(`${repo.mai} ${tag} released`);
   }

   static watch(info)
   {
      const repo = prsRepoInfo(info);
      const send = prsSendInfo(info);

      sendMessage(`${repo.uristr} was starred by ${send.uristr}`);
   }

   static ping(info) {}
   static gollum(info) {}
   static status(info) {}
   static team_add(info) {}
   static repository(info) {}
   static deployment(info) {}
   static membership(info) {}
   static page_build(info) {}
   static deployment_status(info) {}
   static pull_request_review_comment(info) {}
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Dawn;
using Microsoft.Extensions.ObjectPool;

namespace FclEx.Utils
{
    public struct PooledObject<T> : IDisposable where T : class
    {
        private readonly T _value;
        private bool _isDisposed;
        private readonly ObjectPool<T> _pool;

        public PooledObject(ObjectPool<T> pool)
        {
            _pool = Guard.Argument(pool, nameof(pool)).NotNull();
            _value = pool.Get();
            _isDisposed = false;
        }

        private void CheckDisposed()
        {
            if (_isDisposed)
                throw new ObjectDisposedException("The object has been disposed already.");
        }

        public T Value
        {
            get
            {
                CheckDisposed();
                return _value;
            }
        }

        public void Dispose()
        {
            if (_isDisposed) return;
            _pool.Return(_value);
            _isDisposed = true;
        }
    }
}


text:
package com.wix.invoke.types;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

import java.lang.reflect.InvocationTargetException;

/**
 * Created by rotemm on 10/10/2016.
 */

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = ClassTarget.class, name = "Class"),
        @JsonSubTypes.Type(value = InvocationTarget.class, name = "Invocation"),
        @JsonSubTypes.Type(value = ObjectInstanceTarget.class, name = "Espresso"),
})
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class Target {

    Object value;

    public Target(Object value) {
        this.value = value;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public Object invoke(Invocation invocation) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if (this.value instanceof Invocation) {
            Invocation innerInvocation = (Invocation) this.value;
            this.value = innerInvocation.getTarget().invoke(innerInvocation);
        }

        Object[] args = invocation.getArgs();
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof Invocation) {
                Invocation innerInvocation = (Invocation) args[i];
                args[i] = innerInvocation.getTarget().invoke(innerInvocation);
            }
        }
        invocation.setArgs(args);
        return execute(invocation);
    }

    public abstract Object execute(Invocation invocation) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Target)) return false;

        Target target = (Target) o;

        return value != null ? value.equals(target.value) : target.value == null;
    }

    @Override
    public int hashCode() {
        int result = (value != null ? value.hashCode() : 0);
        return result;
    }
}


text:
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
import {HtmlContentModel, HtmlContentResponse} from './html-content.model';
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {Config} from "../../../shared/configs/general.config";
import { API_URL} from "../../../shared/configs/env.config";
import { XhrService } from '../../../shared/services/xhr.service';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { catchError } from 'rxjs/operators/catchError';

@Injectable()
export class HtmlContentService {
    apiRoute:string = "htmlcontent";

    constructor(private xhrService: XhrService, private _http:HttpClient) {

    }

    saveHtmlEditor(objSave:HtmlContentModel) {
        let body = JSON.stringify(objSave);
        return this._http.post(API_URL + this.apiRoute, body)
            .pipe(
                catchError(this.handleError)
            );
    }

    updateHtmlEditor(objUpdate:HtmlContentModel, contentId: string) {
        let body = JSON.stringify(objUpdate);
        return this._http.put(API_URL + this.apiRoute + "/" + contentId, body)
            .pipe(
                catchError(this.handleError)
            );
    }

    deleteHtmlEditor(objUpdate:HtmlContentModel) {
        objUpdate.deleted = true;
        let body = JSON.stringify({});
        return this._http.patch(API_URL + this.apiRoute + "/" + objUpdate._id, body)
            .pipe(
                catchError(this.handleError)
            );
    }

    getHtmlEditorList(perPage:number, currentPage:number):Observable < HtmlContentResponse> {
        let query = new HttpParams();
        query = query.append('perpage', perPage.toString());
        query = query.append('page', currentPage.toString());
        return this._http.get<HtmlContentResponse>(API_URL + this.apiRoute, {params: query})
            .pipe(
                catchError(this.handleError)
            );
    }

    getHtmlEditorById(id:string):Observable < HtmlContentModel> {
        return this._http.get<HtmlContentModel>(API_URL + this.apiRoute + "/" + id)
            .pipe(
                catchError(this.handleError)
            );
    }

    handleError(error: HttpErrorResponse) {
        if (error.error instanceof ErrorEvent) {
            // A client-side or network error occurred. Handle it accordingly.
            console.error('An error occurred:', error.error.message);
          } else {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            console.error(
              `Backend returned code ${error.status}, ` +
              `body was: ${error.error.message}`);
          }
          // return an ErrorObservable with a user-facing error message
          return new ErrorObservable(error.error.message ? error.error.message :
            'Something bad happened; please try again later.');
    }

}


text:
ALTER TABLE users_install ADD COLUMN `install_type` int(11) unsigned NOT NULL;
CREATE INDEX `users_install_install_type` ON `users_install` (`install_type`);


text:
#ifndef USSERVICEREGISTRATION_H
#define USSERVICEREGISTRATION_H

#include "usServiceRegistrationBase.h"

US_BEGIN_NAMESPACE

/**
 * \ingroup MicroServices
 *
 * A registered service.
 *
 *

 * The framework returns a ServiceRegistration object when a
 * ModuleContext#RegisterService() method invocation is successful.
 * The ServiceRegistration object is for the private use of the
 * registering module and should not be shared with other modules.
 *

 * The ServiceRegistration object may be used to update the
 * properties of the service or to unregister the service.
 *
 * @tparam S Class tyoe of the service interface
 * @see ModuleContext#RegisterService()
 * @remarks This class is thread safe.
 */
template<class I1, class I2 = void, class I3 = void>
class ServiceRegistration : public ServiceRegistrationBase
{

public:

  /**
   * Creates an invalid ServiceRegistration object. You can use
   * this object in boolean expressions and it will evaluate to
   * false.
   */
  ServiceRegistration() : ServiceRegistrationBase()
  {
  }

  ///@{
  /**
   * Returns a ServiceReference object for a service being
   * registered.
   *

   * The ServiceReference object may be shared with other
   * modules.
   *
   * @throws std::logic_error If this
   *         ServiceRegistration object has already been
   *         unregistered or if it is invalid.
   * @return ServiceReference object.
   */
  ServiceReference<I1> GetReference(InterfaceType<I1>) const
  {
    return this->ServiceRegistrationBase::GetReference(us_service_interface_iid<I1>());
  }
  ServiceReference<I2> GetReference(InterfaceType<I2>) const
  {
    return this->ServiceRegistrationBase::GetReference(us_service_interface_iid<I2>());
  }
  ServiceReference<I3> GetReference(InterfaceType<I3>) const
  {
    return this->ServiceRegistrationBase::GetReference(us_service_interface_iid<I3>());
  }
  ///@}

  using ServiceRegistrationBase::operator=;

private:

  friend class ModuleContext;

  ServiceRegistration(const ServiceRegistrationBase& base)
    : ServiceRegistrationBase(base)
  {
  }

};

/// \cond
template<class I1, class I2>
class ServiceRegistration<I1, I2, void> : public ServiceRegistrationBase
{

public:

  ServiceRegistration() : ServiceRegistrationBase()
  {
  }

  ServiceReference<I1> GetReference(InterfaceType<I1>) const
  {
    return ServiceReference<I1>(this->ServiceRegistrationBase::GetReference(us_service_interface_iid<I1>()));
  }

  ServiceReference<I2> GetReference(InterfaceType<I2>) const
  {
    return ServiceReference<I2>(this->ServiceRegistrationBase::GetReference(us_service_interface_iid<I2>()));
  }

  using ServiceRegistrationBase::operator=;

private:

  friend class ModuleContext;

  ServiceRegistration(const ServiceRegistrationBase& base)
    : ServiceRegistrationBase(base)
  {
  }

};

template<class I1>
class ServiceRegistration<I1, void, void> : public ServiceRegistrationBase
{

public:

  ServiceRegistration() : ServiceRegistrationBase()
  {
  }

  ServiceReference<I1> GetReference() const
  {
    return this->GetReference(InterfaceType<I1>());
  }

  ServiceReference<I1> GetReference(InterfaceType<I1>) const
  {
    return ServiceReference<I1>(this->ServiceRegistrationBase::GetReference(us_service_interface_iid<I1>()));
  }

  using ServiceRegistrationBase::operator=;

private:

  friend class ModuleContext;

  ServiceRegistration(const ServiceRegistrationBase& base)
    : ServiceRegistrationBase(base)
  {
  }

};

template<>
class ServiceRegistration<void, void, void> : public ServiceRegistrationBase
{
public:

  /**
   * Creates an invalid ServiceReference object. You can use
   * this object in boolean expressions and it will evaluate to
   * false.
   */
  ServiceRegistration() : ServiceRegistrationBase()
  {
  }

  ServiceRegistration(const ServiceRegistrationBase& base)
    : ServiceRegistrationBase(base)
  {
  }

  using ServiceRegistrationBase::operator=;
};
/// \endcond

/**
 * \ingroup MicroServices
 *
 * A service registration object of unknown type.
 */
typedef ServiceRegistration<void> ServiceRegistrationU;

US_END_NAMESPACE

#endif // USSERVICEREGISTRATION_H


text:
package io.hops.metadata.adaptor;

import io.hops.exception.StorageException;
import io.hops.metadata.DalAdaptor;
import io.hops.metadata.hdfs.entity.CachePool;
import io.hops.metadata.hdfs.dal.CachePoolDataAccess;
import java.util.Collection;
import org.apache.hadoop.fs.permission.FsPermission;

public class CachePoolDALAdaptor extends DalAdaptor<org.apache.hadoop.hdfs.server.namenode.CachePool, CachePool>
    implements CachePoolDataAccess<org.apache.hadoop.hdfs.server.namenode.CachePool> {

  private CachePoolDataAccess<CachePool> dataAccess;

  public CachePoolDALAdaptor(CachePoolDataAccess<CachePool> dataAccess) {
    this.dataAccess = dataAccess;
  }

  @Override
  public CachePool convertHDFStoDAL(org.apache.hadoop.hdfs.server.namenode.CachePool cachePool) throws StorageException {
    return new CachePool(cachePool.getPoolName(), cachePool.getOwnerName(), cachePool.getGroupName(), cachePool.
        getMode().toShort(), cachePool.getLimit(), cachePool.getMaxRelativeExpiryMs(), cachePool.getBytesNeeded(),
        cachePool.getBytesCached(), cachePool.getFilesNeeded(), cachePool.getFilesCached());
  }

  @Override
  public org.apache.hadoop.hdfs.server.namenode.CachePool convertDALtoHDFS(CachePool cachePool) {
    if(cachePool==null){
      return null;
    }
    return new org.apache.hadoop.hdfs.server.namenode.CachePool(cachePool.getPoolName(), cachePool.getOwnerName(),
        cachePool.getGroupName(), new FsPermission(cachePool.getMode()), cachePool.getLimit(), cachePool.getMaxRelativeExpiryMs(), cachePool.getBytesNeeded(),
        cachePool.getBytesCached(), cachePool.getFilesNeeded(), cachePool.getFilesCached());
  }

  @Override
  public void prepare(Collection<org.apache.hadoop.hdfs.server.namenode.CachePool> removed,
      Collection<org.apache.hadoop.hdfs.server.namenode.CachePool> newed) throws StorageException {
    dataAccess.prepare(convertHDFStoDAL(removed), convertHDFStoDAL(newed));
  }

  @Override
  public org.apache.hadoop.hdfs.server.namenode.CachePool find(String key) throws StorageException {
    return convertDALtoHDFS(dataAccess.find(key));
  }

  @Override
  public Collection<org.apache.hadoop.hdfs.server.namenode.CachePool> findAboveName(String key) throws StorageException{
    return convertDALtoHDFS(dataAccess.findAboveName(key));
  }

  @Override
  public Collection<org.apache.hadoop.hdfs.server.namenode.CachePool> findAll() throws StorageException{
    return convertDALtoHDFS(dataAccess.findAll());
  }
}


text:
package openeye.logic;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.io.File;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Loader;
import openeye.Log;
import openeye.Proxy;
import openeye.logic.ModMetaCollector.ClassSource;
import openeye.protocol.reports.ReportAnalytics;
import openeye.protocol.reports.ReportCrash;
import openeye.protocol.reports.ReportCrash.ExceptionInfo;
import openeye.protocol.reports.ReportCrash.StackTrace;
import openeye.protocol.reports.ReportEnvironment;
import openeye.protocol.reports.ReportFileContents;
import openeye.protocol.reports.ReportFileContents.ArchiveDirEntry;
import openeye.protocol.reports.ReportFileContents.ArchiveEntry;
import openeye.protocol.reports.ReportFileContents.ArchiveFileEntry;
import openeye.protocol.reports.ReportKnownFiles;

public class ReportBuilders {

	private static final TagsCollector TAGS_COLLECTOR = new TagsCollector();

	private static final Random RANDOM = new Random();

	private static String getSide() {
		return FMLCommonHandler.instance().getSide().toString().toLowerCase(Locale.ENGLISH);
	}

	public static ReportKnownFiles buildKnownFilesReport(ModMetaCollector data) {
		ReportKnownFiles result = new ReportKnownFiles();

		result.signatures = data.getAllFiles();

		return result;
	}

	private static String getJavaVersion() {
		String vendor = Strings.nullToEmpty(System.getProperty("java.vendor"));
		String version = Strings.nullToEmpty(System.getProperty("java.version"));
		return vendor + " " + version;
	}

	private static Map<String, String> getEnvVersions() {
		ImmutableMap.Builder<String, String> versions = ImmutableMap.builder();
		versions.put("mcp", Loader.instance().getMCPVersionString());
		versions.put("fml", Loader.instance().getFMLVersionString());
		versions.put("forge", ForgeVersion.getVersion());
		return versions.build();
	}

	private static void fillEnvInfo(ReportEnvironment report) {
		report.branding = FMLCommonHandler.instance().getBrandings(true);

		report.runtime = getEnvVersions();

		report.minecraft = Loader.instance().getMCVersionString();

		report.javaVersion = getJavaVersion();

		report.side = getSide();

		report.obfuscated = Bootstrap.instance.isRuntimeDeobfuscationEnabled();

		Set<String> tags = TAGS_COLLECTOR.getTags();

		if (!tags.isEmpty()) report.tags = tags;
	}

	public static ReportAnalytics buildAnalyticsReport(ModMetaCollector data, Set<String> prevSignatures) {
		ReportAnalytics analytics = new ReportAnalytics();

		fillEnvInfo(analytics);

		String language = Proxy.instance().getLanguage();
		analytics.language = Strings.isNullOrEmpty(language)? "invalid" : language;

		analytics.locale = Locale.getDefault().toString();

		TimeZone tz = Calendar.getInstance().getTimeZone();
		analytics.timezone = tz.getID();

		analytics.workTime = data.getCollectingDuration() / 1000.0f;

		analytics.signatures = data.getAllFiles();

		Set<String> currentSignatures = data.getAllSignatures();

		analytics.installedSignatures = Sets.difference(currentSignatures, prevSignatures);

		analytics.uninstalledSignatures = Sets.difference(prevSignatures, currentSignatures);

		return analytics;
	}

	private static StackTrace createStackTraceElement(StackTraceElement e, ModMetaCollector collector) {
		StackTrace el = new StackTrace();
		final String clsName = e.getClassName();
		el.className = clsName;
		el.fileName = e.getFileName();
		el.methodName = e.getMethodName();
		el.lineNumber = e.getLineNumber();

		if (collector != null) {
			ClassSource source = collector.identifyClassSource(clsName);
			if (source != null) {
				el.signatures = source.containingClasses;
				if (source.loadedFrom != null) {
					el.source = source.loadedFrom;
					el.signatures.add(source.loadedFrom);
				}
			}
		}
		return el;
	}

	private static ExceptionInfo createStackTrace(Throwable throwable, StackTraceElement[] prevStacktrace, Set<Throwable> alreadySerialized, ModMetaCollector collector) {
		if (alreadySerialized.contains(throwable)) return null; // cyclical reference

		ExceptionInfo info = new ExceptionInfo();

		info.exceptionCls = throwable.getClass().getName();
		info.message = Sanitizers.getSanitizerForThrowable(throwable.getClass()).sanitize(throwable.getMessage());

		alreadySerialized.add(throwable);

		info.stackTrace = Lists.newArrayList();

		StackTraceElement[] stackTrace = throwable.getStackTrace();

		int m = stackTrace.length - 1;
		int n = prevStacktrace.length - 1;
		while (m >= 0 && n >= 0 && stackTrace[m].equals(prevStacktrace[n])) {
			m--;
			n--;
		}

		for (int i = 0; i <= m; i++)
			info.stackTrace.add(createStackTraceElement(stackTrace[i], collector));

		Throwable cause = throwable.getCause();
		if (cause != null) info.cause = createStackTrace(cause, stackTrace, alreadySerialized, collector);

		return info;
	}

	public static ReportCrash buildCrashReport(Throwable throwable, String location, ModMetaCollector collector) {
		ReportCrash crash = new ReportCrash();

		fillEnvInfo(crash);

		crash.timestamp = new Date().getTime();

		crash.location = location;

		Set<Throwable> blacklist = Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
		crash.exception = createStackTrace(throwable, new StackTraceElement[0], blacklist, collector);

		if (collector != null) crash.states = collector.collectStates();

		crash.random = RANDOM.nextInt();

		crash.resolved = collector != null;

		return crash;
	}

	public static void fillFileContents(File container, ReportFileContents report) {
		try {
			ZipFile jarFile = new ZipFile(container);

			List<ArchiveDirEntry> dirs = Lists.newArrayList();
			List<ArchiveFileEntry> files = Lists.newArrayList();

			try {
				Enumeration<? extends ZipEntry> entries = jarFile.entries();

				while (entries.hasMoreElements()) {
					ZipEntry zipEntry = entries.nextElement();

					if (zipEntry.isDirectory()) {
						ArchiveDirEntry resultEntry = new ArchiveDirEntry();
						fillCommonFields(zipEntry, resultEntry);
						dirs.add(resultEntry);
					} else {
						ArchiveFileEntry resultEntry = new ArchiveFileEntry();
						fillCommonFields(zipEntry, resultEntry);
						resultEntry.size = zipEntry.getSize();
						resultEntry.crc = Long.toHexString(zipEntry.getCrc());
						resultEntry.signature = createSignature(jarFile.getInputStream(zipEntry));
						files.add(resultEntry);
					}
				}
			} finally {
				jarFile.close();
			}

			report.dirs = dirs;
			report.files = files;
		} catch (Exception e) {
			Log.warn(e, "Failed to get contents of file %s", container);
		}
	}

	private static void fillCommonFields(ZipEntry zipEntry, ArchiveEntry resultEntry) {
		resultEntry.filename = zipEntry.getName();
		resultEntry.timestamp = zipEntry.getTime();
		resultEntry.comment = zipEntry.getComment();
	}

	private static String createSignature(InputStream is) throws Exception {
		MessageDigest md = MessageDigest.getInstance("SHA-256");
		DigestInputStream dis = new DigestInputStream(is, md);

		byte[] buffer = new byte[1024];

		while (dis.read(buffer) != -1) {}

		dis.close();

		byte[] digest = md.digest();
		return "sha256:" + bytesToHex(digest);
	}

	private static String bytesToHex(byte[] bytes) {
		StringBuilder sb = new StringBuilder(2 * bytes.length);
		for (byte b : bytes)
			sb.append(HEX[(b >> 4) & 0xf]).append(HEX[b & 0xf]);
		return sb.toString();
	}

	private static final char[] HEX = "0123456789abcdef".toCharArray();
}


text:
class AvatarMenuButtonTest : public InProcessBrowserTest {
 public:
  AvatarMenuButtonTest();
  virtual ~AvatarMenuButtonTest();

 protected:
  void CreateTestingProfile();
  AvatarMenuButton* GetAvatarMenuButton();
  void StartAvatarMenu();

 private:
  DISALLOW_COPY_AND_ASSIGN(AvatarMenuButtonTest);
};

AvatarMenuButtonTest::AvatarMenuButtonTest() {
}

AvatarMenuButtonTest::~AvatarMenuButtonTest() {
}

void AvatarMenuButtonTest::CreateTestingProfile() {
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  EXPECT_EQ(1u, profile_manager->GetNumberOfProfiles());

  base::FilePath path;
  PathService::Get(chrome::DIR_USER_DATA, &path);
  path = path.AppendASCII("test_profile");
  if (!base::PathExists(path))
    ASSERT_TRUE(base::CreateDirectory(path));
  Profile* profile =
      Profile::CreateProfile(path, NULL, Profile::CREATE_MODE_SYNCHRONOUS);
  profile_manager->RegisterTestingProfile(profile, true, false);
  EXPECT_EQ(2u, profile_manager->GetNumberOfProfiles());
}

AvatarMenuButton* AvatarMenuButtonTest::GetAvatarMenuButton() {
  BrowserView* browser_view = reinterpret_cast<BrowserView*>(
      browser()->window());
  return browser_view->frame()->GetAvatarMenuButton();
}

void AvatarMenuButtonTest::StartAvatarMenu() {
  AvatarMenuButton* button = GetAvatarMenuButton();
  ASSERT_TRUE(button);

  AvatarMenuBubbleView::clear_close_on_deactivate_for_testing();
  static_cast<views::MenuButtonListener*>(button)->OnMenuButtonClicked(
      NULL, gfx::Point());
  base::MessageLoop::current()->RunUntilIdle();
  EXPECT_TRUE(AvatarMenuBubbleView::IsShowing());
}

// See http://crbug.com/315732
#if defined(OS_WIN)
#define MAYBE_HideOnSecondClick DISABLED_HideOnSecondClick
#elif defined(OS_CHROMEOS)
// This test doesn't make sense for ChromeOS since it has a different
// multi-profiles menu in the system tray instead.
#define MAYBE_HideOnSecondClick DISABLED_HideOnSecondClick
#else
#define MAYBE_HideOnSecondClick HideOnSecondClick
#endif

IN_PROC_BROWSER_TEST_F(AvatarMenuButtonTest, MAYBE_HideOnSecondClick) {
#if defined(OS_WIN) && defined(USE_ASH)
  // Disable this test in Metro+Ash for now (http://crbug.com/262796).
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
    return;
#endif

  // If multiprofile mode is not enabled, you can't switch between profiles.
  if (!profiles::IsMultipleProfilesEnabled())
    return;

  CreateTestingProfile();
  ASSERT_NO_FATAL_FAILURE(StartAvatarMenu());

  // Verify that clicking again doesn't reshow it.
  AvatarMenuButton* button = GetAvatarMenuButton();
  static_cast<views::MenuButtonListener*>(button)->OnMenuButtonClicked(
      NULL, gfx::Point());
  // Hide the bubble manually. In the browser this would normally happen during
  // the event processing.
  AvatarMenuBubbleView::Hide();
  base::MessageLoop::current()->RunUntilIdle();
  EXPECT_FALSE(AvatarMenuBubbleView::IsShowing());
}


text:
<?php

namespace Erivello\Silex\Tests;

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Erivello\Silex\Provider\FacebookServiceProvider;

class FacebookServiceProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testRegister()
    {
        $app = new Application();

        $app->register(new FacebookServiceProvider(), array(
            'facebook.apps' => array(
                'test' => array(
                    'facebook.app_id'     => '12345',
                    'facebook.secret'     => '67890'
                ),
                'foo' => array(
                    'facebook.app_id'     => '54321',
                    'facebook.secret'     => '09876'
                ),
            )
        ));

        $app->get('/', function() use($app) {
            $app['facebook_test'];
            $app['facebook_foo'];
        });
        $request = Request::create('/');
        $app->handle($request);

        $this->assertTrue($app['facebook_test'] instanceof \Facebook);
        $this->assertEquals($app['facebook_test']->getAppId(), '12345');
        $this->assertEquals($app['facebook_test']->getApiSecret(), '67890');
        $this->assertEquals($app['facebook_test']->getAccessToken(), '12345|67890');

        $this->assertTrue($app['facebook_foo'] instanceof \Facebook);
        $this->assertEquals($app['facebook_foo']->getAppId(), '54321');
        $this->assertEquals($app['facebook_foo']->getApiSecret(), '09876');
        $this->assertEquals($app['facebook_foo']->getAccessToken(), '54321|09876');
    }
}


text:
package main

import (
	"fmt"
	"os"

	"github.com/rook/rook/pkg/ceph/mon"
	"github.com/rook/rook/pkg/ceph/rgw"
	"github.com/rook/rook/pkg/util/flags"
	"github.com/spf13/cobra"
)

var rgwCmd = &cobra.Command{
	Use:    "rgw",
	Short:  "Generates rgw config and runs the rgw daemon",
	Hidden: true,
}

var (
	rgwKeyring string
	rgwHost    string
	rgwPort    int
)

func init() {
	rgwCmd.Flags().StringVar(&rgwKeyring, "rgw-keyring", "", "the rgw keyring")
	rgwCmd.Flags().StringVar(&rgwHost, "rgw-host", "", "dns host name")
	rgwCmd.Flags().IntVar(&rgwPort, "rgw-port", 0, "rgw port number")
	addCephFlags(rgwCmd)

	flags.SetFlagsFromEnv(rgwCmd.Flags(), "ROOKD")

	rgwCmd.RunE = startRGW
}

func startRGW(cmd *cobra.Command, args []string) error {
	if err := flags.VerifyRequiredFlags(rgwCmd, []string{"mon-endpoints", "cluster-name", "mon-secret", "admin-secret", "rgw-host", "rgw-keyring"}); err != nil {
		return err
	}

	if rgwPort == 0 {
		return fmt.Errorf("port is required")
	}

	setLogLevel()

	clusterInfo.Monitors = mon.ParseMonEndpoints(cfg.monEndpoints)
	config := &rgw.Config{
		ClusterInfo: &clusterInfo,
		Keyring:     rgwKeyring,
		Host:        rgwHost,
		Port:        rgwPort,
		InProc:      true,
	}

	err := rgw.Run(createContext(), config)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	return nil
}


text:
<?php

namespace Gmorel\StateWorkflowBundle\StateEngine;

/**
 * Allow an entity to have a State
 * @author Guillaume MOREL <github.com/gmorel>
 */
interface HasStateInterface
{
    /**
     * Set entity new state
     * @param StateWorkflow   $stateContext
     * @param StateInterface $newState
     *
     * @return $this
     */
    public function changeState(StateWorkflow $stateContext, StateInterface $newState);

    /**
     * Get current entity state
     * @param StateWorkflow $stateContext
     *
     * @return StateInterface
     */
    public function getState(StateWorkflow $stateContext);
}


text:
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]

HTTP status utility for node.

## API

```js
var status = require('statuses')
```

### var code = status(Integer || String)

If `Integer` or `String` is a valid HTTP code or status message, then the appropriate `code` will be returned. Otherwise, an error will be thrown.

```js
status(403) // => 403
status('403') // => 403
status('forbidden') // => 403
status('Forbidden') // => 403
status(306) // throws, as it's not supported by node.js
```

### status.codes

Returns an array of all the status codes as `Integer`s.

### var msg = status[code]

Map of `code` to `status message`. `undefined` for invalid `code`s.

```js
status[404] // => 'Not Found'
```

### var code = status[msg]

Map of `status message` to `code`. `msg` can either be title-cased or lower-cased. `undefined` for invalid `status message`s.

```js
status['not found'] // => 404
status['Not Found'] // => 404
```

### status.redirect[code]

Returns `true` if a status code is a valid redirect status.

```js
status.redirect[200] // => undefined
status.redirect[301] // => true
```

### status.empty[code]

Returns `true` if a status code expects an empty body.

```js
status.empty[200] // => undefined
status.empty[204] // => true
status.empty[304] // => true
```

### status.retry[code]

Returns `true` if you should retry the rest.

```js
status.retry[501] // => undefined
status.retry[503] // => true
```

## Adding Status Codes

The status codes are primarily sourced from http://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv.
Additionally, custom codes are added from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes.
These are added manually in the `lib/*.json` files.
If you would like to add a status code, add it to the appropriate JSON file.

To rebuild `codes.json`, run the following:

```bash
# update src/iana.json
npm run fetch
# build codes.json
npm run build
```

[npm-image]: https://img.shields.io/npm/v/statuses.svg
[npm-url]: https://npmjs.org/package/statuses
[node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg
[node-version-url]: https://nodejs.org/en/download
[travis-image]: https://img.shields.io/travis/jshttp/statuses.svg
[travis-url]: https://travis-ci.org/jshttp/statuses
[coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg
[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master
[downloads-image]: https://img.shields.io/npm/dm/statuses.svg
[downloads-url]: https://npmjs.org/package/statuses


text:
namespace SharpData.Fluent {
    public interface IRemoveFromTable {
        void FromTable(string tableName);
    }
}


text:
package org.apache.atlas.repository.graphdb.titan1.graphson;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * Configure how the GraphSON utility treats edge and vertex properties.
 *
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public class AtlasElementPropertyConfig {

    public static enum ElementPropertiesRule {
        INCLUDE, EXCLUDE
    }

    private final List<String> vertexPropertyKeys;
    private final List<String> edgePropertyKeys;
    private final ElementPropertiesRule vertexPropertiesRule;
    private final ElementPropertiesRule edgePropertiesRule;
    private final boolean normalized;

    /**
     * A configuration that includes all properties of vertices and edges.
     */
    public static final AtlasElementPropertyConfig AllProperties = new AtlasElementPropertyConfig(null, null,
            ElementPropertiesRule.INCLUDE, ElementPropertiesRule.INCLUDE, false);

    public AtlasElementPropertyConfig(final Set<String> vertexPropertyKeys, final Set<String> edgePropertyKeys,
                                 final ElementPropertiesRule vertexPropertiesRule,
                                 final ElementPropertiesRule edgePropertiesRule) {
        this(vertexPropertyKeys, edgePropertyKeys, vertexPropertiesRule, edgePropertiesRule, false);
    }

    public AtlasElementPropertyConfig(final Set<String> vertexPropertyKeys, final Set<String> edgePropertyKeys,
                                 final ElementPropertiesRule vertexPropertiesRule,
                                 final ElementPropertiesRule edgePropertiesRule, final boolean normalized) {
        this.vertexPropertiesRule = vertexPropertiesRule;
        this.vertexPropertyKeys = sortKeys(vertexPropertyKeys, normalized);
        this.edgePropertiesRule = edgePropertiesRule;
        this.edgePropertyKeys = sortKeys(edgePropertyKeys, normalized);
        this.normalized = normalized;
    }

    /**
     * Construct a configuration that includes the specified properties from both vertices and edges.
     */
    public static AtlasElementPropertyConfig includeProperties(final Set<String> vertexPropertyKeys,
                                                          final Set<String> edgePropertyKeys) {
        return new AtlasElementPropertyConfig(vertexPropertyKeys, edgePropertyKeys, ElementPropertiesRule.INCLUDE,
                ElementPropertiesRule.INCLUDE);
    }

    public static AtlasElementPropertyConfig includeProperties(final Set<String> vertexPropertyKeys,
                                                          final Set<String> edgePropertyKeys, final boolean normalized) {
        return new AtlasElementPropertyConfig(vertexPropertyKeys, edgePropertyKeys, ElementPropertiesRule.INCLUDE,
                ElementPropertiesRule.INCLUDE, normalized);
    }

    /**
     * Construct a configuration that excludes the specified properties from both vertices and edges.
     */
    public static AtlasElementPropertyConfig excludeProperties(final Set<String> vertexPropertyKeys,
                                                          final Set<String> edgePropertyKeys) {
        return new AtlasElementPropertyConfig(vertexPropertyKeys, edgePropertyKeys, ElementPropertiesRule.EXCLUDE,
                ElementPropertiesRule.EXCLUDE);
    }

    public static AtlasElementPropertyConfig excludeProperties(final Set<String> vertexPropertyKeys,
                                                          final Set<String> edgePropertyKeys, final boolean normalized) {
        return new AtlasElementPropertyConfig(vertexPropertyKeys, edgePropertyKeys, ElementPropertiesRule.EXCLUDE,
                ElementPropertiesRule.EXCLUDE, normalized);
    }

    public List<String> getVertexPropertyKeys() {
        return vertexPropertyKeys;
    }

    public List<String> getEdgePropertyKeys() {
        return edgePropertyKeys;
    }

    public ElementPropertiesRule getVertexPropertiesRule() {
        return vertexPropertiesRule;
    }

    public ElementPropertiesRule getEdgePropertiesRule() {
        return edgePropertiesRule;
    }

    public boolean isNormalized() {
        return normalized;
    }

    private static List<String> sortKeys(final Set<String> keys, final boolean normalized) {
        final List<String> propertyKeyList;
        if (keys != null) {
            if (normalized) {
                final List<String> sorted = new ArrayList<String>(keys);
                Collections.sort(sorted);
                propertyKeyList = sorted;
            } else
                propertyKeyList = new ArrayList<String>(keys);
        } else
            propertyKeyList = null;

        return propertyKeyList;
    }
}


text:
cd `dirname \`gem contents trogdoro-el4r | grep setup.rb\``
ruby setup.rb
cd bin/
ruby -S el4r-rctool -p
ruby -S el4r-rctool -i


text:
rethinkdb/horizon#3

### Problem

Horizon needs a concept of a user, and clients of a Horizon server
need to be able to add, delete and list users. Users are a fundamental
entity needed for both the authentication system and permission
system. App developers may also want to add additional meaning to
users depending on their needs.

### Proposed solution

Create a virtual collection called `users` which is really a view into the internal Horizon users table. All operations should transparently operate on a subdocument in the real table.

#### Client changes

No client changes necessary. There will simply appear to be an
ordinary collection in new apps called `users`.

Examples:

```js
horizon('users').find(userId)
horizon('users').findAll({first_name: "John", last_name: "Smith"})
```

#### Protocol changes

No protocol changes.

#### Server changes

A `horizon_internal.users` table exists internally right now for
authentication. We should continue to use this to track users, but
should add a sub-document with the key `app_data`. When a query or
write operation from the client refers to the `users` collection, it
instead should operate on the the `app_data` subdocument.

Example:

Actual document in `horizon_internal.users`:

```json
{
  "id": 23,
  "permissions": [],
  "app_data": {
    "foo": "bar"
  }
}
```
Document returned when client requests user 23:

```json
{
  "id": 23,
  "foo": "bar"
}
```

Resulting document after `horizon('users').update({id: 23, age: 65})`

``` json
{
  "id": 23,
  "permissions": [],
  "app_data": {
    "foo": "bar",
    "age": 65
  }
}
```

Additionally, queries for users will use secondary indexes on the
nested `app_data` document, but queries for users by id will use the
primary key of the document.

Example:

A client query like:

Client query:
```js
horizon('users').findAll({age: 65}).fetch()
```

Backend:
```js
// index creation
r.db('horizon_internal').table('users').indexCreate('app_data_age', x => x('app_data')('age'))
// query
r.db('horizon_internal').table('users').getAll(65, {index: 'app_data_age'})
```


text:
package com.squarespace.less;

import static com.squarespace.less.LessCompiler.LESSJS_VERSION;

import java.nio.file.Path;

import com.squarespace.less.core.Buffer;
import com.squarespace.less.core.StackFormatter;

public class LessMessages {

  private static final String SQUARESPACE_LESS_HEADER = "\n/* Squarespace LESS Compiler " + LESSJS_VERSION + " */\n";

  private static final int DEFAULT_ERROR_INDENT = 4;

  private static final int DEFAULT_STACK_WINDOW = 6;

  private final int errorIndent;

  private final int stackWindow;

  public LessMessages() {
    this(DEFAULT_ERROR_INDENT, DEFAULT_STACK_WINDOW);
  }

  public LessMessages(int errorIndent, int stackWindow) {
    this.errorIndent = errorIndent;
    this.stackWindow = stackWindow;
  }

  public void successHeader(Buffer buf) {
    buf.append(SQUARESPACE_LESS_HEADER);
  }

  public void errorHeader(Buffer buf) {
    buf.append("\n\nSQUARESPACE_LESS_ERROR\n\n");
  }

  public String formatStats(LessStats stats, Path path) {
    return formatStats(new Buffer(0), stats, path).toString();
  }

  public Buffer formatStats(Buffer buf, LessStats stats, Path path) {
    buf.append("/* --------------------------------------------------------\n");
    buf.append("Squarespace LESS compiler ").append(LESSJS_VERSION).append(" Statistics for '");
    buf.append(path.toString()).append("':\n");
    buf.append("    parse time: ").append(formatMs(stats.parseTimeMs())).append('\n');
    buf.append("  compile time: ").append(formatMs(stats.compileTimeMs())).append('\n');
    buf.append("disk wait time: ").append(formatMs(stats.diskWaitTimeMs())).append('\n');
    buf.append("  import count: ").append(stats.importCount()).append('\n');
    buf.append("---------------------------------------------------------- */\n");
    return buf;
  }

  public String formatError(LessException exc) {
    Buffer buf = new Buffer(errorIndent);
    errorHeader(buf);
    StackFormatter fmt = new StackFormatter(exc.errorContext(), 4, stackWindow);
    buf.append(fmt.format()).append('\n');
    buf.append(exc.primaryError().getMessage());
    buf.append('\n');
    return buf.toString();
  }

  private String formatMs(double ms) {
    return String.format("%.3fms", ms);
  }

}


text:
ComponentTableView is component-based , high UITableview controls reuse.

To make it easier UIViewController and decoupling Cell, we propose ComponentTableView. It assembles and business logic Cell entirely encapsulated in its own Component inside ( need to subclass the base class BaseAssemblyComponent), clean up UIViewController load is a completely middleware. Meanwhile Component API services and support internal hair page jump.

# Use Introduction

1.  Your ViewController inherit BaseAssemblyDispatcher class method to rewrite components ; for example :
```object-c
    - (NSArray *)components{
            return [NSArray arrayWithObjects:
            @[@"UIListTimeComponentKey", NSStringFromClass([UIListTimeComponent class])],
            @[@"UITitleNumberComponentKey", NSStringFromClass([UITitleNumberComponent class])] ,nil];
        }
```

2.  Realize their middleware. First Inherited BaseAssemblyComponent, followed by initialization data source or accept the data that comes out in setupComponent source method , and then call the system draws TableviewCell approach. eg: UIListTimeComponent and UITitleNumberComponent

3.  If you want to reuse someone else's middleware, only you need to modify the components method in UIViewController;

#  Demonstrations
![](https://github.com/WPDreamMelody/ComponentTableView/blob/master/img/home.png)
![](https://github.com/WPDreamMelody/ComponentTableView/blob/master/img/detail.png)

# Installation

1. From the first pod search ComponentTableView, if we continue to search for the second step .
   If you can not search , Run pod setup, clone copy locally. Then execute pod search ComponentTableView can see the various versions ;
2. Add the pod "ComponentTableView" in Podfile in .
3. Run pod install or pod update.
4. Import the required header files . For example : #import "BaseAssemblyComponent.h"

# Installation Manual

1. Download ComponentTableView folder all the contents .
2. Add the source file ComponentTableView within ( drag and drop ) to your project .
3. Import the required header files . For example : #import "BaseAssemblyComponent.h"

# Document

You can view the online API documentation CocoaDocs, you can also generate documents in appledoc locally.

# License

ComponentTableView use MIT license , as detailed LICENSE file .


text:
/*!
 * (C) Ionic http://ionicframework.com - MIT License
 * Built with http://stenciljs.com
 */
ion-segment {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.segment-button {
  margin-left: 0;
  margin-right: 0;
  text-align: center;
  position: relative;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

.segment-md ion-segment-button {
  display: flex;
  flex: 1;
}

.segment-md .segment-button {
  flex: 1;
  width: 0;
  height: 4.2rem;
  border-bottom-width: 2px;
  border-bottom-style: solid;
  border-bottom-color: rgba(0, 0, 0, 0.1);
  font-size: 1.2rem;
  font-weight: 500;
  line-height: 4rem;
  text-transform: uppercase;
  color: #327eff;
  background-color: transparent;
  opacity: 0.7;
  transition: 100ms all linear;
  padding: 0 6px;
}

.segment-md .segment-button ion-icon {
  font-size: 2.6rem;
  line-height: 4rem;
}

.segment-md .segment-button.activated, .segment-md .segment-button.segment-activated {
  border-color: #327eff;
  opacity: 1;
}

.segment-md.segment-disabled,
.segment-md .segment-button-disabled {
  opacity: 0.3;
  pointer-events: none;
}

.toolbar .segment-md {
  margin: 0 auto;
}

.toolbar .segment-md .segment-button.activated,
.toolbar .segment-md .segment-button.segment-activated {
  opacity: 1;
}

.segment-md-primary .segment-button {
  color: #327eff;
}

.segment-md-primary .segment-button.activated, .segment-md-primary .segment-button.segment-activated {
  border-color: #327eff;
  color: #327eff;
  opacity: 1;
}

.segment-md-secondary .segment-button {
  color: #32db64;
}

.segment-md-secondary .segment-button.activated, .segment-md-secondary .segment-button.segment-activated {
  border-color: #32db64;
  color: #32db64;
  opacity: 1;
}

.segment-md-danger .segment-button {
  color: #f53d3d;
}

.segment-md-danger .segment-button.activated, .segment-md-danger .segment-button.segment-activated {
  border-color: #f53d3d;
  color: #f53d3d;
  opacity: 1;
}

.segment-md-light .segment-button {
  color: #f4f4f4;
}

.segment-md-light .segment-button.activated, .segment-md-light .segment-button.segment-activated {
  border-color: #f4f4f4;
  color: #f4f4f4;
  opacity: 1;
}

.segment-md-dark .segment-button {
  color: #222;
}

.segment-md-dark .segment-button.activated, .segment-md-dark .segment-button.segment-activated {
  border-color: #222;
  color: #222;
  opacity: 1;
}

ion-segment.💎,
ion-segment-button.💎 {
  visibility: inherit;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" stopOnFailure="false" processIsolation="false" bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="My Test Suite">
            <directory>src/Migration/Tests</directory>
            <exclude>
                <directory>src/Migration/Tests/Base</directory>
            </exclude>
        </testsuite>
  </testsuites>

   <php>
    <const name="DEMO_DATABASE_USER" value="migrations"/>
    <const name="DEMO_DATABASE_PASSWORD" value="mboxpwis?"/>
    <const name="DEMO_DATABASE_SCHEMA" value="sakila"/>
    <const name="DEMO_DATABASE_PORT" value="3306"/>
    <const name="DEMO_DATABASE_HOST" value="127.0.0.1"/>
    <const name="DEMO_DATABASE_TYPE" value="pdo_mysql"/>
    </php>
</phpunit>


text:
# Highlight

This example is borrowed from https://highlightjs.org/static/demo/

```js
import {x, y} as p from 'point';
const ANSWER = 42;

class Car extends Vehicle {
  constructor(speed, cost) {
    super(speed);

    var c = Symbol('cost');
    this[c] = cost;

    this.intro = `This is a car runs at
      ${speed}.`;
  }
}

for (let num of [1, 2, 3]) {
  console.log(num + 0b111110111);
}

function $initHighlight(block, flags) {
  try {
    if (block.className.search(/\bno\-highlight\b/) != -1)
      return processBlock(block.function, true, 0x0F) + ' class=""';
  } catch (e) {
    /* handle exception */
    var e4x =
        <div>Example
            <p>1234</p></div>;
  }
  for (var i = 0 / 2; i < classes.length; i++) { // "0 / 2" should not be parsed as regexp
    if (checkCondition(classes[i]) === undefined)
      return /\d+[\s/]/g;
  }
  console.log(Array.every(classes, Boolean));
}

export  $initHighlight;
```