text:
package com.intellij.aop.psi;

import com.intellij.lang.ASTNode;
import com.intellij.psi.*;
import javax.annotation.Nonnull;

import java.util.Collection;
import java.util.Arrays;

/**
 * @author peter
 */
public class PsiAtTargetExpression extends PsiTypedPointcutExpression implements PsiAtPointcutDesignator{

  public PsiAtTargetExpression(@Nonnull final ASTNode node) {
    super(node);
  }

  public String toString() {
    return "PsiAtTargetExpression";
  }

  @Nonnull
  public PointcutMatchDegree acceptsSubject(final PointcutContext context, final PsiMember member) {
    return PsiAtArgsExpression.canHaveAnnotation(member.getContainingClass(), getTypeReference(), context, PointcutMatchDegree.TRUE, PointcutMatchDegree.FALSE);
  }

  @Nonnull
  public Collection<AopPsiTypePattern> getPatterns() {
    return Arrays.asList(AopPsiTypePattern.TRUE);
  }
}


text:
<?php

namespace Drupal\Tests\Core\DependencyInjection\Fixture;

/**
 * Stub class which acts as a service to test the container.
 *
 * @see \Drupal\Tests\Core\DependencyInjection\ContainerBuilderTest
 * @see \Drupal\Tests\Core\DependencyInjection\Fixture\BazClass
 */
class BarClass {

  /**
   * Storage for a protected BazClass object.
   *
   * @var Drupal\Tests\Core\DependencyInjection\Fixture\BazClass
   */
  protected $baz;

  /**
   * Setter for our BazClass object.
   *
   * This method is called during the service initialization.
   *
   * @param \Drupal\Tests\Core\DependencyInjection\Fixture\BazClass $baz
   *   A BazClass object to store.
   */
  public function setBaz(BazClass $baz) {
    $this->baz = $baz;
  }

  /**
   * Getter for our BazClass object.
   *
   * @return \Drupal\Tests\Core\DependencyInjection\Fixture\BazClass
   *   The stored BazClass object.
   */
  public function getBaz() {
    return $this->baz;
  }

}

redpajama_set_name: RedPajamaGithub


text:
PRAGMA_DISABLE_DEPRECATION_WARNINGS

#include "CoreMinimal.h"
#include "ManageEventSender.h"
#include "Generate/Manage/ManageOnlineSession.h"
#include "Runtime/Engine/Classes/GameFramework/OnlineSession.h"

// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\OnlineSession.h:18

extern "C"
{

	DOTNET_EXPORT INT_PTR E_NewObject_UOnlineSession(UObject* Parent, char* Name)
	{
		return (INT_PTR)NewObject<UOnlineSession>(Parent, FName(UTF8_TO_TCHAR(Name)));
	}

	DOTNET_EXPORT auto E_UOnlineSession_ClearOnlineDelegates(UOnlineSession* Self)
	{
		Self->ClearOnlineDelegates();
	}

	DOTNET_EXPORT auto E_UOnlineSession_EndOnlineSession(UOnlineSession* Self, char* SessionName)
	{
		auto _p0 = ConvertFromManage_FName(SessionName);
		Self->EndOnlineSession(_p0);
	}

	DOTNET_EXPORT auto E_UOnlineSession_RegisterOnlineDelegates(UOnlineSession* Self)
	{
		Self->RegisterOnlineDelegates();
	}

	DOTNET_EXPORT auto E_UOnlineSession_StartOnlineSession(UOnlineSession* Self, char* SessionName)
	{
		auto _p0 = ConvertFromManage_FName(SessionName);
		Self->StartOnlineSession(_p0);
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_ClearOnlineDelegates(UOnlineSession* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__ClearOnlineDelegates();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_RegisterOnlineDelegates(UOnlineSession* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__RegisterOnlineDelegates();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_BeginDestroy(UObject* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__BeginDestroy();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_FinishDestroy(UObject* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__FinishDestroy();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_MarkAsEditorOnlySubobject(UObject* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__MarkAsEditorOnlySubobject();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_PostCDOContruct(UObject* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__PostCDOContruct();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_PostEditImport(UObject* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__PostEditImport();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_PostInitProperties(UObject* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__PostInitProperties();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_PostLoad(UObject* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__PostLoad();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_PostNetReceive(UObject* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__PostNetReceive();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_PostRepNotifies(UObject* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__PostRepNotifies();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_PostSaveRoot(UObject* Self, bool bCleanupIsRequired)
	{
		auto _p0 = bCleanupIsRequired;
		((UManageOnlineSession*)Self)->_Supper__PostSaveRoot(_p0);
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_PreDestroyFromReplication(UObject* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__PreDestroyFromReplication();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_PreNetReceive(UObject* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__PreNetReceive();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_ShutdownAfterError(UObject* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__ShutdownAfterError();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_CreateCluster(UObjectBaseUtility* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__CreateCluster();
	}

	DOTNET_EXPORT auto E__Supper__UOnlineSession_OnClusterMarkedAsPendingKill(UObjectBaseUtility* Self)
	{
		((UManageOnlineSession*)Self)->_Supper__OnClusterMarkedAsPendingKill();
	}

}
PRAGMA_ENABLE_DEPRECATION_WARNINGS


text:
package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("unchecked")
public class Southwest extends Go
{
	public Southwest(){}

	private String[] access={"SOUTHWEST","SW"};
	public String[] getAccessWords(){return access;}
	public boolean execute(MOB mob, Vector commands, int metaFlags)
		throws java.io.IOException
	{
		standIfNecessary(mob,metaFlags);
		if((CMLib.flags().isSitting(mob))||(CMLib.flags().isSleeping(mob)))
		{
			mob.tell("You need to stand up first.");
			return false;
		}
		Go goClass = null;
		if(CMath.bset(mob.getBitmap(),MOB.ATT_AUTORUN)) {
			goClass=(Go)CMClass.getCommand("Run");
		}
		if(goClass == null) goClass = this;
		goClass.move(mob,Directions.SOUTHWEST,false,false,false);
		return false;
	}
	public boolean canBeOrdered(){return true;}
	public boolean securityCheck(MOB mob){return Directions.NUM_DIRECTIONS()>6;}
}


text:
#include "tdb_private.h"

enum TDB_ERROR tdb_error(struct tdb_context *tdb)
{
	return tdb->ecode;
}

static struct tdb_errname {
	enum TDB_ERROR ecode; const char *estring;
} emap[] = { {TDB_SUCCESS, "Success"},
	     {TDB_ERR_CORRUPT, "Corrupt database"},
	     {TDB_ERR_IO, "IO Error"},
	     {TDB_ERR_LOCK, "Locking error"},
	     {TDB_ERR_OOM, "Out of memory"},
	     {TDB_ERR_EXISTS, "Record exists"},
	     {TDB_ERR_NOLOCK, "Lock exists on other keys"},
	     {TDB_ERR_EINVAL, "Invalid parameter"},
	     {TDB_ERR_NOEXIST, "Record does not exist"},
	     {TDB_ERR_RDONLY, "write not permitted"} };

/* Error string for the last tdb error */
const char *tdb_errorstr(struct tdb_context *tdb)
{
	uint32_t i;
	for (i = 0; i < sizeof(emap) / sizeof(struct tdb_errname); i++)
		if (tdb->ecode == emap[i].ecode)
			return emap[i].estring;
	return "Invalid error code";
}


text:
sudo apt-get update

## Install AWS CLI
sudo apt-get -y install awscli

## Install Amazon Codedeploy agent
sudo apt-get update
sudo apt-get -y install python-pip
sudo apt-get -y install ruby
cd /home/ubuntu
wget https://aws-codedeploy-us-east-2.s3.amazonaws.com/latest/install
chmod +x ./install
sudo ./install auto
sudo service codedeploy-agent start

## Install Docker
sudo apt-get -y install apt-transport-https ca-certificates
curl -fsSL https://yum.dockerproject.org/gpg | sudo apt-key add -
sudo apt-get -y install software-properties-common
sudo add-apt-repository        "deb https://apt.dockerproject.org/repo/ ubuntu-$(lsb_release -cs) main"
sudo apt-get update
sudo apt-get -y install docker-engine

## Install HAProxy
sudo apt-get install -y haproxy
sudo chmod 777 /etc/default/haproxy
echo "ENABLED=1" > /etc/default/haproxy
cd /etc/haproxy
sudo wget -N https://raw.githubusercontent.com/airavata-courses/spring17-devops/feature-loadbalancer/haproxy.cfg
sudo service haproxy stop
sudo service haproxy start

## Start consul server
sudo touch /var/log/sga-consul.log
sudo chmod 777 /var/log/sga-consul.log
sudo docker run -d -e SERVICE_IGNORE -p 8400:8400 -p 8500:8500 -p 8300:8300 -p 8301:8301 -p 8301:8301/udp -p 8302:8302 -p 8302:8302/udp -p 8600:53/udp -h consul --name consul progrium/consul -server -advertise `wget -qO- http://instance-data/latest/meta-data/public-ipv4` -bootstrap >> /var/log/sga-consul.log 2>&1

## Start Registrator
sudo docker run -d --name=registrator --net=host --volume=/var/run/docker.sock:/tmp/docker.sock gliderlabs/registrator:latest consul://localhost:8500


text:
using UnityEngine;
using System.Collections;

public class Camera_Zoom : MonoBehaviour
{

	public Camera _camera;
	public GameObject _player;
	public float speed;
	public float MaxSize = 7.5f;
	public float MinSize = 5.5f;
	float CameraSize = 6f;

	void Start(){

		_player = GameObject.Find("03_Player");
	}

	void Update ()
	{

		if (_player != null)
			CameraSize = 5f + _player.transform.position.y;

		if (CameraSize >= MaxSize) {
			CameraSize = MaxSize;
		}

		if (CameraSize <= MinSize) {
			CameraSize = MinSize;
		}

		//단순히 카메라값을 바꾸는경우
		//_camera.orthographicSize = 4.5f+_player.transform.position.y;

		//카메라값을 부드럽게 바꾸는경우

		_camera.orthographicSize = Mathf.Lerp (_camera.orthographicSize, CameraSize, Time.deltaTime / speed);

	}
}


text:
package deferstats

import (
	"database/sql"
	"sync"
	"time"
)

// FIXME
var (
	// Querylist is the list of db_queries that will be sent to
	// deferpanic
	Querylist deferDBList

	// selectThreshold is the size in milliseconds that if a query goes
	// over it will be added to the Querylist
	selectThreshold int
)

// DB wraps sql.DB to provide latency timing against various db
// operations
type DB struct {
	Other *sql.DB
}

// Tx wraps sql.Tx to provide latency timing against various db
// operations
type Tx struct {
	Db    *DB
	Other *sql.Tx
}

// Stmt wraps sql.Stmt to provide latency timing against various db
// operations
type Stmt struct {
	Db       *DB
	QueryStr string
	Other    *sql.Stmt
}

// DeferDB holds the query and latency for each sql query whose
// threshold was overran
type DeferDB struct {
	Query string `json:"Query"`
	Time  int    `json:"Time"`
}

// deferDBList is used to keep a list of DeferDB objects
// and interact with them in a thread-safe manner
type deferDBList struct {
	lock sync.RWMutex
	list []DeferDB
}

// Add adds a DeferDB object to the list
func (d *deferDBList) Add(item DeferDB) {
	d.lock.Lock()
	d.list = append(d.list, item)
	d.lock.Unlock()
}

// List returns a copy of the list
func (d *deferDBList) List() []DeferDB {
	d.lock.RLock()
	list := make([]DeferDB, len(d.list))
	for i, v := range d.list {
		list[i] = v
	}
	d.lock.RUnlock()
	return list
}

// Reset removes all entries from the list
func (d *deferDBList) Reset() {
	d.lock.Lock()
	d.list = []DeferDB{}
	d.lock.Unlock()
}

// NewDB is a constructor for wrapped database
func NewDB(db *sql.DB) *DB {
	selectThreshold = 500

	return &DB{
		db,
	}
}

// NewTx is a constructor for wrapped transaction
func NewTx(db *DB, tx *sql.Tx) *Tx {
	return &Tx{
		Db:    db,
		Other: tx,
	}
}

// NewStmt is a constructor for wrapped statement
func NewStmt(db *DB, querystr string, stmt *sql.Stmt) *Stmt {
	return &Stmt{
		Db:       db,
		QueryStr: querystr,
		Other:    stmt,
	}
}

// logQuery takes a startTime and a query string and if it is over the
// selectThreshold than it appends to a long running query list
func (db *DB) logQuery(startTime time.Time, query string) {
	endTime := time.Now()
	t := int(((endTime.Sub(startTime)).Nanoseconds() / 1000000))

	ddb := DeferDB{
		Query: query,
		Time:  t,
	}

	if t >= selectThreshold {
		Querylist.Add(ddb)
	}
}

// Query is a method for returning query results
func (db *DB) Query(query string, args ...interface{}) (*sql.Rows, error) {
	startTime := time.Now()
	defer db.logQuery(startTime, query)
	return db.Other.Query(query, args...)
}

// QueryRow is a method for returning query row
func (db *DB) QueryRow(query string, args ...interface{}) *sql.Row {
	startTime := time.Now()
	defer db.logQuery(startTime, query)
	return db.Other.QueryRow(query, args...)
}

// Exec is method for executing query
func (db *DB) Exec(query string, args ...interface{}) (sql.Result, error) {
	startTime := time.Now()
	defer db.logQuery(startTime, query)
	return db.Other.Exec(query, args...)
}

// Prepare is a method for preparing query
func (db *DB) Prepare(query string) (*Stmt, error) {
	startTime := time.Now()
	defer db.logQuery(startTime, query)
	stmt, err := db.Other.Prepare(query)
	return NewStmt(db, query, stmt), err
}

// Begin is a method for beginning transaction
func (db *DB) Begin() (*Tx, error) {
	startTime := time.Now()
	defer db.logQuery(startTime, "begin")
	tx, err := db.Other.Begin()
	return NewTx(db, tx), err
}

// Commit is a method for committing transaction
func (tx *Tx) Commit() error {
	startTime := time.Now()
	defer tx.Db.logQuery(startTime, "commit")
	return tx.Other.Commit()
}

// Rollback is a method for rollbacking transaction
func (tx *Tx) Rollback() error {
	startTime := time.Now()
	defer tx.Db.logQuery(startTime, "rollback")
	return tx.Other.Rollback()
}

// Query is a method for returning query results
func (tx *Tx) Query(query string, args ...interface{}) (*sql.Rows, error) {
	startTime := time.Now()
	defer tx.Db.logQuery(startTime, query)
	return tx.Other.Query(query, args...)
}

// QueryRow is a method for returning query row
func (tx *Tx) QueryRow(query string, args ...interface{}) *sql.Row {
	startTime := time.Now()
	defer tx.Db.logQuery(startTime, query)
	return tx.Other.QueryRow(query, args...)
}

// Exec is method for executing query
func (tx *Tx) Exec(query string, args ...interface{}) (sql.Result, error) {
	startTime := time.Now()
	defer tx.Db.logQuery(startTime, query)
	return tx.Other.Exec(query, args...)
}

// Prepare is a method for preparing query
func (tx *Tx) Prepare(query string) (*Stmt, error) {
	startTime := time.Now()
	defer tx.Db.logQuery(startTime, query)
	stmt, err := tx.Other.Prepare(query)
	return NewStmt(tx.Db, query, stmt), err
}

// Query is a method for returning query results
func (stmt *Stmt) Query(args ...interface{}) (*sql.Rows, error) {
	startTime := time.Now()
	defer stmt.Db.logQuery(startTime, stmt.QueryStr)
	return stmt.Other.Query(args...)
}

// QueryRow is a method for returning query row
func (stmt *Stmt) QueryRow(args ...interface{}) *sql.Row {
	startTime := time.Now()
	defer stmt.Db.logQuery(startTime, stmt.QueryStr)
	return stmt.Other.QueryRow(args...)
}

// Exec is method for executing query
func (stmt *Stmt) Exec(args ...interface{}) (sql.Result, error) {
	startTime := time.Now()
	defer stmt.Db.logQuery(startTime, stmt.QueryStr)
	return stmt.Other.Exec(args...)
}


text:
/**
 *
 */
package org.minnal.autopojo.resolver;

import java.lang.reflect.Array;
import java.lang.reflect.Type;

/**
 * @author ganeshs
 *
 */
public class ArrayResolver extends AbstractAttributeResolver {

	public ArrayResolver() {
	}

	public Object[] resolve(Class<?> clazz, int maxDepth, Type... genericTypes) {
		Class<?> elementType = ((Class<?>) clazz).getComponentType();
		Object array = Array.newInstance(elementType, configuration.getNoOfElementsInCollection());
		for (int i = 0; i < configuration.getNoOfElementsInCollection(); i++) {
            Array.set(array, i, strategy.resolve(elementType, maxDepth));
		}
		return (Object[]) array;
	}

}


text:
Mgnt Utilities
This utility package provides some convenience Utilities That provide some manipulations with several data types.
It introduces a new type "Version" as well as "VersionRange" and provides tools for version comparison, conversion from
and to String as well as work with Version ranges.

The Javadoc API could be found here:
MgntUtils javadoc API

Probably the most interesting and useful feature is stacktrace extractor that allows to extract full or shortened
version of stacktrace. In particular it is very useful in J2EE environment. Exceptions on the server side usually
come with HUGE tail of application server related packages. That makes logs very verbose and hard to read and
search. TextUtils provides various getStacktrace methods that may drastically reduce such stacktraces in a very smart
way so all the important information is preserved. It sifts through "caused by" and "suppressed" parts of the stacktrace
as well. Also the same utility (starting from version 1.5.0.3) allows to filter and shorten stacktrace as a string the same way
as the stacktrace extracted from exception. So, essentially stacktraces could be filtered "on the fly" at run time or later on from
any text source such as log.

Another important feature (since 1.6.0.0) is JSON parser (JsonUtils class) that provides some simple methods to serialize
any object into JSON String and parse (deserialize) JSON string back into the instance of the class. This class is a simplifying wrapper
over basic functionality of Jason-Jackson library. It provides simplicity but doesn't handle well deserialization of List/Set/Map of Objects.
If that functionality is needed than just use the original Json-Jackson library (or any other JSON library)

Other features include parsing String into most of the implementations of Number interface without having
to catch NullPointerException of NumberFormatException. The methods take String value to parse, default value in case of
failure and messages (optional) that will be printed into log if some error occurred.

Another useful feature is parsing String to time interval. It parses Strings with numerical value and optional time unit
suffix (for example  string "38s" will be parsed as 38 seconds, "24m" - 24 minutes "4h" - 4 hours, "3d" - 3 days and "45"
as 45 milliseconds.) This method may be very useful for parsing time interval properties such as timeouts or waiting
periods from configuration files.

 Also there is a feature that converts String to preserve indentation formatting for html without use of escape
 characters. It converts a String in such a way that its spaces are not modified by HTML renderer i.e. it replaces
 regular space characters with non-breaking spaces known as '&nbsp;' but they look in your source as regular space
 '  ' and not as '&nbsp;' It also replaces new line character with '<br>'.

Another feature is some small infrastructure that simplifies and automates working with Factories that provide concrete
implementations of an Interface. The package contains just 2 classes: BaseEntityFactory and BaseEntity. In short what
this infrastructure does is that if you create a factory that extends BaseEntityFactory and some Interface with all its
concrete implementations extending BaseEntity then each your concrete implementation class instances will be
automatically inserted into your factory. You won't have to worry about how and when to populate your factory.
The infrastructure will do it for you when the constructor of your concrete implementation class is invoked. So all you
will have to do is to create any number of concrete implementation classes and make sure that for each one constructor
is invoked. After that you can use your factory to get any of your concrete implementation classes anywhere in your code.

An infrastructure that can run user implemented Task classes in a separate thread at configured
time interval. The interval could be parsed from String in human readable format such as "9h" for 9 hours. This is based
on use of the parsing String to time interval feature mentioned above

Class HttpClient provides a base class for implementations that can open HTTP connections to spesific URLs, but also can
be used on its own for sending HTTP requests.

Also class
StringUnicodeEncoderDecoder converts String into sequence of unicodes and vise-versa.

Finally WebUtils class provides
a method for chunked reading of HttpRequest content. This could be useful when receiving large files from client on the
server side and the reading speed of the server is faster then writing speed of the client. The utility allows for
auto throttle to adjust to the client.

This library is available on Maven Central. Here are the artifacts:

        <dependency>

              <groupId>com.github.michaelgantman</groupId>

              <artifactId>MgntUtils</artifactId>

              <version>1.6.0.5</version>

        </dependency>

        <dependency>

              <groupId>com.github.michaelgantman</groupId>

              <artifactId>MgntUtils</artifactId>

              <version>1.6.0.5</version>

              <classifier>javadoc</classifier>

        </dependency>

        <dependency>

              <groupId>com.github.michaelgantman</groupId>

              <artifactId>MgntUtils</artifactId>

              <version>1.6.0.5</version>

              <classifier>sources</classifier>

        </dependency>

If have any feedback feel free to drop me a note at michael_gantman@yahoo.com


text:
package com.google.cloud.pubsub.client.demos.appengine.servlet;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.cloud.pubsub.client.demos.appengine.Constants;

import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Fetches messages for display.
 */
public class FetchMessagesServlet extends HttpServlet {

    /**
     * Number of messages for a single fetch call.
     */
    private static final int MAX_COUNT = 20;

    @Override
    @SuppressWarnings("unchecked")
    public final void doGet(final HttpServletRequest req,
                            final HttpServletResponse resp)
            throws IOException {
        // First retrieve messages from the memcache
        MemcacheService memcacheService = MemcacheServiceFactory
                .getMemcacheService();
        List<String> messages =
                (List<String>) memcacheService.get(Constants.MESSAGE_CACHE_KEY);
        if (messages == null) {
            // If no messages in the memcache, look for the datastore
            DatastoreService datastore =
                    DatastoreServiceFactory.getDatastoreService();
            PreparedQuery query = datastore.prepare(
                    new Query("PubsubMessage").addSort("receipt-time",
                            Query.SortDirection.DESCENDING));
            messages = new ArrayList<>();
            for (Entity entity : query.asIterable(
                    FetchOptions.Builder.withLimit(MAX_COUNT))) {
                String message = (String) entity.getProperty("message");
                messages.add(message);
            }
            // Store them to the memcache for future use.
            memcacheService.put(Constants.MESSAGE_CACHE_KEY, messages);
        }
        ObjectMapper mapper = new ObjectMapper();
        resp.setContentType("application/json; charset=UTF-8");
        mapper.writeValue(resp.getWriter(), messages);
        resp.getWriter().close();
    }
}


text:
<?php

class MercadoPago_Core_Helper_StatusMessage
    extends MercadoPago_Core_Helper_Message_Abstract
{
    protected $messagesMap = [
            "approved"   => [
                'title'   => 'Done, your payment was accredited!',
                'message' => ''
            ],

            "in_process" => [
                'title'   => 'We are processing the payment.',
                'message' => 'In less than 2 business days we will tell you by e-mail if it is accredited or if we need more information.'
            ],

            "authorized" => [
                'title'   => 'We are processing the payment.',
                'message' => 'In less than an hour we will send you by e-mail the result.'
            ],

            "pending"    => [
                'title'   => 'We are processing the payment.',
                'message' => 'In less than an hour we will send you by e-mail the result.'
            ],

            "rejected"   => [
                'title'   => 'We could not process your payment.',
                'message' => ''
            ],

            "cancelled"  => [
                'title'   => 'Payments were canceled.',
                'message' => 'Contact for more information.'
            ],

            "other"      => [
                'title'   => 'Thank you for your purchase!',
                'message' => ''
            ]
    ];

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


text:
package org.aludratest.scheduler.impl;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.aludratest.PreconditionFailedException;
import org.aludratest.config.AludraTestConfig;
import org.aludratest.invoker.TestInvoker;
import org.aludratest.scheduler.AnnotationBasedExecution;
import org.aludratest.scheduler.RunnerTree;
import org.aludratest.scheduler.RunnerTreeBuilder;
import org.aludratest.scheduler.TestClassFilter;
import org.aludratest.scheduler.node.ExecutionMode;
import org.aludratest.scheduler.node.RunnerGroup;
import org.aludratest.scheduler.node.RunnerLeaf;
import org.aludratest.scheduler.node.RunnerNode;
import org.aludratest.scheduler.sort.Alphabetic;
import org.aludratest.scheduler.sort.RunnerTreeSortUtil;
import org.aludratest.scheduler.util.CommonRunnerLeafAttributes;
import org.aludratest.testcase.AludraTestCase;
import org.aludratest.testcase.Parallel;
import org.aludratest.testcase.Sequential;
import org.aludratest.testcase.SequentialGroup;
import org.aludratest.testcase.Suite;
import org.aludratest.testcase.Test;
import org.aludratest.testcase.data.TestCaseData;
import org.aludratest.testcase.data.TestDataProvider;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.databene.commons.BeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Default implementation of the RunnerTreeBuilder component interface.
 *
 * @author falbrech */
@Component(role = RunnerTreeBuilder.class, instantiationStrategy = "per-lookup")
public class RunnerTreeBuilderImpl implements RunnerTreeBuilder {

    private static final Logger LOGGER = LoggerFactory.getLogger(RunnerTreeBuilder.class);

    private final AtomicLong errorCount;

    private final AtomicInteger nextLeafId;

    /** Used to trace added files and detect recursions & multi-uses of classes */
    private Set<Class<?>> addedClasses;

    /** Map Class -> Assertion Error for classes where an assertion failed */
    private Map<Class<?>, String> assertionErrorClasses;

    @Requirement
    private TestDataProvider testDataProvider;

    @Requirement
    private AludraTestConfig aludraConfig;

    /**
     * Default constructor
     */
    public RunnerTreeBuilderImpl() {
        this.errorCount = new AtomicLong();
        this.nextLeafId = new AtomicInteger();
        this.addedClasses = new HashSet<Class<?>>();
        this.assertionErrorClasses = new HashMap<Class<?>, String>();
    }

    @Override
    public RunnerTree buildRunnerTree(Class<?> suiteOrTestClass) {
        RunnerTree tree = new RunnerTree();
        parseTestOrSuiteClass(suiteOrTestClass, null, tree);
        if (!assertionErrorClasses.isEmpty()) {
            // concatenate all exceptions
            Iterator<Map.Entry<Class<?>, String>> iter = assertionErrorClasses.entrySet().iterator();
            throw concatAssertionExceptions(iter, null);
        }

        return tree;
    }

    @Override
    public RunnerTree buildRunnerTree(AnnotationBasedExecution executionConfig) {
        // find all class files matching the filter
        List<Class<? extends AludraTestCase>> testClasses;

        File searchRoot = executionConfig.getJarOrClassRoot();
        if (searchRoot.isDirectory()) {
            testClasses = findMatchingClassesInFolder(searchRoot, "", executionConfig.getFilter(),
                    executionConfig.getClassLoader());
        }
        else if (searchRoot.isFile()) {
            try {
                testClasses = findMatchingClassesInJar(searchRoot, executionConfig.getFilter(), executionConfig.getClassLoader());
            }
            catch (IOException e) {
                throw new PreconditionFailedException("Could not search JAR file " + searchRoot.getAbsolutePath()
                + " for test classes", e);
            }
        }
        else {
            throw new PreconditionFailedException("Unknown file type for class root " + searchRoot.getAbsolutePath());
        }

        RunnerTree tree = new RunnerTree();
        tree.createRoot("All Tests", true);

        CategoryBuilder categoryBuilder;
        if (executionConfig.getGroupingAttributes().isEmpty()) {
            String commonPackageRoot = getCommonPackageRoot(testClasses);
            categoryBuilder = new CategoryBuilder(commonPackageRoot);
        }
        else {
            categoryBuilder = new CategoryBuilder(executionConfig.getGroupingAttributes());
        }

        for (Class<? extends AludraTestCase> clz : testClasses) {
            parseTestClass(clz, categoryBuilder.getParentRunnerGroup(tree, clz), tree);
        }

        // sort tree according to sort configuration
        String sortClassName = aludraConfig.getRunnerTreeSorterName();
        if (sortClassName == null) {
            sortClassName = Alphabetic.class.getName();
        }

        if (!sortClassName.contains(".")) {
            sortClassName = Alphabetic.class.getPackage().getName() + "." + sortClassName; // NOSONAR
        }

        try {
            Class<?> clz = Class.forName(sortClassName);
            @SuppressWarnings("unchecked")
            Comparator<RunnerNode> comparator = (Comparator<RunnerNode>) clz.newInstance();
            RunnerTreeSortUtil.sortTree(tree, comparator);
        }
        catch (Exception e) {
            LOGGER.error("Could not sort runner tree because comparator could not be created.", e);
        }

        return tree;
    }

    @SuppressWarnings("unchecked")
    private List<Class<? extends AludraTestCase>> findMatchingClassesInFolder(File folder, String packagePrefix,
            TestClassFilter filter, ClassLoader classLoader) {
        List<Class<? extends AludraTestCase>> result = new ArrayList<Class<? extends AludraTestCase>>();
        File[] children = folder.listFiles();
        for (File file : children) {
            if (file.isDirectory()) {
                result.addAll(findMatchingClassesInFolder(file,
                        packagePrefix + ("".equals(packagePrefix) ? "" : ".") + file.getName(), filter, classLoader));
            }
            else if (file.isFile() && (file.getName().endsWith(".class") || file.getName().endsWith(".java"))) {
                String className = packagePrefix + "." + file.getName().substring(0, file.getName().lastIndexOf('.'));
                try {
                    Class<?> clz;
                    if (classLoader != null) {
                        clz = classLoader.loadClass(className);
                    }
                    else {
                        clz = Class.forName(className);
                    }
                    if (AludraTestCase.class.isAssignableFrom(clz) && !result.contains(clz)
                            && filter.matches((Class<? extends AludraTestCase>) clz)) {
                        result.add((Class<? extends AludraTestCase>) clz);
                    }
                }
                catch (Throwable t) {
                    // ignore that class
                }
            }
        }
        return result;
    }

    private List<Class<? extends AludraTestCase>> findMatchingClassesInJar(File jarFile, TestClassFilter filter,
            ClassLoader classLoader)
                    throws IOException {
        Pattern classPattern = Pattern.compile("(.+/|)([^/]+)\\.class");

        List<Class<? extends AludraTestCase>> result = new ArrayList<Class<? extends AludraTestCase>>();

        JarFile jf = new JarFile(jarFile);
        try {
            Enumeration<JarEntry> entries = jf.entries();
            while (entries.hasMoreElements()) {
                JarEntry je = entries.nextElement();
                Matcher m = classPattern.matcher(je.getName());
                if (m.matches()) {
                    String pkgName = m.group(1).replace('/', '.');
                    if (pkgName.endsWith(".")) {
                        pkgName = pkgName.substring(0, pkgName.length() - 1);
                    }
                    String className = m.group(2);
                    if (!pkgName.isEmpty()) {
                        className = pkgName + "." + className; // NOSONAR
                    }
                    checkJarClass(className, filter, classLoader, result);
                }
            }
        }
        finally {
            try {
                jf.close();
            }
            catch (IOException e) {
                // ignore
            }
        }

        return result;
    }

    @SuppressWarnings("unchecked")
    private void checkJarClass(String className, TestClassFilter filter, ClassLoader classLoader,
            List<Class<? extends AludraTestCase>> result) {
        try {
            Class<?> clz;
            if (classLoader != null) {
                clz = classLoader.loadClass(className);
            }
            else {
                clz = Class.forName(className);
            }
            if (AludraTestCase.class.isAssignableFrom(clz) && filter.matches((Class<? extends AludraTestCase>) clz)) {
                result.add((Class<? extends AludraTestCase>) clz);
            }
        }
        catch (Throwable t) {
            // ignore that class
        }
    }

    private String getCommonPackageRoot(List<Class<? extends AludraTestCase>> testClasses) {
        if (testClasses.isEmpty()) {
            return "";
        }
        String commonPrefix = testClasses.get(0).getName();
        for (Class<?> clz : testClasses) {
            String cn = clz.getName();
            commonPrefix = getCommonPrefix(commonPrefix, cn);
            if ("".equals(commonPrefix)) {
                // totally unequal
                return commonPrefix;
            }
        }

        if (commonPrefix.contains(".")) {
            commonPrefix = commonPrefix.substring(0, commonPrefix.lastIndexOf('.'));
        }
        else {
            return "";
        }

        return commonPrefix;
    }

    private String getCommonPrefix(String s1, String s2) {
        int i;
        for (i = 0; i < s1.length() && i < s2.length() && s1.charAt(i) == s2.charAt(i); i++) {
            // empty loop that sets i to the first index of non-equal characters
        }
        return s1.substring(0, i);
    }

    private PreconditionFailedException concatAssertionExceptions(Iterator<Map.Entry<Class<?>, String>> iterator,
            PreconditionFailedException cause) {
        if (!iterator.hasNext()) {
            if (cause != null)
                return cause;
            else
                throw new IllegalArgumentException("Method called with empty iterator and no cause exception");
        }
        Map.Entry<Class<?>, String> entry = iterator.next();
        String msg = entry.getValue() + ": " + entry.getKey().getName();
        PreconditionFailedException ex = (cause == null ? new PreconditionFailedException(msg) : new PreconditionFailedException(
                msg, cause));
        return concatAssertionExceptions(iterator, ex);
    }

    /** Parses an AludraTest test class or suite. */
    private void parseTestOrSuiteClass(Class<?> testClass, RunnerGroup parentGroup, RunnerTree tree) {
        // check test class type
        if (isTestSuiteClass(testClass)) {
            parseSuiteClass(testClass, parentGroup, tree);
        }
        else {
            if (assertTestClass(testClass)) {
                parseTestClass(testClass, parentGroup, tree);
            }
        }
    }

    private boolean isTestSuiteClass(Class<?> testClass) {
        return (testClass.getAnnotation(Suite.class) != null);
    }

    private boolean assertTestClass(Class<?> testClass) {
        if ((testClass.getModifiers() & Modifier.ABSTRACT) == Modifier.ABSTRACT) {
            assertionErrorClasses.put(testClass, "Abstract class not suitable as test class");
            return false;
        }
        else if (!AludraTestCase.class.isAssignableFrom(testClass)) {
            assertionErrorClasses.put(testClass, "Test class does not inherit from " + AludraTestCase.class.getName());
            return false;
        }
        else if (testMethodCount(testClass) == 0) {
            assertionErrorClasses.put(testClass, "No @Test methods found in class");
            return false;
        }

        return true;
    }

    private int testMethodCount(Class<?> testClass) {
        int count = 0;
        for (Method method : testClass.getMethods()) {
            if (method.getAnnotation(Test.class) != null) {
                count++;
            }
        }
        return count;
    }

    private void checkAddTestClass(Class<?> clazz) {
        if (addedClasses.contains(clazz)) {
            throw new PreconditionFailedException("The class " + clazz
                    + " is used in more than one test suite, or part of a test suite recursion.");
        }
        addedClasses.add(clazz);
    }

    /** Parses an AludraTest test suite class. */
    private void parseSuiteClass(Class<?> testClass, RunnerGroup parentGroup, RunnerTree tree) {
        LOGGER.debug("Parsing suite class: {}", testClass.getName());
        checkAddTestClass(testClass);
        addedClasses.add(testClass);
        Suite suite = testClass.getAnnotation(Suite.class);
        if (suite == null) {
            throw new IllegalArgumentException("Class has no @Suite annotation");
        }
        RunnerGroup group = createRunnerGroupForTestClass(testClass, parentGroup, tree);
        for (Class<?> component : suite.value()) {
            parseTestOrSuiteClass(component, group, tree);
        }
    }

    /** Parses an AludraTest test class. */
    private void parseTestClass(Class<?> testClass, RunnerGroup parentGroup, RunnerTree tree) {
        LOGGER.debug("Parsing test class: {}", testClass.getName());
        checkAddTestClass(testClass);
        RunnerGroup classGroup = createRunnerGroupForTestClass(testClass, parentGroup, tree);
        for (Method method : testClass.getMethods()) {
            parseMethod(method, testClass, classGroup, tree);
        }
    }

    /** Creates a {@link RunnerGroup} for an AludraTest test class */
    private RunnerGroup createRunnerGroupForTestClass(Class<?> testClass, RunnerGroup parentGroup, RunnerTree tree) {
        ExecutionMode mode;
        if (testClass.getAnnotation(Parallel.class) != null) {
            mode = ExecutionMode.PARALLEL;
        }
        else if (testClass.getAnnotation(Sequential.class) != null) {
            mode = ExecutionMode.SEQUENTIAL;
        }
        else {
            mode = ExecutionMode.INHERITED;
        }
        RunnerGroup group = tree.createGroup(testClass.getName(), mode, parentGroup);

        addSequentialGroupAttributes(group, testClass);

        return group;
    }

    /** Parses a method */
    private void parseMethod(Method method, Class<?> testClass, RunnerGroup classGroup, RunnerTree tree) {
        if (method.getAnnotation(Test.class) != null) {
            LOGGER.debug("Parsing test class method: {}", method);
            ExecutionMode mode;
            if (method.getAnnotation(Parallel.class) != null) {
                mode = ExecutionMode.PARALLEL;
            }
            else if (method.getAnnotation(Sequential.class) != null) {
                mode = ExecutionMode.SEQUENTIAL;
            }
            else {
                mode = ExecutionMode.INHERITED;
            }
            String methodTestSuiteName = createMethodTestSuiteName(testClass, method);
            RunnerGroup methodGroup = tree.createGroup(methodTestSuiteName, mode, classGroup);
            addSequentialGroupAttributes(methodGroup, method);

            try {
                // iterate through method invocations
                List<TestCaseData> invocationParams = testDataProvider.getTestDataSets(method);
                for (TestCaseData data : invocationParams) {
                    if (data.getException() == null) {
                        createTestRunnerForMethodInvocation(method, data, methodGroup, tree);
                    }
                    else {
                        createTestRunnerForErrorReporting(method, data.getException(), methodGroup, tree,
                                data.getExternalTestId());
                    }
                }
            }
            catch (Exception e) {
                createTestRunnerForErrorReporting(method, e, methodGroup, tree, null);
            }
        }
    }

    /** Creates a test runner for a single method invocation */
    private void createTestRunnerForMethodInvocation(Method method, TestCaseData data, RunnerGroup methodGroup, RunnerTree tree) {
        // create log4testing TestCase
        String invocationTestCaseName = createInvocationTestCaseName(data.getId(), methodGroup.getName());
        // Create test object
        @SuppressWarnings("unchecked")
        AludraTestCase testObject = BeanUtil.newInstance((Class<? extends AludraTestCase>) method.getDeclaringClass());
        TestInvoker invoker = new AludraTestMethodInvoker(testObject, method, data, aludraConfig.isDeferredScriptEvaluation());
        createRunnerForTestInvoker(invoker, methodGroup, tree, invocationTestCaseName, data.isIgnored(), data.getIgnoredReason(),
                false, data.getExternalTestId());
    }

    /** Creates a test runner for error reporting.
     * @param e The exception that occurred. */
    private void createTestRunnerForErrorReporting(Method method, Throwable e, RunnerGroup methodGroup, RunnerTree tree,
            String externalTestId) {
        LOGGER.error("createTestRunnerForErrorReporting('{}', {}, {}, ...)", new Object[] { method, e, methodGroup });
        // create log4testing TestCase name
        String invocationTestCaseName = createMethodTestSuiteName(method.getDeclaringClass(), method) + "_error_"
                + errorCount.incrementAndGet();
        // Create test object
        TestInvoker invoker = new ErrorReportingInvoker(method, e);
        createRunnerForTestInvoker(invoker, methodGroup, tree, invocationTestCaseName, false, null, true, externalTestId);
    }

    private void createRunnerForTestInvoker(TestInvoker invoker, RunnerGroup parentGroup, RunnerTree tree, String testCaseName,
            boolean ignore, String ignoredReason, boolean error, String externalTestId) {
        RunnerLeaf leaf = tree.addLeaf(nextLeafId.incrementAndGet(), invoker, testCaseName, parentGroup);
        if (null != externalTestId) {
            leaf.setAttribute(CommonRunnerLeafAttributes.EXTERNAL_TEST_ID, externalTestId);
        }
        if (ignore) {
            leaf.setAttribute(CommonRunnerLeafAttributes.IGNORE, Boolean.valueOf(ignore));
            if (ignoredReason != null) {
                leaf.setAttribute(CommonRunnerLeafAttributes.IGNORE_REASON, ignoredReason);
            }
        }
        if (error) {
            leaf.setAttribute(CommonRunnerLeafAttributes.BUILDER_ERROR, Boolean.TRUE);
        }
    }

    private void addSequentialGroupAttributes(RunnerGroup group, AnnotatedElement testClassOrMethod) {
        SequentialGroup annot = testClassOrMethod.getAnnotation(SequentialGroup.class);
        if (annot != null) {
            group.setAttribute(CommonRunnerLeafAttributes.SEQUENTIAL_GROUP_NAME, annot.groupName());
            group.setAttribute(CommonRunnerLeafAttributes.SEQUENTIAL_GROUP_INDEX, Integer.valueOf(annot.index()));
        }
    }

    /** Creates a test case name for a test method. */
    private static String createMethodTestSuiteName(Class<?> testClass, Method method) {
        return testClass.getName() + '.' + method.getName();
    }

    /** Creates a test case name for a test method invocation. */
    private static String createInvocationTestCaseName(String testInfo, String methodTestSuiteName) {
        return methodTestSuiteName + '-' + testInfo;
    }

}


text:
class Artifacts::CoverageReport < Artifacts::Base
  def total_coverage
    response_body.metrics.covered_percent
  end
end


text:
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Vidyano.Service.Repository;

namespace Data.Service
{
    public static class ImageProcessor
    {
        public static void Fix(PersistentObjectAttribute attr)
        {
            if (!attr.IsValueChanged)
                return;

            var data = (byte[])attr;
            if (data == null) // TODO: Or wrong image extension...
                return;

            var maxHeight = 64;
            if (attr.DataTypeHints != null)
            {
                var match = Regex.Match(attr.DataTypeHints, "Height=(\\d+)");
                if (match.Success)
                    maxHeight = int.Parse(match.Groups[1].Value);
            }

            attr.SetValue(Fix(data, maxHeight));
        }

        public static byte[] Fix(byte[] data, int? maxHeight = null, int? maxWidth = null)
        {
            if (!maxHeight.HasValue && !maxWidth.HasValue)
                return data;

            var bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.StreamSource = new MemoryStream(data);
            bmp.EndInit();

            var source = (BitmapSource)bmp;
            if (source.CanFreeze)
                source.Freeze();

            var pixelWidth = source.PixelWidth;
            var pixelHeight = source.PixelHeight;
            var resize = (maxWidth.HasValue && pixelWidth > maxWidth.GetValueOrDefault()) || (maxHeight.HasValue && pixelHeight > maxHeight.GetValueOrDefault());
            if (resize)
            {
                // NOTE: Resize image first
                var widthScale = (double)pixelWidth / maxWidth;
                var heightScale = (double)pixelHeight / maxHeight;
                var scale = Math.Max(widthScale.GetValueOrDefault(), heightScale.GetValueOrDefault());
                var scaledWidth = (int)(pixelWidth / scale);
                var scaledHeight = (int)(pixelHeight / scale);

                var group = new DrawingGroup();
                RenderOptions.SetBitmapScalingMode(group, BitmapScalingMode.HighQuality);
                group.Children.Add(new ImageDrawing(source, new Rect(0, 0, scaledWidth, scaledHeight)));

                var drawingVisual = new DrawingVisual();
                using (var drawingContext = drawingVisual.RenderOpen())
                    drawingContext.DrawDrawing(group);

                var resizedImage = new RenderTargetBitmap(scaledWidth, scaledHeight, 96, 96, PixelFormats.Default);
                resizedImage.Render(drawingVisual);

                source = resizedImage;
            }

            // NOTE: Save as both png/jpg and use smallest size
            var pngEncoder = new PngBitmapEncoder();
            pngEncoder.Frames.Add(BitmapFrame.Create(source));
            var pngStream = new MemoryStream();
            pngEncoder.Save(pngStream);

            if (HasTransparentPixels(source))
                return resize || pngStream.Length < data.Length ? pngStream.ToArray() : data;

            var jpgEncoder = new JpegBitmapEncoder { QualityLevel = 100 };
            jpgEncoder.Frames.Add(BitmapFrame.Create(source));
            var jpgStream = new MemoryStream();
            jpgEncoder.Save(jpgStream);

            // Use smallest (or original)
            if (pngStream.Length < jpgStream.Length)
                return resize || pngStream.Length < data.Length ? pngStream.ToArray() : data;

            return resize || jpgStream.Length < data.Length ? jpgStream.ToArray() : data;
        }

        public static byte[] ResizeImage(byte[] image, int maxDimensions)
        {
            var bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.StreamSource = new MemoryStream(image);
            bmp.EndInit();

            var source = (BitmapSource)bmp;
            if (source.CanFreeze)
                source.Freeze();

            var pixelWidth = source.PixelWidth;
            var pixelHeight = source.PixelHeight;
            var scale = pixelWidth > pixelHeight ? (double)pixelWidth / maxDimensions : (double)pixelHeight / maxDimensions;
            var scaledWidth = (int)(pixelWidth / scale);
            var scaledHeight = (int)(pixelHeight / scale);

            var group = new DrawingGroup();
            RenderOptions.SetBitmapScalingMode(group, BitmapScalingMode.HighQuality);
            group.Children.Add(new ImageDrawing(source, new Rect(0, 0, scaledWidth, scaledHeight)));

            var drawingVisual = new DrawingVisual();
            using (var drawingContext = drawingVisual.RenderOpen())
                drawingContext.DrawDrawing(group);

            var resizedImage = new RenderTargetBitmap(scaledWidth, scaledHeight, 96, 96, PixelFormats.Default);
            resizedImage.Render(drawingVisual);

            source = resizedImage;

            var pngEncoder = new PngBitmapEncoder();
            pngEncoder.Frames.Add(BitmapFrame.Create(source));
            var pngStream = new MemoryStream();
            pngEncoder.Save(pngStream);

            if (HasTransparentPixels(source))
                return pngStream.ToArray();

            var jpgEncoder = new JpegBitmapEncoder { QualityLevel = 100 };
            jpgEncoder.Frames.Add(BitmapFrame.Create(source));
            var jpgStream = new MemoryStream();
            jpgEncoder.Save(jpgStream);

            // Use smallest
            return pngStream.Length < jpgStream.Length ? pngStream.ToArray() : jpgStream.ToArray();
        }

        private static unsafe bool HasTransparentPixels(BitmapSource source)
        {
            var width = source.PixelWidth;
            var height = source.PixelHeight;
            var result = new byte[height * width * 4];

            fixed (byte* buffer = &result[0])
                source.CopyPixels(
                  new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight),
                  (IntPtr)(buffer),
                  height * width * 4,
                  width * 4);

            for (var x = 0; x < width; x++)
            {
                for (var y = 0; y < height; y++)
                {
                    if (result[(y * width + x) * 4 + 3] < 255)
                        return true;
                }
            }

            return false;
        }
    }
}


text:
package jadx.tests.integration.variables;

import org.junit.jupiter.api.Test;

import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.IntegrationTest;

import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class TestVariables5 extends IntegrationTest {

	public static class TestCls {
		public String f = "str//ing";
		private boolean enabled;

		private void testIfInLoop() {
			int i = 0;
			for (int i2 = 0; i2 < f.length(); i2++) {
				char ch = f.charAt(i2);
				if (ch == '/') {
					i++;
					if (i == 2) {
						setEnabled(true);
						return;
					}
				}
			}
			setEnabled(false);
		}

		private void setEnabled(boolean b) {
			this.enabled = b;
		}

		public void check() {
			setEnabled(false);
			testIfInLoop();
			assertTrue(enabled);
		}
	}

	@Test
	public void test() {
		noDebugInfo();
		ClassNode cls = getClassNode(TestCls.class);
		assertThat(cls)
				.code()
				.doesNotContain("int i2++;")
				.containsOne("int i = 0;")
				.containsOneOf("i++;", "&& (i = i + 1) == 2");
	}
}


text:
var openmdao = (typeof openmdao === "undefined" || !openmdao ) ? {} : openmdao ;

openmdao.WorkflowTreePane = function(elm, project, select_fn, dblclick_fn, workflow_fn, dataflow_fn) {
    /***********************************************************************
     *  private
     ***********************************************************************/
    // initialize private variables
    var self = this;

    self.pathname = false;

    /** convert json to structure required for jstree */
    function convertJSON(json, parent, openNodes) {
        var data = [];
        jQuery.each(json, function(idx, item) {
            var pathname   = item.pathname,
                type       = item.type,
                interfaces = item.interfaces,
                name = openmdao.Util.getName(pathname);

            // Figure out what type we are (lacking interfaces)
            if (item.workflow) {
                interfaces = ['IDriver'];
                subpath = pathname;

                // Exception: top is always an assembly
                if (name === 'driver') {
                    interfaces = ['IAssembly'];
                    pathname = openmdao.Util.getPath(pathname);
                    name = openmdao.Util.getName(pathname) + '.driver';
                    parent = name;
                    subpath = pathname + '.driver';
                }
            }
            else if (item.driver) {
                interfaces = ['IAssembly'];
                name = name + '.driver';
                subpath = pathname + '.driver';
            }
            else {
                interfaces = ['IComponent'];
            }

            interfaces = JSON.stringify(interfaces);
            var node = { 'data': name  };
            node.attr = {
                 'type'  : type,
                 'path'  : pathname,
                 'interfaces' : interfaces,
                 'parent' : parent
            };

            // Driver recursion
            if (item.workflow) {
                node.children = convertJSON(item.workflow, subpath,
                                            openNodes);
            }
            // Assembly recursion
            else if (item.driver) {
                node.children = convertJSON(item.driver.workflow,
                                            subpath, openNodes);
            }

            if (openNodes.indexOf(pathname) >= 0) {
                node.state = 'open';
            }
            data.push(node);
        });

        return data;
    }

    /** update the tree with JSON project data */
    function updateTree(json) {

        // Grab paths of currently open nodes.
        var openNodes = [];
        elm.find("li.jstree-open").each(function () {
            openNodes.push(this.getAttribute("path"));
        });

        // We may get a single workflow object or a list of workflow objects
        // if we get a single workflow, stick it in a list for consistency
        if (!jQuery.isArray(json)) {
            json = [json];
        }

        elm.empty();
        elm.jstree({
            plugins     : [ "json_data", "themes", "types", "cookies", "contextmenu", "ui", "crrm" ],
            json_data   : { "data": convertJSON(json, '', openNodes) },
            themes      : { "theme":  "openmdao" },
            cookies     : { "prefix": "objtree", opts : { path : '/' } },
            contextmenu : { "items":  contextMenu },
            core        : { "animation" : 0 },
            crrm        : { "move" : {
                                // don't allow moving within the tree (for now anyway)
                                "check_move" : function (m) {
                                    return false;
                                }
                            }
                          }
        })
        /*.bind("select_node.jstree", function(e, data) {
            if (typeof select_fn === 'function') {
                var path = data.rslt.obj.attr("path");
                select_fn(path);
            }
        })*/
        .bind("dblclick.jstree", function (e, data) {
            if (typeof dblclick_fn === 'function') {
                var node = jQuery(e.target).closest("li"),
                    path = node.attr("path"),
                    iface = node.attr('interfaces');
                if (iface.indexOf("IAssembly") >= 0) {
                    path = path + '.driver';
                }
                dblclick_fn(path);
            }
        })
        .bind("loaded.jstree", function (e, data) {
            elm.find('li').each(function() {
                // add classes so that the items in the tree are specific
                // to what they are: assembly, driver or component
                if (this.getAttribute("interfaces").indexOf("IAssembly") >= 0) {
                    this.children[1].children[0].addClass("jstree-assembly");
                }
                else if (this.getAttribute("interfaces").indexOf("IDriver") >= 0) {
                    this.children[1].children[0].addClass("jstree-driver");
                }
                else if (this.getAttribute("interfaces").indexOf("IComponent") >= 0) {
                    this.children[1].children[0].addClass("jstree-component");
                }

                // make drop targets
                jQuery(this.children[1]).droppable({
                    accept: '.DataflowFigure',
                    greedy: true,
                    tolerance: 'pointer',
                    out: function(ev, ui){
                        target_iface = this.parentElement.getAttribute('interfaces');
                        if (target_iface.indexOf("IComponent") >= 0) {
                            //this.parentElement.parentElement.parentElement.children[1].removeClass('jstree-hovered');
                        }
                        else {
                            this.removeClass('jstree-hovered');
                        }
                    },
                    over: function(ev, ui){
                        target_iface = this.parentElement.getAttribute('interfaces');
                        if (target_iface.indexOf("IComponent") >= 0) {
                            //this.parentElement.parentElement.parentElement.children[1].addClass('jstree-hovered');
                        }
                        else {
                            this.addClass('jstree-hovered');
                        }
                    },
                    drop: function(ev, ui) {

                        var droppedObject = jQuery(ui.draggable).clone(),
                            source_path = droppedObject.attr('pathname'),
                            target_iface = this.parentElement.getAttribute('interfaces');

                        if (target_iface.indexOf("IComponent") >= 0) {
                            // Don't do anything if we drop on a component.
                            cmd='';
                        }
                        if (target_iface.indexOf("IAssembly") >= 0) {
                            // Assemblies require some extra care.
                            target_path = this.parentElement.getAttribute('path');
                            cmd = target_path + '.driver.workflow.add("' + openmdao.Util.getName(source_path) + '", check=True)';
                        }
                        else {
                            target_path = this.parentElement.getAttribute('path');
                            cmd = target_path + '.workflow.add("' + openmdao.Util.getName(source_path) + '", check=True)';
                        }
                        if (cmd) {
                            //console.log(cmd);
                            project.issueCommand(cmd);
                        }
                    }
                });
            });
        });
    }

    /** get a context menu for the specified node */
    function contextMenu(node) {
        var path = node.attr('path'),
            name = openmdao.Util.getName(path);
            type = node.attr('type'),
            parent = node.attr('parent'),
            interfaces = jQuery.parseJSON(node.attr('interfaces')),
            menu = {};

        menu.properties = {
            "label"  : 'Properties',
            "action" :  function(node) {
                            if (jQuery.inArray('IAssembly',interfaces) >= 0) {
                                subpath = path + '.driver';
                            }
                            else {
                                subpath = path;
                            }
                            var id = (subpath+'-properties').replace(/\./g,'-');
                            new openmdao.PropertiesFrame(id, project).editObject(subpath);
                        }
        };
        if (jQuery.inArray('IAssembly',interfaces) >= 0) {
            menu.show_dataflow = {
                "label"  : 'Show Dataflow',
                "action" :  function(node) {
                                dataflow_fn(path);
                            }
            };
            // shortcut to driver workflow
            menu.show_workflow = {
                "label"  : 'Show Workflow',
                "action" :  function(node) {
                                workflow_fn(path+'.driver');
                            }
            };
        }
        if (jQuery.inArray('IDriver',interfaces) >= 0) {
            menu.show_workflow = {
                "label"  : 'Show Workflow',
                "action" :  function(node) {
                                workflow_fn(path);
                            }
            };
        }
        menu.run = {
            "label"  : 'Run this Component',
            "action" :  function(node) {
                            project.runComponent(path);
                        }
        };
        if (parent !== '') {
            menu.remove = {
                "label"  : 'Remove from Workflow',
                "action" :  function(node) {
                                var cmd = parent +".workflow.remove('" + name + "')";
                                //console.log(cmd);
                                project.issueCommand(cmd);
                            }
            };
        }
        return menu;
    }

    function handleMessage(message) {
        if (message.length !== 2) {
            debug.warn('Invalid component data for:', self.pathname, message);
        }
        else {
            if (message[1].hasOwnProperty('Workflow')) {
                var workflow = message[1].Workflow;
                if (typeof workflow === 'string') {
                    workflow = jQuery.parseJSON(workflow);
                }
                updateTree(workflow);
            }
        }
    }

    // listen for 'workflow' messages and update object tree accordingly
    project.addListener('', handleMessage);

    /***********************************************************************
     *  privileged
     ***********************************************************************/

    this.destructor = function() {
        project.removeListener('', handleMessage);
    };

    /** update the tree, with data from the project  */
    this.update = function() {
        project.getWorkflow('')
            .done(updateTree)
            .fail(function(jqXHR, textStatus, err) {
                debug.error("Error getting workflow", jqXHR, textStatus, err);
            });
    };

    this.update();
};


text:
namespace AgileObjects.AgileMapper.ObjectPopulation
{
    using System.Collections.Generic;
#if NET35
    using Microsoft.Scripting.Ast;
#else
    using System.Linq.Expressions;
#endif
    using DataSources;
    using Extensions;
    using Extensions.Internal;
    using Members;
    using static InvocationPosition;

    internal class MappingCreationContext
    {
        private IList<Expression> _memberMappingExpressions;
        private IList<IConfiguredDataSource> _toTargetDataSources;

        public MappingCreationContext(IObjectMappingData mappingData)
        {
            MappingData = mappingData;
            MapToNullCondition = GetMapToNullConditionOrNull(MapperData);
            InstantiateLocalVariable = true;
            MappingExpressions = new List<Expression>();

            if (RuleSet.Settings.UseSingleRootMappingExpression)
            {
                return;
            }

            var callbackQueryMapperData = MapperData.WithNoTargetMember();

            PreMappingCallback = callbackQueryMapperData.GetMappingCallbackOrNull(Before, MapperData);
            PostMappingCallback = callbackQueryMapperData.GetMappingCallbackOrNull(After, MapperData);
        }

        private static Expression GetMapToNullConditionOrNull(IMemberMapperData mapperData)
            => mapperData.MapperContext.UserConfigurations.GetMapToNullConditionOrNull(mapperData);

        public MapperContext MapperContext => MapperData.MapperContext;

        public MappingRuleSet RuleSet => MappingData.MappingContext.RuleSet;

        public ObjectMapperData MapperData => MappingData.MapperData;

        public QualifiedMember TargetMember => MapperData.TargetMember;

        public IObjectMappingData MappingData { get; }

        public Expression PreMappingCallback { get; }

        public Expression PostMappingCallback { get; }

        public Expression MapToNullCondition { get; }

        public List<Expression> MappingExpressions { get; }

        public bool InstantiateLocalVariable { get; set; }

        public bool RemoveEmptyMappings
            => !MapperData.TargetMemberIsEnumerableElement() || RuleSet.Settings.RemoveEmptyElementMappings;

        /// <summary>
        /// Gets or sets a value indicating whether the MappingExpressions collection contains a
        /// complete mapping, and no further Expressions are required.
        /// </summary>
        public bool MappingComplete { get; set; }

        public IList<IConfiguredDataSource> ToTargetDataSources
            => _toTargetDataSources ??= MappingData.GetToTargetDataSources();

        public Expression GetMappingExpression() => MappingExpressions.ToExpression();

        public IList<Expression> GetMemberMappingExpressions()
        {
            if (_memberMappingExpressions?.Count == MappingExpressions.Count)
            {
                return _memberMappingExpressions ?? Enumerable<Expression>.EmptyArray;
            }

            return _memberMappingExpressions = MappingExpressions.GetMemberMappingExpressions();
        }

        public MappingCreationContext WithToTargetDataSource(IDataSource dataSource)
        {
            var newSourceMappingData = MappingData.WithToTargetSource(dataSource.SourceMember);
            var isAlternate = !dataSource.IsSequential;

            var newContext = new MappingCreationContext(newSourceMappingData)
            {
                InstantiateLocalVariable = isAlternate
            };

            var newMapperData = newContext.MapperData;

            newMapperData.SourceObject = dataSource.Value;
            newMapperData.TargetObject = MapperData.TargetObject;

            if (TargetMember.IsComplex)
            {
                if (isAlternate)
                {
                    newMapperData.LocalVariable = MapperData.LocalVariable;
                }

                newMapperData.TargetInstance = MapperData.TargetInstance;
            }
            else if (TargetMember.IsEnumerable)
            {
                UpdateEnumerableVariablesIfAppropriate(MapperData, newMapperData);
            }

            return newContext;
        }

        public void UpdateFrom(MappingCreationContext toTargetContext, IDataSource toTargetDataSource)
        {
            var toTargetMappingData = toTargetContext.MappingData;
            MappingData.MapperKey.AddSourceMemberTypeTesterIfRequired(toTargetMappingData);

            if (!MapperData.IsRoot)
            {
                var dataSourceSet = DataSourceSet.For(toTargetDataSource, toTargetMappingData);
                MapperData.RegisterTargetMemberDataSources(dataSourceSet);
            }

            if (TargetMember.IsComplex)
            {
                UpdateChildMemberDataSources(toTargetContext.MapperData);
                return;
            }

            UpdateEnumerableVariablesIfAppropriate(toTargetContext.MapperData, MapperData);
        }

        private void UpdateChildMemberDataSources(ObjectMapperData toTargetMapperData)
        {
            var targetMemberDataSources = MapperData.DataSourcesByTargetMember;
            var targetMembers = targetMemberDataSources.Keys.ToArray();
            var dataSources = targetMemberDataSources.Values.ToArray();

            var toTargetTargetMemberDataSources = toTargetMapperData.DataSourcesByTargetMember;

            var targetMembersCount = targetMembers.Length;
            var targetMemberIndex = 0;

            foreach (var toTargetMemberAndDataSource in toTargetTargetMemberDataSources)
            {
                var toTargetMember = toTargetMemberAndDataSource.Key.LeafMember;

                for (var i = targetMemberIndex; i < targetMembersCount; ++i)
                {
                    ++targetMemberIndex;

                    var targetMember = targetMembers[i];

                    if (!targetMember.LeafMember.Equals(toTargetMember))
                    {
                        continue;
                    }

                    if (!dataSources[i].HasValue)
                    {
                        targetMemberDataSources[targetMember] = toTargetMemberAndDataSource.Value;
                    }

                    break;
                }
            }
        }

        private static void UpdateEnumerableVariablesIfAppropriate(
            ObjectMapperData fromMapperData,
            ObjectMapperData toMapperData)
        {
            if (fromMapperData.EnumerablePopulationBuilder.TargetVariable == null)
            {
                return;
            }

            toMapperData.LocalVariable = fromMapperData.LocalVariable;
            toMapperData.EnumerablePopulationBuilder.TargetVariable = fromMapperData.EnumerablePopulationBuilder.TargetVariable;
        }
    }
}


text:
  Vallecalle est
       un village
       localisé dans le département de Haute-Corse en Corse. Elle comptait 103 habitants en 2008.

À coté de Vallecalle sont situées les villes de
Santo-Pietro-di-Tenda localisée à 6 km, 333 habitants,
Olmeta-di-Tuda localisée à 1 km, 324 habitants,
Oletta à 4 km, 1 236 habitants,
Poggio-d'Oletta à 4 km, 204 habitants,
Rapale à 3 km, 151 habitants,
Murato localisée à 2 km, 590 habitants,
 entre autres. De plus, Vallecalle est située à seulement quatorze km de Bastia.

Si vous envisagez de venir habiter à Vallecalle, vous pourrez facilement trouver une maison à vendre.

Le nombre de logements, à Vallecalle, était réparti en 2011 en 50 appartements et 78 maisons soit
 un marché plutôt équilibré.


text:
@interface AppDelegate : CommonAppDelegate <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end


text:
package exercicio01;

public class SMS extends Mensagem {

	public SMS(String conteudo) {
		super(conteudo);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void imprimirMensagem(int codigo) {
		if(codigo== this.getCodigo())
			System.out.println(this.getConteudo());

	}

	@Override
	public void enviarMensagem() {
		this.setStatus("SMS Enviado");
	}

}


text:
<!-- Font CSS -->
{% if site.environment == "production" -%}
<link href="{{ site.cdn.fontawe }}" integrity="{{ site.cdn.fontawe_hash }}" crossorigin="anonymous" rel="stylesheet">
{% else -%}
<link href="{{ site.path }}/assets{{ pathVersion }}/fonts/fontawesome/css/all.min.css" rel="stylesheet">
{% endif %}

{% if layout == "doc" and search != false -%}
<!-- Algolia DocSearch CSS -->
<link href="https://cdn.jsdelivr.net/npm/@docsearch/css@3" rel="stylesheet">
{% endif -%}

<!-- Figuration CSS -->
{% if site.environment == "production" -%}
<link href="{{ site.path }}/assets{{ pathVersion }}/dist/css/figuration.min.css" rel="stylesheet" id="cssCore">
{%- else -%}
<link href="{{ site.path }}/assets{{ pathVersion }}/dist/css/figuration.css" rel="stylesheet" id="cssCore">
{% endif -%}

<!-- Docs CSS -->
{% if site.environment == "production" -%}
<link href="{{ site.path }}/assets{{ pathVersion }}/css/docs.min.css" rel="stylesheet" id="cssDocs">
{%- else -%}
<link href="{{ site.path }}/assets{{ pathVersion }}/css/docs.css" rel="stylesheet" id="cssDocs">
{% endif -%}


text:
title: "Machine Learning, Week 1"
date: 2017-08-31T10:25:51-06:00
tags: ["Machine Learning"]
draft: false
---

Taking the [Coursera Machine Learning](https://www.coursera.org/learn/machine-learning) course. Will post condensed notes every week as part of the review process. All material originates from the free Coursera course, taught by [Andrew Ng](http://www.andrewng.org/).

{{% toc %}}

* Lecture notes:
  * [Lecture1](/docs/coursera-machine-learning-week1/Lecture1.pdf)
  * [Lecture2](/docs/coursera-machine-learning-week1/Lecture2.pdf)
  * [Lecture3](/docs/coursera-machine-learning-week1/Lecture3.pdf)

# Introduction

## Machine Learning

### What is Machine Learning

* **Arthur Samuel (1959)**: The field of study that gives computers the ability to
learn without explicitly programmed.
* **Tom Mitchell (1998)**: Well-posed Learning Problem; A computer program is said to _learn_ from experience **E** with respect to some task **T** and some performance measure **P** if its performance on **T**, as measured by **P**, improves with experience **E**.

Example: playing checkers.

* **E** = The experience of playing many games of checkers.
* **T** = The task of playing checkers.
* **P** = The probability that the program will win the next game.

In general, any machine learning problem can be assigned to one of two broad classifications, Supervised learning and Unsupervised learning.

### Supervised Learning

In supervised learning, we have a data set and we already know what the correct output should look like. There is an idea that a relationship exists between the input and output.

Supervised learning is categorized into **regression** and **classification** problems.

* **Regression**: Results are within a continuous output. We are trying to map input variables to some continuous function.
* **Classification**: Results are discrete. We are trying to map input variables into separate categories.

Example 1:

Given data about the sizes of houses on the real estate market, attempt to predict price. Price as a function of size is a continuous output, so this is a _regression_ problem.

Example 2:

Given data about a patient with a tumor, predict whether or not the tumor is malignant or benign. The function does not produce a continuous output, only two categories are given, therefore this is a _classification_ problem.

Examples:

* Given email labeled as spam/not spam, learn a spam filter
* Given a dataset of patients diagnosed as either having diabetes or not, learn to classify new patients as having diabetes or not.

### Unsupervised Learning

Unsupervised learning allows approaches to problems with little or no idea what the results should look like. Structure is derived from data where we do not know the effect of the variables. This can be done by clustering the data based on relationships or variables within the data.

With unsupervised learning, there is no feedback based on the prediction results.

Examples:

* **Clustering**: Take a collection fo 1,000,000 different genes and find a way to automatically group these genes into groups that are somehow similar or related by different variables, such as lifespan, location, roles, etc.
* **Non-Clustering**: The "Cocktail Party Algorithm" allows you to find structure in a chaotic environment (such as identifying individual voices and music from a mesh of sounds at a cocktail party).

* Given a set of news articles found on the web, group them into sets of articles about the same stories.
* Given a database of customer data, automatically discover market segments and group customers into different market segments.

## Linear Regression with One Variable

### Model Representation

This is the notation we will use moving forward.

* Input variables (features) are denoted as $x^{(i)}$.
* Output variables are denoted as $y^{(i)}$.
* A pair $(x^{(i)}, y^{(i)})$ is called a training example.
* The dataset we'll be using to learn is a list of training examples is called a training set and is denoted as $(x^{(i)}, y^{(i)}); i = 1, ..., m$
* The value $X$ is used to denote the space of input values and $Y$ is used to denote the space of output values.
  * $X = Y = \mathbb{R}$
* Note: The _(i)_ is not exponentiation, but identifying.

Given a training set, learn a function $h:X \rightarrow Y$ such that $h(x)$ is a _good_ predictor for the corresponding value of $y$. For historical reasons, the function $h$ is called a hypothesis.

![hypothesis](/img/coursera-machine-learning-week1/hypothesis.png)

### Cost Function & Intuitions

We measure the accuracy of a hypothesis functions by using a **cost function**. This takes an average difference of all the results of the hypothesis with inputs from X and the outputs Y.

The cost function we will be using for now is the **Squared Error Function**, also known as **Mean Squared Error**.

$$ J(\theta\_{0}, \theta\_{1}) = \dfrac{1}{2m} \sum\_{i=1}^m (\hat{y}\_{i} - y\_{i})^{2} = \dfrac{1}{2m} \sum\_{i=1}^m (h\_{\theta}(x\_{i}) - y\_{i})^{2}  $$

Thinking about this in visual terms, training data set is scattered on the x,y plane. We are trying to make a straight line pass through these scattered points. We want the best possible line such that the average squared vertical distances of the scattered points from the line will be the least.

![cost_function_1](/img/coursera-machine-learning-week1/cost_function_1.png)
![cost_function_2](/img/coursera-machine-learning-week1/cost_function_2.png)
![cost_function_3](/img/coursera-machine-learning-week1/cost_function_3.png)
![cost_function_4](/img/coursera-machine-learning-week1/cost_function_4.png)

### Gradient Descent

Gradient descent is a method of estimating the parameters in the hypothesis function using the cost function. Imagine that we graph the hypothesis function based on its fields $\theta\_0, \theta\_1$. We put these variables on the x and y axis and we plot the cost function on the vertical z axis. The points on the graph will be the result of the cost function using the hypothesis with those specific theta parameters.

![gradient_descent_1](/img/coursera-machine-learning-week1/gradient_descent_1.png)

We need to minimize our cost function by "stepping" down from the top to the bottom points of this graph. The red arrows show local minimums in the graph.

This is done by taking the derivative (the tangential line to a function) of our cost function. The slope of the tangent is the derivative at that point and it will give us a direction to move towards. We make steps down the cost function in the direction with the steepest descent. The size of each step is determined by the parameter (alpha), which is the learning rate.

The gradient descent algorithm is:

_repeat until convergence:_
$$\theta\_j := \theta\_j - \alpha \dfrac{\partial}{\partial\theta\_j} J(\theta\_0,\theta\_1)$$
_where:_ $j = 0,1$ represents the feature index number.

At each iteration j, one should simultaneously update the parameters $\theta\_1, \theta\_2, \dots, \theta\_n$. Updating a specific parameter prior to calculating another one on the $j^{(th)}$ iteration leads to a wrong implementation.

![gradient_descent_2](/img/coursera-machine-learning-week1/gradient_descent_2.png)

Regardless of the slope's sign for the derivative, $\theta\_1$ eventually converges to its minimum value. The following figure shows that when the slope is negative, the value of $\theta\_1$ increases. When the slope is positive, the value of $\theta\_1$ decreases.

![gradient_descent_3](/img/coursera-machine-learning-week1/gradient_descent_3.png)

We must adjust the parameter alpha to ensure that the gradient descent algorithm converges in reasonable time. Failure to converge or too much time to obtain the minimum value implies that the step size is wrong.

![gradient_descent_4](/img/coursera-machine-learning-week1/gradient_descent_4.png)

Even with a fixed step size, gradient descent can converge. The reason is because as we approach the bottom of the convex function, the derivative approaches zero.

![gradient_descent_5](/img/coursera-machine-learning-week1/gradient_descent_5.png)

### Gradient Descent for Linear Regression

Applying the gradient descent algorithm to the cost functions defined earlier, we must calculate the necessary derivatives.

![gradient_descent_linear_regression_1](/img/coursera-machine-learning-week1/gradient_descent_linear_regression_1.png)

This gives us the new gradient descent algorithm:

_repeat until convergence:_
$$\theta\_0 := \theta\_0 - \alpha \frac{1}{m} \sum\limits\_{i=1}^{m}(h\_\theta(x\_{i}) - y\_{i})$$
$$\theta\_1 := \theta\_1 - \alpha \frac{1}{m} \sum\limits\_{i=1}^{m}((h\_\theta(x\_{i}) - y\_{i}) x\_{i}$$

If we start with a guess for our hypothesis function and we repeatedly apply the gradient descent equations, our hypothesis will become more and more accurate.

This is simply gradient descent on the original cost function J. This method looks at every example in the entire training set at every step, therefore this is called **batch gradient descent**. Note: while gradient descent can be susceptible to local minima in general, the optimization problem we have posed here for linear regression has only one global, and no other local, optima. Thus, gradient descent here always converges (assuming alpha isn't too large) to the global minimum. J is a convex quadratic function.

![gradient_descent_linear_regression_2](/img/coursera-machine-learning-week1/gradient_descent_linear_regression_2.png)

The ellipses shown above are the contours of a quadratic function. Also shown is the trajectory taken by gradient descent, which was initialized at (48, 30). The x's in the figure represent each step in gradient descent as it converged to its minimum.

# Optional Linear Algebra

## Linear Algebra Review

### Matrices and Vectors

Matrices are 2-dimensional arrays:

$$\begin{bmatrix} a & b & c \newline d & e & f \newline g & h & i \newline j & k & l\end{bmatrix}$$

The above matrix has four rows and three columns, therefore it is a 4 x 3 matrix.

A vector is a matrix with one column and many rows:

$$\begin{bmatrix} w \newline x \newline y \newline z \end{bmatrix}$$

Vectors are a subset of matrices. The above vector is a 4 x 1 matrix.

**Notation and terms:**

* $A\_{ij}$ refers to the element in the ith row and jth column of matrix A.
* A vector with 'n' rows is referred to as an 'n'-dimensional vector.
* $v\_i$ refers to the element in the ith row of the vector.
* In general, all vectors and matrices will be 1-indexed from the top left corner.
* Matrices are usually denoted by uppercase names while vectors are lowercase.
* "Scalar" means that an object is a single value, not a vector or matrix.
* $\mathbb{R}$ refers to the set of scalar real numbers.
* $\mathbb{R}^\mathbb{n}$ refers to the set of n-dimensional vectors of real numbers.

```octave
% The ; denotes we are going back to a new row.
A = [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12]

% Initialize a vector
v = [1;2;3]

% Get the dimension of the matrix A where m = rows and n = columns
[m,n] = size(A)

% You could also store it this way
dim_A = size(A)

% Get the dimension of the vector v
dim_v = size(v)

% Now let's index into the 2nd row 3rd column of matrix A
A_23 = A(2,3)
```
```text
A =

    1    2    3
    4    5    6
    7    8    9
   10   11   12

v =

   1
   2
   3

m =  4
n =  3
dim_A =

   4   3

dim_v =

   3   1

A_23 =  6
```

### Matrix Addition and Scalar Operations

Addition and Subtraction occur **element-wise**, simply add or subtract each corresponding element.

$$\begin{bmatrix} a & b \newline c & d \newline \end{bmatrix} +\begin{bmatrix} w & x \newline y & z \newline \end{bmatrix} =\begin{bmatrix} a+w & b+x \newline c+y & d+z \newline \end{bmatrix}$$
$$\begin{bmatrix} a & b \newline c & d \newline \end{bmatrix} - \begin{bmatrix} w & x \newline y & z \newline \end{bmatrix} =\begin{bmatrix} a-w & b-x \newline c-y & d-z \newline \end{bmatrix}$$

To add or subtract two matrices, their dimensions must be **the same**.

In scalar multiplication and division, we simply multiply or divide every element by the scalar value.

$$\begin{bmatrix} a & b \newline c & d \newline \end{bmatrix} * x =\begin{bmatrix} a*x & b*x \newline c*x & d*x \newline \end{bmatrix}$$
$$\begin{bmatrix} a & b \newline c & d \newline \end{bmatrix} / x =\begin{bmatrix} a /x & b/x \newline c /x & d /x \newline \end{bmatrix}$$

```octave
% Initialize matrix A and B
A = [1, 2, 4; 5, 3, 2]

% Initialize constant s
s = 2

% What happens if we have a Matrix + scalar?
add_As = A + s

sub_As = A - s
```

```text
A =

   1   2   4
   5   3   2

s =  2
add_As =

   3   4   6
   7   5   4

sub_As =

  -1   0   2
   3   1   0
```

### Matrix-Vector Multiplication

When multiplying a matrix with a vector, we map the column of the vector onto each row of the matrix, multiplying each element and summing the result.

$$\begin{bmatrix} a & b \newline c & d \newline e & f \end{bmatrix} *\begin{bmatrix} x \newline y \newline \end{bmatrix} =\begin{bmatrix} a*x + b*y \newline c*x + d*y \newline e*x + f*y\end{bmatrix}$$

An **m x n matrix** multiplied by an **n x 1 vector** results in an **m x 1 vector**.

The result is a **vector**. The number of **columns of the matrix** must equal the number of **rows in the vector**.

```octave
% Initialize matrix A
A = [1, 2, 3; 4, 5, 6;7, 8, 9; 434, 54, 3]

% Initialize vector v
v = [1; 1; 1;]

% Multiply A * v
Av = A * v
```
```text
A =

     1     2     3
     4     5     6
     7     8     9
   434    54     3

v =

   1
   1
   1

Av =

     6
    15
    24
   491
```

### Matrix-Matrix Multiplication

Two matrices are multiplied by breaking it into several vector multiplications and concatenating the result.

$$\begin{bmatrix} a & b \newline c & d \newline e & f \end{bmatrix} *\begin{bmatrix} w & x \newline y & z \newline \end{bmatrix} =\begin{bmatrix} a*w + b*y & a*x + b*z \newline c*w + d*y & c*x + d*z \newline e*w + f*y & e*x + f*z\end{bmatrix}$$

An **m x n matrix** multiplied by an **n x o matrix** results in an **m x o matrix**. In the above example, a 3 x 2 matrix multiplied by a 2 x 2 matrix resulted in a 3 x 2 matrix.

![matrix_matrix_multiplication](/img/coursera-machine-learning-week1/matrix_matrix_multiplication.png)

To multiply two matrices, the number of **columns** of the first matrix must equal the number of **rows** of the second matrix.

```octave
% Initialize a 3 by 2 matrix
A = [1, 2; 3, 4;5, 6]

% Initialize a 2 by 1 matrix
B = [1; 2]

% We expect a resulting matrix of (3 by 2)*(2 by 1) = (3 by 1)
mult_AB = A*B
```
```text
A =

   1   2
   3   4
   5   6

B =

   1
   2

mult_AB =

    5
   11
   17
```

### Matrix Multiplication Properties

Matrices are **not commutative**, that is $A * B \neq B * A$. Matrices are **associative**, that is $(A * B) * C = A * (B * C)$

Identity Matrices, when multiplied by any matrix of the same dimensions, returns the original matrix. Identity matrices have ones along the diagonals and zeros everywhere else. They are **n x n** dimensioned.

$$\begin{bmatrix} 1 & 0 & 0 \newline 0 & 1 & 0 \newline 0 & 0 & 1 \newline \end{bmatrix}$$

![identity_matrix](/img/coursera-machine-learning-week1/identity_matrix.png)

Note, the identity matrix $I$ does not have the same dimensions in $A * I$ and $I * A$, as the dimensions of $I$ are implicit from the context of $A$.

```octave
% Initialize random matrices A and B
A = [1,2;4,5]
B = [1,1;0,2]

% Initialize a 2 by 2 identity matrix
I = eye(2)

% The above notation is the same as I = [1,0;0,1]

% What happens when we multiply I*A ?
IA = I*A

% How about A*I ?
AI = A*I

% Compute A*B
AB = A*B

% Is it equal to B*A?
BA = B*A

% Note that IA = AI but AB != BA
```
```text
A =

   1   2
   4   5

B =

   1   1
   0   2

I =

Diagonal Matrix

   1   0
   0   1

IA =

   1   2
   4   5

AI =

   1   2
   4   5

AB =

    1    5
    4   14

BA =

    5    7
    8   10
```

### Inverse and Transpose

When a matrix is multiplied by its inverse, you get the identity. The **inverse** of a matrix $A$ is denoted $A^{-1}$.

$$ A * A^{-1} = I $$

A non square matrix does not have an inverse matrix. We can compute inverses of matrices in octave with the `pinv(A)` function, and in Matlab with the `inv(A)` function. Matrices that do not have an inverse are _singular_ or _degenerate_.

The **transposition** of a matrix is like the result of rotating the matrix $90^\circ$ in a clockwise direction then reversing it. This can be computed in octave with `A'` or in Matlab with the `transpose(A)` function.

$$A = \begin{bmatrix} a & b \newline c & d \newline e & f \end{bmatrix}$$
$$A^T = \begin{bmatrix} a & c & e \newline b & d & f \newline \end{bmatrix}$$

In other words: $A\_{ij} = A^T\_{ji}$

```octave
% Initialize matrix A
A = [1,2,0;0,5,6;7,0,9]

% Transpose A
A_trans = A'

% Take the inverse of A
A_inv = inv(A)

% What is A^(-1)*A?
A_invA = inv(A)*A
```
```text
A =

   1   2   0
   0   5   6
   7   0   9

A_trans =

   1   0   7
   2   5   0
   0   6   9

A_inv =

   0.348837  -0.139535   0.093023
   0.325581   0.069767  -0.046512
  -0.271318   0.108527   0.038760

A_invA =

   1.00000  -0.00000   0.00000
   0.00000   1.00000  -0.00000
  -0.00000   0.00000   1.00000
```

---

Move on to [Week 2]({{% relref "coursera-machine-learning-week2.md" %}}).


text:
python3 -m venv env3
source env3/bin/activate
pip install --upgrade pip
pip install -r requirements.txt


text:
$(document).ready(function(){
  var keyword = "";
  var resultArea = $("#results");
  var searchBar = $("#searchBar");
  var searchButton = $(".glyphicon-search");
  var searchUrl = "https://en.wikipedia.org/w/api.php";
  var displayResults = function(){
    $.ajax({
      url: searchUrl,
      dataType: 'jsonp',
      data: {
        action: 'query',
        format: 'json',
        generator: 'search',
          gsrsearch: keyword,
          gsrnamespace: 0,
          gsrlimit: 10,
        prop:'extracts|pageimages',
          exchars: 200,
          exlimit: 'max',
          explaintext: true,
          exintro: true,
          piprop: 'thumbnail',
          pilimit: 'max',
          pithumbsize: 200
      },
      success: function(json){
        var results = json.query.pages;
        $.map(results, function(result){
          var link = "http://en.wikipedia.org/?curid="+result.pageid;
          var elem1 = $('<a>');
          elem1.attr("href",link);
          elem1.attr("target","_blank");
          var elem2 = $('<li>');
          elem2.append($('<h3>').text(result.title));
          //if(result.thumbnail) elem.append($('<img>').attr('width',150).attr('src',result.thumbnail.source));
          elem2.append($('<p>').text(result.extract));
          elem1.append(elem2);
          resultArea.append(elem1);
        });
        $("footer").append("<p>----x--------x----</p>");
      }
    });
  };
 /*
  searchBar.autocomplete({
        source: function (request, response) {
            $.ajax({
                url: searchUrl,
                dataType: 'jsonp',
                data: {
                    'action': "opensearch",
                    'format': "json",
                    'search': request.term
                },
                success: function (data) {
                    response(data[1]);
                }
            });
        }
    });
  */
  searchButton.click(function(){
    keyword = searchBar.val();
    resultArea.empty();
    displayResults();
    $("footer").empty();
    $("#searchBox").animate({'padding-top':"0"}, 600);
    $(".container-fluid").animate({height:"30vh"}, 600);
  });
  searchBar.keypress(function(e){
      if(e.keyCode==13)
      $(searchButton).click();
  });
});


text:
<?php

namespace Xidea\Bundle\BaseBundle\DependencyInjection\Helper;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Definition;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class ExtensionHelper
{
    /*
     * @var string
     */
    protected $alias;

    public function __construct($alias)
    {
        $this->alias = $alias;
    }

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

    public function loadRoutingSection(array $config, array $routes, ContainerBuilder $container, Loader\YamlFileLoader $loader)
    {
        if(isset($config['routing'])) {
            $routes = array_merge($routes, $config['routing']['routes']);

            $parameters = array(
                'routing.scope' => $config['routing']['scope'],
                'routing.routes' => $routes
            );
            foreach($parameters as $name => $value) {
                $container->setParameter(sprintf('%s.%s', $this->getAlias(), $name), $value);
            }

            $routingConfigurationName = sprintf('%s.routing.configuration', $this->getAlias());
            $defaultRoutingConfigurationName = $routingConfigurationName.'.default';

            if(!$container->hasDefinition($defaultRoutingConfigurationName)) {
                $container->setDefinition($defaultRoutingConfigurationName, new Definition('Xidea\Bundle\BaseBundle\Routing\Configuration\DefaultConfiguration', [
                    $config['routing']['scope'],
                    $routes
                ]))
                ->addTag('xidea_base.routing.configuration', [
                    'priority' => $config['routing']['priority']
                ]);
            }

            $container->setAlias($routingConfigurationName, $config['routing']['configuration']);
        }
    }

    public function loadTemplatingSection(array $config, array $templates, ContainerBuilder $container, Loader\YamlFileLoader $loader)
    {
        if(isset($config['templating'])) {
            $templates = array_merge($templates, $config['templating']['templates']);

            $parameters = array(
                'templating.scope' => $config['templating']['scope'],
                'templating.engine' => $config['templating']['engine'],
                'templating.templates' => $templates
            );
            foreach($parameters as $name => $value) {
                $container->setParameter(sprintf('%s.%s', $this->getAlias(), $name), $value);
            }

            $templateConfigurationName = sprintf('%s.templating.configuration', $this->getAlias());
            $defaultTemplateConfigurationName = $templateConfigurationName.'.default';

            if(!$container->hasDefinition($defaultTemplateConfigurationName)) {
                $container->setDefinition($defaultTemplateConfigurationName, new Definition('Xidea\Bundle\BaseBundle\Templating\Configuration\DefaultConfiguration', [
                    $config['templating']['scope'],
                    $templates,
                    $config['templating']['engine']
                ]))
                ->addTag('xidea_base.templating.configuration', [
                    'priority' => $config['templating']['priority']
                ]);
            }

            $container->setAlias($templateConfigurationName, $config['templating']['configuration']);
        }
    }

    public function loadPaginationSection(array $config, ContainerBuilder $container, Loader\YamlFileLoader $loader)
    {
        if(isset($config['pagination'])) {
            $paginatorDefinitionName = sprintf('%s.paginator', $this->getAlias());
            if($container->hasDefinition($paginatorDefinitionName)) {
                $paginatorDefinition = $container->getDefinition($paginatorDefinitionName);
                $paginatorDefinition->addMethodCall('setOptions', [[
                    'parameterName' => $config['pagination']['parameter_name']
                ]]);
            }
            $sorterDefinitionName = sprintf('%s.sorter', $this->getAlias());
            if($container->hasDefinition($sorterDefinitionName)) {
                $sorterDefinition = $container->getDefinition($sorterDefinitionName);
                $sorterDefinition->addMethodCall('setOptions', [[
                    'parameterName' => $config['pagination']['sorter']['parameter_name'],
                    'defaultDirectionValue' => $config['pagination']['sorter']['default_direction_value']
                ]]);
            }
        }
    }
}


text:
module OmniAuth
  module Tecnologiedemocratiche
    VERSION = '1.3.1'
  end
end