text:
//////////////////////////////////////////////////////////////////////////////
//
//                    Copyright 2020, Cornutum Project
//                             www.cornutum.org
//
//////////////////////////////////////////////////////////////////////////////

package org.cornutum.tcases.openapi.resolver;

import static org.cornutum.tcases.openapi.resolver.DataValues.*;

import java.math.BigDecimal;
import java.util.Arrays;

/**
 * Base class for {@link MessageData} builders
 */
@SuppressWarnings("unchecked")
public abstract class AbstractMessageDataBuilder<T extends AbstractMessageDataBuilder<T>>
  {
  public T mediaType( String mediaType)
    {
    mediaType_ = mediaType;
    return (T) this;
    }

  public T valid( boolean valid)
    {
    valid_ = valid;
    return (T) this;
    }

  public MessageData build()
    {
    return new MessageData( value_, mediaType_, valid_);
    }

  public T arrayData( DataValue<?>... itemValues)
    {
    value_ = arrayOfAny( Arrays.asList( itemValues));
    return (T) this;
    }

  public T binaryData( byte[] value)
    {
    value_ = valueOf( value);
    return (T) this;
    }

  public T booleanData( boolean value)
    {
    value_ = valueOf( value);
    return (T) this;
    }

  public T decimalData( BigDecimal value)
    {
    value_ = valueOf( value);
    return (T) this;
    }

  public T integerData( int value)
    {
    value_ = valueOf( value);
    return (T) this;
    }

  public T longData( long value)
    {
    value_ = valueOf( value);
    return (T) this;
    }

  public T nullData()
    {
    value_ = nullValue();
    return (T) this;
    }

  public T objectData( ObjectValueBuilder builder)
    {
    value_ = builder.build();
    return (T) this;
    }

  public T stringData( String value)
    {
    value_ = stringOf( value);
    return (T) this;
    }

  public T base64Data( String value)
    {
    value_ = base64Of( value);
    return (T) this;
    }

  public T dateTimeData( String value)
    {
    value_ = dateTimeOf( value);
    return (T) this;
    }

  public T dateData( String value)
    {
    value_ = dateOf( value);
    return (T) this;
    }

  public T emailData( String value)
    {
    value_ = emailOf( value);
    return (T) this;
    }

  public T uuidData( String value)
    {
    value_ = uuidOf( value);
    return (T) this;
    }

  private DataValue<?> value_;
  private String mediaType_;
  private boolean valid_ = true;
  }


text:
'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    path = require('path'),
    db = require(path.resolve('config/sequelize'));

module.exports = function() {
    // Use local strategy
    passport.use(new LocalStrategy({
            usernameField: 'username',
            passwordField: 'password'
        }, function(username, password, done) {
            console.log('********************** LOCAL *************************');
            db.User.findOne({
                where: {
                    username: username,
                    active: true
                }, attributes: ['id', 'firstname', 'lastname', 'displayname', 'username', 'password', 'salt', 'roles']
            }).then(function(user) {
                if (!user) {
                    return done(null, false, {
                        message: 'Authentication failure: Username/Password is invalid.'
                    });
                }
                if (!user.authenticate(password)) {
                    return done(null, false, {
                        message: 'Authentication failure: Username/Password is invalid.'
                    });
                }
                done(null, user);
                return null;
            }).catch(function(err){
                return done(err);
            });
        }
    ));
};

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<testsuites tests="0" failures="0"/>


text:
package br.com.netbrasoft.gnuob.generic;

import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.PAGING_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.ZERO;
import static org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString;
import static org.apache.commons.lang3.builder.ToStringStyle.SHORT_PREFIX_STYLE;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = PAGING_NAME)
public class Paging {

  private int first;
  private int max;

  public Paging() {
    this(ZERO, ZERO);
  }

  private Paging(final int first, final int max) {
    this.first = first;
    this.max = max;
  }

  public static Paging getInstance(final int first, final int max) {
    return new Paging(first, max);
  }

  @XmlElement
  public int getFirst() {
    return first;
  }

  @XmlElement
  public int getMax() {
    return max;
  }

  public void setFirst(final int first) {
    this.first = first;
  }

  public void setMax(final int max) {
    this.max = max;
  }

  @Override
  public String toString() {
    return reflectionToString(this, SHORT_PREFIX_STYLE);
  }
}


text:
<?php

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

// Load the view framework
jimport( 'joomla.application.component.view');

/**
 * HTML View class for maintaining the state
 *
 * @package	VirtueMart
 * @subpackage State
 * @author RolandD, jseros
 */
class VirtuemartViewState extends JViewLegacy {

	function display($tpl = null) {

		$states = array();
		$db = JFactory::getDBO();
		//retrieving countries id
		$country_ids = vRequest::getString('virtuemart_country_id');
		$country_ids = explode(',', $country_ids);

		foreach($country_ids as $country_id){
			$q= 'SELECT `virtuemart_state_id`, `state_name` FROM `#__virtuemart_states`  WHERE `virtuemart_country_id`= "'.(int)$country_id.'"
				ORDER BY `#__virtuemart_states`.`state_name`';
			$db->setQuery($q);

			$states[$country_id] = $db->loadAssocList();
		}

		echo json_encode($states);
	}
}
// pure php no closing tag


text:
var PDFDESIGNER_ERROR_001 = 'There is no stream.';
var PDFDESIGNER_ERROR_002 = 'Index out of range.';
var PDFDESIGNER_ERROR_003 = 'Unimplemented';
var PDFDESIGNER_ERROR_004 = 'ObjectID is invalid.';
var PDFDESIGNER_ERROR_005 = 'Stream is invalid.';
var PDFDESIGNER_ERROR_006 = 'FirstPage does not exist.';
var PDFDESIGNER_ERROR_007 = 'The position of the cross-reference table is invalid.';
var PDFDESIGNER_ERROR_008 = 'Top object number of the cross-reference table is invalid.';
var PDFDESIGNER_ERROR_009 = 'Number of items in the cross-reference table is invalid.';
var PDFDESIGNER_ERROR_010 = 'Trailer is not correct.';
var PDFDESIGNER_ERROR_011 = 'It failed to get RootID.';
var PDFDESIGNER_ERROR_012 = 'It failed to get PrevID.';
var PDFDESIGNER_ERROR_013 = 'It failed to get InfoID.';
var PDFDESIGNER_ERROR_014 = 'File is corrupted.';
var PDFDESIGNER_ERROR_015 = 'Not a PDF file.';
var PDFDESIGNER_ERROR_016 = '%%EOF is not.';
var PDFDESIGNER_ERROR_017 = 'The position of the cross-reference table could not be accurately obtained.';
var PDFDESIGNER_ERROR_018 = 'RootID could not be obtained accurately.';
var PDFDESIGNER_ERROR_019 = 'FirstPagebID could not be obtained accurately.';
var PDFDESIGNER_ERROR_020 = '(Reservation)';
var PDFDESIGNER_ERROR_021 = '(Reservation)';
var PDFDESIGNER_ERROR_022 = '(Reservation)';
var PDFDESIGNER_ERROR_023 = '(Reservation)';
var PDFDESIGNER_ERROR_024 = '(Reservation)';

// all class
var PDFDESIGNER_ERROR_025 = 'It does not support encrypted files.';
var PDFDESIGNER_ERROR_026 = '(Reservation)';
var PDFDESIGNER_ERROR_027 = '(Reservation)';
var PDFDESIGNER_ERROR_028 = '(Reservation)';
var PDFDESIGNER_ERROR_029 = '(Reservation)';

// TPDFKnife,TPDFDeletePage,TPDFRotatePage,TPDFOutLineManager
var PDFDESIGNER_ERROR_030 = 'The page is out of range.';
var PDFDESIGNER_ERROR_031 = '(Reservation)';
var PDFDESIGNER_ERROR_032 = '(Reservation)';
var PDFDESIGNER_ERROR_033 = '(Reservation)';
var PDFDESIGNER_ERROR_034 = '(Reservation)';

// TPDFDeletePage
var PDFDESIGNER_ERROR_035 = 'It is not possible to remove all of the page.';
var PDFDESIGNER_ERROR_036 = '(Reservation)';
var PDFDESIGNER_ERROR_037 = '(Reservation)';
var PDFDESIGNER_ERROR_038 = '(Reservation)';
var PDFDESIGNER_ERROR_039 = '(Reservation)';

// TPDFRotatePage
var PDFDESIGNER_ERROR_040 = 'Please set 1-3 to Rotate the third argument.';
var PDFDESIGNER_ERROR_041 = '(Reservation)';
var PDFDESIGNER_ERROR_042 = '(Reservation)';
var PDFDESIGNER_ERROR_043 = '(Reservation)';
var PDFDESIGNER_ERROR_044 = '(Reservation)';

// TPDFCode
var PDFDESIGNER_ERROR_045 = 'Unicode strings are interrupted in the middle.';
var PDFDESIGNER_ERROR_046 = '(Reservation)';
var PDFDESIGNER_ERROR_047 = '(Reservation)';
var PDFDESIGNER_ERROR_048 = '(Reservation)';
var PDFDESIGNER_ERROR_049 = '(Reservation)';

// TPDFNode,TPDFNodeList,TPDFOutLineManager
var PDFDESIGNER_ERROR_050 = 'Child node is not created.';
var PDFDESIGNER_ERROR_051 = 'Index is invalid.';
var PDFDESIGNER_ERROR_052 = 'Hierarchy level of bookmark is up to five levels. No more, you can not add a child node.';
var PDFDESIGNER_ERROR_053 = 'Node is not created.';
var PDFDESIGNER_ERROR_054 = '(Reservation)';


text:
namespace DistanceBetweenPoints
{
    using System;
    using System.Linq;

    class Distance
    {
        static void Main()
        {
            int[] first = Console.ReadLine().Split().Select(int.Parse).ToArray();
            int[] second = Console.ReadLine().Split().Select(int.Parse).ToArray();

            Point one = new Point(first[0], first[1]);
            Point two = new Point(second[0], second[1]);

            int a = Math.Abs(one.X - two.X);
            int b = Math.Abs(one.Y - two.Y);

            double distance = Math.Sqrt(a * a + b * b);

            Console.WriteLine("{0:f3}", distance);

        }
    }

    class Point
    {
        public int X { get; set; }

        public int Y { get; set; }

        public Point(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }
}


text:
<!doctype html>

		<meta charset='utf-8' />
		<meta name='viewport' content='width=device-width' />
		<meta http-equiv='X-UA-Compatible' content='ie=edge'>
		<title>Miguel Laginha is on xbar</title>
		<link rel='stylesheet' href='/public/css/xbar.css?cb=08%20Mar%2021%2015%3a22%20GMT'>
		<link rel='preconnect' href='https://fonts.gstatic.com'>
		<link rel='preconnect' href='https://fonts.googleapis.com'>
		<link rel='stylesheet' href='https://fonts.googleapis.com/css2?family=Bodoni+Moda:wght@500&display=swap'>

	<meta name='description' content='Miguel Laginha is on xbar.'>
	<meta name='author' content='Miguel Laginha'>
	<meta name='keywords' content='macos,menubar,xbar,bitbar'>
	<meta itemprop='image' content='https://avatars.githubusercontent.com/u/19879?v=4'>
	<meta itemprop='name' content='Miguel Laginha is on xbar.'>
	<meta itemprop='description' content='Miguel Laginha is on xbar.'>
	<meta name='twitter:card' content='summary_large_image'>
	<meta name='twitter:title' content='Miguel Laginha is on xbar.'>
	<meta name='twitter:description' content='Miguel Laginha is on xbar.'>
	<meta name='twitter:image' content='https://avatars.githubusercontent.com/u/19879?v=4'>
	<meta name='twitter:creator' content='matryer'>
	<meta property='og:title' content='Miguel Laginha is on xbar.'>
	<meta property='og:description' content='Miguel Laginha is on xbar.'>
	<meta property='og:url' content='https://xbarapp.com/contributors/brecke.html'>
	<meta property='og:site_name' content='Browse and install plugins by Miguel Laginha on xbar.'>
	<meta property='og:type' content='article:author'>
	<meta property='og:image' content='https://avatars.githubusercontent.com/u/19879?v=4'>
	<link rel='apple-touch-icon' sizes='180x180' href='https://avatars.githubusercontent.com/u/19879?v=4'>
	<link rel='icon' type='image/png' sizes='32x32' href='https://avatars.githubusercontent.com/u/19879?v=4'>
	<link rel='shortcut icon' href='https://avatars.githubusercontent.com/u/19879?v=4'>
	<meta name='msapplication-TileColor' content='#ffffff'>
	<meta name='msapplication-config' content='/public/browserconfig.xml'>
	<meta name='theme-color' content='#ffffff'>

						xbar

						💜 Sponsor

						Coming soon

					AWS

					Cryptocurrency

					Dev

					E-Commerce

					Email

					Environment

					Finance

					Games

					IoT

					Lifestyle

					Music

					Network

					Politics

					Science

					Sports

					System

					Time

					Tools

					Travel

					Weather

					Web

					Meet other xbar contributors.

					Miguel Laginha—@brecke

							Miguel Laginha—@brecke

					Hacker of all trades, manager of none; Open $(web|data|source) developer and enthusiast. Former hacker @OneStopTransport & Sciencematters. Portuguese.

						Visit @brecke on GitHub

						VPN Country Flag

						It shows the country flag corresponding to your IP Address (useful when using VPNs).

									Miguel Laginha

										(@brecke)

						GitHub project
						•
						Writing plugins guide

						Copyright ©2021 Mat Ryer + contributors • @matryer

						Last updated on 08 Mar 21 15:22 GMT


text:
  Sainte-Eulalie-d'Olt est
       un village
       situé dans le département de l'Aveyron en Midi-Pyrénées. Elle totalisait 329 habitants en 2008.

À coté de Sainte-Eulalie-d'Olt sont situées les communes de
Coussergues localisée à 7 km, 220 habitants,
Lassouts située à 6 km, 313 habitants,
Aurelle-Verlac située à 6 km, 178 habitants,
Saint-Martin-de-Lenne à 3 km, 219 habitants,
Saint-Saturnin-de-Lenne localisée à 7 km, 353 habitants,
Prades-d'Aubrac à 7 km, 415 habitants,
 entre autres. De plus, Sainte-Eulalie-d'Olt est située à seulement 29 km de Marvejols.

La ville offre quelques  équipements, elle dispose, entre autres, de deux boucles de randonnée.

Si vous pensez venir habiter à Sainte-Eulalie-d'Olt, vous pourrez facilement trouver une maison à vendre.

Le nombre d'habitations, à Sainte-Eulalie-d'Olt, se décomposait en 2011 en dix appartements et 304 maisons soit
 un marché plutôt équilibré.


text:
using System;
using System.Collections.Generic;
using System.Text;
using OKHOSTING.UI.Controls;
using OKHOSTING.UI.Controls.Layout;

namespace OKHOSTING.UI.Test.Css.Grids
{
	public class Auto_Colum_Auto_Row : Controller
	{
		protected override void OnStart()
		{
			IStack StackPrincipal = Core.BaitAndSwitch.Create<IStack>();

			ILabel lblGridAutorow = Core.BaitAndSwitch.Create<ILabel>();
			lblGridAutorow.Text = "***************grid-auto-rows ***************";
			StackPrincipal.Children.Add(lblGridAutorow);

			IButton btnExit = Core.BaitAndSwitch.Create<IButton>();
			btnExit.Text = "Exit";
			btnExit.Click += btnExit_Click;
			StackPrincipal.Children.Add(btnExit);

			IGrid AutoRow = Core.BaitAndSwitch.Create<IGrid>();
			AutoRow.Name = "AutoRow";
			AutoRow.ColumnCount = 4;
			AutoRow.RowCount = 4;
			StackPrincipal.Children.Add(AutoRow);

			ILabel lbl1l = Core.BaitAndSwitch.Create<ILabel>();
			lbl1l.Name = "lbl1";
			lbl1l.Text = "Primer Label";
			AutoRow.SetContent(0, 0, lbl1l);

			ILabel lbl2l = Core.BaitAndSwitch.Create<ILabel>();
			lbl2l.Name = "lbl2";
			lbl2l.Text = "Segundo label";
			AutoRow.SetContent(1, 0, lbl2l);

			ILabel lbl3l = Core.BaitAndSwitch.Create<ILabel>();
			lbl3l.Name = "lbl3";
			lbl3l.Text = "Tercer label";
			AutoRow.SetContent(2, 0, lbl3l);

			ILabel lbl4l = Core.BaitAndSwitch.Create<ILabel>();
			lbl4l.Name = "lbl4";
			lbl4l.Text = "Cuarto label";
			AutoRow.SetContent(3, 0, lbl4l);

			ITextBox txt1t = Core.BaitAndSwitch.Create<ITextBox>();
			txt1t.Name = "txt1";
			txt1t.Value = "Primer textbox";
			AutoRow.SetContent(0, 1, txt1t);

			ITextBox txt2t = Core.BaitAndSwitch.Create<ITextBox>();
			txt2t.Name = "txt2";
			txt2t.Value = "Segudo textbox";
			AutoRow.SetContent(1, 1, txt2t);

			ITextBox txt3t = Core.BaitAndSwitch.Create<ITextBox>();
			txt3t.Name = "txt3";
			txt3t.Value = "Tercer textbox";
			AutoRow.SetContent(2, 1, txt3t);

			ITextBox txt4t = Core.BaitAndSwitch.Create<ITextBox>();
			txt4t.Name = "txt4";
			txt4t.Value = "cuarto textbox";
			AutoRow.SetContent(3, 1, txt4t);

			IButton btn1b = Core.BaitAndSwitch.Create<IButton>();
			btn1b.Name = "btn1";
			btn1b.Text = "Primer boton";
			AutoRow.SetContent(2, 2, btn1b);

			IButton btn2b = Core.BaitAndSwitch.Create<IButton>();
			btn2b.Name = "btn2";
			btn2b.Text = "Segundo boton";
			AutoRow.SetContent(2, 3, btn2b);

			IButton btn3b = Core.BaitAndSwitch.Create<IButton>();
			btn3b.Name = "btn3";
			btn3b.Text = "Tercer boton";
			AutoRow.SetContent(3, 2, btn3b);

			IButton btn4b = Core.BaitAndSwitch.Create<IButton>();
			btn4b.Name = "btn4";
			btn4b.Text = "Cuarto botn";
			AutoRow.SetContent(3, 3, btn4b);

			ILabel lblGridAutoColumn = Core.BaitAndSwitch.Create<ILabel>();
			lblGridAutoColumn.Text = "***************grid-auto-column ***************";
			StackPrincipal.Children.Add(lblGridAutoColumn);

			IGrid AutoColumn = Core.BaitAndSwitch.Create<IGrid>();
			AutoColumn.Name = "AutoColumn";
			AutoColumn.ColumnCount = 4;
			AutoColumn.RowCount = 4;
			StackPrincipal.Children.Add(AutoColumn);

			ILabel label1 = Core.BaitAndSwitch.Create<ILabel>();
			label1.Name = "label1";
			label1.Text = "Primer Label";
			AutoColumn.SetContent(0, 0, label1);

			ILabel label2 = Core.BaitAndSwitch.Create<ILabel>();
			label2.Name = "label2";
			label2.Text = "Segundo label";
			AutoColumn.SetContent(1, 0, label2);

			ILabel label3 = Core.BaitAndSwitch.Create<ILabel>();
			label3.Name = "label3";
			label3.Text = "Tercer label";
			AutoColumn.SetContent(2, 0, label1);

			ILabel label4 = Core.BaitAndSwitch.Create<ILabel>();
			label4.Name = "label4";
			label4.Text = "Cuarto label";
			AutoColumn.SetContent(3, 0, label4);

			ITextBox text1 = Core.BaitAndSwitch.Create<ITextBox>();
			text1.Name = "text1";
			text1.Value = "Primer textbox";
			AutoColumn.SetContent(0, 1, text1);

			ITextBox text2 = Core.BaitAndSwitch.Create<ITextBox>();
			text2.Name = "text2";
			text2.Value = "Segudo textbox";
			AutoColumn.SetContent(1, 1, text2);

			ITextBox text3 = Core.BaitAndSwitch.Create<ITextBox>();
			text3.Name = "text3";
			text3.Value = "Tercer textbox";
			AutoColumn.SetContent(2, 1, text3);

			ITextBox text4 = Core.BaitAndSwitch.Create<ITextBox>();
			text4.Name = "text4";
			text4.Value = "cuarto textbox";
			AutoColumn.SetContent(3, 1, text4);

			IButton button1 = Core.BaitAndSwitch.Create<IButton>();
			button1.Name = "button1";
			button1.Text = "Primer boton";
			AutoColumn.SetContent(2, 2, button1);

			IButton button2 = Core.BaitAndSwitch.Create<IButton>();
			button2.Name = "button2";
			button2.Text = "Segundo boton";
			AutoColumn.SetContent(2, 3, button2);

			IButton button3 = Core.BaitAndSwitch.Create<IButton>();
			button3.Name = "button3";
			button3.Text = "Tercer boton";
			AutoColumn.SetContent(3, 2, button3);

			IButton button4 = Core.BaitAndSwitch.Create<IButton>();
			button4.Name = "button4";
			button4.Text = "Cuarto boton";
			AutoColumn.SetContent(3, 3, button4);

			ILabel lblGridAutoColumnAndAutoRow = Core.BaitAndSwitch.Create<ILabel>();
			lblGridAutoColumnAndAutoRow.Text = "***************grid-auto-column-and-auto-row***************";
			StackPrincipal.Children.Add(lblGridAutoColumnAndAutoRow);

			IGrid AutoColumnAutoColumn = Core.BaitAndSwitch.Create<IGrid>();
			AutoColumnAutoColumn.Name = "AutoColumnAndAutoRow";
			AutoColumnAutoColumn.ColumnCount = 4;
			AutoColumnAutoColumn.RowCount = 4;
			StackPrincipal.Children.Add(AutoColumnAutoColumn);

			ILabel label1l = Core.BaitAndSwitch.Create<ILabel>();
			label1l.Name = "label1l";
			label1l.Text = "Primer Label";
			AutoColumnAutoColumn.SetContent(0, 0, label1l);

			ILabel label2l = Core.BaitAndSwitch.Create<ILabel>();
			label2l.Name = "label2l";
			label2l.Text = "Segundo label";
			AutoColumnAutoColumn.SetContent(1, 0, label2l);

			ILabel label3l = Core.BaitAndSwitch.Create<ILabel>();
			label3l.Name = "label3l";
			label3l.Text = "Tercer label";
			AutoColumnAutoColumn.SetContent(2, 0, label1l);

			ILabel label4l = Core.BaitAndSwitch.Create<ILabel>();
			label4l.Name = "label4l";
			label4l.Text = "Cuarto label";
			AutoColumnAutoColumn.SetContent(3, 0, label4l);

			ITextBox text1t = Core.BaitAndSwitch.Create<ITextBox>();
			text1t.Name = "txt1t";
			text1t.Value = "Primer textbox";
			AutoColumnAutoColumn.SetContent(0, 1, text1t);

			ITextBox text2t = Core.BaitAndSwitch.Create<ITextBox>();
			text2t.Name = "text2t";
			text2t.Value = "Segudo textbox";
			AutoColumnAutoColumn.SetContent(1, 1, text2t);

			ITextBox text3t = Core.BaitAndSwitch.Create<ITextBox>();
			text3t.Name = "txt3t";
			text3t.Value = "Tercer textbox";
			AutoColumnAutoColumn.SetContent(2, 1, text3t);

			ITextBox text4t = Core.BaitAndSwitch.Create<ITextBox>();
			text4t.Name = "txt4t";
			text4t.Value = "cuarto textbox";
			AutoColumnAutoColumn.SetContent(3, 1, text4t);

			IButton button1b = Core.BaitAndSwitch.Create<IButton>();
			button1b.Name = "button1b";
			button1b.Text = "Primer boton";
			AutoColumnAutoColumn.SetContent(2, 2, button1b);

			IButton button2b = Core.BaitAndSwitch.Create<IButton>();
			button2b.Name = "button2b";
			button2b.Text = "Segundo boton";
			AutoColumnAutoColumn.SetContent(2, 3, button2b);

			IButton button3b = Core.BaitAndSwitch.Create<IButton>();
			button3b.Name = "button3b";
			button3b.Text = "Tercer boton";
			AutoColumnAutoColumn.SetContent(3, 2, button3b);

			IButton button4b = Core.BaitAndSwitch.Create<IButton>();
			button4b.Name = "btn4b";
			button4b.Text = "Cuarto botn";
			AutoColumnAutoColumn.SetContent(3, 3, button4b);

			Page.Title = "grid-template";
			Page.Content = StackPrincipal;

			CSS.Style style = new CSS.Style();
			style.Parse(@"

				#AutoRow
					{
						display: grid;
						grid-template-rows: 40px 40px 40px;
						grid-auto-rows: 50px;

					}

				#AutoColumn
					{
						display: grid;
						grid-template-columns: 80px 80px;
						grid-auto-columns: 120px;
					}

				#AutoColumnAndAutoRow
					{
						display: grid;
						grid-template-rows: 40px 40px 40px;
						grid-auto-rows: 50px;
						grid-template-columns: 80px 80px;
						grid-auto-columns: 120px;
					}

			");
			style.Apply(Page);
		}

		private void btnExit_Click(object sender, EventArgs e)
		{
			this.Finish();
		}

	}
}


text:
.class public final Lcom/payu/android/sdk/internal/dv;
.super Ljava/lang/Object;

# direct methods
.method public constructor <init>()V
    .locals 0

    .line 8
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static a(Ljava/lang/String;)Ljava/lang/String;
    .locals 2

    .line 11
    invoke-static {}, Lcom/payu/android/sdk/internal/vg;->b()Lcom/payu/android/sdk/internal/ve;

    move-result-object v0

    invoke-interface {v0}, Lcom/payu/android/sdk/internal/ve;->a()Lcom/payu/android/sdk/internal/vf;

    move-result-object v0

    sget-object v1, Lcom/payu/android/sdk/internal/sq;->c:Ljava/nio/charset/Charset;

    invoke-interface {v0, p0, v1}, Lcom/payu/android/sdk/internal/vf;->a(Ljava/lang/CharSequence;Ljava/nio/charset/Charset;)Lcom/payu/android/sdk/internal/vf;

    move-result-object v0

    invoke-interface {v0}, Lcom/payu/android/sdk/internal/vf;->a()Lcom/payu/android/sdk/internal/vd;

    move-result-object v0

    invoke-virtual {v0}, Lcom/payu/android/sdk/internal/vd;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method


text:
package de.tudarmstadt.lt.utilities.collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 *
 * @author Steffen Remus
 *
 * @param <E>
 */
public class TreeBag<E> extends TreeMap<E, Integer> implements Bag<E> {

	private static final long serialVersionUID = -4846894099215164962L;

	public TreeBag() {
		super();
	}

	public TreeBag(Comparator<? super E> comparator) {
		super(comparator);
	}

	public TreeBag(Map<? extends E, ? extends Integer> m) {
		super(m);
	}

	public TreeBag(SortedMap<E, ? extends Integer> m) {
		super(m);
	}

	@Override
	public Integer add(E e) {
		Integer quant = get(e);
		if(quant == null)
			quant = Integer.valueOf(0);
		quant += 1;
		put(e, quant);
		return quant;
	}

	@Override
	public Integer removeOne(E e) {
		Integer quant = get(e);
		if(quant == null)
			return Integer.valueOf(0);
		quant -= 1;
		if(quant.equals(Integer.valueOf(0)))
			remove(e);
		else
			put(e, quant);
		return quant;
	}

	@Override
	public Integer removeAll(E e) {
		return remove(e);
	}

	@Override
	public List<Entry<E,Integer>> entrySetSortedbyQuantity(boolean decreasing){
		List<Entry<E, Integer>> sortedbyQuantity = new ArrayList<Entry<E, Integer>>(entrySet());
		Collections.sort(sortedbyQuantity, decreasing ? decreasingQuantityComparator : increasingQuantityComparator);
		return sortedbyQuantity;
	}

	@Override
	public Integer getQuantity(E e) {
		Integer r = get(e);
		return r == null ? Integer.valueOf(0) : r;
	}

}


text:
from __future__ import absolute_import

import copy
import json

import pytest
import requests_mock
from six import StringIO

from databasin.client import Client
from databasin.exceptions import LoginRequiredError
from .utils import make_api_key_callback

try:
    from unittest import mock  # Py3
except ImportError:
    import mock  # Py2

try:
    import __builtin__ as builtins
except ImportError:
    import builtins

@pytest.fixture
def tmp_file_data():
    return {
        'uuid': '1234',
        'date': '2015-11-17T22:42:06+00:00',
        'is_image': False,
        'filename': '',
        'url': 'https://example.com/file.txt'
    }

def test_temporary_file_upload(tmp_file_data):
    with requests_mock.mock() as m:
        m.post('https://databasin.org/uploads/upload-temporary-file/', text=json.dumps({'uuid': '1234'}))
        m.get('https://databasin.org/api/v1/uploads/temporary-files/1234/', text=json.dumps(tmp_file_data))

        c = Client()
        c._session.cookies['csrftoken'] = 'abcd'
        tmp_file = c.upload_temporary_file(StringIO('foo'))

        assert tmp_file.uuid == '1234'
        assert tmp_file.filename == ''
        assert m.call_count == 2

def test_temporary_file_upload_login_required():
    with requests_mock.mock() as m:
        m.post('https://databasin.org/uploads/upload-temporary-file/', status_code=401)

        c = Client()
        c._session.cookies['csrftoken'] = 'abcd'

        with pytest.raises(LoginRequiredError):
            c.upload_temporary_file(StringIO('foo'))

def test_temporary_file_upload_with_api_key(tmp_file_data):
    key = 'abcde12345'

    with requests_mock.mock() as m:
        m.post(
            'https://databasin.org/uploads/upload-temporary-file/',
            text=make_api_key_callback(json.dumps({'uuid': '1234'}), key)
        )
        m.get('https://databasin.org/api/v1/uploads/temporary-files/1234/', text=json.dumps(tmp_file_data))

        c = Client()
        c.set_api_key('user', key)
        c._session.cookies['csrftoken'] = 'abcd'
        tmp_file = c.upload_temporary_file(StringIO('foo'))

        assert tmp_file.uuid == '1234'
        assert tmp_file.filename == ''
        assert m.call_count == 2

def test_temporary_file_upload_from_path(tmp_file_data):
    with requests_mock.mock() as m:
        m.post('https://databasin.org/uploads/upload-temporary-file/', text=json.dumps({'uuid': '1234'}))
        m.get('https://databasin.org/api/v1/uploads/temporary-files/1234/', text=json.dumps(tmp_file_data))

        with mock.patch.object(builtins, 'open', mock.mock_open(read_data='foo')) as open_mock:
            c = Client()
            c._session.cookies['csrftoken'] = 'abcd'
            tmp_file = c.upload_temporary_file('/path/to/foo.txt')

            assert tmp_file.uuid == '1234'
            open_mock.assert_called_once_with('/path/to/foo.txt', 'rb')
            assert 'filename="foo.txt"' in str(m.request_history[0].body)

def test_temporary_file_upload_from_path_with_api_key(tmp_file_data):
    key = 'abcde12345'

    with requests_mock.mock() as m:
        m.post(
            'https://databasin.org/uploads/upload-temporary-file/',
            text=make_api_key_callback(json.dumps({'uuid': '1234'}), key)
        )
        m.get(
            'https://databasin.org/api/v1/uploads/temporary-files/1234/',
            text=make_api_key_callback(json.dumps(tmp_file_data), key)
        )

        with mock.patch.object(builtins, 'open', mock.mock_open(read_data='foo')) as open_mock:
            c = Client()
            c.set_api_key('user', key)
            c._session.cookies['csrftoken'] = 'abcd'
            tmp_file = c.upload_temporary_file('/path/to/foo.txt')

            assert tmp_file.uuid == '1234'
            open_mock.assert_called_once_with('/path/to/foo.txt', 'rb')
            assert 'filename="foo.txt"' in str(m.request_history[0].body)

def test_get_temporary_file(tmp_file_data):
    with requests_mock.mock() as m:
        m.get('https://databasin.org/api/v1/uploads/temporary-files/1234/', text=json.dumps(tmp_file_data))

        c = Client()
        tmp_file = c.get_temporary_file('1234')

        assert m.called
        assert tmp_file.uuid == '1234'

def test_get_temporary_file_login_required(tmp_file_data):
    with requests_mock.mock() as m:
        m.get('https://databasin.org/api/v1/uploads/temporary-files/1234/', status_code=401)

        c = Client()

        with pytest.raises(LoginRequiredError):
            tmp_file = c.get_temporary_file('1234')

def test_get_temporary_file_with_api_key(tmp_file_data):
    key = 'abcde12345'

    with requests_mock.mock() as m:
        m.get(
            'https://databasin.org/api/v1/uploads/temporary-files/1234/',
            text=make_api_key_callback(json.dumps(tmp_file_data), key)
        )

        c = Client()
        c.set_api_key('user', key)
        tmp_file = c.get_temporary_file('1234')

        assert m.called
        assert tmp_file.uuid == '1234'

def test_list_temporary_files(tmp_file_data):
    data = {
        'meta': {'next': None, 'total_count': 2},
        'objects': [
            tmp_file_data,
            copy.copy(tmp_file_data)
        ]
    }
    data['objects'][1]['uuid'] = 1235

    with requests_mock.mock() as m:
        m.get('https://databasin.org/api/v1/uploads/temporary-files/', text=json.dumps(data))

        c = Client()
        tmp_files = c.list_temporary_files()

        assert len(tmp_files) == 2
        tmp_files = list(tmp_files)
        assert tmp_files[0].uuid == '1234'
        assert tmp_files[1].uuid == '1235'

def test_list_temporary_files_with_api_key(tmp_file_data):
    key = 'abcde12345'
    data = {
        'meta': {'next': None, 'total_count': 2},
        'objects': [
            tmp_file_data,
            copy.copy(tmp_file_data)
        ]
    }
    data['objects'][1]['uuid'] = 1235

    with requests_mock.mock() as m:
        m.get(
            'https://databasin.org/api/v1/uploads/temporary-files/',
            text=make_api_key_callback(json.dumps(data), key)
        )

        c = Client()
        c.set_api_key('user', key)
        tmp_files = c.list_temporary_files()

        assert len(tmp_files) == 2
        tmp_files = list(tmp_files)
        assert tmp_files[0].uuid == '1234'
        assert tmp_files[1].uuid == '1235'


text:
package org.openestate.io.immobiliare_it.xml;

import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for status.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="status">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="in costruzione"/>
 *     <enumeration value="nuovo"/>
 *     <enumeration value="abitabile"/>
 *     <enumeration value="ottimo"/>
 *     <enumeration value="buono"/>
 *     <enumeration value="ristrutturato"/>
 *     <enumeration value="da ristrutturare"/>
 *     <enumeration value="discreto"/>
 *     <enumeration value="nd"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "status")
@XmlEnum
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public enum StatusType {

    @XmlEnumValue("in costruzione")
    IN_COSTRUZIONE("in costruzione"),
    @XmlEnumValue("nuovo")
    NUOVO("nuovo"),
    @XmlEnumValue("abitabile")
    ABITABILE("abitabile"),
    @XmlEnumValue("ottimo")
    OTTIMO("ottimo"),
    @XmlEnumValue("buono")
    BUONO("buono"),
    @XmlEnumValue("ristrutturato")
    RISTRUTTURATO("ristrutturato"),
    @XmlEnumValue("da ristrutturare")
    DA_RISTRUTTURARE("da ristrutturare"),
    @XmlEnumValue("discreto")
    DISCRETO("discreto"),
    @XmlEnumValue("nd")
    ND("nd");
    private final String value;

    StatusType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static StatusType fromValue(String v) {
        for (StatusType c: StatusType.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
[![Gem Version](https://badge.fury.io/rb/movie_show_times.png)](http://badge.fury.io/rb/movie_show_times)
[![Code Climate](https://codeclimate.com/github/chrishein/movie_show_times.png)](https://codeclimate.com/github/chrishein/movie_show_times)

Get Movies Show Times for all theaters near a given location.

The gem crawls and parses Google Movies pages.

## Installation

Add this line to your application's Gemfile:

    gem 'movie_show_times'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install movie_show_times

## Usage

* <tt>:location</tt> (required string) name of city, town, location
* <tt>:language</tt> (optional string) language code, like en, es, de, fr.
* <tt>:days\_ahead</tt> (optional integer) number of days after today for which to get show times

A location is required to initialize the crawling. By default, it gets show times for the current date in English.

    movieShowTimes = MovieShowTimes::Crawler.new({ :location => 'Buenos Aires' })

    theater = movieShowTimes.theaters['Monumental']
    puts theater # => { :name => 'Monumental', :info => 'Lavalle 780, Buenos Aires, Argentina - 0-11-4393-9008',
                        :movies => [ ... ]
                      }

    puts theater[:movies][0] # => {		:name => 'Titanic 3D',
                                       	:info => { 	:duration => 10814,
													:language => 'English',
													:genre => 'Action/Adventure/Drama'
												}
                                       	:times => ['1:30pm', '5:30pm', '9:30pm', '1:00am']
                                     }

You can retrieve movie show times for following days. There is no definition for how far in the future will this information be available, so use with caution as it may be the cause for retrieving no show times at all.

    movieShowTimes = MovieShowTimes::Crawler.new({ 	:location => 'Buenos Aires',
													:days_ahead => 2
 												})

Getting show times info in Spanish:

    movieShowTimes = MovieShowTimes::Crawler.new({
													:location => 'Buenos Aires',
													:language => 'es'
												})

	puts theater[:movies][0] # => { :name => 'Titanic 3D',
                                    :info => {
												:duration => 10814,
												:language => 'English',
												:genre => 'Acción/Aventura/Drama'
											}
                                       :times => ['13:30', '17:30', '21:30', '01:00']
                                     }

## TODO

Improve API

Include more movie info from other data sources

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## License

Copyright © 2012 Christian Hein, released under the MIT license


text:
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------

namespace System.ServiceModel.Description
{
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Net.Security;
    using System.Reflection;
    using System.ServiceModel.Security;

    [DebuggerDisplay("Name={name}, Namespace={ns}, Type={Type}, Index={index}}")]
    public class MessagePartDescription
    {
        XmlName name;
        string ns;
        int index;
        Type type;
        int serializationPosition;
        ProtectionLevel protectionLevel;
        bool hasProtectionLevel;
        MemberInfo memberInfo;
        ICustomAttributeProvider additionalAttributesProvider;

        bool multiple;
        string baseType;
        string uniquePartName;

        public MessagePartDescription(string name, string ns)
        {
            if (name == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name", SR.GetString(SR.SFxParameterNameCannotBeNull));
            }

            this.name = new XmlName(name, true /*isEncoded*/);

            if (!string.IsNullOrEmpty(ns))
            {
                NamingHelper.CheckUriParameter(ns, "ns");
            }

            this.ns = ns;
        }

        internal MessagePartDescription(MessagePartDescription other)
        {
            this.name = other.name;
            this.ns = other.ns;
            this.index = other.index;
            this.type = other.type;
            this.serializationPosition = other.serializationPosition;
            this.hasProtectionLevel = other.hasProtectionLevel;
            this.protectionLevel = other.protectionLevel;
            this.memberInfo = other.memberInfo;
            this.multiple = other.multiple;
            this.additionalAttributesProvider = other.additionalAttributesProvider;
            this.baseType = other.baseType;
            this.uniquePartName = other.uniquePartName;
        }

        internal virtual MessagePartDescription Clone()
        {
            return new MessagePartDescription(this);
        }

        internal string BaseType
        {
            get { return this.baseType; }
            set { this.baseType = value; }
        }

        internal XmlName XmlName
        {
            get { return this.name; }
        }

        internal string CodeName
        {
            get { return this.name.DecodedName; }
        }

        public string Name
        {
            get { return this.name.EncodedName; }
        }

        public string Namespace
        {
            get { return this.ns; }
        }

        public Type Type
        {
            get { return type; }
            set { type = value; }
        }

        public int Index
        {
            get { return index; }
            set { index = value; }
        }

        [DefaultValue(false)]
        public bool Multiple
        {
            get { return this.multiple; }
            set { this.multiple = value; }
        }

        public ProtectionLevel ProtectionLevel
        {
            get { return this.protectionLevel; }
            set
            {
                if (!ProtectionLevelHelper.IsDefined(value))
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
                this.protectionLevel = value;
                this.hasProtectionLevel = true;
            }
        }

        public bool HasProtectionLevel
        {
            get { return this.hasProtectionLevel; }
        }

        public MemberInfo MemberInfo
        {
            get { return this.memberInfo; }
            set { this.memberInfo = value; }
        }

        internal ICustomAttributeProvider AdditionalAttributesProvider
        {
            get { return this.additionalAttributesProvider ?? this.memberInfo; }
            set { this.additionalAttributesProvider = value; }
        }

        internal string UniquePartName
        {
            get { return this.uniquePartName; }
            set { this.uniquePartName = value; }
        }

        internal int SerializationPosition
        {
            get { return serializationPosition; }
            set { serializationPosition = value; }
        }

        internal void ResetProtectionLevel()
        {
            this.protectionLevel = ProtectionLevel.None;
            this.hasProtectionLevel = false;
        }
    }
}


text:
var fs = require('fs'),
    chld = require('child_process'),
    red, yellow, green;

function gpio_export(pin, direction, callback) {
    function done () {
        fs.writeFile('/sys/class/gpio/gpio' + pin + '/direction', direction,
                     callback);
    }
    fs.exists('/sys/class/gpio/gpio' + pin, function(exists) {
        if (!exists) {
            fs.writeFile('/sys/class/gpio/export', pin,
                function(error) {
                    if(error) {
                        throw error;
                    }
                    done();
                });
            return;
        }
        done();
    });
    return pin;
}

function set(pin, value) {
    var val = value ? '1': '0';
    fs.writeFile('/sys/class/gpio/gpio' + pin + '/value', val,
        function(err){
            if (err) {
                throw err;
            }
    });
}

function init(callback) {
    red = gpio_export(17, 'out', function() {
        yellow = gpio_export(27, 'out', function() {
            green = gpio_export(22, 'out', function() {
                if (typeof callback === 'function') {
                    callback();
                }
            });
        });
    });
}

function setGreen() {
    set(red, 0);
    set(yellow, 0);
    set(green, 1);
}

function setYellow() {
    set(red, 0);
    set(yellow, 1);
    set(green, 0);
}

function setRed() {
    set(red, 1);
    set(yellow, 0);
    set(green, 0);
}

exports.init = init;
exports.setGreen = setGreen;
exports.setYellow = setYellow;
exports.setRed = setRed;


text:
package org.modeshape.jcr.perftests.read;

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.modeshape.jcr.perftests.AbstractPerformanceTestSuite;
import org.modeshape.jcr.perftests.SuiteConfiguration;
import org.modeshape.jcr.perftests.util.BinaryHelper;
import org.modeshape.jcr.perftests.util.BinaryImpl;
import java.util.Calendar;

/**
 * Performance test which reads repeatedly several nodes which represent small files.
 */
public class SmallFileReadTestSuite extends AbstractPerformanceTestSuite {

    private static final int FILE_SIZE_MB = 10 * 1024;

    private Session session;
    private Node root;
    private int fileCount;

    public SmallFileReadTestSuite( SuiteConfiguration suiteConfiguration ) {
        super(suiteConfiguration);
    }

    @Override
    public void beforeSuite() throws RepositoryException {
        fileCount = suiteConfiguration.getNodeCount();
        session = newSession();

        root = session.getRootNode().addNode("SmallFileReadTestSuite", "nt:folder");
        for (int i = 0; i < fileCount; i++) {
            Node file = root.addNode("file" + i, "nt:file");
            Node content = file.addNode("jcr:content", "nt:resource");
            content.setProperty("jcr:mimeType", "application/octet-stream");
            content.setProperty("jcr:lastModified", Calendar.getInstance());
            content.setProperty("jcr:data", new BinaryImpl(FILE_SIZE_MB));
        }
        session.save();
    }

    @Override
    public void runTest() throws Exception {
        for (int i = 0; i < fileCount; i++) {
            Node file = root.getNode("file" + i);
            Node content = file.getNode("jcr:content");
            BinaryHelper.assertExpectedSize(content.getProperty("jcr:data").getBinary(), FILE_SIZE_MB);
        }
    }

    @Override
    public void afterSuite() throws RepositoryException {
        root.remove();
        session.save();
        session.logout();
    }
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const NS_DOWNLOADHISTORY_CID = "{2ee83680-2af0-4bcb-bfa0-c9705f6554f1}";

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyGetter(this, "Services", function() {
  Components.utils.import("resource://gre/modules/Services.jsm");
  return Services;
});

function testLinkVistedObserver()
{
  const NS_LINK_VISITED_EVENT_TOPIC = "link-visited";
  var ios = Cc["@mozilla.org/network/io-service;1"].
            getService(Ci.nsIIOService);
  var testURI = ios.newURI("http://google.com/", null, null);

  var gh = Cc["@mozilla.org/browser/global-history;2"].
           getService(Ci.nsIGlobalHistory2);
  do_check_false(gh.isVisited(testURI));

  var topicReceived = false;
  var obs = {
    observe: function tlvo_observe(aSubject, aTopic, aData)
    {
      if (NS_LINK_VISITED_EVENT_TOPIC == aTopic) {
        do_check_eq(testURI, aSubject);
        topicReceived = true;
      }
    }
  };

  var os = Cc["@mozilla.org/observer-service;1"].
           getService(Ci.nsIObserverService);
  os.addObserver(obs, NS_LINK_VISITED_EVENT_TOPIC, false);

  var dh = Components.classesByID[NS_DOWNLOADHISTORY_CID].
           getService(Ci.nsIDownloadHistory);
  dh.addDownload(testURI);
  do_check_true(topicReceived);
  do_check_true(gh.isVisited(testURI));
}

var tests = [testLinkVistedObserver];

function run_test()
{
  // Not everyone uses/defines an nsGlobalHistory* service. Especially if
  // MOZ_PLACES is not defined. If getService fails, then abort gracefully.
  try {
    Cc["@mozilla.org/browser/global-history;2"].
      getService(Ci.nsIGlobalHistory2);
  }
  catch (ex) {
    return;
  }

  // Needed to properly setup and shutdown the profile.
  do_get_profile();

  Services.prefs.setBoolPref("places.history.enabled", true);

  for (var i = 0; i < tests.length; i++)
    tests[i]();

  cleanup();
}


text:
#include "config.h"
#include "CSSGradientValue.h"

#include "CSSCalculationValue.h"
#include "CSSValueKeywords.h"
#include "GeneratorGeneratedImage.h"
#include "Gradient.h"
#include "Image.h"
#include "IntSize.h"
#include "IntSizeHash.h"
#include "NodeRenderStyle.h"
#include "RenderObject.h"
#include "StyleResolver.h"
#include "WebCoreMemoryInstrumentation.h"
#include <wtf/MemoryInstrumentationVector.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/WTFString.h>

using namespace std;

namespace WebCore {

void CSSGradientColorStop::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
{
    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
    info.addMember(m_position);
    info.addMember(m_color);
}

PassRefPtr<Image> CSSGradientValue::image(RenderObject* renderer, const IntSize& size)
{
    if (size.isEmpty())
        return 0;

    bool cacheable = isCacheable();
    if (cacheable) {
        if (!clients().contains(renderer))
            return 0;

        // Need to look up our size.  Create a string of width*height to use as a hash key.
        Image* result = getImage(renderer, size);
        if (result)
            return result;
    }

    // We need to create an image.
    RefPtr<Gradient> gradient;

    if (isLinearGradient())
        gradient = static_cast<CSSLinearGradientValue*>(this)->createGradient(renderer, size);
    else {
        ASSERT(isRadialGradient());
        gradient = static_cast<CSSRadialGradientValue*>(this)->createGradient(renderer, size);
    }

    RefPtr<Image> newImage = GeneratorGeneratedImage::create(gradient, size);
    if (cacheable)
        putImage(size, newImage);

    return newImage.release();
}

// Should only ever be called for deprecated gradients.
static inline bool compareStops(const CSSGradientColorStop& a, const CSSGradientColorStop& b)
{
    double aVal = a.m_position->getDoubleValue(CSSPrimitiveValue::CSS_NUMBER);
    double bVal = b.m_position->getDoubleValue(CSSPrimitiveValue::CSS_NUMBER);

    return aVal < bVal;
}

void CSSGradientValue::sortStopsIfNeeded()
{
    ASSERT(m_deprecatedType);
    if (!m_stopsSorted) {
        if (m_stops.size())
            std::stable_sort(m_stops.begin(), m_stops.end(), compareStops);
        m_stopsSorted = true;
    }
}

struct GradientStop {
    Color color;
    float offset;
    bool specified;

    GradientStop()
        : offset(0)
        , specified(false)
    { }
};

PassRefPtr<CSSGradientValue> CSSGradientValue::gradientWithStylesResolved(StyleResolver* styleResolver)
{
    bool derived = false;
    for (unsigned i = 0; i < m_stops.size(); i++)
        if (styleResolver->colorFromPrimitiveValueIsDerivedFromElement(m_stops[i].m_color.get())) {
            m_stops[i].m_colorIsDerivedFromElement = true;
            derived = true;
            break;
        }

    RefPtr<CSSGradientValue> result;
    if (!derived)
        result = this;
    else if (isLinearGradient())
        result = static_cast<CSSLinearGradientValue*>(this)->clone();
    else if (isRadialGradient())
        result = static_cast<CSSRadialGradientValue*>(this)->clone();
    else {
        ASSERT_NOT_REACHED();
        return 0;
    }

    for (unsigned i = 0; i < result->m_stops.size(); i++)
        result->m_stops[i].m_resolvedColor = styleResolver->colorFromPrimitiveValue(result->m_stops[i].m_color.get());

    return result.release();
}

void CSSGradientValue::addStops(Gradient* gradient, RenderObject* renderer, RenderStyle* rootStyle, float maxLengthForRepeat)
{
    RenderStyle* style = renderer->style();

    if (m_deprecatedType) {
        sortStopsIfNeeded();

        for (unsigned i = 0; i < m_stops.size(); i++) {
            const CSSGradientColorStop& stop = m_stops[i];

            float offset;
            if (stop.m_position->isPercentage())
                offset = stop.m_position->getFloatValue(CSSPrimitiveValue::CSS_PERCENTAGE) / 100;
            else
                offset = stop.m_position->getFloatValue(CSSPrimitiveValue::CSS_NUMBER);

            gradient->addColorStop(offset, stop.m_resolvedColor);
        }

        // The back end already sorted the stops.
        gradient->setStopsSorted(true);
        return;
    }

    size_t numStops = m_stops.size();

    Vector<GradientStop> stops(numStops);

    float gradientLength = 0;
    bool computedGradientLength = false;

    FloatPoint gradientStart = gradient->p0();
    FloatPoint gradientEnd;
    if (isLinearGradient())
        gradientEnd = gradient->p1();
    else if (isRadialGradient())
        gradientEnd = gradientStart + FloatSize(gradient->endRadius(), 0);

    for (size_t i = 0; i < numStops; ++i) {
        const CSSGradientColorStop& stop = m_stops[i];

        stops[i].color = stop.m_resolvedColor;

        if (stop.m_position) {
            if (stop.m_position->isPercentage())
                stops[i].offset = stop.m_position->getFloatValue(CSSPrimitiveValue::CSS_PERCENTAGE) / 100;
            else if (stop.m_position->isLength() || stop.m_position->isCalculatedPercentageWithLength()) {
                if (!computedGradientLength) {
                    FloatSize gradientSize(gradientStart - gradientEnd);
                    gradientLength = gradientSize.diagonalLength();
                }
                float length;
                if (stop.m_position->isLength())
                    length = stop.m_position->computeLength<float>(style, rootStyle, style->effectiveZoom());
                else
                    length = stop.m_position->cssCalcValue()->toCalcValue(style, rootStyle, style->effectiveZoom())->evaluate(gradientLength);
                stops[i].offset = (gradientLength > 0) ? length / gradientLength : 0;
            } else {
                ASSERT_NOT_REACHED();
                stops[i].offset = 0;
            }
            stops[i].specified = true;
        } else {
            // If the first color-stop does not have a position, its position defaults to 0%.
            // If the last color-stop does not have a position, its position defaults to 100%.
            if (!i) {
                stops[i].offset = 0;
                stops[i].specified = true;
            } else if (numStops > 1 && i == numStops - 1) {
                stops[i].offset = 1;
                stops[i].specified = true;
            }
        }

        // If a color-stop has a position that is less than the specified position of any
        // color-stop before it in the list, its position is changed to be equal to the
        // largest specified position of any color-stop before it.
        if (stops[i].specified && i > 0) {
            size_t prevSpecifiedIndex;
            for (prevSpecifiedIndex = i - 1; prevSpecifiedIndex; --prevSpecifiedIndex) {
                if (stops[prevSpecifiedIndex].specified)
                    break;
            }

            if (stops[i].offset < stops[prevSpecifiedIndex].offset)
                stops[i].offset = stops[prevSpecifiedIndex].offset;
        }
    }

    ASSERT(stops[0].specified && stops[numStops - 1].specified);

    // If any color-stop still does not have a position, then, for each run of adjacent
    // color-stops without positions, set their positions so that they are evenly spaced
    // between the preceding and following color-stops with positions.
    if (numStops > 2) {
        size_t unspecifiedRunStart = 0;
        bool inUnspecifiedRun = false;

        for (size_t i = 0; i < numStops; ++i) {
            if (!stops[i].specified && !inUnspecifiedRun) {
                unspecifiedRunStart = i;
                inUnspecifiedRun = true;
            } else if (stops[i].specified && inUnspecifiedRun) {
                size_t unspecifiedRunEnd = i;

                if (unspecifiedRunStart < unspecifiedRunEnd) {
                    float lastSpecifiedOffset = stops[unspecifiedRunStart - 1].offset;
                    float nextSpecifiedOffset = stops[unspecifiedRunEnd].offset;
                    float delta = (nextSpecifiedOffset - lastSpecifiedOffset) / (unspecifiedRunEnd - unspecifiedRunStart + 1);

                    for (size_t j = unspecifiedRunStart; j < unspecifiedRunEnd; ++j)
                        stops[j].offset = lastSpecifiedOffset + (j - unspecifiedRunStart + 1) * delta;
                }

                inUnspecifiedRun = false;
            }
        }
    }

    // If the gradient is repeating, repeat the color stops.
    // We can't just push this logic down into the platform-specific Gradient code,
    // because we have to know the extent of the gradient, and possible move the end points.
    if (m_repeating && numStops > 1) {
        // If the difference in the positions of the first and last color-stops is 0,
        // the gradient defines a solid-color image with the color of the last color-stop in the rule.
        float gradientRange = stops[numStops - 1].offset - stops[0].offset;
        if (!gradientRange) {
            stops.first().offset = 0;
            stops.first().color = stops.last().color;
            stops.shrink(1);
            numStops = 1;
        } else {
            float maxExtent = 1;

            // Radial gradients may need to extend further than the endpoints, because they have
            // to repeat out to the corners of the box.
            if (isRadialGradient()) {
                if (!computedGradientLength) {
                    FloatSize gradientSize(gradientStart - gradientEnd);
                    gradientLength = gradientSize.diagonalLength();
                }

                if (maxLengthForRepeat > gradientLength)
                    maxExtent = maxLengthForRepeat / gradientLength;
            }

            size_t originalNumStops = numStops;
            size_t originalFirstStopIndex = 0;

            // Work backwards from the first, adding stops until we get one before 0.
            float firstOffset = stops[0].offset;
            if (firstOffset > 0) {
                float currOffset = firstOffset;
                size_t srcStopOrdinal = originalNumStops - 1;

                while (true) {
                    GradientStop newStop = stops[originalFirstStopIndex + srcStopOrdinal];
                    newStop.offset = currOffset;
                    stops.prepend(newStop);
                    ++originalFirstStopIndex;
                    if (currOffset < 0)
                        break;

                    if (srcStopOrdinal)
                        currOffset -= stops[originalFirstStopIndex + srcStopOrdinal].offset - stops[originalFirstStopIndex + srcStopOrdinal - 1].offset;
                    srcStopOrdinal = (srcStopOrdinal + originalNumStops - 1) % originalNumStops;
                }
            }

            // Work forwards from the end, adding stops until we get one after 1.
            float lastOffset = stops[stops.size() - 1].offset;
            if (lastOffset < maxExtent) {
                float currOffset = lastOffset;
                size_t srcStopOrdinal = 0;

                while (true) {
                    size_t srcStopIndex = originalFirstStopIndex + srcStopOrdinal;
                    GradientStop newStop = stops[srcStopIndex];
                    newStop.offset = currOffset;
                    stops.append(newStop);
                    if (currOffset > maxExtent)
                        break;
                    if (srcStopOrdinal < originalNumStops - 1)
                        currOffset += stops[srcStopIndex + 1].offset - stops[srcStopIndex].offset;
                    srcStopOrdinal = (srcStopOrdinal + 1) % originalNumStops;
                }
            }
        }
    }

    numStops = stops.size();

    // If the gradient goes outside the 0-1 range, normalize it by moving the endpoints, and adjusting the stops.
    if (numStops > 1 && (stops[0].offset < 0 || stops[numStops - 1].offset > 1)) {
        if (isLinearGradient()) {
            float firstOffset = stops[0].offset;
            float lastOffset = stops[numStops - 1].offset;
            float scale = lastOffset - firstOffset;

            for (size_t i = 0; i < numStops; ++i)
                stops[i].offset = (stops[i].offset - firstOffset) / scale;

            FloatPoint p0 = gradient->p0();
            FloatPoint p1 = gradient->p1();
            gradient->setP0(FloatPoint(p0.x() + firstOffset * (p1.x() - p0.x()), p0.y() + firstOffset * (p1.y() - p0.y())));
            gradient->setP1(FloatPoint(p1.x() + (lastOffset - 1) * (p1.x() - p0.x()), p1.y() + (lastOffset - 1) * (p1.y() - p0.y())));
        } else if (isRadialGradient()) {
            // Rather than scaling the points < 0, we truncate them, so only scale according to the largest point.
            float firstOffset = 0;
            float lastOffset = stops[numStops - 1].offset;
            float scale = lastOffset - firstOffset;

            // Reset points below 0 to the first visible color.
            size_t firstZeroOrGreaterIndex = numStops;
            for (size_t i = 0; i < numStops; ++i) {
                if (stops[i].offset >= 0) {
                    firstZeroOrGreaterIndex = i;
                    break;
                }
            }

            if (firstZeroOrGreaterIndex > 0) {
                if (firstZeroOrGreaterIndex < numStops && stops[firstZeroOrGreaterIndex].offset > 0) {
                    float prevOffset = stops[firstZeroOrGreaterIndex - 1].offset;
                    float nextOffset = stops[firstZeroOrGreaterIndex].offset;

                    float interStopProportion = -prevOffset / (nextOffset - prevOffset);
                    // FIXME: when we interpolate gradients using premultiplied colors, this should do premultiplication.
                    Color blendedColor = blend(stops[firstZeroOrGreaterIndex - 1].color, stops[firstZeroOrGreaterIndex].color, interStopProportion);

                    // Clamp the positions to 0 and set the color.
                    for (size_t i = 0; i < firstZeroOrGreaterIndex; ++i) {
                        stops[i].offset = 0;
                        stops[i].color = blendedColor;
                    }
                } else {
                    // All stops are below 0; just clamp them.
                    for (size_t i = 0; i < firstZeroOrGreaterIndex; ++i)
                        stops[i].offset = 0;
                }
            }

            for (size_t i = 0; i < numStops; ++i)
                stops[i].offset /= scale;

            gradient->setStartRadius(gradient->startRadius() * scale);
            gradient->setEndRadius(gradient->endRadius() * scale);
        }
    }

    for (unsigned i = 0; i < numStops; i++)
        gradient->addColorStop(stops[i].offset, stops[i].color);

    gradient->setStopsSorted(true);
}

static float positionFromValue(CSSPrimitiveValue* value, RenderStyle* style, RenderStyle* rootStyle, const IntSize& size, bool isHorizontal)
{
    float zoomFactor = style->effectiveZoom();

    if (value->isNumber())
        return value->getFloatValue() * zoomFactor;

    int edgeDistance = isHorizontal ? size.width() : size.height();
    if (value->isPercentage())
        return value->getFloatValue() / 100.f * edgeDistance;

    if (value->isCalculatedPercentageWithLength())
        return value->cssCalcValue()->toCalcValue(style, rootStyle, style->effectiveZoom())->evaluate(edgeDistance);

    switch (value->getIdent()) {
    case CSSValueTop:
        ASSERT(!isHorizontal);
        return 0;
    case CSSValueLeft:
        ASSERT(isHorizontal);
        return 0;
    case CSSValueBottom:
        ASSERT(!isHorizontal);
        return size.height();
    case CSSValueRight:
        ASSERT(isHorizontal);
        return size.width();
    }

    return value->computeLength<float>(style, rootStyle, zoomFactor);
}

FloatPoint CSSGradientValue::computeEndPoint(CSSPrimitiveValue* first, CSSPrimitiveValue* second, RenderStyle* style, RenderStyle* rootStyle, const IntSize& size)
{
    FloatPoint result;

    if (first)
        result.setX(positionFromValue(first, style, rootStyle, size, true));

    if (second)
        result.setY(positionFromValue(second, style, rootStyle, size, false));

    return result;
}

bool CSSGradientValue::isCacheable() const
{
    for (size_t i = 0; i < m_stops.size(); ++i) {
        const CSSGradientColorStop& stop = m_stops[i];

        if (stop.m_colorIsDerivedFromElement)
            return false;

        if (!stop.m_position)
            continue;

        if (stop.m_position->isFontRelativeLength())
            return false;
    }

    return true;
}

void CSSGradientValue::reportBaseClassMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
{
    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
    CSSImageGeneratorValue::reportBaseClassMemoryUsage(memoryObjectInfo);
    info.addMember(m_firstX);
    info.addMember(m_firstY);
    info.addMember(m_secondX);
    info.addMember(m_secondY);
    info.addMember(m_stops);
}

String CSSLinearGradientValue::customCssText() const
{
    StringBuilder result;
    if (m_deprecatedType) {
        result.appendLiteral("-webkit-gradient(linear, ");
        result.append(m_firstX->cssText());
        result.append(' ');
        result.append(m_firstY->cssText());
        result.appendLiteral(", ");
        result.append(m_secondX->cssText());
        result.append(' ');
        result.append(m_secondY->cssText());

        for (unsigned i = 0; i < m_stops.size(); i++) {
            const CSSGradientColorStop& stop = m_stops[i];
            result.appendLiteral(", ");
            if (stop.m_position->getDoubleValue(CSSPrimitiveValue::CSS_NUMBER) == 0) {
                result.appendLiteral("from(");
                result.append(stop.m_color->cssText());
                result.append(')');
            } else if (stop.m_position->getDoubleValue(CSSPrimitiveValue::CSS_NUMBER) == 1) {
                result.appendLiteral("to(");
                result.append(stop.m_color->cssText());
                result.append(')');
            } else {
                result.appendLiteral("color-stop(");
                result.append(String::number(stop.m_position->getDoubleValue(CSSPrimitiveValue::CSS_NUMBER)));
                result.appendLiteral(", ");
                result.append(stop.m_color->cssText());
                result.append(')');
            }
        }
    } else {
        if (m_repeating)
            result.appendLiteral("-webkit-repeating-linear-gradient(");
        else
            result.appendLiteral("-webkit-linear-gradient(");

        if (m_angle)
            result.append(m_angle->cssText());
        else {
            if (m_firstX && m_firstY) {
                result.append(m_firstX->cssText());
                result.append(' ');
                result.append(m_firstY->cssText());
            } else if (m_firstX || m_firstY) {
                if (m_firstX)
                    result.append(m_firstX->cssText());

                if (m_firstY)
                    result.append(m_firstY->cssText());
            }
        }

        for (unsigned i = 0; i < m_stops.size(); i++) {
            const CSSGradientColorStop& stop = m_stops[i];
            result.appendLiteral(", ");
            result.append(stop.m_color->cssText());
            if (stop.m_position) {
                result.append(' ');
                result.append(stop.m_position->cssText());
            }
        }
    }

    result.append(')');
    return result.toString();
}

// Compute the endpoints so that a gradient of the given angle covers a box of the given size.
static void endPointsFromAngle(float angleDeg, const IntSize& size, FloatPoint& firstPoint, FloatPoint& secondPoint)
{
    angleDeg = fmodf(angleDeg, 360);
    if (angleDeg < 0)
        angleDeg += 360;

    if (!angleDeg) {
        firstPoint.set(0, 0);
        secondPoint.set(size.width(), 0);
        return;
    }

    if (angleDeg == 90) {
        firstPoint.set(0, size.height());
        secondPoint.set(0, 0);
        return;
    }

    if (angleDeg == 180) {
        firstPoint.set(size.width(), 0);
        secondPoint.set(0, 0);
        return;
    }

    if (angleDeg == 270) {
        firstPoint.set(0, 0);
        secondPoint.set(0, size.height());
        return;
    }

    float slope = tan(deg2rad(angleDeg));

    // We find the endpoint by computing the intersection of the line formed by the slope,
    // and a line perpendicular to it that intersects the corner.
    float perpendicularSlope = -1 / slope;

    // Compute start corner relative to center.
    float halfHeight = size.height() / 2;
    float halfWidth = size.width() / 2;
    FloatPoint endCorner;
    if (angleDeg < 90)
        endCorner.set(halfWidth, halfHeight);
    else if (angleDeg < 180)
        endCorner.set(-halfWidth, halfHeight);
    else if (angleDeg < 270)
        endCorner.set(-halfWidth, -halfHeight);
    else
        endCorner.set(halfWidth, -halfHeight);

    // Compute c (of y = mx + c) using the corner point.
    float c = endCorner.y() - perpendicularSlope * endCorner.x();
    float endX = c / (slope - perpendicularSlope);
    float endY = perpendicularSlope * endX + c;

    // We computed the end point, so set the second point, flipping the Y to account for angles going anticlockwise.
    secondPoint.set(halfWidth + endX, size.height() - (halfHeight + endY));
    // Reflect around the center for the start point.
    firstPoint.set(size.width() - secondPoint.x(), size.height() - secondPoint.y());
}

PassRefPtr<Gradient> CSSLinearGradientValue::createGradient(RenderObject* renderer, const IntSize& size)
{
    ASSERT(!size.isEmpty());

    RenderStyle* rootStyle = renderer->document()->documentElement()->renderStyle();

    FloatPoint firstPoint;
    FloatPoint secondPoint;
    if (m_angle) {
        float angle = m_angle->getFloatValue(CSSPrimitiveValue::CSS_DEG);
        endPointsFromAngle(angle, size, firstPoint, secondPoint);
    } else {
        firstPoint = computeEndPoint(m_firstX.get(), m_firstY.get(), renderer->style(), rootStyle, size);

        if (m_secondX || m_secondY)
            secondPoint = computeEndPoint(m_secondX.get(), m_secondY.get(), renderer->style(), rootStyle, size);
        else {
            if (m_firstX)
                secondPoint.setX(size.width() - firstPoint.x());
            if (m_firstY)
                secondPoint.setY(size.height() - firstPoint.y());
        }
    }

    RefPtr<Gradient> gradient = Gradient::create(firstPoint, secondPoint);

    // Now add the stops.
    addStops(gradient.get(), renderer, rootStyle, 1);

    return gradient.release();
}

void CSSLinearGradientValue::reportDescendantMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
{
    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
    CSSGradientValue::reportBaseClassMemoryUsage(memoryObjectInfo);
    info.addMember(m_angle);
}

String CSSRadialGradientValue::customCssText() const
{
    StringBuilder result;

    if (m_deprecatedType) {
        result.appendLiteral("-webkit-gradient(radial, ");
        result.append(m_firstX->cssText());
        result.append(' ');
        result.append(m_firstY->cssText());
        result.appendLiteral(", ");
        result.append(m_firstRadius->cssText());
        result.appendLiteral(", ");
        result.append(m_secondX->cssText());
        result.append(' ');
        result.append(m_secondY->cssText());
        result.appendLiteral(", ");
        result.append(m_secondRadius->cssText());

        // FIXME: share?
        for (unsigned i = 0; i < m_stops.size(); i++) {
            const CSSGradientColorStop& stop = m_stops[i];
            result.appendLiteral(", ");
            if (stop.m_position->getDoubleValue(CSSPrimitiveValue::CSS_NUMBER) == 0) {
                result.appendLiteral("from(");
                result.append(stop.m_color->cssText());
                result.append(')');
            } else if (stop.m_position->getDoubleValue(CSSPrimitiveValue::CSS_NUMBER) == 1) {
                result.appendLiteral("to(");
                result.append(stop.m_color->cssText());
                result.append(')');
            } else {
                result.appendLiteral("color-stop(");
                result.append(String::number(stop.m_position->getDoubleValue(CSSPrimitiveValue::CSS_NUMBER)));
                result.appendLiteral(", ");
                result.append(stop.m_color->cssText());
                result.append(')');
            }
        }
    } else {
        if (m_repeating)
            result.appendLiteral("-webkit-repeating-radial-gradient(");
        else
            result.appendLiteral("-webkit-radial-gradient(");

        if (m_firstX && m_firstY) {
            result.append(m_firstX->cssText());
            result.append(' ');
            result.append(m_firstY->cssText());
        } else if (m_firstX)
            result.append(m_firstX->cssText());
         else if (m_firstY)
            result.append(m_firstY->cssText());
        else
            result.appendLiteral("center");

        if (m_shape || m_sizingBehavior) {
            result.appendLiteral(", ");
            if (m_shape) {
                result.append(m_shape->cssText());
                result.append(' ');
            } else
                result.appendLiteral("ellipse ");

            if (m_sizingBehavior)
                result.append(m_sizingBehavior->cssText());
            else
                result.appendLiteral("cover");

        } else if (m_endHorizontalSize && m_endVerticalSize) {
            result.appendLiteral(", ");
            result.append(m_endHorizontalSize->cssText());
            result.append(' ');
            result.append(m_endVerticalSize->cssText());
        }

        for (unsigned i = 0; i < m_stops.size(); i++) {
            const CSSGradientColorStop& stop = m_stops[i];
            result.appendLiteral(", ");
            result.append(stop.m_color->cssText());
            if (stop.m_position) {
                result.append(' ');
                result.append(stop.m_position->cssText());
            }
        }
    }

    result.append(')');
    return result.toString();
}

float CSSRadialGradientValue::resolveRadius(CSSPrimitiveValue* radius, RenderStyle* style, RenderStyle* rootStyle, float* widthOrHeight)
{
    float zoomFactor = style->effectiveZoom();

    float result = 0;
    if (radius->isNumber()) // Can the radius be a percentage?
        result = radius->getFloatValue() * zoomFactor;
    else if (widthOrHeight && radius->isPercentage())
        result = *widthOrHeight * radius->getFloatValue() / 100;
    else
        result = radius->computeLength<float>(style, rootStyle, zoomFactor);

    return result;
}

static float distanceToClosestCorner(const FloatPoint& p, const FloatSize& size, FloatPoint& corner)
{
    FloatPoint topLeft;
    float topLeftDistance = FloatSize(p - topLeft).diagonalLength();

    FloatPoint topRight(size.width(), 0);
    float topRightDistance = FloatSize(p - topRight).diagonalLength();

    FloatPoint bottomLeft(0, size.height());
    float bottomLeftDistance = FloatSize(p - bottomLeft).diagonalLength();

    FloatPoint bottomRight(size.width(), size.height());
    float bottomRightDistance = FloatSize(p - bottomRight).diagonalLength();

    corner = topLeft;
    float minDistance = topLeftDistance;
    if (topRightDistance < minDistance) {
        minDistance = topRightDistance;
        corner = topRight;
    }

    if (bottomLeftDistance < minDistance) {
        minDistance = bottomLeftDistance;
        corner = bottomLeft;
    }

    if (bottomRightDistance < minDistance) {
        minDistance = bottomRightDistance;
        corner = bottomRight;
    }
    return minDistance;
}

static float distanceToFarthestCorner(const FloatPoint& p, const FloatSize& size, FloatPoint& corner)
{
    FloatPoint topLeft;
    float topLeftDistance = FloatSize(p - topLeft).diagonalLength();

    FloatPoint topRight(size.width(), 0);
    float topRightDistance = FloatSize(p - topRight).diagonalLength();

    FloatPoint bottomLeft(0, size.height());
    float bottomLeftDistance = FloatSize(p - bottomLeft).diagonalLength();

    FloatPoint bottomRight(size.width(), size.height());
    float bottomRightDistance = FloatSize(p - bottomRight).diagonalLength();

    corner = topLeft;
    float maxDistance = topLeftDistance;
    if (topRightDistance > maxDistance) {
        maxDistance = topRightDistance;
        corner = topRight;
    }

    if (bottomLeftDistance > maxDistance) {
        maxDistance = bottomLeftDistance;
        corner = bottomLeft;
    }

    if (bottomRightDistance > maxDistance) {
        maxDistance = bottomRightDistance;
        corner = bottomRight;
    }
    return maxDistance;
}

// Compute horizontal radius of ellipse with center at 0,0 which passes through p, and has
// width/height given by aspectRatio.
static inline float horizontalEllipseRadius(const FloatSize& p, float aspectRatio)
{
    // x^2/a^2 + y^2/b^2 = 1
    // a/b = aspectRatio, b = a/aspectRatio
    // a = sqrt(x^2 + y^2/(1/r^2))
    return sqrtf(p.width() * p.width() + (p.height() * p.height()) / (1 / (aspectRatio * aspectRatio)));
}

// FIXME: share code with the linear version
PassRefPtr<Gradient> CSSRadialGradientValue::createGradient(RenderObject* renderer, const IntSize& size)
{
    ASSERT(!size.isEmpty());

    RenderStyle* rootStyle = renderer->document()->documentElement()->renderStyle();

    FloatPoint firstPoint = computeEndPoint(m_firstX.get(), m_firstY.get(), renderer->style(), rootStyle, size);
    if (!m_firstX)
        firstPoint.setX(size.width() / 2);
    if (!m_firstY)
        firstPoint.setY(size.height() / 2);

    FloatPoint secondPoint = computeEndPoint(m_secondX.get(), m_secondY.get(), renderer->style(), rootStyle, size);
    if (!m_secondX)
        secondPoint.setX(size.width() / 2);
    if (!m_secondY)
        secondPoint.setY(size.height() / 2);

    float firstRadius = 0;
    if (m_firstRadius)
        firstRadius = resolveRadius(m_firstRadius.get(), renderer->style(), rootStyle);

    float secondRadius = 0;
    float aspectRatio = 1; // width / height.
    if (m_secondRadius)
        secondRadius = resolveRadius(m_secondRadius.get(), renderer->style(), rootStyle);
    else if (m_endHorizontalSize || m_endVerticalSize) {
        float width = size.width();
        float height = size.height();
        secondRadius = resolveRadius(m_endHorizontalSize.get(), renderer->style(), rootStyle, &width);
        aspectRatio = secondRadius / resolveRadius(m_endVerticalSize.get(), renderer->style(), rootStyle, &height);
    } else {
        enum GradientShape { Circle, Ellipse };
        GradientShape shape = Ellipse;
        if (m_shape && m_shape->getIdent() == CSSValueCircle)
            shape = Circle;

        enum GradientFill { ClosestSide, ClosestCorner, FarthestSide, FarthestCorner };
        GradientFill fill = FarthestCorner;

        switch (m_sizingBehavior ? m_sizingBehavior->getIdent() : 0) {
        case CSSValueContain:
        case CSSValueClosestSide:
            fill = ClosestSide;
            break;
        case CSSValueClosestCorner:
            fill = ClosestCorner;
            break;
        case CSSValueFarthestSide:
            fill = FarthestSide;
            break;
        case CSSValueCover:
        case CSSValueFarthestCorner:
            fill = FarthestCorner;
            break;
        }

        // Now compute the end radii based on the second point, shape and fill.

        // Horizontal
        switch (fill) {
        case ClosestSide: {
            float xDist = min(secondPoint.x(), size.width() - secondPoint.x());
            float yDist = min(secondPoint.y(), size.height() - secondPoint.y());
            if (shape == Circle) {
                float smaller = min(xDist, yDist);
                xDist = smaller;
                yDist = smaller;
            }
            secondRadius = xDist;
            aspectRatio = xDist / yDist;
            break;
        }
        case FarthestSide: {
            float xDist = max(secondPoint.x(), size.width() - secondPoint.x());
            float yDist = max(secondPoint.y(), size.height() - secondPoint.y());
            if (shape == Circle) {
                float larger = max(xDist, yDist);
                xDist = larger;
                yDist = larger;
            }
            secondRadius = xDist;
            aspectRatio = xDist / yDist;
            break;
        }
        case ClosestCorner: {
            FloatPoint corner;
            float distance = distanceToClosestCorner(secondPoint, size, corner);
            if (shape == Circle)
                secondRadius = distance;
            else {
                // If <shape> is ellipse, the gradient-shape has the same ratio of width to height
                // that it would if closest-side or farthest-side were specified, as appropriate.
                float xDist = min(secondPoint.x(), size.width() - secondPoint.x());
                float yDist = min(secondPoint.y(), size.height() - secondPoint.y());

                secondRadius = horizontalEllipseRadius(corner - secondPoint, xDist / yDist);
                aspectRatio = xDist / yDist;
            }
            break;
        }

        case FarthestCorner: {
            FloatPoint corner;
            float distance = distanceToFarthestCorner(secondPoint, size, corner);
            if (shape == Circle)
                secondRadius = distance;
            else {
                // If <shape> is ellipse, the gradient-shape has the same ratio of width to height
                // that it would if closest-side or farthest-side were specified, as appropriate.
                float xDist = max(secondPoint.x(), size.width() - secondPoint.x());
                float yDist = max(secondPoint.y(), size.height() - secondPoint.y());

                secondRadius = horizontalEllipseRadius(corner - secondPoint, xDist / yDist);
                aspectRatio = xDist / yDist;
            }
            break;
        }
        }
    }

    RefPtr<Gradient> gradient = Gradient::create(firstPoint, firstRadius, secondPoint, secondRadius, aspectRatio);

    // addStops() only uses maxExtent for repeating gradients.
    float maxExtent = 0;
    if (m_repeating) {
        FloatPoint corner;
        maxExtent = distanceToFarthestCorner(secondPoint, size, corner);
    }

    // Now add the stops.
    addStops(gradient.get(), renderer, rootStyle, maxExtent);

    return gradient.release();
}

void CSSRadialGradientValue::reportDescendantMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
{
    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
    CSSGradientValue::reportBaseClassMemoryUsage(memoryObjectInfo);
    info.addMember(m_firstRadius);
    info.addMember(m_secondRadius);
    info.addMember(m_shape);
    info.addMember(m_sizingBehavior);
    info.addMember(m_endHorizontalSize);
    info.addMember(m_endVerticalSize);
}

} // namespace WebCore


text:
<!DOCTYPE html>

      <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />

    <title>Tech Deviant</title>

    <meta charset="utf-8" />
    <link href="https://gouravchawla.com/blog/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="Tech Deviant Full Atom Feed" />
    <link href="https://gouravchawla.com/blog/feeds/conference-diaries.atom.xml" type="application/atom+xml" rel="alternate" title="Tech Deviant Categories Atom Feed" />
    <link rel="stylesheet" href="https://gouravchawla.com/blog/theme/css/poole.css"/>
    <link rel="stylesheet" href="https://gouravchawla.com/blog/theme/css/syntax.css"/>
    <link rel="stylesheet" href="https://gouravchawla.com/blog/theme/css/lanyon.css"/>
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700%7CPT+Sans:400">
    <link rel="stylesheet" href="https://gouravchawla.com/blog/theme/css/styles.css"/>

    <meta name="tags" contents="python" />
    <meta name="tags" contents="conference" />
    <meta name="tags" contents="pydata" />
    <meta name="tags" contents="machine-learning" />

<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox">

  Home
  About
  Archives

    @techdeviant

	©  2019 Tech Deviant | Pelicanyan v0.1 | Powered by Pelican

            Tech Deviant
            Navigating the 21st century - Tech, Culture and more

      PyData Delhi 2017 - Conference diaries

    September 12, 2017

PyData is an educational program of NumFOCUS which supports users and developers of data analysis tools. PyData Delhi is one of the chapters of PyData. The conference was organized by the Delhi chapter in IIIT-Delhi for the first time. People from around the world were present there. Mumbai, Pune, Chandigarh, Bangalore, Nepal, London & Amsterdam are some of the places where people came from for the conference.

The conference opened with the first Keynote by Siraj Raval. He talked about the Maths behind Deep Learning. He was our special guest from Amsterdam along with James Powell from New York(my dream city).

[tl;dr] Below is a list of talks that I attended with what I learned and discovered.

The next talk was Regression Analysis - The good, the bad and the untold by Jalem Raj Rohit. This talk was interesting and shared some thoughts which I otherwise would have overlooked given the hype of deep learning, neural nets and what not. He talked about the importance of Regression and how you should look at the data first to understand what sort of data analysis technique you should apply on the data. Another good point that he put up was that linear regression/regression techniques might fit your data better than other fancy techniques available today. So, understand your data and you shall live happily ever after.

The next talk that I attended was Topic Modelling with Gensim by Parul Sethi. I really enjoyed this one even though it showed that the presenter was doing it for the first time. And I really appreciate that she did. I had explored and worked on a similar topic before, so I was able to relate to the content. This talk gave me some ideas on tackling the problem I worked on in a different way. I'm going to give it a shot and see how the results vary. I don't have the presentation to link right now but I have the next best thing – the tale about her GSoC contribution.

The next one was by Nabarun Pal - Building camera based intelligent applications. This talk introduced me to Firefly and along with most other people in the conference, I think this is a pretty cool library.

The next one was the keynote - Recent Advances in NLP by Anuj Gupta. This was an interesting one mostly because of my interest in NLP and because it was informative yet interesting in general. The talk introduced me to Unsupervised sentiment neuron, generative text, neural complete. He even recommended a course for people who wanted to learn.

The next talk was by Shagun Sodhani on Machine Learning Architectures. He has been active in the meetup groups around Delhi and shares him knowledge by speaking in these meetups. Although, this talk was a bit above my understanding but I learned about the Quora duplicate questions dataset.  He talked about different machine learning architectures like Siamese Network etc. in this talk.

The next day started with a keynote by Prabhu Ramachandran titled My Experiments with Python. This was an awe-inspiring talk. It is always very interesting to hear people's perspective and experience on technology before the Internet era. He shared his experiences with Python and how he used it to build some really awesome tools to help him and the community. His contribution in Open Source is immense.

After this I decided to attend a workshop titled Create a sense2vec model using Gensim and Spacy from scraped news data and integrate it with Flask by Tanu Mittal and Abhishek Kapoor. These guys wanted to cover alot but due to time restrictions weren't able to cover all of it. The setup time ate some of the explanation time even though they had come prepared with the setup and scripts. Even though they weren't able to cover the whole thing, I'm sure if I give it a try after what they shared I'll be able to make it work.

The last few sessions were amazing as well. Here is a list of the sessions:

Panel Discussion: I got some ideas out of the discussion, learned few things about Data Science in general and gained some perspective on all things Data Science.

Data Science for Social Good by Dr. Ponnurangam Kumaraguru:  He shared his ideas and the research work he is doing.

Understanding Clustering: Supervising the unsupervised by Janu Verma

Beyond Clicks: Deep Sequential Models for Task Satisfaction Prediction with Conversational Agents by Rishabh Mehrotra

Real-time log analytics using Probabilistic Data Structures in Redis by Srinivasan Rangarajan

Parting thoughts

Overall, the conference was fun and informative. There were people from around the world which is always a good thing. I gained some perspective on the whole Data Science field and learned a lot of new things. I've tried to include links to profiles of speakers. The presentation decks were not available at the time of this writing. If you have stumbled upon this article and have some information or suggestion then post them in the comments below.

Comments !

            Please enable JavaScript to view the comments.

			©  2019 Tech Deviant | Pelicanyan v0.1 | Powered by Pelican


text:
===================================
LBL: C wrapper around MA27 and MA57
===================================

:Author: Dominique Orban <dominique.orban@gerad.ca>

LBL is a unified C interface to the multifrontal symmetric indefinite linear
system solvers MA27 and MA57 from the Harwell Subroutine Library.

Example
=======

Here are the essential bits of a typical example (see `examples/examples.c`
for the complete code)::

    #include "lbl.h"
    LBL_Data *lbl;           // Main data structure.
    lbl = LBL_Initialize(nnz, n, stderr, 1);
    LBL_Analyze(lbl, 0);     // 0 = automatic pivot choice.
    LBL_Factorize(lbl, val); // val is an array of doubles.
    LBL_Solve(lbl, rhs);     // rhs is an array of doubles.
    LBL_Finalize(lbl);

Installing LBL
==============

1. Place the source files for MA27 and MA57 in some directory. You will need
   fd15d.f ma27ad.f mc21d.f mc34d.f mc47d.f mc59d.f mc64d.f mc71d.f ma57d.f.
   See http://www.hsl.rl.ac.uk/hsl2007

2. Edit and customize make.inc

3. Type ``make all``.

You can clean out temporary files with ``make clean`` and sanitize everything
with ``make purge``.

Testing LBL
===========

Type ``make example``. Change to the `example` directory and type
``./example``.

The expected output is::

   Input matrix:
   1  1  2.000000
   1  2  3.000000
   2  3  4.000000
   2  5  6.000000
   3  3  1.000000
   3  4  5.000000
   5  5  1.000000
   Input right-hand side:
   8.000000 45.000000 31.000000 15.000000 17.000000
   Solution:
   1.000000 2.000000 3.000000 4.000000 5.000000

Bugs, Comments, Feature Requests
================================

Please send bugs, comments, feature requests, test cases, chocolate and coffee
to the `Lighthouse LBL page
<http://pykrylov.lighthouseapp.com/projects/54633-lbl>`_.

Enjoy!

.. image:: https://d2weczhvl823v0.cloudfront.net/dpo/lbl/trend.png
   :alt: Bitdeli badge
   :target: https://bitdeli.com/free


text:
import time

from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.remote.command import Command

from .common import WAIT_STALE_ELEMENT_MAX_TRY, WAIT_ELEMENT_POLL_FREQUENCY

class ActionChains(webdriver.ActionChains):
    def __move_to(self, element, xoffset=None, yoffset=None):
        params = {'element': element.id}
        if xoffset is not None and yoffset is not None:
            params.update({'xoffset': int(xoffset),
                           'yoffset': int(yoffset)})

        def loop():
            attempt = 0
            while attempt < WAIT_STALE_ELEMENT_MAX_TRY:
                try:
                    self._driver.execute(Command.MOVE_TO, params)
                    break
                except StaleElementReferenceException:
                    time.sleep(WAIT_ELEMENT_POLL_FREQUENCY)
                    element.reload()
                    params['element'] = element.id
                attempt += 1

        return loop

    def move_to_element_with_offset(self, to_element, xoffset, yoffset):
        self._actions.append(self.__move_to(to_element, xoffset, yoffset))
        return self

    def move_to_element(self, to_element):
        self._actions.append(self.__move_to(to_element))
        return self

class TouchActions(webdriver.TouchActions):
    def __safe_execute(self, driver_command, element, param=None):
        param = {} if param is None else param
        attempt = 0
        while attempt < WAIT_STALE_ELEMENT_MAX_TRY:
            try:
                param['element'] = element.id
                self._driver.execute(driver_command, param)
                break
            except StaleElementReferenceException:
                time.sleep(WAIT_ELEMENT_POLL_FREQUENCY)
                element.reload()
            attempt += 1

    def tap(self, on_element):
        """
        Taps on a given element.

        Args:
            on_element: The element to tap.
        """
        self._actions.append(lambda: self.__safe_execute(Command.SINGLE_TAP, on_element))
        return self

    def double_tap(self, on_element):
        """
        Double taps on a given element.

        Args:
            on_element: The element to tap.
        """
        self._actions.append(lambda: self.__safe_execute(Command.DOUBLE_TAP, on_element))
        return self

    def scroll_from_element(self, on_element, xoffset, yoffset):
        """
        Touch and scroll starting at on_element, moving by xoffset and yoffset.

        Args:
          on_element: The element where scroll starts.
          xoffset: X offset to scroll to.
          yoffset: Y offset to scroll to.
        """
        self._actions.append(lambda: self.__safe_execute(Command.TOUCH_SCROLL, on_element,
                                                         {'xoffset': int(xoffset),
                                                          'yoffset': int(yoffset)}))
        return self

    def long_press(self, on_element):
        """
        Long press on an element.

        Args:
          on_element: The element to long press.
        """
        self._actions.append(lambda: self.__safe_execute(Command.LONG_PRESS, on_element))
        return self

    def flick_element(self, on_element, xoffset, yoffset, speed):
        """
        Flick starting at on_element, and moving by the xoffset and yoffset
        with specified speed.

        Args:
          on_element: Flick will start at center of element.
          xoffset: X offset to flick to.
          yoffset: Y offset to flick to.
          speed: Pixels per second to flick.
        """
        self._actions.append(lambda: self.__safe_execute(Command.FLICK, on_element, {
            'xoffset': int(xoffset),
            'yoffset': int(yoffset),
            'speed': int(speed)}))
        return self


text:
  La Chapelle-Huon est
       un village
       situé dans le département de Sarthe en Pays de la Loire. Elle totalisait 525 habitants en 2008.

La ville compte quelques  aménagements, elle dispose, entre autres, de une boucle de randonnée.

Si vous envisagez de venir habiter à La Chapelle-Huon, vous pourrez facilement trouver une maison à vendre.

À proximité de La Chapelle-Huon sont situées les communes de
Bonneveau localisée à 4 km, 500 habitants,
Cellé située à 3 km, 258 habitants,
Saint-Calais à 7 km, 3 589 habitants,
Sainte-Cérotte localisée à 6 km, 323 habitants,
Marolles-lès-Saint-Calais à 7 km, 267 habitants,
Bessé-sur-Braye localisée à 2 km, 2 430 habitants,
 entre autres. De plus, La Chapelle-Huon est située à seulement 25 km de Vendôme.

Le nombre de logements, à La Chapelle-Huon, se décomposait en 2011 en trois appartements et 289 maisons soit
 un marché plutôt équilibré.

À La Chapelle-Huon, le prix moyen à l'achat d'un appartement s'évalue à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 068 € du m². À la location la valorisation moyenne se situe à 3,64 € du m² par mois.