text:
public partial class GameContext {

    public GameEntity iSomeInterfaceEntity { get { return GetGroup(GameMatcher.ISomeInterface).GetSingleEntity(); } }
    public ISomeInterfaceComponent iSomeInterface { get { return iSomeInterfaceEntity.iSomeInterface; } }
    public bool hasISomeInterface { get { return iSomeInterfaceEntity != null; } }

    public GameEntity SetISomeInterface(ISomeInterface newValue) {
        if (hasISomeInterface) {
            throw new Entitas.EntitasException("Could not set ISomeInterface!\n" + this + " already has an entity with ISomeInterfaceComponent!",
                "You should check if the context already has a iSomeInterfaceEntity before setting it or use context.ReplaceISomeInterface().");
        }
        var entity = CreateEntity();
        entity.AddISomeInterface(newValue);
        return entity;
    }

    public void ReplaceISomeInterface(ISomeInterface newValue) {
        var entity = iSomeInterfaceEntity;
        if (entity == null) {
            entity = SetISomeInterface(newValue);
        } else {
            entity.ReplaceISomeInterface(newValue);
        }
    }

    public void RemoveISomeInterface() {
        iSomeInterfaceEntity.Destroy();
    }
}

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by Entitas.CodeGeneration.Plugins.ComponentEntityApiGenerator.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class GameEntity {

    public ISomeInterfaceComponent iSomeInterface { get { return (ISomeInterfaceComponent)GetComponent(GameComponentsLookup.ISomeInterface); } }
    public bool hasISomeInterface { get { return HasComponent(GameComponentsLookup.ISomeInterface); } }

    public void AddISomeInterface(ISomeInterface newValue) {
        var index = GameComponentsLookup.ISomeInterface;
        var component = (ISomeInterfaceComponent)CreateComponent(index, typeof(ISomeInterfaceComponent));
        component.value = newValue;
        AddComponent(index, component);
    }

    public void ReplaceISomeInterface(ISomeInterface newValue) {
        var index = GameComponentsLookup.ISomeInterface;
        var component = (ISomeInterfaceComponent)CreateComponent(index, typeof(ISomeInterfaceComponent));
        component.value = newValue;
        ReplaceComponent(index, component);
    }

    public void RemoveISomeInterface() {
        RemoveComponent(GameComponentsLookup.ISomeInterface);
    }
}

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by Entitas.CodeGeneration.Plugins.ComponentMatcherApiGenerator.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public sealed partial class GameMatcher {

    static Entitas.IMatcher<GameEntity> _matcherISomeInterface;

    public static Entitas.IMatcher<GameEntity> ISomeInterface {
        get {
            if (_matcherISomeInterface == null) {
                var matcher = (Entitas.Matcher<GameEntity>)Entitas.Matcher<GameEntity>.AllOf(GameComponentsLookup.ISomeInterface);
                matcher.componentNames = GameComponentsLookup.componentNames;
                _matcherISomeInterface = matcher;
            }

            return _matcherISomeInterface;
        }
    }
}


text:
namespace SIM.Pipelines.Delete
{
  using SIM.Pipelines.Processors;
  using Sitecore.Diagnostics.Base;
  using Sitecore.Diagnostics.Base.Annotations;

  #region

  #endregion

  public abstract class DeleteProcessor : Processor
  {
    #region Methods

    protected override sealed void Process([NotNull] ProcessorArgs args)
    {
      Assert.ArgumentNotNull(args, nameof(args));

      this.Process((DeleteArgs)args);
    }

    protected abstract void Process([NotNull] DeleteArgs args);

    #endregion
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/* * *
 * http://localhost:8080/pvcloud_backend/app_get_list_by_account.php?account_id=1
 *
 * * */
error_reporting(E_ERROR);

class simpleResponse {

    public $status = "";
    public $message = "";
    public $data = [];

}

require_once './DA/da_conf.php';
require_once './DA/da_helper.php';
require_once './DA/da_account.php';
require_once './DA/da_session.php';
require_once './DA/da_apps_registry.php';

/**
 *
 *
 * @return \simpleResponse
 */
function execute() {
    $response = new simpleResponse();
    try {

        include './inc/incWebServiceSessionValidation.php';

        $app_id = filter_input(INPUT_GET, "app_id");

        $appToModify = da_apps_registry::GetApp($app_id);
        $appToModify->account_id = filter_input(INPUT_GET, "account_id");
        $appToModify->app_nickname = filter_input(INPUT_GET, "app_nickname");
        $appToModify->app_description = filter_input(INPUT_GET, "app_description");
        $appToModify->visibility_type_id = filter_input(INPUT_GET, "visibility_type_id");

        if ($appToModify->account_id > 0 && $appToModify->app_nickname != "" && $appToModify->app_description != "" && $appToModify->visibility_type_id > 0 ) {
            $modifiedApp = da_apps_registry::UpdateApp($appToModify);
            $response->status = "OK";
            $response->message = "SUCCESS";
            $response->data = $modifiedApp;
        } else {
            $response->status = "ERROR";
            if (!$appToModify->account_id > 0)
                $response->message = "Parámetros Inválidos - AccountID";
            if ($appToModify->app_nickname == "")
                $response->message = "Parámetros Inválidos - Nickname";
            if ($appToModify->app_description == "")
                $response->message = "Parámetros Inválidos - Description";
        }
    } catch (Exception $ex) {
        $response->status = "EXCEPTION";
        $response->message = $ex->getMessage();
    }
    return $response;
}

include './inc/incJSONHeaders.php';
echo json_encode(execute());


text:
package org.apache.tomcat.util.net;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ScatteringByteChannel;
import java.nio.channels.SocketChannel;

import org.apache.tomcat.util.net.NioEndpoint.NioSocketWrapper;
import org.apache.tomcat.util.res.StringManager;

/**
 * Base class for a SocketChannel wrapper used by the endpoint.
 * This way, logic for an SSL socket channel remains the same as for
 * a non SSL, making sure we don't need to code for any exception cases.
 */
public class NioChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel {

    protected static final StringManager sm = StringManager.getManager(NioChannel.class);

    protected static final ByteBuffer emptyBuf = ByteBuffer.allocate(0);

    protected final SocketBufferHandler bufHandler;
    protected SocketChannel sc = null;
    protected NioSocketWrapper socketWrapper = null;

    public NioChannel(SocketBufferHandler bufHandler) {
        this.bufHandler = bufHandler;
    }

    /**
     * Reset the channel
     *
     * @param channel the socket channel
     * @param socketWrapper the socket wrapper
     * @throws IOException If a problem was encountered resetting the channel
     */
    public void reset(SocketChannel channel, NioSocketWrapper socketWrapper) throws IOException {
        this.sc = channel;
        this.socketWrapper = socketWrapper;
        bufHandler.reset();
    }

    /**
     * @return the socketWrapper
     */
    NioSocketWrapper getSocketWrapper() {
        return socketWrapper;
    }

    /**
     * Free the channel memory
     */
    public void free() {
        bufHandler.free();
    }

    /**
     * Closes this channel.
     *
     * @throws IOException If an I/O error occurs
     */
    @Override
    public void close() throws IOException {
        sc.close();
    }

    /**
     * Close the connection.
     *
     * @param force Should the underlying socket be forcibly closed?
     * @throws IOException If closing the secure channel fails.
     */
    public void close(boolean force) throws IOException {
        if (isOpen() || force) {
            close();
        }
    }

    /**
     * Tells whether or not this channel is open.
     *
     * @return true if, and only if, this channel is open
     */
    @Override
    public boolean isOpen() {
        return sc.isOpen();
    }

    /**
     * Writes a sequence of bytes to this channel from the given buffer.
     *
     * @param src The buffer from which bytes are to be retrieved
     * @return The number of bytes written, possibly zero
     * @throws IOException If some other I/O error occurs
     */
    @Override
    public int write(ByteBuffer src) throws IOException {
        checkInterruptStatus();
        return sc.write(src);
    }

    @Override
    public long write(ByteBuffer[] srcs) throws IOException {
        return write(srcs, 0, srcs.length);
    }

    @Override
    public long write(ByteBuffer[] srcs, int offset, int length)
            throws IOException {
        checkInterruptStatus();
        return sc.write(srcs, offset, length);
    }

    /**
     * Reads a sequence of bytes from this channel into the given buffer.
     *
     * @param dst The buffer into which bytes are to be transferred
     * @return The number of bytes read, possibly zero, or -1 if
     *         the channel has reached end-of-stream
     * @throws IOException If some other I/O error occurs
     */
    @Override
    public int read(ByteBuffer dst) throws IOException {
        return sc.read(dst);
    }

    @Override
    public long read(ByteBuffer[] dsts) throws IOException {
        return read(dsts, 0, dsts.length);
    }

    @Override
    public long read(ByteBuffer[] dsts, int offset, int length)
            throws IOException {
        return sc.read(dsts, offset, length);
    }

    public SocketBufferHandler getBufHandler() {
        return bufHandler;
    }

    public SocketChannel getIOChannel() {
        return sc;
    }

    public boolean isClosing() {
        return false;
    }

    public boolean isHandshakeComplete() {
        return true;
    }

    /**
     * Performs SSL handshake hence is a no-op for the non-secure
     * implementation.
     *
     * @param read  Unused in non-secure implementation
     * @param write Unused in non-secure implementation
     * @return Always returns zero
     * @throws IOException Never for non-secure channel
     */
    public int handshake(boolean read, boolean write) throws IOException {
        return 0;
    }

    @Override
    public String toString() {
        return super.toString() + ":" + sc.toString();
    }

    public int getOutboundRemaining() {
        return 0;
    }

    /**
     * Return true if the buffer wrote data. NO-OP for non-secure channel.
     *
     * @return Always returns {@code false} for non-secure channel
     * @throws IOException Never for non-secure channel
     */
    public boolean flushOutbound() throws IOException {
        return false;
    }

    /**
     * This method should be used to check the interrupt status before
     * attempting a write.
     *
     * If a thread has been interrupted and the interrupt has not been cleared
     * then an attempt to write to the socket will fail. When this happens the
     * socket is removed from the poller without the socket being selected. This
     * results in a connection limit leak for NIO as the endpoint expects the
     * socket to be selected even in error conditions.
     *
     * @throws IOException If the current thread was interrupted
     */
    protected void checkInterruptStatus() throws IOException {
        if (Thread.interrupted()) {
            throw new IOException(sm.getString("channel.nio.interrupted"));
        }
    }

    private ApplicationBufferHandler appReadBufHandler;
    public void setAppReadBufHandler(ApplicationBufferHandler handler) {
        this.appReadBufHandler = handler;
    }
    protected ApplicationBufferHandler getAppReadBufHandler() {
        return appReadBufHandler;
    }

    static final NioChannel CLOSED_NIO_CHANNEL = new NioChannel(SocketBufferHandler.EMPTY) {
        @Override
        public void close() throws IOException {
        }
        @Override
        public boolean isOpen() {
            return false;
        }
        @Override
        public void reset(SocketChannel channel, NioSocketWrapper socketWrapper) throws IOException {
        }
        @Override
        public void free() {
        }
        @Override
        protected ApplicationBufferHandler getAppReadBufHandler() {
            return ApplicationBufferHandler.EMPTY;
        }
        @Override
        public void setAppReadBufHandler(ApplicationBufferHandler handler) {
        }
        @Override
        public int read(ByteBuffer dst) throws IOException {
            return -1;
        }
        @Override
        public long read(ByteBuffer[] dsts, int offset, int length)
                throws IOException {
            return -1L;
        }
        @Override
        public int write(ByteBuffer src) throws IOException {
            checkInterruptStatus();
            throw new ClosedChannelException();
        }
        @Override
        public long write(ByteBuffer[] srcs, int offset, int length)
                throws IOException {
            throw new ClosedChannelException();
        }
        @Override
        public String toString() {
            return "Closed NioChannel";
        }
    };

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>DaVinci LMS</title>
  <meta name="description" content="Back in university we used WebCT, which sucked and worked at the same time. My first project in Ruby on Rails was my implementation of the good things in Web...">

  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="https://nerian.es/articles/2012/04/26/davinci-lms.html">
  <link rel="alternate" type="application/rss+xml" title="Gonzalo Rodríguez-Baltanás Díaz" href="https://nerian.es/feed.xml">
  <link rel="shortcut icon" href="/assets/images/logo-128x98.png" type="image/x-icon">

  <link rel="stylesheet" href="/assets/icons-mind/style.css">
  <link rel="stylesheet" href="/assets/icon54/style.css">
  <link rel="stylesheet" href="/assets/web/assets/mobirise-icons/mobirise-icons.css">
  <link rel="stylesheet" href="/assets/tether/tether.min.css">
  <link rel="stylesheet" href="/assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="/assets/bootstrap/css/bootstrap-grid.min.css">
  <link rel="stylesheet" href="/assets/bootstrap/css/bootstrap-reboot.min.css">
  <link rel="stylesheet" href="/assets/socicon/css/styles.css">
  <link rel="stylesheet" href="/assets/dropdown/css/style.css">
  <link rel="stylesheet" href="/assets/gdpr-plugin/gdpr-styles.css">
  <link rel="stylesheet" href="/assets/theme/css/style.css">
  <link rel="stylesheet" href="/assets/mobirise/css/mbr-additional.css" type="text/css">

                    © Copyright 2019 Gonzalo Rodríguez-Baltanás Díaz - All Rights Reserved

      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

                      Gonzalo Rodríguez-Baltanás Díaz

                      Blog

                      About

                      Hire me

CV

                      Research

                      Portfolio

                    DaVinci LMS

                  DaVinci LMS is a minimal Learning Management System

When I was in university Pablo de Olavide we used WebCT for the online presence of teachers and students. It was an extremely useful web system. Among the many thing WebCT could do was to manage documents. So teachers will upload notes for the Java class at the start of the course and students will be able to download it, study it and raise questions before the actual class starts. It was a very useful document store. Another very useful feature that we used intensively was the Task system. So a teacher will say 'Solve problems 13-18 and send me the code'. We will solve them and then send back the code, all using the web interface. It was very handy.

There are many other features, but they were all irrelevant since we didn't use them. Nonetheless it wasn't all perfect. It was far from perfect. The idea, the utility of the application was very good, yet the implementation could be much better. It was slow. The UI was ugly. Some times it will just explode and we will be without WebCT a few days until the IT figure it out what went wrong. Also, it was incredible costly for the university to use it, not just because of the important investment in IT infrastructure to serve 20000 users, but the actual cost of licensing the software. To get you an idea, they can't afford to upgrade to new versions of WebCT. And since the world is in recession and particularly in Spain the government is cutting education budget by 20% (for real) it doesn't seem likely that they will be able to update in years.

So that was the situation. When I was at my final year I took a web development course. I learnt a lot of technologies but the one that caught my eye was Ruby on Rails. It was an amazing piece of technology that allowed small teams to deliver working software in a matter of days instead of weeks or months. Real speed. I decided that I wanted to give it a go to creating a Learning Management System(LMS). I deliberately wanted it to be dead simple to use and to install. I didn't want universities to need a whole staff of IT just to support the platform. It must be open source, so that they could modify the source code to meet they particular needs. It needed to be fast so that people could spend their time actually learning and not just using the learning platform. It should be able to store documents and manage tasks.

Speed

Open source

Easy to use

Easy to deploy

Document store

Task Management

My first attempt was a shit. I didn't really knew how to use Rails and I was a beginner in CSS, HTML, knew nothing about JS. I made every possible mistake. I failed to create useful software, but I learned more and more of Rails. I started again. And again. And again. Each time a new project. Each time a new approach, different tools, different UI, different database, different testing approach, etc. It has become sort of my 'Hello World' application whenever I want to test a new cutting edge tech.

This time, the new tech I wanted to give it a try was Apotomo, a component oriented framework for Rails. I also happen to be reading Designed For Use, a book on Usability, how to improve user interfaces so that they are intuitive, natural, discoverable, easy to learn and master. So as a was reading the book I was designing the UI of the new DaVinci LMS prototype. I think this time I have actually achieve to produce a fully working application that meets the IT needs of a school. And so I wanted to make it public, so that people can try it and give me feedback on what they love and what they hate. Also, I could use more fellow developers on this project so you are welcome to contribute.

Check it out: https://github.com/Nerian/DaVinci-LMS

And there is an online demo: http://davinci-lms-testing.herokuapp.com/en/login

                    SHARE THIS PAGE!

                    © Copyright 2019 Gonzalo Rodríguez-Baltanás Díaz - All Rights Reserved


text:
"use strict";
(function () {
 this.ConvertKitToProductRequest = function (kitId) {
  ///
  /// Contains the data that is needed to convert a kit to a product.
  ///
  ///<param name="kitId"  type="String">
  /// Sets the ID of the kit. Required.
  ///</param>
  if (!(this instanceof Sdk.ConvertKitToProductRequest)) {
   return new Sdk.ConvertKitToProductRequest(kitId);
  }
  Sdk.OrganizationRequest.call(this);

  // Internal properties
  var _kitId = null;

  // internal validation functions

  function _setValidKitId(value) {
   if (Sdk.Util.isGuid(value)) {
    _kitId = value;
   }
   else {
    throw new Error("Sdk.ConvertKitToProductRequest KitId property is required and must be a String.")
   }
  }

  //Set internal properties from constructor parameters
  if (typeof kitId != "undefined") {
   _setValidKitId(kitId);
  }

  function getRequestXml() {
   return ["<d:request>",
           "",

             "",
               "KitId",
              (_kitId == null) ? "" :
              ["", _kitId, ""].join(""),
             "",

           "",
           "",
           "ConvertKitToProduct",
         "</d:request>"].join("");
  }

  this.setResponseType(Sdk.ConvertKitToProductResponse);
  this.setRequestXml(getRequestXml());

  // Public methods to set properties
  this.setKitId = function (value) {
   ///
   /// Sets the ID of the kit. Required.
   ///
   ///<param name="value" type="String">
   /// The ID of the kit.
   ///</param>
   _setValidKitId(value);
   this.setRequestXml(getRequestXml());
  }

 }
 this.ConvertKitToProductRequest.__class = true;

 this.ConvertKitToProductResponse = function (responseXml) {
  ///
  /// Response to ConvertKitToProductRequest
  ///
  if (!(this instanceof Sdk.ConvertKitToProductResponse)) {
   return new Sdk.ConvertKitToProductResponse(responseXml);
  }
  Sdk.OrganizationResponse.call(this)

  // This message returns no values
 }
 this.ConvertKitToProductResponse.__class = true;
}).call(Sdk)

Sdk.ConvertKitToProductRequest.prototype = new Sdk.OrganizationRequest();
Sdk.ConvertKitToProductResponse.prototype = new Sdk.OrganizationResponse();


text:
package com.github.hualuomoli.raml.join.adaptor.mocha;

import java.util.List;
import java.util.Map;

import org.raml.model.ActionType;
import org.raml.model.MimeType;
import org.raml.model.parameter.FormParameter;

import com.github.hualuomoli.raml.join.JoinParser.Adapter;
import com.github.hualuomoli.raml.join.adaptor.MochaActionAdaptor;
import com.github.hualuomoli.raml.util.RamlUtils;
import com.google.common.collect.Lists;

/**
 * POST URLEncoded
 * @author hualuomoli
 *
 */
public class MochaPostUrlEncodedActionAdaptor extends MochaActionAdaptor {

	@Override
	public boolean support(Adapter adapter) {
		if (adapter.action.getType() != ActionType.POST) {
			return false;
		}
		if (!RamlUtils.isEmptyOr200JsonResponse(adapter)) {
			return false;
		}
		Map<String, MimeType> body = adapter.action.getBody();
		if (body == null) {
			return false;
		}
		MimeType mimeType = body.get(MIME_TYPE_URLENCODED);
		if (mimeType == null) {
			return false;
		}
		Map<String, List<FormParameter>> formParameters = mimeType.getFormParameters();
		if (formParameters == null || formParameters.size() == 0) {
			return false;
		}
		return true;
	}

	@Override
	public List<String> getContent(Adapter adapter) {

		List<String> datas = Lists.newArrayList();

		// request
		// .post('/api/uri')
		// .send('name=花落莫离')
		// .expect(200)
		// .end(done);

		datas.add("");
		datas.add("request");
		datas.add(RamlUtils.getIndentCharts(INDENT_CHAR, 1) + ".post('" + Tool.getRequestUri(adapter) + "')");
		// param
		Map<String, String> formParameter = Tool.getFormParams(adapter);

		for (String displayName : formParameter.keySet()) {
			datas.add(RamlUtils.getIndentCharts(INDENT_CHAR, 1) + ".send('" + displayName + "=" + formParameter.get(displayName) + "')");
		}
		datas.add(RamlUtils.getIndentCharts(INDENT_CHAR, 1) + ".expect(200)");

		datas.add(RamlUtils.getIndentCharts(INDENT_CHAR, 1) + ".end(done);");

		return datas;
	}
}


text:
'use strict';
var utils = require('../lib/utils.js')
var fs = require('fs')

/**
 * sanitize Checkboxes is used on an /action request
 * take every paths and set resolved directories, paths acccordingly
 */
function sanitizeCheckboxes(req, res, next) {
  var paths = []
  var directories = []

  if(typeof req.body.path == 'string')
    req.body.path = [req.body.path]

  //validating paths
  for(let i in req.body.path) {
    var path = utils.higherPath(req.options.root, req.body.path[i])

    if(path != req.options.root) {
      try {
        var stat = fs.statSync(path)
      } catch(err) {
        return utils.handleSystemError(next)(err)
      }

      if(stat.isDirectory()) {
        directories.push(path)
      } else {
        paths.push(path)
      }
    }
  }

  req.options.directories = directories
  req.options.paths = paths

  return next()
}

module.exports = sanitizeCheckboxes


text:
UIKIT_EXTERN NSString *const kYCXBannerPhotoLoadingDidEndNotification;

/// 通知:图片加载进度
UIKIT_EXTERN NSString *const kYCXBannerPhotoProgressNotification;

@protocol YCXBannerPhotoProtocol <NSObject>

/// 最终用于显示的图片
@property (nonatomic, strong) UIImage *underlyingImage;

/// 取消加载
- (void)cancelAnyLoading;

/// 加载最终图片,并且发送通知
- (void)loadUnderlyingImageAndNotify;

@end


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Consultorio.ConsultaAmbulatoria.ControlPerinatal.Interconsultas {

    public partial class Edit {

        /// <summary>
        /// lFecha control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lFecha;

        /// <summary>
        /// txtFecha control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtFecha;

        /// <summary>
        /// lMotivo control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lMotivo;

        /// <summary>
        /// txtMotivo control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtMotivo;

        /// <summary>
        /// lObservacion control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lObservacion;

        /// <summary>
        /// txtObservacion control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtObservacion;

        /// <summary>
        /// lProfesional control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lProfesional;

        /// <summary>
        /// ddlProfesional control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.DropDownList ddlProfesional;

        /// <summary>
        /// btnGuardar control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnGuardar;

        /// <summary>
        /// btnCancelar control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnCancelar;

        /// <summary>
        /// Master property.
        /// </summary>
        /// <remarks>
        /// Auto-generated property.
        /// </remarks>
        public new ConsultaAmbulatoria.MasterPages.ConsultorioPerinatal Master {
            get {
                return ((ConsultaAmbulatoria.MasterPages.ConsultorioPerinatal)(base.Master));
            }
        }
    }
}


text:
package net.danielmaly.scheme.builtin.predicates;

import com.oracle.truffle.api.dsl.GenerateNodeFactory;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.nodes.NodeInfo;
import net.danielmaly.scheme.builtin.BuiltinExpression;
import net.danielmaly.scheme.eval.Utils;

@NodeInfo(shortName = "string?")
@GenerateNodeFactory
public abstract class IsString extends BuiltinExpression {

    @Specialization
    public boolean isString(Object a) {
        return a instanceof String;
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="CodeBlueDev">
//   Copyright (c) CodeBlueDev. All rights reserved.
// </copyright>
// <summary>
//    Information about the assembly.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CodeBlueDev.PluralSight.Core.Models")]
[assembly: AssemblyDescription("PluralSight Core Models that can be used by other applications.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("CodeBlueDev")]
[assembly: AssemblyProduct("CodeBlueDev.PluralSight.Core.Models")]
[assembly: AssemblyCopyright("Copyright ©  2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fe1381a7-0829-4440-9bb1-a370bf787e1d")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyInformationalVersion("3.0.0.0")]


text:
/*global xAPS */
/**
 * A module for the Unit List page.
 *
 * Closely related to the Report page, from where it is being redirected from in the first place, because of zooming.
 *
 * Can also be accessed directly.
 *
 * Does not need to be initialized.
 *
 * TEMPLATES
 * /WebContent/templates/unit-list/index.ftl // Includes this script
 *
 * @author Jarl Andre Hubenthal
 */
xAPS.createModule("unit.list", function($this,$super,$) {
	/**
	 * The configuration.
	 */
	$this.settings = {
        submit : {
            onchange : ".submitonchange",
            button : "#updateButton"
        }
	};

	/**
	 * The constructor.
	 *
	 * Configures calendars, and change/onclick event handlers.
	 */
	$this._initForm = function() {
		$super.setupFromCalendar();
		$super.setupToCalendar();
		$($this.settings.submit.onchange).change(function() {
			return $this.submitUnitListForm();
		});
		$($this.settings.submit.button).click(function() {
			return $this.submitUnitListForm();
		});
	};

	/**
	 * Submits the form if the end date is higher than the start date.
	 * Else it pops up an alert.
	 */
	$this.submitUnitListForm = function() {
		if($super.parseDate($("#start").val())>$super.parseDate($("#end").val())){
			alert("Start date is not before end date!");
			return false;
		}else{
			// In earlier times the following was used to display a please wait dialog
			//$super.pleaseWait();
			// Submits the default form
			$super.submitForm();
		}
	};
});


text:
$.widget("ui.filepreview", {
    _init: function() {
        var takePicture = $(this.element),
            showPicture = $('#'+this.options.preview),
            self = this;

        if (takePicture.length && showPicture.length) {
            takePicture.on('change', function (event) {
                var files = event.target.files,
                    file;

                if (files && files.length > 0) {
                    file = files[0];
                    try {
                        // Get window.URL object
                        var URL = window.URL || window.webkitURL;
                        var imgURL = URL.createObjectURL(file);
                        showPicture
                            .attr('src', imgURL)
                            .addClass('has-preview');
                        URL.revokeObjectURL(imgURL);
                    }
                    catch (e) {
                        try {
                            // Fallback if createObjectURL is not supported
                            var fileReader = new FileReader();
                            fileReader.onload = function (event) {
                                showPicture
                                    .attr('src', event.target.result)
                                    .addClass('has-preview');
                            };
                            fileReader.readAsDataURL(file);
                        }
                        catch (e2) {
                            showPicture
                                .attr('src', this.options.placeholder)
                                .removeClass('has-preview');
                        }
                    }
                }
                else {
                    showPicture
                        .attr('src', this.options.placeholder)
                        .removeClass('has-preview');
                }
            });

            showPicture.on('click', function() { takePicture.click(); });
        }
    }
});

$.ui.filepreview.defaults = {
    preview: '',
    placeholder: '/lib/images/noun/photo-camera.png'
};


text:
<?php

include("../connect.php");

$startsy = $_GET['startsy'];
$endsy = $_GET['endsy'];
$term = $_GET['term'];

$query = mysql_query("SELECT s.id, CONCAT(s.lname, ', ', s.fname, ' ', s.mi) as studentname, te.course_code
  FROM student s, thesis_enrollment te
  WHERE s.id=te.student_id AND te.start_sy='$startsy' AND te.end_sy='$endsy' AND te.term='$term'");

$students = array();
while ($student = mysql_fetch_assoc($query)) $students[] = $student;

echo json_encode($students);


text:
/*
 * A very basic demo of SFML.
 *
 * REQUIRE:
 *    libsfml-dev (Debian)
 *
 * USAGE:
 *    g++ -c window.cc
 *    g++ -o window window.o -lsfml-graphics -lsfml-window -lsfml-system
 *
 * SEE:
 *    http://www.sfml-dev.org/tutorials/1.6/graphics-sprite.php
 */

#include <iostream>
#include <SFML/Graphics.hpp>

const int WIDTH = 640;
const int HEIGHT = 480;
const int SPEED = 150;

int main()
{
    std::string filename("image.png");

    // Load the sprite image from a file
    sf::Image image;
    if(!image.LoadFromFile(filename)) {
        // Error...
        std::cerr << filename << ": wrong image file." << std::endl;
    }
    image.SetSmooth(false);

    // Create sprite
    sf::Sprite sprite(image);
    sprite.SetPosition(WIDTH/2, HEIGHT/2);

    //////////

    sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT, 24), "SFML Window");

    const sf::Input & input = window.GetInput();

    // Main Loop
    while(window.IsOpened()) {

        // Events
        sf::Event event;
        while(window.GetEvent(event)) {
            // Window closed
            if(event.Type == sf::Event::Closed) {
                window.Close();
            }

            // 'Esc' key pressed
            if((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Escape)) {
                window.Close();
            }
        }

        // Real time inputs
        if(input.IsKeyDown(sf::Key::Left)) {
            sprite.Move(-SPEED * window.GetFrameTime(), 0);
        }

        if(input.IsKeyDown(sf::Key::Right)) {
            sprite.Move(SPEED * window.GetFrameTime(), 0);
        }

        if(input.IsKeyDown(sf::Key::Up)) {
            sprite.Move(0, -SPEED * window.GetFrameTime());
        }

        if(input.IsKeyDown(sf::Key::Down)) {
            sprite.Move(0, SPEED * window.GetFrameTime());
        }

        // Clear the window (with white pixels)
        window.Clear(sf::Color(255, 255, 255));

        // Display sprite in our window
        window.Draw(sprite);

        // Display
        window.Display();

    }

    return 0;
}


text:
namespace Dynamix.Metadata
{
    public abstract class MemberWithBody : ConstructMember
    {
    }
}


text:
define(function (require) {
	return function ($scope, $modalInstance,lang) {
//		values
		$scope.lang=lang;

//		buttons
			$scope.ok = function () {
				$modalInstance.close();
			};

			$scope.cancel = function () {
				$modalInstance.dismiss('cancel');
			};

	}

});


text:
#include <aws/eventbridge/model/ListEventSourcesResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::EventBridge::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

ListEventSourcesResult::ListEventSourcesResult()
{
}

ListEventSourcesResult::ListEventSourcesResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

ListEventSourcesResult& ListEventSourcesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("EventSources"))
  {
    Aws::Utils::Array<JsonView> eventSourcesJsonList = jsonValue.GetArray("EventSources");
    for(unsigned eventSourcesIndex = 0; eventSourcesIndex < eventSourcesJsonList.GetLength(); ++eventSourcesIndex)
    {
      m_eventSources.push_back(eventSourcesJsonList[eventSourcesIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("NextToken"))
  {
    m_nextToken = jsonValue.GetString("NextToken");

  }

  return *this;
}


text:
<?php
use tebazil\dbseeder\Generator;

/**
 * Created by PhpStorm.
 * User: tebazil
 * Date: 10.09.15
 * Time: 22:49
 */
class GeneratorTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var Generator
     */
    private $generator;

    /**
     * @return mixed
     */
    public function getGenerator()
    {
        if(is_null($this->generator)) {
            $this->generator = new Generator(new \tebazil\dbseeder\Seeder(new Pdo('mysql:localhost','root','test'))); //yeah, I know we can benefit from some decoupling here
        }
        return $this->generator;
    }

    public function testPk()
    {
        /**
         * @var $generator Generator
         */
        $generator = $this->getGenerator();
        $this->assertEquals(1, $generator->getValue(Generator::PK, false));
        $this->assertEquals(2, $generator->getValue(Generator::PK, false));
        $generator->reset();
        $this->assertEquals(1, $generator->getValue(Generator::PK, false));
        $this->assertEquals(2, $generator->getValue([Generator::PK], false));
    }

    public function testAnonymousFunctions() {
        $generator = $this->getGenerator();
        $this->assertEquals([1,2,3], $generator->getValue(function() {return [1,2,3];}, false));
        $this->assertEquals(2, $generator->getValue(function() {return 2;}, false));
    }

    public function testFaker() {
        $generator = $this->getGenerator();
        /* property */
        $this->assertNotEmpty($generator->getValue([Generator::FAKER, 'name'], false));
        /* method with params */
        $this->assertEquals(10, strlen($generator->getValue([Generator::FAKER, 'password',[10,10]], false)));
        /* method with no params */
        $this->assertNotEmpty($generator->getValue([Generator::FAKER, 'password',[]], false));
        /* method as property */
        $this->assertNotEmpty($generator->getValue([Generator::FAKER, 'password'], false));
        /* empty options array defined */
        $this->assertNotEmpty($generator->getValue([Generator::FAKER, 'password', [],[]], false));
        /* optional */
        $values = [];
        for($i=0;$i<100;$i++) {
            $values[]= $generator->getValue([Generator::FAKER, 'password', [],['optional'=>[]]], false);
        }
        $this->assertTrue(in_array(null, $values), 'fakers optional() is working');

        //try with options

        /* unique */
        //try all options applied

    }

    public function testConstantValue() {
        $generator = $this->getGenerator();
        $value = 'input_equals_output';
        $this->assertEquals($value, $generator->getValue($value, false));
    }

    public function testRelations() {
        $generator = $this->getGenerator();
        $relatedColumnValues = [1,2,3,45,6,6,7, 8];
        $this->generator->setColumns('book', [
            'id'=> $relatedColumnValues,
        ]);
        for($i=0;$i<4;$i++) {
            $this->assertTrue(in_array($generator->getValue([Generator::RELATION, 'book','id']), $relatedColumnValues));
        }
    }

}


text:
package com.qiscus.sdk.ui.adapter.viewholder;

import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.customtabs.CustomTabsIntent;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.qiscus.nirmana.Nirmana;
import com.qiscus.sdk.Qiscus;
import com.qiscus.sdk.R;
import com.qiscus.sdk.data.model.QiscusMentionConfig;
import com.qiscus.sdk.data.model.QiscusComment;
import com.qiscus.sdk.ui.adapter.OnItemClickListener;
import com.qiscus.sdk.ui.adapter.OnLongItemClickListener;
import com.qiscus.sdk.ui.view.ClickableMovementMethod;
import com.qiscus.sdk.ui.view.QiscusProgressView;
import com.qiscus.sdk.util.QiscusImageUtil;
import com.qiscus.sdk.util.QiscusPatterns;
import com.qiscus.sdk.util.QiscusTextUtil;

import java.io.File;
import java.util.regex.Matcher;

/**
 * Created on : September 27, 2016
 * Author     : zetbaitsu
 * Name       : Zetra
 * GitHub     : https://github.com/zetbaitsu
 */
public abstract class QiscusBaseImageMessageViewHolder extends QiscusBaseMessageViewHolder<QiscusComment>
        implements QiscusComment.ProgressListener, QiscusComment.DownloadingListener {

    @NonNull protected ImageView thumbnailView;
    @Nullable protected TextView captionView;
    @Nullable protected ImageView imageFrameView;
    @Nullable protected QiscusProgressView progressView;
    @Nullable protected ImageView downloadIconView;

    protected int rightProgressFinishedColor;
    protected int leftProgressFinishedColor;

    protected QiscusComment qiscusComment;

    public QiscusBaseImageMessageViewHolder(View itemView, OnItemClickListener itemClickListener,
                                            OnLongItemClickListener longItemClickListener) {
        super(itemView, itemClickListener, longItemClickListener);
        thumbnailView = getThumbnailView(itemView);
        captionView = getCaptionView(itemView);
        imageFrameView = getImageFrameView(itemView);
        progressView = getProgressView(itemView);
        downloadIconView = getDownloadIconView(itemView);
        if (captionView != null) {
            captionView.setMovementMethod(ClickableMovementMethod.getInstance());
            captionView.setClickable(false);
            captionView.setLongClickable(false);
        }
    }

    @Override
    protected void loadChatConfig() {
        super.loadChatConfig();
        rightProgressFinishedColor = ContextCompat.getColor(Qiscus.getApps(), Qiscus.getChatConfig().getRightProgressFinishedColor());
        leftProgressFinishedColor = ContextCompat.getColor(Qiscus.getApps(), Qiscus.getChatConfig().getLeftProgressFinishedColor());
    }

    @NonNull
    protected abstract ImageView getThumbnailView(View itemView);

    @Nullable
    protected abstract TextView getCaptionView(View itemView);

    @Nullable
    protected abstract ImageView getImageFrameView(View itemView);

    @Nullable
    protected abstract QiscusProgressView getProgressView(View itemView);

    @Nullable
    protected abstract ImageView getDownloadIconView(View itemView);

    @Override
    public void bind(QiscusComment qiscusComment) {
        super.bind(qiscusComment);
        this.qiscusComment = qiscusComment;
        qiscusComment.setProgressListener(this);
        qiscusComment.setDownloadingListener(this);
        setUpDownloadIcon(qiscusComment);
        showProgressOrNot(qiscusComment);
        if (captionView != null) {
            setUpLinks();
        }
    }

    protected void setUpDownloadIcon(QiscusComment qiscusComment) {
        if (downloadIconView != null) {
            if (qiscusComment.getState() <= QiscusComment.STATE_SENDING) {
                downloadIconView.setImageResource(R.drawable.ic_qiscus_upload);
            } else {
                downloadIconView.setImageResource(R.drawable.ic_qiscus_download);
            }
        }
    }

    protected void showProgressOrNot(QiscusComment qiscusComment) {
        if (progressView != null) {
            progressView.setProgress(qiscusComment.getProgress());
            progressView.setVisibility(qiscusComment.isDownloading() ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    protected void setUpColor() {
        if (imageFrameView != null) {
            imageFrameView.setColorFilter(messageFromMe ? rightBubbleColor : leftBubbleColor);
        }
        if (progressView != null) {
            progressView.setFinishedColor(messageFromMe ? rightProgressFinishedColor : leftProgressFinishedColor);
        }
        if (captionView != null) {
            captionView.setTextColor(messageFromMe ? rightBubbleTextColor : leftBubbleTextColor);
            captionView.setLinkTextColor(messageFromMe ? rightLinkTextColor : leftLinkTextColor);
        }
        super.setUpColor();
    }

    @Override
    protected void showMessage(QiscusComment qiscusComment) {
        showImage(qiscusComment);
        showCaption(qiscusComment);
    }

    protected void showCaption(QiscusComment qiscusComment) {
        if (captionView != null) {
            captionView.setVisibility(TextUtils.isEmpty(qiscusComment.getCaption()) ? View.GONE : View.VISIBLE);
            QiscusMentionConfig mentionConfig = Qiscus.getChatConfig().getMentionConfig();
            Spannable spannable = QiscusTextUtil.createQiscusSpannableText(
                    qiscusComment.getCaption(),
                    roomMembers,
                    messageFromMe ? mentionConfig.getRightMentionAllColor() : mentionConfig.getLeftMentionAllColor(),
                    messageFromMe ? mentionConfig.getRightMentionOtherColor() : mentionConfig.getLeftMentionOtherColor(),
                    messageFromMe ? mentionConfig.getRightMentionMeColor() : mentionConfig.getLeftMentionMeColor(),
                    mentionConfig.getMentionClickHandler()
            );
            captionView.setText(spannable);
        }
    }

    protected void showImage(QiscusComment qiscusComment) {
        if (qiscusComment.getAttachmentUri().toString().startsWith("http")) { //We have sent it
            showSentImage(qiscusComment);
        } else { //Still uploading the image
            showSendingImage(qiscusComment);
        }
    }

    protected void showSentImage(QiscusComment qiscusComment) {
        File localPath = Qiscus.getDataStore().getLocalPath(qiscusComment.getId());
        if (localPath == null) { //If the image not yet downloaded
            showDownloadIcon(true);
            showBlurryImage(qiscusComment);
        } else {
            showDownloadIcon(false);
            showLocalFileImage(localPath);
        }
    }

    protected void showLocalFileImage(File localPath) {
        Nirmana.getInstance().get()
                .load(localPath)
                .dontAnimate()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .placeholder(R.drawable.qiscus_image_placeholder)
                .error(R.drawable.qiscus_image_placeholder)
                .into(thumbnailView);
    }

    protected void showSendingImage(QiscusComment qiscusComment) {
        showDownloadIcon(true);
        File localPath = new File(qiscusComment.getAttachmentUri().toString());
        if (localPath.exists()) { //If the image still exist
            showLocalFileImage(localPath);
        } else { //If the image file have been removed
            Nirmana.getInstance().get()
                    .load(R.drawable.qiscus_image_placeholder)
                    .dontAnimate()
                    .into(thumbnailView);
        }
    }

    protected void showBlurryImage(QiscusComment qiscusComment) {
        Nirmana.getInstance().get()
                .load(QiscusImageUtil.generateBlurryThumbnailUrl(qiscusComment.getAttachmentUri().toString()))
                .dontAnimate()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .placeholder(R.drawable.qiscus_image_placeholder)
                .error(R.drawable.qiscus_image_placeholder)
                .into(thumbnailView);
    }

    protected void showDownloadIcon(boolean show) {
        if (downloadIconView != null) {
            downloadIconView.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void onProgress(QiscusComment qiscusComment, int percentage) {
        if (qiscusComment.equals(this.qiscusComment) && progressView != null) {
            progressView.setProgress(percentage);
        }
    }

    @Override
    public void onDownloading(QiscusComment qiscusComment, boolean downloading) {
        if (qiscusComment.equals(this.qiscusComment) && progressView != null) {
            progressView.setVisibility(downloading ? View.VISIBLE : View.GONE);
        }
    }

    private void setUpLinks() {
        String message = captionView.getText().toString();
        Matcher matcher = QiscusPatterns.AUTOLINK_WEB_URL.matcher(message);
        while (matcher.find()) {
            int start = matcher.start();
            if (start > 0 && message.charAt(start - 1) == '@') {
                continue;
            }
            int end = matcher.end();
            clickify(start, end, () -> {
                String url = message.substring(start, end);
                if (!url.startsWith("http")) {
                    url = "http://" + url;
                }
                new CustomTabsIntent.Builder()
                        .setToolbarColor(ContextCompat.getColor(Qiscus.getApps(), Qiscus.getChatConfig().getAppBarColor()))
                        .setShowTitle(true)
                        .addDefaultShareMenuItem()
                        .enableUrlBarHiding()
                        .build()
                        .launchUrl(captionView.getContext(), Uri.parse(url));
            });
        }
    }

    private static class ClickSpan extends ClickableSpan {
        private OnClickListener listener;

        public ClickSpan(OnClickListener listener) {
            this.listener = listener;
        }

        @Override
        public void onClick(View widget) {
            if (listener != null) {
                listener.onClick();
            }
        }

        public interface OnClickListener {
            void onClick();
        }
    }

    private void clickify(int start, int end, ClickSpan.OnClickListener listener) {
        CharSequence text = captionView.getText();
        ClickSpan span = new ClickSpan(listener);

        if (start == -1) {
            return;
        }

        if (text instanceof Spannable) {
            ((Spannable) text).setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            SpannableString s = SpannableString.valueOf(text);
            s.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            captionView.setText(s);
        }
    }
}


text:
/*
 * File:   BumblebeeStereo.hpp
 * Author: satya
 *
 * Created on December 12, 2013, 9:47 PM
 */

#ifndef BUMBLEBEESTEREO_HPP
#define	BUMBLEBEESTEREO_HPP

#include <environment/Sensor.hpp>

class BumblebeeStereo : public environment::Sensor {
public:
    bool connect();
    bool disconnect();
    bool fetch();
    BumblebeeStereo();
    BumblebeeStereo(int argc, char** argv);
    BumblebeeStereo(const BumblebeeStereo& orig);
    virtual ~BumblebeeStereo();
};

#endif	/* BUMBLEBEESTEREO_HPP */


text:
package com.opengamma.analytics.financial.model.volatility.smile.function;

import java.util.Arrays;

import org.apache.commons.lang.Validate;

/**
 *
 */
public class SVIFormulaData implements SmileModelData {
  private static final int NUM_PARAMETERS = 5;
  private final double[] _parameters;

  public SVIFormulaData(final double[] parameters) {
    Validate.notNull(parameters, "parameters are null");
    Validate.isTrue(parameters.length == NUM_PARAMETERS, "must be " + NUM_PARAMETERS + " parameters");
    Validate.isTrue(parameters[0] >= 0, "Need a >= 0");
    Validate.isTrue(parameters[1] >= 0, "Need b >= 0");
    Validate.isTrue(parameters[2] >= -1 && parameters[2] <= 1, "Need -1 <= rho <= 1");
    Validate.isTrue(parameters[3] >= 0, "Need nu >= 0");

    _parameters = new double[NUM_PARAMETERS];
    System.arraycopy(parameters, 0, _parameters, 0, NUM_PARAMETERS);
  }

  public SVIFormulaData(final double a, final double b, final double rho, final double nu, final double m) {
    this(new double[] {a, b, rho, nu, m });
  }

  @Override
  public boolean isAllowed(final int index, final double value) {
    switch (index) {
      case 0:
      case 1:
      case 3:
        return value >= 0;
      case 2:
        return value >= -1 && value <= 1;
      case 4:
        return true;
      default:
        throw new IllegalArgumentException("index " + index + " outside range");
    }
  }

  public double getA() {
    return _parameters[0];
  }

  public double getB() {
    return _parameters[1];
  }

  public double getRho() {
    return _parameters[2];
  }

  public double getNu() {
    return _parameters[3];
  }

  public double getM() {
    return _parameters[4];
  }

  @Override
  public int getNumberOfParameters() {
    return NUM_PARAMETERS;
  }

  @Override
  public double getParameter(final int index) {
    return _parameters[index];
  }

  @Override
  public SmileModelData with(final int index, final double value) {
    final double[] temp = new double[NUM_PARAMETERS];
    System.arraycopy(_parameters, 0, temp, 0, NUM_PARAMETERS);
    temp[index] = value;
    return new SVIFormulaData(temp);
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + Arrays.hashCode(_parameters);
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final SVIFormulaData other = (SVIFormulaData) obj;
    if (!Arrays.equals(_parameters, other._parameters)) {
      return false;
    }
    return true;
  }

  @Override
  public String toString() {
    return "SVIFormulaData [a=" + getA() + ", b=" + getB() + ", rho=" + getRho() + ", nu=" + getNu() + ", m=" + getM() + "]";
  }

}


text:
package com.facebook.buck.ocaml;

import com.facebook.buck.cxx.CxxPreprocessables;
import com.facebook.buck.cxx.CxxPreprocessorDep;
import com.facebook.buck.cxx.CxxPreprocessorInput;
import com.facebook.buck.cxx.NativeLinkable;
import com.facebook.buck.cxx.NativeLinkableInput;
import com.facebook.buck.cxx.NativeLinkables;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.rules.AbstractBuildRule;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePaths;
import com.facebook.buck.rules.coercer.OCamlSource;
import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;

import java.nio.file.Path;

/**
 * Compute transitive dependencies and generate ocaml build rules
 */
public class OCamlRuleBuilder {

  public static final BuildRuleType TYPE = new BuildRuleType("ocaml_library");
  private static final Flavor STATIC_FLAVOR = new Flavor("static");

  private OCamlRuleBuilder() {
  }

  public static final Function<BuildRule, ImmutableList<String>> getLibInclude() {
    return
      new Function<BuildRule, ImmutableList<String>>() {
        @Override
        public ImmutableList<String> apply(BuildRule input) {
          if (input instanceof OCamlLibrary) {
            OCamlLibrary library = (OCamlLibrary) input;
            return ImmutableList.of(library.getIncludeLibDir().toString());
          } else {
            return ImmutableList.of();
          }
        }
      };
  }

  public static ImmutableList<SourcePath> getInput(Iterable<OCamlSource> source) {
    return ImmutableList.copyOf(
        FluentIterable.from(source)
            .transform(
                new Function<OCamlSource, SourcePath>() {
                  @Override
                  public SourcePath apply(OCamlSource input) {
                    return input.getSource();
                  }
                })
    );
  }

  public static BuildTarget createStaticLibraryBuildTarget(BuildTarget target) {
    return BuildTargets.extendFlavoredBuildTarget(target, STATIC_FLAVOR);
  }

  public static AbstractBuildRule createBuildRule(
      OCamlBuckConfig ocamlBuckConfig,
      final BuildRuleParams params,
      BuildRuleResolver resolver,
      ImmutableList<OCamlSource> srcs,
      boolean isLibrary,
      ImmutableList<String> argFlags,
      final ImmutableList<String> linkerFlags) {

    ImmutableList<String> includes = FluentIterable.from(params.getDeps())
        .transformAndConcat(getLibInclude())
        .toList();

    final FluentIterable<SourcePath> srcSourcePaths = FluentIterable.from(srcs).transform(
        OCamlSource.TO_SOURCE_PATH);
    final FluentIterable<Path> srcPaths = srcSourcePaths.transform(SourcePaths.TO_PATH);

    NativeLinkableInput linkableInput = NativeLinkables.getTransitiveNativeLinkableInput(
        params.getDeps(),
        NativeLinkable.Type.STATIC,
        /* reverse */ false);

    ImmutableList<OCamlLibrary> ocamlInput = OCamlUtil.getTransitiveOCamlInput(params.getDeps());

    ImmutableList<SourcePath> allInputs =
        ImmutableList.<SourcePath>builder()
            .addAll(getInput(srcs))
            .addAll(linkableInput.getInputs())
            .build();

    BuildTarget buildTarget =
        isLibrary ? createStaticLibraryBuildTarget(params.getBuildTarget())
            : params.getBuildTarget();
    final BuildRuleParams compileParams = params.copyWithChanges(
        NativeLinkable.NATIVE_LINKABLE_TYPE,
        buildTarget,
        /* declaredDeps */ ImmutableSortedSet.copyOf(SourcePaths.filterBuildRuleInputs(allInputs)),
        /* extraDeps */ ImmutableSortedSet.<BuildRule>of());

    ImmutableList<String> flags = ImmutableList.<String>builder()
        .addAll(argFlags)
        .build();

    CxxPreprocessorInput cxxPreprocessorInputFromDeps =
        CxxPreprocessables.getTransitiveCxxPreprocessorInput(
            FluentIterable.from(params.getDeps())
                .filter(Predicates.instanceOf(CxxPreprocessorDep.class)));

    final OCamlBuildContext ocamlContext = OCamlBuildContext.builder(ocamlBuckConfig)
        .setFlags(flags)
        .setIncludes(includes)
        .setOcamlInput(ocamlInput)
        .setLinkableInput(linkableInput)
        .setUpDirectories(buildTarget, isLibrary)
        .setCxxPreprocessorInput(cxxPreprocessorInputFromDeps)
        .setInput(getInput(srcs))
        .build();

    if (isLibrary) {
      final OCamlBuild ocamlLibraryBuild = new OCamlBuild(
          compileParams,
          ocamlContext,
          ocamlBuckConfig.getCCompiler(),
          ocamlBuckConfig.getCxxCompiler());

      resolver.addToIndex(ocamlLibraryBuild);

      return new OCamlStaticLibrary(
          params,
          compileParams,
          linkerFlags,
          srcPaths,
          ocamlContext,
          ocamlLibraryBuild);
    } else {
      return new OCamlBuild(
          compileParams,
          ocamlContext,
          ocamlBuckConfig.getCCompiler(),
          ocamlBuckConfig.getCxxCompiler());
    }
  }

}


text:
<?php include_once '../global.php';
if(!isset($_SESSION['housekeeping']) or !isset($_GET['newsid']))
{
	header('Location: /me');
	die();
}
$Article = $core->GetArticle($_GET['newsid']);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="author" content="Paweł 'kilab' Balicki - kilab.pl" />
<title><?php echo $CONFIG['TPL']['NAME']; ?> -> Housekeeping</title>
<link rel="stylesheet" type="text/css" href="css/style.css" media="screen" />
<link rel="stylesheet" type="text/css" href="css/navi.css" media="screen" />

Welkom, <?php echo $_SESSION['username']; ?>

Laatst Ingelogd: <?php echo date('d-M-Y \o\m\  H:i', $habbo->SelectFromUsername($_SESSION['username'], 'last_online'));?>

› Site

Dashboard

Plaats nieuws

Plaats campaign

› Spelers

Ban een speler

› Info

PHP info

Logs

Nieuws Bewerken

				<?php
			if(isset($_POST['Title']) && isset($_POST['ShortStory']) && isset($_POST['Image']) && isset($_POST['LongStory']))
			{
				echo $management->EditNews($_POST['Title'], $_POST['ShortStory'], $_POST['LongStory'], $_SESSION['username'], $_POST['Image']);
			}
			?>
				<form action="" method="post">

						Titel
						<input id="name" value="<?php echo $Article['title']; ?>" name="Titel" class="text" />

						ShortStory
						<input id="name" value="<?php echo $Article['shortstory']; ?>" name="ShortStory" class="text" />

						Plaatje
						<select name="Image" class="">
							<?php
							foreach(glob('../web-gallery/promo/*') as $image)
							{
								$image = str_replace('../web-gallery/promo/', '', $image);
								echo '<option value="'.$image.'">'.$image.'</option>';
							}
							?>

						</select>

						Bericht (required)
						<textarea name="LongStory" class="textarea" rows="10"><?php echo $Article['longstory']; ?></textarea>

						<button type="submit" class="add">Plaats</button>
						Nieuws Paneel

				</form>

TyphoonCMS  | Used for <?php echo $CONFIG['TPL']['NAME']; ?> hotel

			© 2013 - VIS000DEVELOPMENT


text:
package git4idea.push;

import com.intellij.util.containers.HashMap;
import git4idea.GitBranch;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;

import java.util.Map;

/**
 * Holds information about a single Git push action which is to be executed or has been executed.
 *
 * @author Kirill Likhodedov
 */
public final class GitPushInfo {

  @NotNull private final GitCommitsByRepoAndBranch myCommits;
  @NotNull private final Map<GitRepository, GitPushSpec> myPushSpecs;

  /**
   * We pass the complex {@link GitCommitsByRepoAndBranch} structure here instead of just the list of repositories,
   * because later (after successful push, for example) it may be needed for showing useful notifications, such as number of commits pushed.
   */
  public GitPushInfo(@NotNull GitCommitsByRepoAndBranch commits, @NotNull Map<GitRepository, GitPushSpec> pushSpecs) {
    myCommits = commits;
    myPushSpecs = pushSpecs;
  }

  @NotNull
  public Map<GitRepository, GitPushSpec> getPushSpecs() {
    return myPushSpecs;
  }

  @NotNull
  public GitCommitsByRepoAndBranch getCommits() {
    return myCommits;
  }

  @NotNull
  public GitPushInfo retain(Map<GitRepository, GitBranch> repoBranchMap) {
    return new GitPushInfo(myCommits.retainAll(repoBranchMap), new HashMap<GitRepository, GitPushSpec>(myPushSpecs));
  }
}


text:
import React from 'react'
import {
  View,
  Text,
  Image,
  TouchableOpacity
} from 'react-native'
import Styles from './Styles/RowStyle'
import {Images, Metrics, Colors} from '../Themes'

const data = {
  onPress: null,
  style: {},
  subs: [
    {
      type: 'image'
    },
    {
      onPress: null, // func / null
      style: {},
      subs: [
        {
          style: {},
          wrapperStyle: {},
          type: 'text',
          text: '123'
        },
        {
          style: {},
          type: 'text',
          text: '456'
        }
      ]
    }
  ]
}

export default class Row extends React.Component {

  static key = 1;

  renderComponent(sub) {
    const {type, style = {}} = sub;

    switch (type) {
      case 'text':
        return <Text {...sub}>{sub.text}</Text>;
        break
      case 'image':
        return <Image resizeMode="cover" {...sub} />;
        break
    }
  }

  renderSubs(subs, isWrapper = true) {
    const views = [];
    subs.forEach((sub) => {
      const {wrapperStyle = {}, onPress} = sub;
      const Wrapper = onPress ? TouchableOpacity : View;
      const rowStyle = isWrapper ? Styles.rowDetail : Styles.flex;
      Row.key++;
      // console.log(sub, isWrapper)
      if (sub.subs) {
        views.push(
          <Wrapper key={Row.key} style={[Styles.rowDetail, wrapperStyle]}>
            { this.renderSubs(sub.subs, false) }
          </Wrapper>
        )
      } else {
        views.push(
          <Wrapper key={Row.key} style={[rowStyle, wrapperStyle]}>
            { this.renderComponent(sub) }
          </Wrapper>
        )
      }
    });

    return views
  }

  render() {
    const {
      onPress = () => {
      },
      wrapperStyle = {},
      subs = null,
    } = this.props.data || {};

    if (!subs) return null;

    const subView = this.renderSubs(subs);

    return (
      <View onPress={onPress} style={[wrapperStyle, Styles.horizontal]}>
        {subView}
      </View>
    )
  }
}


text:
layout: post
title: Exercising the SUT asynchronously
tags:
    - xUnit.net
---

In unit testing, there are times were the [SUT](http://xunitpatterns.com/SUT.html) has to be exercised **asynchronously**.

How can we wait for the exercise to complete execution?

* An instance of the SUT can be created on the main thread.
* The main *(waiting)* thread **spins in user mode** while starting the exercise of the SUT asynchronously.
* Once the result has been received, the execution continues on the main thread.
* The assertion takes place.

The [SpinWait](http://msdn.microsoft.com/en-us/library/system.threading.spinwait.aspx) synchronization type contains a method named [SpinUntil](http://msdn.microsoft.com/en-us/library/system.threading.spinwait.spinuntil.aspx) which works perfect for the described scenario.

``` csharp
// Fixture setup
var sut = new ObjectLocalStorage();
sut.Set(@object, expected);
object result = null;

// Exercise system
new Task(() => result = sut.Get(@object)).Start();
SpinWait.SpinUntil(() => result != null);

// Verify outcome
Assert.Equal(expected, result);
// Teardown
```

* Once the `Task` has been created it is immediately scheduled for execution by calling the `Start` method.
* As long as the unit test runs fast, the waiting thread spins in user mode, which is a [good thing](http://msdn.microsoft.com/en-us/library/ee722114.aspx).

There is also a [SpinUntil overload](http://msdn.microsoft.com/en-us/library/dd449238.aspx) accepting a TimeSpan timeout.


text:
layout: single
title:  "Concepts"
sidebar:
  nav: concepts
redirect_from:
  - /docs
  - /docs/
  - /docs/overview
---

{% include toc %}

Spinnaker is an open source, multi-cloud continuous delivery platform that helps you release software changes with high velocity and confidence.

It provides two core sets of features: *cluster management* and *deployment management*. Here is an overview of these features:

## Cluster Management

You use Spinnaker's cluster management features to view and manage your resources in the cloud.

![](clusters.png)

### Server Group

The base resource, the *Server Group*, identifies the deployable artifact (VM image, Docker image, source location) and basic configuration settings such as number of instances, autoscaling policies, metadata, etc. This resource is associated with a Load Balancer and a Security Group. When deployed, a Server Group is a collection of instances of the running software (VM instances, Kubernetes pods).

Server groups follow the **application-stack-detail-version** naming convention.

### Cluster

You can define *Clusters*, which are logical groupings of Server Groups in Spinnaker. These
groups are based on the **application-stack-detail** naming convention.

### Applications

*Applications* are logical groupings of Clusters in Spinnaker from the **application-stack-detail**
 naming convention.

### Load Balancer

A *Load Balancer* is associated with an ingress protocol and port range. It balances traffic among instances in its Server Groups. Optionally, you can enable health checks for a load balancer, with flexiblity to define health criteria and specify the health check endpoint.

### Security Group

A *Security Group* defines network traffic access. It is effectively a set of firewall rules defined by an IP range (CIDR) along with a communication protocol (e.g., TCP) and port range.

> Learn more about cluster management on the [Clusters](/concepts/clusters/) page.

## Deployment Management

You use Spinnaker's deployment management features to construct and manage continuous delivery workflows.

### Pipeline

![](pipelines.png)

*Pipelines* are the key deployment management construct in Spinnaker. They consist of a sequence of actions, known as stages. You can pass parameters from stage to stage along the pipeline. You can start a pipeline manually, or you can configure it to be started by automatic triggering events, such as a Jenkins job completing, a new Docker image appearing in your registry, a CRON schedule, or a stage in another pipeline. You can configure the pipeline to emit notifications to interested parties at various points during pipeline execution (such as on pipeline start/complete/fail), by email, SMS or HipChat.

### Stage

A *Stage* in Spinnaker is an action that forms an atomic building block for a pipeline. You can sequence stages in a Pipeline in any order, though some stage sequences may be more common than others. Spinnaker provides a number of stages such as Deploy, Resize, Disable, Manual Judgment, and many more. You can see the full list of stages and read about implementation details for each provider in the [Reference](/reference/providers) section.

### Deployment Strategies

![](deployment-strategies.png)

Spinnaker treats cloud-native deployment strategies as first class constructs, handling the underlying orchestration such as verifying health checks, disabling old server groups and enabling new server groups. Spinnaker supports the red/black (a.k.a. blue/green) strategy, with rolling red/black and canary strategies in active development.

> Learn more about deployment management on the [Pipelines](/concepts/pipelines/) page.


text:
from __future__ import absolute_import

from sentry.interfaces.base import Interface
from sentry.utils.json import prune_empty_keys
from sentry.interfaces.stacktrace import Stacktrace
from sentry.utils.safe import trim

__all__ = ("Threads",)

def get_stacktrace(value, raw=False):
    # Special case: if the thread has no frames we set the
    # stacktrace to none.  Otherwise this will fail really
    # badly.
    if value and value.get("frames"):
        return Stacktrace.to_python(value, slim_frames=True, raw=raw)

class Threads(Interface):
    score = 1900
    grouping_variants = ["system", "app"]

    @classmethod
    def to_python(cls, data):
        threads = []

        for thread in data.get("values") or ():
            if thread is None:
                # XXX(markus): We should handle this in the UI and other
                # consumers of this interface
                continue
            threads.append(
                {
                    "stacktrace": get_stacktrace(thread.get("stacktrace")),
                    "raw_stacktrace": get_stacktrace(thread.get("raw_stacktrace"), raw=True),
                    "id": trim(thread.get("id"), 40),
                    "crashed": bool(thread.get("crashed")),
                    "current": bool(thread.get("current")),
                    "name": trim(thread.get("name"), 200),
                }
            )

        return cls(values=threads)

    def to_json(self):
        def export_thread(data):
            if data is None:
                return None

            rv = {
                "id": data["id"],
                "current": data["current"],
                "crashed": data["crashed"],
                "name": data["name"],
                "stacktrace": None,
            }
            if data["stacktrace"]:
                rv["stacktrace"] = data["stacktrace"].to_json()
            if data["raw_stacktrace"]:
                rv["raw_stacktrace"] = data["raw_stacktrace"].to_json()
            return prune_empty_keys(rv)

        return prune_empty_keys({"values": [export_thread(x) for x in self.values]})

    def get_api_context(self, is_public=False, platform=None):
        def export_thread(data):
            rv = {
                "id": data["id"],
                "current": data["current"],
                "crashed": data["crashed"],
                "name": data["name"],
                "stacktrace": None,
                "rawStacktrace": None,
            }
            if data["stacktrace"]:
                rv["stacktrace"] = data["stacktrace"].get_api_context(is_public=is_public)
            if data["raw_stacktrace"]:
                rv["rawStacktrace"] = data["raw_stacktrace"].get_api_context(is_public=is_public)
            return rv

        return {"values": [export_thread(x) for x in self.values]}

    def get_meta_context(self, meta, is_public=False, platform=None):
        if meta and "values" not in meta:
            return {"values": meta}
        else:
            return meta


text:
<!DOCTYPE HTML>

	<title>Webcomponents</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=792, user-scalable=no">
	<meta http-equiv="x-ua-compatible" content="ie=edge">
	<link rel="stylesheet" href="node_modules/shower-ribbon/styles/screen.css">

Webcomponents

Giovanny Gongora, Mozilla.

Webcomponents

Quien soy yo?

JavaScriptero desde que me acuerdo

Mozilla Rep

Open source es mi día a día

Fully keyboard accessible

Printable to PDF

Webcomponents for lazy cats

From Googlers

¿Por qué desarrollar proyectos pensando en la necesidad del usuario cuando el usuario no sabe que necesita o como algo podría hacer su vida mejor? Lo mejor es dedicar tiempo en desarrollar ideas que nosotros aseguramos servirán a muchos, bajo nuestros conceptos, así el usuario entenderá que Google lo entiende. No suena casual, cierto? igual somos Google, no?

Google

Show me the code

			<!--Esto solo funciona en Chrome-->
			    <github-card user="Gioyik"></github-card>

			<!--Esto solo funciona en todos los navegadores-->
			    <x-github-card user="Gioyik"></x-github-card>

Alguien ha implementado esto?

Polymer - Google

X-tag - Mozilla

Bonsoic

Webcomponents IN

MozBrick

Que hay de malo con la implementación de Polymer?

No son estandar en su totalidad

Soporte enfocado hacia Chrome

Chrome no es el unico navegador

Perdida del concepto puro de un webcomponent

So much incompatibility

Tabla de comparación

			X-tag
			Polymer
			Bonsoic

			Varios navegadores
			Si
			No
			Si/No

			Extended
			Si
			No
			No

			LOaded on DOM
			Yes
			Yes
			Yes

			Documentación
			Yes
			Yes
			Yes

webcomponents son buena idea?

Slides en mi GitHub


text:
namespace net {

class PartialData;
struct HttpRequestInfo;
class HttpTransactionDelegate;
struct LoadTimingInfo;

// This is the transaction that is returned by the HttpCache transaction
// factory.
class HttpCache::Transaction : public HttpTransaction {
 public:
  // The transaction has the following modes, which apply to how it may access
  // its cache entry.
  //
  //  o If the mode of the transaction is NONE, then it is in "pass through"
  //    mode and all methods just forward to the inner network transaction.
  //
  //  o If the mode of the transaction is only READ, then it may only read from
  //    the cache entry.
  //
  //  o If the mode of the transaction is only WRITE, then it may only write to
  //    the cache entry.
  //
  //  o If the mode of the transaction is READ_WRITE, then the transaction may
  //    optionally modify the cache entry (e.g., possibly corresponding to
  //    cache validation).
  //
  //  o If the mode of the transaction is UPDATE, then the transaction may
  //    update existing cache entries, but will never create a new entry or
  //    respond using the entry read from the cache.
  enum Mode {
    NONE            = 0,
    READ_META       = 1 << 0,
    READ_DATA       = 1 << 1,
    READ            = READ_META | READ_DATA,
    WRITE           = 1 << 2,
    READ_WRITE      = READ | WRITE,
    UPDATE          = READ_META | WRITE,  // READ_WRITE & ~READ_DATA
  };

  Transaction(RequestPriority priority,
              HttpCache* cache,
              HttpTransactionDelegate* transaction_delegate);
  virtual ~Transaction();

  Mode mode() const { return mode_; }

  const std::string& key() const { return cache_key_; }

  // Writes |buf_len| bytes of meta-data from the provided buffer |buf|. to the
  // HTTP cache entry that backs this transaction (if any).
  // Returns the number of bytes actually written, or a net error code. If the
  // operation cannot complete immediately, returns ERR_IO_PENDING, grabs a
  // reference to the buffer (until completion), and notifies the caller using
  // the provided |callback| when the operation finishes.
  //
  // The first time this method is called for a given transaction, previous
  // meta-data will be overwritten with the provided data, and subsequent
  // invocations will keep appending to the cached entry.
  //
  // In order to guarantee that the metadata is set to the correct entry, the
  // response (or response info) must be evaluated by the caller, for instance
  // to make sure that the response_time is as expected, before calling this
  // method.
  int WriteMetadata(IOBuffer* buf,
                    int buf_len,
                    const CompletionCallback& callback);

  // This transaction is being deleted and we are not done writing to the cache.
  // We need to indicate that the response data was truncated.  Returns true on
  // success. Keep in mind that this operation may have side effects, such as
  // deleting the active entry.
  bool AddTruncatedFlag();

  HttpCache::ActiveEntry* entry() { return entry_; }

  // Returns the LoadState of the writer transaction of a given ActiveEntry. In
  // other words, returns the LoadState of this transaction without asking the
  // http cache, because this transaction should be the one currently writing
  // to the cache entry.
  LoadState GetWriterLoadState() const;

  const CompletionCallback& io_callback() { return io_callback_; }

  const BoundNetLog& net_log() const;

  // HttpTransaction methods:
  virtual int Start(const HttpRequestInfo* request_info,
                    const CompletionCallback& callback,
                    const BoundNetLog& net_log) OVERRIDE;
  virtual int RestartIgnoringLastError(
      const CompletionCallback& callback) OVERRIDE;
  virtual int RestartWithCertificate(
      X509Certificate* client_cert,
      const CompletionCallback& callback) OVERRIDE;
  virtual int RestartWithAuth(const AuthCredentials& credentials,
                              const CompletionCallback& callback) OVERRIDE;
  virtual bool IsReadyToRestartForAuth() OVERRIDE;
  virtual int Read(IOBuffer* buf,
                   int buf_len,
                   const CompletionCallback& callback) OVERRIDE;
  virtual void StopCaching() OVERRIDE;
  virtual bool GetFullRequestHeaders(
      HttpRequestHeaders* headers) const OVERRIDE;
  virtual void DoneReading() OVERRIDE;
  virtual const HttpResponseInfo* GetResponseInfo() const OVERRIDE;
  virtual LoadState GetLoadState() const OVERRIDE;
  virtual UploadProgress GetUploadProgress(void) const OVERRIDE;
  virtual bool GetLoadTimingInfo(
      LoadTimingInfo* load_timing_info) const OVERRIDE;
  virtual void SetPriority(RequestPriority priority) OVERRIDE;

 private:
  static const size_t kNumValidationHeaders = 2;
  // Helper struct to pair a header name with its value, for
  // headers used to validate cache entries.
  struct ValidationHeaders {
    ValidationHeaders() : initialized(false) {}

    std::string values[kNumValidationHeaders];
    bool initialized;
  };

  enum State {
    STATE_NONE,
    STATE_GET_BACKEND,
    STATE_GET_BACKEND_COMPLETE,
    STATE_SEND_REQUEST,
    STATE_SEND_REQUEST_COMPLETE,
    STATE_SUCCESSFUL_SEND_REQUEST,
    STATE_NETWORK_READ,
    STATE_NETWORK_READ_COMPLETE,
    STATE_INIT_ENTRY,
    STATE_OPEN_ENTRY,
    STATE_OPEN_ENTRY_COMPLETE,
    STATE_CREATE_ENTRY,
    STATE_CREATE_ENTRY_COMPLETE,
    STATE_DOOM_ENTRY,
    STATE_DOOM_ENTRY_COMPLETE,
    STATE_ADD_TO_ENTRY,
    STATE_ADD_TO_ENTRY_COMPLETE,
    STATE_ADD_TO_ENTRY_COMPLETE_AFTER_DELAY,
    STATE_START_PARTIAL_CACHE_VALIDATION,
    STATE_COMPLETE_PARTIAL_CACHE_VALIDATION,
    STATE_UPDATE_CACHED_RESPONSE,
    STATE_UPDATE_CACHED_RESPONSE_COMPLETE,
    STATE_OVERWRITE_CACHED_RESPONSE,
    STATE_TRUNCATE_CACHED_DATA,
    STATE_TRUNCATE_CACHED_DATA_COMPLETE,
    STATE_TRUNCATE_CACHED_METADATA,
    STATE_TRUNCATE_CACHED_METADATA_COMPLETE,
    STATE_PARTIAL_HEADERS_RECEIVED,
    STATE_CACHE_READ_RESPONSE,
    STATE_CACHE_READ_RESPONSE_COMPLETE,
    STATE_CACHE_WRITE_RESPONSE,
    STATE_CACHE_WRITE_TRUNCATED_RESPONSE,
    STATE_CACHE_WRITE_RESPONSE_COMPLETE,
    STATE_CACHE_READ_METADATA,
    STATE_CACHE_READ_METADATA_COMPLETE,
    STATE_CACHE_QUERY_DATA,
    STATE_CACHE_QUERY_DATA_COMPLETE,
    STATE_CACHE_READ_DATA,
    STATE_CACHE_READ_DATA_COMPLETE,
    STATE_CACHE_WRITE_DATA,
    STATE_CACHE_WRITE_DATA_COMPLETE
  };

  // Used for categorizing transactions for reporting in histograms. Patterns
  // cover relatively common use cases being measured and considered for
  // optimization. Many use cases that are more complex or uncommon are binned
  // as PATTERN_NOT_COVERED, and details are not reported.
  // NOTE: This enumeration is used in histograms, so please do not add entries
  // in the middle.
  enum TransactionPattern {
    PATTERN_UNDEFINED,
    PATTERN_NOT_COVERED,
    PATTERN_ENTRY_NOT_CACHED,
    PATTERN_ENTRY_USED,
    PATTERN_ENTRY_VALIDATED,
    PATTERN_ENTRY_UPDATED,
    PATTERN_ENTRY_CANT_CONDITIONALIZE,
    PATTERN_MAX,
  };

  // This is a helper function used to trigger a completion callback.  It may
  // only be called if callback_ is non-null.
  void DoCallback(int rv);

  // This will trigger the completion callback if appropriate.
  int HandleResult(int rv);

  // Runs the state transition loop.
  int DoLoop(int result);

  // Each of these methods corresponds to a State value.  If there is an
  // argument, the value corresponds to the return of the previous state or
  // corresponding callback.
  int DoGetBackend();
  int DoGetBackendComplete(int result);
  int DoSendRequest();
  int DoSendRequestComplete(int result);
  int DoSuccessfulSendRequest();
  int DoNetworkRead();
  int DoNetworkReadComplete(int result);
  int DoInitEntry();
  int DoOpenEntry();
  int DoOpenEntryComplete(int result);
  int DoCreateEntry();
  int DoCreateEntryComplete(int result);
  int DoDoomEntry();
  int DoDoomEntryComplete(int result);
  int DoAddToEntry();
  int DoAddToEntryComplete(int result);
  int DoAddToEntryCompleteAfterDelay(int result);
  int DoStartPartialCacheValidation();
  int DoCompletePartialCacheValidation(int result);
  int DoUpdateCachedResponse();
  int DoUpdateCachedResponseComplete(int result);
  int DoOverwriteCachedResponse();
  int DoTruncateCachedData();
  int DoTruncateCachedDataComplete(int result);
  int DoTruncateCachedMetadata();
  int DoTruncateCachedMetadataComplete(int result);
  int DoPartialHeadersReceived();
  int DoCacheReadResponse();
  int DoCacheReadResponseComplete(int result);
  int DoCacheWriteResponse();
  int DoCacheWriteTruncatedResponse();
  int DoCacheWriteResponseComplete(int result);
  int DoCacheReadMetadata();
  int DoCacheReadMetadataComplete(int result);
  int DoCacheQueryData();
  int DoCacheQueryDataComplete(int result);
  int DoCacheReadData();
  int DoCacheReadDataComplete(int result);
  int DoCacheWriteData(int num_bytes);
  int DoCacheWriteDataComplete(int result);

  // Sets request_ and fields derived from it.
  void SetRequest(const BoundNetLog& net_log, const HttpRequestInfo* request);

  // Returns true if the request should be handled exclusively by the network
  // layer (skipping the cache entirely).
  bool ShouldPassThrough();

  // Called to begin reading from the cache.  Returns network error code.
  int BeginCacheRead();

  // Called to begin validating the cache entry.  Returns network error code.
  int BeginCacheValidation();

  // Called to begin validating an entry that stores partial content.  Returns
  // a network error code.
  int BeginPartialCacheValidation();

  // Validates the entry headers against the requested range and continues with
  // the validation of the rest of the entry.  Returns a network error code.
  int ValidateEntryHeadersAndContinue();

  // Called to start requests which were given an "if-modified-since" or
  // "if-none-match" validation header by the caller (NOT when the request was
  // conditionalized internally in response to LOAD_VALIDATE_CACHE).
  // Returns a network error code.
  int BeginExternallyConditionalizedRequest();

  // Called to restart a network transaction after an error.  Returns network
  // error code.
  int RestartNetworkRequest();

  // Called to restart a network transaction with a client certificate.
  // Returns network error code.
  int RestartNetworkRequestWithCertificate(X509Certificate* client_cert);

  // Called to restart a network transaction with authentication credentials.
  // Returns network error code.
  int RestartNetworkRequestWithAuth(const AuthCredentials& credentials);

  // Called to determine if we need to validate the cache entry before using it.
  bool RequiresValidation();

  // Called to make the request conditional (to ask the server if the cached
  // copy is valid).  Returns true if able to make the request conditional.
  bool ConditionalizeRequest();

  // Makes sure that a 206 response is expected.  Returns true on success.
  // On success, handling_206_ will be set to true if we are processing a
  // partial entry.
  bool ValidatePartialResponse();

  // Handles a response validation error by bypassing the cache.
  void IgnoreRangeRequest();

  // Changes the response code of a range request to be 416 (Requested range not
  // satisfiable).
  void FailRangeRequest();

  // Setups the transaction for reading from the cache entry.
  int SetupEntryForRead();

  // Reads data from the network.
  int ReadFromNetwork(IOBuffer* data, int data_len);

  // Reads data from the cache entry.
  int ReadFromEntry(IOBuffer* data, int data_len);

  // Called to write data to the cache entry.  If the write fails, then the
  // cache entry is destroyed.  Future calls to this function will just do
  // nothing without side-effect.  Returns a network error code.
  int WriteToEntry(int index, int offset, IOBuffer* data, int data_len,
                   const CompletionCallback& callback);

  // Called to write response_ to the cache entry. |truncated| indicates if the
  // entry should be marked as incomplete.
  int WriteResponseInfoToEntry(bool truncated);

  // Called to append response data to the cache entry.  Returns a network error
  // code.
  int AppendResponseDataToEntry(IOBuffer* data, int data_len,
                                const CompletionCallback& callback);

  // Called when we are done writing to the cache entry.
  void DoneWritingToEntry(bool success);

  // Returns an error to signal the caller that the current read failed. The
  // current operation |result| is also logged. If |restart| is true, the
  // transaction should be restarted.
  int OnCacheReadError(int result, bool restart);

  // Deletes the current partial cache entry (sparse), and optionally removes
  // the control object (partial_).
  void DoomPartialEntry(bool delete_object);

  // Performs the needed work after receiving data from the network, when
  // working with range requests.
  int DoPartialNetworkReadCompleted(int result);

  // Performs the needed work after receiving data from the cache, when
  // working with range requests.
  int DoPartialCacheReadCompleted(int result);

  // Restarts this transaction after deleting the cached data. It is meant to
  // be used when the current request cannot be fulfilled due to conflicts
  // between the byte range request and the cached entry.
  int DoRestartPartialRequest();

  // Returns true if we should bother attempting to resume this request if it
  // is aborted while in progress. If |has_data| is true, the size of the stored
  // data is considered for the result.
  bool CanResume(bool has_data);

  // Called to signal completion of asynchronous IO.
  void OnIOComplete(int result);

  void ReportCacheActionStart();
  void ReportCacheActionFinish();
  void ReportNetworkActionStart();
  void ReportNetworkActionFinish();
  void UpdateTransactionPattern(TransactionPattern new_transaction_pattern);
  void RecordHistograms();

  // Resets cache_io_start_ to the current time, if |return_value| is
  // ERR_IO_PENDING.
  // Returns |return_value|.
  int ResetCacheIOStart(int return_value);

  void ScheduleDelayedLoop(base::TimeDelta delay, int result);
  void RunDelayedLoop(base::TimeTicks delay_start_time,
                      base::TimeDelta intended_delay, int result);

  // Resets |network_trans_|, which must be non-NULL.  Also updates
  // |old_network_trans_load_timing_|, which must be NULL when this is called.
  void ResetNetworkTransaction();

  State next_state_;
  const HttpRequestInfo* request_;
  RequestPriority priority_;
  BoundNetLog net_log_;
  scoped_ptr<HttpRequestInfo> custom_request_;
  HttpRequestHeaders request_headers_copy_;
  // If extra_headers specified a "if-modified-since" or "if-none-match",
  // |external_validation_| contains the value of those headers.
  ValidationHeaders external_validation_;
  base::WeakPtr<HttpCache> cache_;
  HttpCache::ActiveEntry* entry_;
  HttpCache::ActiveEntry* new_entry_;
  scoped_ptr<HttpTransaction> network_trans_;
  CompletionCallback callback_;  // Consumer's callback.
  HttpResponseInfo response_;
  HttpResponseInfo auth_response_;
  const HttpResponseInfo* new_response_;
  std::string cache_key_;
  Mode mode_;
  State target_state_;
  bool reading_;  // We are already reading.
  bool invalid_range_;  // We may bypass the cache for this request.
  bool truncated_;  // We don't have all the response data.
  bool is_sparse_;  // The data is stored in sparse byte ranges.
  bool range_requested_;  // The user requested a byte range.
  bool handling_206_;  // We must deal with this 206 response.
  bool cache_pending_;  // We are waiting for the HttpCache.
  bool done_reading_;
  bool vary_mismatch_;  // The request doesn't match the stored vary data.
  bool couldnt_conditionalize_request_;
  scoped_refptr<IOBuffer> read_buf_;
  int io_buf_len_;
  int read_offset_;
  int effective_load_flags_;
  int write_len_;
  scoped_ptr<PartialData> partial_;  // We are dealing with range requests.
  UploadProgress final_upload_progress_;
  base::WeakPtrFactory<Transaction> weak_factory_;
  CompletionCallback io_callback_;

  // Members used to track data for histograms.
  TransactionPattern transaction_pattern_;
  base::TimeTicks entry_lock_waiting_since_;
  base::TimeTicks first_cache_access_since_;
  base::TimeTicks send_request_since_;

  // For sensitivity analysis (field trials emulating longer cache IO times),
  // the time at which a cache IO action has started, or base::TimeTicks()
  // if no cache IO action is currently in progress.
  base::TimeTicks cache_io_start_;

  // For OpenEntry and CreateEntry, if sensitivity analysis would mandate
  // a delay on return, we must defer that delay until AddToEntry has been
  // called, to avoid a race condition on the address returned.
  base::TimeDelta deferred_cache_sensitivity_delay_;
  bool defer_cache_sensitivity_delay_;

  // For sensitivity analysis, the simulated increase in cache service times,
  // in percent.
  int sensitivity_analysis_percent_increase_;

  HttpTransactionDelegate* transaction_delegate_;

  // Load timing information for the last network request, if any.  Set in the
  // 304 and 206 response cases, as the network transaction may be destroyed
  // before the caller requests load timing information.
  scoped_ptr<LoadTimingInfo> old_network_trans_load_timing_;
};

}  // namespace net

#endif  // NET_HTTP_HTTP_CACHE_TRANSACTION_H_


text:
"use strict";

function setupClickHandlers() {
  var instagramRemoveIcons = document.querySelectorAll("#instagram .icon-remove");
  var twitterRemoveIcons = document.querySelectorAll("#twitter .icon-remove");
  var hashtagRemoveIcons = document.querySelectorAll("#hashtags .icon-remove");
  var twitterLoginLink = document.querySelector(".twitterLogin");

  twitterLoginLink.addEventListener("click", function () {
    var xhr = new XMLHttpRequest();
    xhr.open("get", window.location.origin + "/admin/twitter_callback");
    xhr.send();
  });

  for (var i = 0; i < instagramRemoveIcons.length; i++) {
    var handler = removeInstagramAccount.bind(document, i);
    instagramRemoveIcons[i].addEventListener("click", handler);
  }

  for (var i = 0; i < twitterRemoveIcons.length; i++) {
    var handler = removeTwitterAccount.bind(document, i);
    twitterRemoveIcons[i].addEventListener("click", handler);
  }

  for (var i = 0; i < hashtagRemoveIcons.length; i++) {
    var handler = removeHashtag.bind(document, i);
    hashtagRemoveIcons[i].addEventListener("click", removeHashtag);
  }

  var addHashtagIcon = document.querySelector("#hashtags .icon-add");
  addHashtagIcon.addEventListener("click", addHashtag);
}

function removeInstagramAccount(index) {
  console.log("removing account at index " + index);
  var xhr = new XMLHttpRequest();
  xhr.open("delete", window.location.origin + "/admin/remove_instagram_account?" + index);
  console.log(xhr);
  xhr.send();
}

function removeTwitterAccount(index) {
  console.log("removing twitter account at index: " + index);
}

function removeHashtag(event) {
  event.stopPropagation();
  //console.log(`removing hashtag at index: ${index}`);
  var hashtagsContainer = document.getElementById("hashtags");

  var target = event.target;
  while (target.tagName.toLowerCase() !== "p") {
    target = target.parentNode;
  }

  hashtagsContainer.removeChild(target);
}

function addHashtag(event) {
  event.stopPropagation();
  console.log("adding new hashtag");

  var hashtagsContainer = document.getElementById("hashtags");
  var addingRow = hashtagsContainer.lastElementChild;
  var clonedRow = addingRow.cloneNode(true);

  var inputs = clonedRow.getElementsByTagName("input");
  inputs[0].value = "";

  var svgTags = addingRow.getElementsByTagName("svg");
  var useTags = addingRow.getElementsByTagName("use");

  var svgRemove = svgTags[0]; //currently the add icon, will be the new remove icon
  var svgRemoveUse = useTags[0];

  svgTags = clonedRow.getElementsByTagName("svg");

  var svgAdd = svgTags[0]; //add icon in new row

  svgRemove.classList.remove("icon-add");
  svgRemove.classList.add("icon-remove");

  svgRemoveUse.setAttribute("xlink:href", "#icon-remove");

  svgRemove.removeEventListener("click", addHashtag);
  svgRemove.addEventListener("click", removeHashtag);
  svgAdd.addEventListener("click", addHashtag);
  hashtagsContainer.appendChild(clonedRow);
}

window.onload = setupClickHandlers;


text:
describe Fastlane do
  describe Fastlane::FastFile do
    describe "Snapshot Integration" do
      it "works with default setting" do
        result = Fastlane::FastFile.new.parse("lane :test do
          snapshot
        end").runner.execute(:test)
        expect(result).to eq(true)

        expect(Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::SNAPSHOT_SCREENSHOTS_PATH]).to eq(File.expand_path('..', Dir.pwd))
      end

      it "works with :noclean" do
        result = Fastlane::FastFile.new.parse("lane :test do
          snapshot(noclean: true)
        end").runner.execute(:test)
        expect(result).to eq(false)

        expect(Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::SNAPSHOT_SCREENSHOTS_PATH]).to eq(File.expand_path('..', Dir.pwd))
      end
    end
  end
end