text:
package org.jfree.data.xy;

import org.jfree.data.DefaultKeyedValues2D;
import org.jfree.data.DomainInfo;
import org.jfree.data.Range;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.util.PublicCloneable;

public class CategoryTableXYDataset extends AbstractIntervalXYDataset implements TableXYDataset, IntervalXYDataset, DomainInfo, PublicCloneable {
    private IntervalXYDelegate intervalDelegate;
    private DefaultKeyedValues2D values;

    public CategoryTableXYDataset() {
        this.values = new DefaultKeyedValues2D(true);
        this.intervalDelegate = new IntervalXYDelegate(this);
        addChangeListener(this.intervalDelegate);
    }

    public void add(double x, double y, String seriesName) {
        add(new Double(x), new Double(y), seriesName, true);
    }

    public void add(Number x, Number y, String seriesName, boolean notify) {
        this.values.addValue(y, (Comparable) x, seriesName);
        if (notify) {
            fireDatasetChanged();
        }
    }

    public void remove(double x, String seriesName) {
        remove(new Double(x), seriesName, true);
    }

    public void remove(Number x, String seriesName, boolean notify) {
        this.values.removeValue((Comparable) x, seriesName);
        if (notify) {
            fireDatasetChanged();
        }
    }

    public void clear() {
        this.values.clear();
        fireDatasetChanged();
    }

    public int getSeriesCount() {
        return this.values.getColumnCount();
    }

    public Comparable getSeriesKey(int series) {
        return this.values.getColumnKey(series);
    }

    public int getItemCount() {
        return this.values.getRowCount();
    }

    public int getItemCount(int series) {
        return getItemCount();
    }

    public Number getX(int series, int item) {
        return (Number) this.values.getRowKey(item);
    }

    public Number getStartX(int series, int item) {
        return this.intervalDelegate.getStartX(series, item);
    }

    public Number getEndX(int series, int item) {
        return this.intervalDelegate.getEndX(series, item);
    }

    public Number getY(int series, int item) {
        return this.values.getValue(item, series);
    }

    public Number getStartY(int series, int item) {
        return getY(series, item);
    }

    public Number getEndY(int series, int item) {
        return getY(series, item);
    }

    public double getDomainLowerBound(boolean includeInterval) {
        return this.intervalDelegate.getDomainLowerBound(includeInterval);
    }

    public double getDomainUpperBound(boolean includeInterval) {
        return this.intervalDelegate.getDomainUpperBound(includeInterval);
    }

    public Range getDomainBounds(boolean includeInterval) {
        if (includeInterval) {
            return this.intervalDelegate.getDomainBounds(includeInterval);
        }
        return DatasetUtilities.iterateDomainBounds(this, includeInterval);
    }

    public double getIntervalPositionFactor() {
        return this.intervalDelegate.getIntervalPositionFactor();
    }

    public void setIntervalPositionFactor(double d) {
        this.intervalDelegate.setIntervalPositionFactor(d);
        fireDatasetChanged();
    }

    public double getIntervalWidth() {
        return this.intervalDelegate.getIntervalWidth();
    }

    public void setIntervalWidth(double d) {
        this.intervalDelegate.setFixedIntervalWidth(d);
        fireDatasetChanged();
    }

    public boolean isAutoWidth() {
        return this.intervalDelegate.isAutoWidth();
    }

    public void setAutoWidth(boolean b) {
        this.intervalDelegate.setAutoWidth(b);
        fireDatasetChanged();
    }

    public boolean equals(Object obj) {
        if (!(obj instanceof CategoryTableXYDataset)) {
            return false;
        }
        CategoryTableXYDataset that = (CategoryTableXYDataset) obj;
        if (this.intervalDelegate.equals(that.intervalDelegate) && this.values.equals(that.values)) {
            return true;
        }
        return false;
    }

    public Object clone() throws CloneNotSupportedException {
        CategoryTableXYDataset clone = (CategoryTableXYDataset) super.clone();
        clone.values = (DefaultKeyedValues2D) this.values.clone();
        clone.intervalDelegate = new IntervalXYDelegate(clone);
        clone.intervalDelegate.setFixedIntervalWidth(getIntervalWidth());
        clone.intervalDelegate.setAutoWidth(isAutoWidth());
        clone.intervalDelegate.setIntervalPositionFactor(getIntervalPositionFactor());
        return clone;
    }
}


text:
namespace BlogSystem.Web.Api
{
    using System.Data.Entity;

    using Data;
    using Data.Migrations;

    public class DatabaseConfig
    {
        public static void Configure()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<BlogSystemDbContext, Configuration>());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"io"
	"testing"

	"github.com/spf13/cobra"

	"k8s.io/helm/pkg/helm"
)

func TestDependencyListCmd(t *testing.T) {

	tests := []releaseCase{
		{
			name: "No such chart",
			args: []string{"/no/such/chart"},
			err:  true,
		},
		{
			name:     "No requirements.yaml",
			args:     []string{"testdata/testcharts/alpine"},
			expected: "WARNING: no requirements at ",
		},
		{
			name: "Requirements in chart dir",
			args: []string{"testdata/testcharts/reqtest"},
			expected: "NAME        \tVERSION\tREPOSITORY                \tSTATUS  \n" +
				"reqsubchart \t0.1.0  \thttps://example.com/charts\tunpacked\n" +
				"reqsubchart2\t0.2.0  \thttps://example.com/charts\tunpacked\n" +
				"reqsubchart3\t>=0.1.0\thttps://example.com/charts\tok      \n\n",
		},
		{
			name:     "Requirements in chart archive",
			args:     []string{"testdata/testcharts/reqtest-0.1.0.tgz"},
			expected: "NAME        \tVERSION\tREPOSITORY                \tSTATUS \nreqsubchart \t0.1.0  \thttps://example.com/charts\tmissing\nreqsubchart2\t0.2.0  \thttps://example.com/charts\tmissing\n",
		},
	}

	runReleaseCases(t, tests, func(c *helm.FakeClient, out io.Writer) *cobra.Command {
		return newDependencyListCmd(out)
	})
}


text:
function csvdata = read_csv_with_headers(file)

headers = get_csv_headers(file);

row_offset = 1; % skip header
col_offset = 0;
data = csvread(file, row_offset, col_offset); %#ok<NASGU>

csvdata = struct;

for i=1:1:length(headers)
    header = headers(i);
    cmd_array = ['csvdata.' header ' = ' 'data(:,', int2str(i), ');'];
    cmd = strjoin(cmd_array, '');
    disp(cmd);
    eval(cmd);
end


text:
package org.kuali.rice.krad.datadictionary.impl;

import java.util.Comparator;
import java.util.List;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.lang.StringUtils;

/**
 * The super class which implementations of the FieldOverride interface will extend.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 *
 */
public class FieldOverrideForListElementBase {

    private String propertyName;
    private Object element;
    protected String propertyNameForElementCompare;

    public String getPropertyNameForElementCompare() {
        return propertyNameForElementCompare;
    }

    public void setPropertyNameForElementCompare(String propertyNameForElementCompare) {
        this.propertyNameForElementCompare = propertyNameForElementCompare;
    }

    protected int getElementPositionInList(Object object, List theList) {
        Comparator comparator = this.getComparator();
        int pos = -1;

        if ( object != null && theList != null )
        {
            for ( int i = 0; i < theList.size(); ++i )
            {
                Object item = theList.get(i);
                boolean equalFlag = false;
                if ( comparator != null )
                {
                    equalFlag = comparator.compare(object, item) == 0;
                }
                else
                {
                    equalFlag = item.equals(object);
                }
                if ( equalFlag )
                {
                    pos = i;
                    break;
                }
            }
        }
        return pos;
    }

    public String getPropertyName() {
        return propertyName;
    }

    public void setPropertyName(String propertyName) {
        this.propertyName = propertyName;
    }

    public Object getElement() {
        return element;
    }

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

    public FieldOverrideForListElementBase() {
        super();
    }

    protected Comparator getComparator() {
        Comparator comparator = null;
        if ( StringUtils.isNotBlank(propertyNameForElementCompare))
        {
            comparator = new BeanComparator(propertyNameForElementCompare);
        }
        else
        {
            throw new RuntimeException("Missing required comparator definitions.");
        }
        return comparator;
    }

}


text:
<!doctype html>
<title>Alert during dragenter for file drag</title>

Drag a file (one that your browser cannot open natively, such as an executable file) from your system file manager over the orange square.

An alert may appear - release the mouse over a blank part of the page, not the dialog. Dismiss it (you may need to use keyboard or mouse gestures such as gesture-down,gesture-right). If it does not appear, release the drag and accept any prompt to upload the file.

If a file download dialog appears, cancel it and return to this page.

Fail if the alert reappears.

The mouse cursor may continue to show that a drag is in operation. If so, attempt to select some of this text with the mouse before continuing to the text step.

Fail if the mouse continues to show that a drag is in operation.

Try to select some text in this sentence. Fail if it is not possible.


text:
'***********************************************************************************************************************
' File Name            : <User_Action_Trial>
' Location             : In-Solutions Global Pvt. Ltd., Malad
' Author               : unknown
' PADss Created        :<Tejas Pinge>, Emp. No: <C1857>
' Date of Creation     :
' PADss Date           :<28-Jun-13>
' Description          : USER ACTION TRIAL
'***********************************************************************************************************************
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Public Class admin_User_Action_Trial
    Inherits System.Web.UI.Page
    Dim path As String = System.IO.Directory.GetDirectoryRoot(AppDomain.CurrentDomain.BaseDirectory) & "NPCI_LoyaltyReports\ADMIN\UserActionTrail_REPORT\"
    Dim filename As String
    Dim rpt As New Reports
#Region " Web Form Designer Generated Code "
    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    End Sub
    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object
    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        ViewStateUserKey = Session.SessionID
        InitializeComponent()
    End Sub

#End Region
    Dim conn As New SqlConnection(ConfigurationManager.AppSettings("ConnectionStringV"))
    Dim cmd As New SqlCommand
    Dim cmd1 As New SqlCommand
    Dim da As New SqlDataAdapter
    Dim da1 As New SqlDataAdapter
    Dim ds As New DataSet
    Dim ds1 As New DataSet
    Dim acs As New HelperClass

    Dim strQry1 As String = " SELECT USER_NAME [USER NAME],UPDATED_BY [UPDATED BY],ACTION,ACTION_DATE [ACTIONDATE] FROM ADMIN_MAPS_USER_ACTION_TRAIL WHERE 1=1 "
    Dim strQry2 As String = " SELECT USER_NAME [USER NAME],UPDATED_BY [UPDATED BY],ACTION,ACTION_DATE [ACTIONDATE] FROM ADMIN_MAPS_USER_ACTION_TRAIL WHERE 1=1 "
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
        Response.Buffer = True
        Response.ExpiresAbsolute = DateTime.Now.AddDays(-1.0)
        Response.Expires = 0
        Response.CacheControl = "no-cache"
        'If Session("UserCode") = "" Then
        '    Response.Write("<script language=javascript>alert('Your Session Has EXPIRE/NOT LOGGED  IN Please Login Again.')</script>")
        '    Response.Redirect(acs.mapLink(Request.Path))
        'End If

        'Session("UserCode") = "ADMIN"
        If Session("UserCode") = "" Then
            Response.Write("<script language=javascript>alert('Your Session Has EXPIRE/NOT LOGGED  IN Please Login Again.')</script>")
            Response.Redirect(acs.mapLink(Request.Path))
        End If

        If Not Page.IsPostBack Then
            Dim strchk As String = acs.CheckSession(Session("UserCode"), System.IO.Path.GetFileName(Request.PhysicalPath))

            'strchk = "VALID"

            If strchk = "INVALID" Then
                Session("HomeFlag") = "N"
                Session("UserCode") = ""
                Response.Redirect(acs.mapLink(Request.Path))
            End If
            pop_username()
            pop_Action()
            LoadReport(0)
        End If

        'To enable back btn
        Response.Write("<script language=javascript>window.history.forward(1)</script>")
    End Sub
    'Binding list of username to dropdownlist
    Private Sub pop_username()
        Dim d As New data
        Dim Strmcc As String = "select distinct user_name from ADMIN_MAPS_USER_MASTER WHERE USER_NAME <>'SUPERADMIN' UNION ALL select distinct ' ' user_name from ADMIN_MAPS_USER_MASTER WHERE USER_NAME <> 'SUPERADMIN' ORDER BY user_name"
        Dim dsmcc As DataSet = d.GetData(Strmcc)
        ddlUserName.DataTextField = "user_name"
        ddlUserName.DataValueField = "user_name"
        ddlUserName.DataSource = dsmcc
        ddlUserName.DataBind()
        ddlUserName.Dispose()
    End Sub
    'Binding the list of a actions to dropdownlist
    Private Sub pop_Action()
        Dim d As New data
        Dim Strmcc As String = "SELECT Action from ADMIN_MAPS_USER_ACTION_TRAIL UNION select distinct ''  ACTION from ADMIN_MAPS_USER_ACTION_TRAIL ORDER BY ACTION DESC"
        Dim dsmcc As DataSet = d.GetData(Strmcc)
        ddlAction.DataTextField = "ACTION"
        ddlAction.DataValueField = "ACTION"
        ddlAction.DataSource = dsmcc
        ddlAction.DataBind()
        ddlAction.Dispose()
    End Sub
    'Populates data into datagrid and generate excel according to condition
    Private Sub LoadReport(ByVal a As Integer)
        Dim prmFromDate As New SqlParameter("FromDate", SqlDbType.DateTime)
        Dim prmToDate As New SqlParameter("ToDate", SqlDbType.DateTime)
        Dim prmTID As New SqlParameter("TID", SqlDbType.VarChar, 30)
        Dim prmMECODE As New SqlParameter("MECODE", SqlDbType.VarChar, 50)
        Dim strQry As String = ""
        Dim prmMENAME As New SqlParameter("MENAME", SqlDbType.VarChar, 100)
        Dim prmACN As New SqlParameter("ACN", SqlDbType.VarChar, 100)

        If ddlUserName.SelectedItem.Text.Trim <> "" Then
            strQry = strQry & "  and  ltrim(rtrim(USER_NAME))=ltrim(rtrim(@MENAME)) "
            prmMENAME.Value = ddlUserName.SelectedItem.Text.Trim
            cmd.Parameters.Add(prmMENAME)
        End If

        If ddlAction.SelectedItem.Text.Trim <> "" Then
            strQry = strQry & "  and  ltrim(rtrim(ACTION))=ltrim(rtrim(@ACN)) "
            prmACN.Value = ddlAction.SelectedItem.Text.Trim
            cmd.Parameters.Add(prmACN)
        End If

        If conn.State = ConnectionState.Closed Then conn.Open()
        If a = 0 Then
            cmd.CommandText = strQry1 & strQry & " order by  ACTION_DATE "
        Else
            cmd.CommandText = strQry2 & strQry & " order by  ACTION_DATE "
        End If

        cmd.Connection = conn
        da.SelectCommand = cmd
        da.Fill(ds)
        DataGrid1.DataSource = ds
        DataGrid1.DataBind()
        If a = 1 Then
            generateExcel(ds)
        End If
        If conn.State = ConnectionState.Open Then conn.Close()
    End Sub
    'To Bind data to datagrid
    Private Sub lnkQuery_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkQuery.Click
        Session("SelectedMCODE") = ""
        DataGrid1.DataBind()
        DataGrid1.CurrentPageIndex = 0
        LoadReport(0)
    End Sub
    Private Sub lnkExportToExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        LoadReport(1)
    End Sub
    'To generate excel
    Private Sub generateExcel(ByVal ds As DataSet)
        filename = "UserActionTrail" & Format(DateTime.Now(), "MMMdd")

        If Directory.Exists(path) = False Then
            Directory.CreateDirectory(path)
        End If
        rpt.WriteToExcelNew(ds, path, filename)

        'to create zip file
        rpt.create_zip(path & "\", filename, "*.xls")

        'to write LOG
        acs.writeLogDB(Session("UserCode"), System.IO.Path.GetFileName(Request.Path).ToString, filename + ".xls")

        'To delete file from the path
        rpt.deletedumpxl(path, "*.xls")

        'TO download file
        Dim flname As New System.IO.FileInfo(path + filename & ".zip")
        Response.Clear()
        Response.AppendHeader("content-disposition", "attachment; filename=" + filename & ".zip")
        Response.WriteFile(flname.FullName)
        Response.End()
    End Sub

    'To go to selected page in datagrid
    Private Sub DataGrid1_PageIndexChanged(ByVal source As System.Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles DataGrid1.PageIndexChanged
        DataGrid1.CurrentPageIndex = e.NewPageIndex
        LoadReport(0)
    End Sub
    'To downaload excel
    Private Sub lnkExportToExcelME_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkExportToExcelME.Click
        LoadReport(1)
    End Sub
    'Go to Home Page

    Private Sub DataGrid1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataGrid1.SelectedIndexChanged
    End Sub
    'PROCEDURE FOR DISPLAYING ERROR PAGE IF ERROR OCCURS IDURING APPLICATION EXCUTION
    Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Error
        Dim PhyFilePath As String = System.AppDomain.CurrentDomain.BaseDirectory
        Dim sUser As String = Session("UserCode")
        Dim sLastError As String = Server.GetLastError.Message.ToString
        Dim sStackTrace As String = Server.GetLastError.StackTrace.ToString
        acs.WriteError(sLastError, sStackTrace, sUser, PhyFilePath, "NPCI_Loyalty User Action Trail")
    End Sub
End Class
'***********************************************************************************************************************
'End of <User_Action_Trial>
'***********************************************************************************************************************


text:
namespace TraktApiSharp.Tests.Objects.Basic.Json.Writer
{
    using FluentAssertions;
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Traits;
    using TraktApiSharp.Objects.Basic;
    using TraktApiSharp.Objects.Basic.Json.Writer;
    using Xunit;

    [Category("Objects.Basic.JsonWriter")]
    public partial class RatingObjectJsonWriter_Tests
    {
        [Fact]
        public void Test_RatingObjectJsonWriter_WriteObject_Object_Exceptions()
        {
            var traktJsonWriter = new RatingObjectJsonWriter();
            Func<Task<string>> action = () => traktJsonWriter.WriteObjectAsync(default(ITraktRating));
            action.Should().Throw<ArgumentNullException>();
        }

        [Fact]
        public async Task Test_RatingObjectJsonWriter_WriteObject_Object_Only_Rating_Property()
        {
            ITraktRating traktRating = new TraktRating
            {
                Rating = 7.4561f
            };

            var traktJsonWriter = new RatingObjectJsonWriter();
            string json = await traktJsonWriter.WriteObjectAsync(traktRating);
            json.Should().Be(@"{""rating"":7.4561}");
        }

        [Fact]
        public async Task Test_RatingObjectJsonWriter_WriteObject_Object_Only_Votes_Property()
        {
            ITraktRating traktRating = new TraktRating
            {
                Votes = 2453
            };

            var traktJsonWriter = new RatingObjectJsonWriter();
            string json = await traktJsonWriter.WriteObjectAsync(traktRating);
            json.Should().Be(@"{""votes"":2453}");
        }

        [Fact]
        public async Task Test_RatingObjectJsonWriter_WriteObject_Object_Only_Distribution_Property()
        {
            ITraktRating traktRating = new TraktRating
            {
                Distribution = new Dictionary<string, int>
                {
                    ["1"] = 1,
                    ["2"] = 2,
                    ["3"] = 3,
                    ["4"] = 4,
                    ["5"] = 5,
                    ["6"] = 6,
                    ["7"] = 7,
                    ["8"] = 8,
                    ["9"] = 9,
                    ["10"] = 10
                }
            };

            var traktJsonWriter = new RatingObjectJsonWriter();
            string json = await traktJsonWriter.WriteObjectAsync(traktRating);
            json.Should().Be(@"{""distribution"":{""1"":1,""2"":2,""3"":3,""4"":4,""5"":5,""6"":6,""7"":7,""8"":8,""9"":9,""10"":10}}");
        }

        [Fact]
        public async Task Test_RatingObjectJsonWriter_WriteObject_Object_Only_Distribution_Property_Incomplete()
        {
            ITraktRating traktRating = new TraktRating
            {
                Distribution = new Dictionary<string, int>
                {
                    ["1"] = 1,
                    ["2"] = 2,
                    ["3"] = 3,
                    ["5"] = 5,
                    ["6"] = 6,
                    ["8"] = 8,
                    ["9"] = 9
                }
            };

            var traktJsonWriter = new RatingObjectJsonWriter();
            string json = await traktJsonWriter.WriteObjectAsync(traktRating);
            json.Should().Be(@"{""distribution"":{""1"":1,""2"":2,""3"":3,""4"":0,""5"":5,""6"":6,""7"":0,""8"":8,""9"":9,""10"":0}}");
        }

        [Fact]
        public async Task Test_RatingObjectJsonWriter_WriteObject_Object_Complete()
        {
            ITraktRating traktRating = new TraktRating
            {
                Rating = 7.4561f,
                Votes = 2453,
                Distribution = new Dictionary<string, int>
                {
                    ["1"] = 1,
                    ["2"] = 2,
                    ["3"] = 3,
                    ["4"] = 4,
                    ["5"] = 5,
                    ["6"] = 6,
                    ["7"] = 7,
                    ["8"] = 8,
                    ["9"] = 9,
                    ["10"] = 10
                }
            };

            var traktJsonWriter = new RatingObjectJsonWriter();
            string json = await traktJsonWriter.WriteObjectAsync(traktRating);
            json.Should().Be(@"{""rating"":7.4561,""votes"":2453," +
                             @"""distribution"":{""1"":1,""2"":2,""3"":3,""4"":4,""5"":5,""6"":6,""7"":7,""8"":8,""9"":9,""10"":10}}");
        }
    }
}


text:
from webiopi.utils.types import toint
from webiopi.devices.i2c import I2C
from webiopi.devices.digital import GPIOPort

class PCF8574(I2C, GPIOPort):
    FUNCTIONS = [GPIOPort.IN for i in range(8)]

    def __init__(self, slave=0x20):
        slave = toint(slave)
        if slave in range(0x20, 0x28):
            self.name = "PCF8574"
        elif slave in range(0x38, 0x40):
            self.name = "PCF8574A"
        else:
            raise ValueError("Bad slave address for PCF8574(A) : 0x%02X not in range [0x20..0x27, 0x38..0x3F]" % slave)

        I2C.__init__(self, slave)
        GPIOPort.__init__(self, 8)
        self.portWrite(0xFF)
        self.portRead()

    def __str__(self):
        return "%s(slave=0x%02X)" % (self.name, self.slave)

    def __getFunction__(self, channel):
        return self.FUNCTIONS[channel]

    def __setFunction__(self, channel, value):
        if not value in [self.IN, self.OUT]:
            raise ValueError("Requested function not supported")
        self.FUNCTIONS[channel] = value

    def __digitalRead__(self, channel):
        mask = 1 << channel
        d = self.readByte()
        return (d & mask) == mask

    def __portRead__(self):
        return self.readByte()

    def __digitalWrite__(self, channel, value):
        mask = 1 << channel
        b = self.readByte()
        if value:
            b |= mask
        else:
            b &= ~mask
        self.writeByte(b)

    def __portWrite__(self, value):
        self.writeByte(value)

class PCF8574A(PCF8574):
    def __init__(self, slave=0x38):
        PCF8574.__init__(self, slave)


text:
import Ember from 'ember';

export default Ember.Object.extend({
    meta: null,
    value: null,
    model: null,

    hasValue: Ember.computed.alias('value'),

    /** observes the value and update the
     * model content if needed
     */
    _valueObserver: Ember.observer('value', function() {
        var fieldName = this.get('meta.name');
        var value = this.get('value');
        this.set(`model.${fieldName}`, value);
    })
});


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClumsyWordsUniversal.Data
{
    public class TermDefinition
    {
        public TermDefinition()
            :this(String.Empty, new List<TermProperties>())
        {
        }

        public TermDefinition(List<TermProperties> items)
            :this(String.Empty, items)
        {
        }

        public TermDefinition(string term, List<TermProperties> items)
        {
            this.Term = term;
            this.TermProperties = items;
        }

        //public TermDefinition(string term, List<Group<TermProperties, PartOfSpeech>> tpList)
        //{
        //    this.Term = term;
        //    this.TermPropertiesList = tpList;
        //}

        /// <summary>
        /// The actual word that is being defined.
        /// </summary>
        public string Term { get; set; }

        public List<TermProperties> TermProperties { get; set; }

        public List<Group<PartOfSpeech, TermProperties>> GroupedTermProperties
        {
            get { return Group<PartOfSpeech, TermProperties>.GetGroups(this.TermProperties, p => p.PartOfSpeech).ToList(); }
            private set { this.GroupedTermProperties = value; }
        }

        //public IEnumerable<Group<TermProperties, PartOfSpeech>> Items { get; set; }

        ///// <summary>
        ///// A collection of all term properties objects.
        ///// </summary>
        //public List<Group<TermProperties, PartOfSpeech>> TermPropertiesList { get; set; }

        //public bool IsEmpty()
        //{
        //    if (string.IsNullOrEmpty(this.Term)) return true;
        //    return false;
        //}
    }

    public class Group<U, T> : List<T>
    {
        public Group()
            :base()
        {
        }

        public Group(U key, IEnumerable<T> items)
            : base(items)
        {
            this.Key = key;
        }

        public U Key
        {
            get;
            set;
        }

        public static IEnumerable<Group<U, T>> GetGroups(List<T> itemList, Func<T, U> getKeyFunc)
        {
            IEnumerable<Group<U, T>> groupList = from item in itemList
                                                 group item by getKeyFunc(item) into g
                                                 orderby g.Key
                                                 select new Group<U,T>(g.Key, g);

            return groupList;
        }
    }
}


text:
<?php

namespace DoctrineMigrations;

use Doctrine\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

class Version20160503093009 extends AbstractMigration
{
    public function getDescription() : string
    {
        return '';
    }

    public function up(Schema $schema) : void
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE posts ADD pinned TINYINT(1) NOT NULL');
    }

    public function down(Schema $schema) : void
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE posts DROP pinned');
    }
}


text:
"use strict";

var performanceNow = require("./performanceNow");

var ReactDefaultPerf = {};

if (true) {
  ReactDefaultPerf = {
    /**
     * Gets the stored information for a given object's function.
     *
     * @param {string} objName
     * @param {string} fnName
     * @return {?object}
     */
    getInfo: function(objName, fnName) {
      if (!this.info[objName] || !this.info[objName][fnName]) {
        return null;
      }
      return this.info[objName][fnName];
    },

    /**
     * Gets the logs pertaining to a given object's function.
     *
     * @param {string} objName
     * @param {string} fnName
     * @return {?array<object>}
     */
    getLogs: function(objName, fnName) {
      if (!this.getInfo(objName, fnName)) {
        return null;
      }
      return this.logs.filter(function(log) {
        return log.objName === objName && log.fnName === fnName;
      });
    },

    /**
     * Runs through the logs and builds an array of arrays, where each array
     * walks through the mounting/updating of each component underneath.
     *
     * @param {string} rootID The reactID of the root node, e.g. '.r[2cpyq]'
     * @return {array<array>}
     */
    getRawRenderHistory: function(rootID) {
      var history = [];
      /**
       * Since logs are added after the method returns, the logs are in a sense
       * upside-down: the inner-most elements from mounting/updating are logged
       * first, and the last addition to the log is the top renderComponent.
       * Therefore, we flip the logs upside down for ease of processing, and
       * reverse the history array at the end so the earliest event has index 0.
       */
      var logs = this.logs.filter(function(log) {
        return log.reactID.indexOf(rootID) === 0;
      }).reverse();

      var subHistory = [];
      logs.forEach(function(log, i) {
        if (i && log.reactID === rootID && logs[i - 1].reactID !== rootID) {
          subHistory.length && history.push(subHistory);
          subHistory = [];
        }
        subHistory.push(log);
      });
      if (subHistory.length) {
        history.push(subHistory);
      }
      return history.reverse();
    },

    /**
     * Runs through the logs and builds an array of strings, where each string
     * is a multiline formatted way of walking through the mounting/updating
     * underneath.
     *
     * @param {string} rootID The reactID of the root node, e.g. '.r[2cpyq]'
     * @return {array<string>}
     */
    getRenderHistory: function(rootID) {
      var history = this.getRawRenderHistory(rootID);

      return history.map(function(subHistory) {
        var headerString = (
          'log# Component (execution time) [bloat from logging]\n' +
          '================================================================\n'
        );
        return headerString + subHistory.map(function(log) {
          // Add two spaces for every layer in the reactID.
          var indents = '\t' + Array(log.reactID.split('.[').length).join('  ');
          var delta = _microTime(log.timing.delta);
          var bloat = _microTime(log.timing.timeToLog);

          return log.index + indents + log.name + ' (' + delta + 'ms)' +
            ' [' + bloat + 'ms]';
        }).join('\n');
      });
    },

    /**
     * Print the render history from `getRenderHistory` using console.log.
     * This is currently the best way to display perf data from
     * any React component; working on that.
     *
     * @param {string} rootID The reactID of the root node, e.g. '.r[2cpyq]'
     * @param {number} index
     */
    printRenderHistory: function(rootID, index) {
      var history = this.getRenderHistory(rootID);
      if (!history[index]) {
        console.warn(
          'Index', index, 'isn\'t available! ' +
          'The render history is', history.length, 'long.'
        );
        return;
      }
      console.log(
        'Loading render history #' + (index + 1) +
        ' of ' + history.length + ':\n' + history[index]
      );
    },

    /**
     * Prints the heatmap legend to console, showing how the colors correspond
     * with render times. This relies on console.log styles.
     */
    printHeatmapLegend: function() {
      if (!this.options.heatmap.enabled) {
        return;
      }
      var max = this.info.React
        && this.info.React.renderComponent
        && this.info.React.renderComponent.max;
      if (max) {
        var logStr = 'Heatmap: ';
        for (var ii = 0; ii <= 10 * max; ii += max) {
          logStr += '%c ' + (Math.round(ii) / 10) + 'ms ';
        }
        console.log(
          logStr,
          'background-color: hsla(100, 100%, 50%, 0.6);',
          'background-color: hsla( 90, 100%, 50%, 0.6);',
          'background-color: hsla( 80, 100%, 50%, 0.6);',
          'background-color: hsla( 70, 100%, 50%, 0.6);',
          'background-color: hsla( 60, 100%, 50%, 0.6);',
          'background-color: hsla( 50, 100%, 50%, 0.6);',
          'background-color: hsla( 40, 100%, 50%, 0.6);',
          'background-color: hsla( 30, 100%, 50%, 0.6);',
          'background-color: hsla( 20, 100%, 50%, 0.6);',
          'background-color: hsla( 10, 100%, 50%, 0.6);',
          'background-color: hsla(  0, 100%, 50%, 0.6);'
        );
      }
    },

    /**
     * Measure a given function with logging information, and calls a callback
     * if there is one.
     *
     * @param {string} objName
     * @param {string} fnName
     * @param {function} func
     * @return {function}
     */
    measure: function(objName, fnName, func) {
      var info = _getNewInfo(objName, fnName);

      var fnArgs = _getFnArguments(func);

      return function() {
        var timeBeforeFn = performanceNow();
        var fnReturn = func.apply(this, arguments);
        var timeAfterFn = performanceNow();

        /**
         * Hold onto arguments in a readable way: args[1] -> args.component.
         * args is also passed to the callback, so if you want to save an
         * argument in the log, do so in the callback.
         */
        var args = {};
        for (var i = 0; i < arguments.length; i++) {
          args[fnArgs[i]] = arguments[i];
        }

        var log = {
          index: ReactDefaultPerf.logs.length,
          fnName: fnName,
          objName: objName,
          timing: {
            before: timeBeforeFn,
            after: timeAfterFn,
            delta: timeAfterFn - timeBeforeFn
          }
        };

        ReactDefaultPerf.logs.push(log);

        /**
         * The callback gets:
         * - this (the component)
         * - the original method's arguments
         * - what the method returned
         * - the log object, and
         * - the wrapped method's info object.
         */
        var callback = _getCallback(objName, fnName);
        callback && callback(this, args, fnReturn, log, info);

        log.timing.timeToLog = performanceNow() - timeAfterFn;

        return fnReturn;
      };
    },

    /**
     * Holds information on wrapped objects/methods.
     * For instance, ReactDefaultPerf.info.React.renderComponent
     */
    info: {},

    /**
     * Holds all of the logs. Filter this to pull desired information.
     */
    logs: [],

    /**
     * Toggle settings for ReactDefaultPerf
     */
    options: {
      /**
       * The heatmap sets the background color of the React containers
       * according to how much total time has been spent rendering them.
       * The most temporally expensive component is set as pure red,
       * and the others are colored from green to red as a fraction
       * of that max component time.
       */
      heatmap: {
        enabled: true
      }
    }
  };

  /**
   * Gets a info area for a given object's function, adding a new one if
   * necessary.
   *
   * @param {string} objName
   * @param {string} fnName
   * @return {object}
   */
  var _getNewInfo = function(objName, fnName) {
    var info = ReactDefaultPerf.getInfo(objName, fnName);
    if (info) {
      return info;
    }
    ReactDefaultPerf.info[objName] = ReactDefaultPerf.info[objName] || {};

    return ReactDefaultPerf.info[objName][fnName] = {
      getLogs: function() {
        return ReactDefaultPerf.getLogs(objName, fnName);
      }
    };
  };

  /**
   * Gets a list of the argument names from a function's definition.
   * This is useful for storing arguments by their names within wrapFn().
   *
   * @param {function} fn
   * @return {array<string>}
   */
  var _getFnArguments = function(fn) {
    var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
    var fnStr = fn.toString().replace(STRIP_COMMENTS, '');
    fnStr = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')'));
    return fnStr.match(/([^\s,]+)/g);
  };

  /**
   * Store common callbacks within ReactDefaultPerf.
   *
   * @param {string} objName
   * @param {string} fnName
   * @return {?function}
   */
  var _getCallback = function(objName, fnName) {
    switch (objName + '.' + fnName) {
      case 'React.renderComponent':
        return _renderComponentCallback;
      case 'ReactDOMComponent.mountComponent':
      case 'ReactDOMComponent.updateComponent':
        return _nativeComponentCallback;
      case 'ReactCompositeComponent.mountComponent':
      case 'ReactCompositeComponent.updateComponent':
        return _compositeComponentCallback;
      default:
        return null;
    }
  };

  /**
   * Callback function for React.renderComponent
   *
   * @param {object} component
   * @param {object} args
   * @param {?object} fnReturn
   * @param {object} log
   * @param {object} info
   */
  var _renderComponentCallback =
    function(component, args, fnReturn, log, info) {
    log.name = args.nextComponent.constructor.displayName || '[unknown]';
    log.reactID = fnReturn._rootNodeID || null;

    if (ReactDefaultPerf.options.heatmap.enabled) {
      var container = args.container;
      if (!container.loggedByReactDefaultPerf) {
        container.loggedByReactDefaultPerf = true;
        info.components = info.components || [];
        info.components.push(container);
      }

      container.count = container.count || 0;
      container.count += log.timing.delta;
      info.max = info.max || 0;
      if (container.count > info.max) {
        info.max = container.count;
        info.components.forEach(function(component) {
          _setHue(component, 100 - 100 * component.count / info.max);
        });
      } else {
        _setHue(container, 100 - 100 * container.count / info.max);
      }
    }
  };

  /**
   * Callback function for ReactDOMComponent
   *
   * @param {object} component
   * @param {object} args
   * @param {?object} fnReturn
   * @param {object} log
   * @param {object} info
   */
  var _nativeComponentCallback =
    function(component, args, fnReturn, log, info) {
    log.name = component.tagName || '[unknown]';
    log.reactID = component._rootNodeID;
  };

  /**
   * Callback function for ReactCompositeComponent
   *
   * @param {object} component
   * @param {object} args
   * @param {?object} fnReturn
   * @param {object} log
   * @param {object} info
   */
  var _compositeComponentCallback =
    function(component, args, fnReturn, log, info) {
    log.name = component.constructor.displayName || '[unknown]';
    log.reactID = component._rootNodeID;
  };

  /**
   * Using the hsl() background-color attribute, colors an element.
   *
   * @param {DOMElement} el
   * @param {number} hue [0 for red, 120 for green, 240 for blue]
   */
  var _setHue = function(el, hue) {
    el.style.backgroundColor = 'hsla(' + hue + ', 100%, 50%, 0.6)';
  };

  /**
   * Round to the thousandth place.
   * @param {number} time
   * @return {number}
   */
  var _microTime = function(time) {
    return Math.round(time * 1000) / 1000;
  };
}

module.exports = ReactDefaultPerf;


text:
'use strict';

angular.module('projetobrasil.ufc.personagem.controllers', [])
	.controller('PersonagemCtrl', ['Personagens', function (Personagens){
		Personagens.carregaAssets();
	}]);


text:
<?php

class Base_Model_DbTable_ExceptionLog extends Zend_Db_Table
{
	protected $_name = 'ExceptionLog';

	public function saveException(Exception $exception)
	{
		if (!in_array($this->_name, $this->getAdapter()->listTables())) {
			return false;
		}

		return $this->createRow(array(
			'file' => $exception->getFile(),
			'line' => $exception->getLine(),
			'message' => $exception->getMessage(),
			'trace' => $exception->getTraceAsString(),
		))->save();
	}
}


text:
package com.github.ambry.network;

import com.github.ambry.commons.SSLFactory;
import com.github.ambry.utils.Time;
import java.io.EOFException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.channels.UnresolvedAddressException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A selector doing non-blocking multi-connection network I/O.
 *

 * This class works with {@link NetworkSend} and {@link NetworkReceive} to transmit network requests and responses.
 *

 * A connection can be added to the selector by doing
 *
 *

 * selector.connect("connectionId", new InetSocketAddress("linkedin.com", server.port), 64000, 64000);
 *

 *
 * The connect call does not block on the creation of the TCP connection, so the connect method only begins initiating
 * the connection. The successful invocation of this method does not mean a valid connection has been established. The
 * call on return provides a unique id that identifies this connection
 *
 * Sending requests, receiving responses, processing connection completions, and disconnections on the existing
 * connections are all done using the poll() call.
 *
 *

 * List<NetworkSend> requestsToSend = Arrays.asList(new NetworkSend(0, bytes), new NetworkSend(1, otherBytes));
 * selector.poll(TIMEOUT_MS, requestsToSend);
 *

 *
 * The selector maintains several lists that are reset by each call to poll() which are available via
 * various getters. These are reset by each call to poll().
 *
 * This class is not thread safe!
 */
public class Selector implements Selectable {
  private static final Logger logger = LoggerFactory.getLogger(Selector.class);

  private final java.nio.channels.Selector nioSelector;
  private final Map<String, SelectionKey> keyMap;
  private final List<NetworkSend> completedSends;
  private final List<NetworkReceive> completedReceives;
  private final List<String> disconnected;
  private final List<String> closedConnections;
  private final List<String> connected;
  private final Set<String> unreadyConnections;
  private final Time time;
  private final NetworkMetrics metrics;
  private final AtomicLong IdGenerator;
  private final AtomicLong numActiveConnections;
  private final SSLFactory sslFactory;

  /**
   * Create a new selector
   */
  public Selector(NetworkMetrics metrics, Time time, SSLFactory sslFactory) throws IOException {
    this.nioSelector = java.nio.channels.Selector.open();
    this.time = time;
    this.keyMap = new HashMap<String, SelectionKey>();
    this.completedSends = new ArrayList<NetworkSend>();
    this.completedReceives = new ArrayList<NetworkReceive>();
    this.connected = new ArrayList<String>();
    this.disconnected = new ArrayList<String>();
    this.closedConnections = new ArrayList<>();
    this.metrics = metrics;
    this.IdGenerator = new AtomicLong(0);
    numActiveConnections = new AtomicLong(0);
    unreadyConnections = new HashSet<>();
    metrics.registerSelectorActiveConnections(numActiveConnections);
    this.sslFactory = sslFactory;
  }

  /**
   * Generate an unique connection id
   * @param channel The channel between two hosts
   * @return The id for the connection that was created
   */
  private String generateConnectionId(SocketChannel channel) {
    Socket socket = channel.socket();
    String localHost = socket.getLocalAddress().getHostAddress();
    int localPort = socket.getLocalPort();
    String remoteHost = socket.getInetAddress().getHostAddress();
    int remotePort = socket.getPort();
    long connectionIdSuffix = IdGenerator.getAndIncrement();
    StringBuilder connectionIdBuilder = new StringBuilder();
    connectionIdBuilder.append(localHost)
        .append(":")
        .append(localPort)
        .append("-")
        .append(remoteHost)
        .append(":")
        .append(remotePort)
        .append("_")
        .append(connectionIdSuffix);
    return connectionIdBuilder.toString();
  }

  /**
   * Begin connecting to the given address and add the connection to this selector and returns an id that identifies
   * the connection
   *

   * Note that this call only initiates the connection, which will be completed on a future {@link #poll(long)}
   * call. Check {@link #connected()} to see which (if any) connections have completed after a given poll call.
   * @param address The address to connect to
   * @param sendBufferSize The networkSend buffer size for the new connection
   * @param receiveBufferSize The receive buffer size for the new connection
   * @param portType {@PortType} which represents the type of connection to establish
   * @return The id for the connection that was created
   * @throws IllegalStateException if there is already a connection for that id
   * @throws IOException if DNS resolution fails on the hostname or if the server is down
   */
  @Override
  public String connect(InetSocketAddress address, int sendBufferSize, int receiveBufferSize, PortType portType)
      throws IOException {
    SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);
    Socket socket = channel.socket();
    socket.setKeepAlive(true);
    socket.setSendBufferSize(sendBufferSize);
    socket.setReceiveBufferSize(receiveBufferSize);
    socket.setTcpNoDelay(true);
    try {
      channel.connect(address);
    } catch (UnresolvedAddressException e) {
      channel.close();
      throw new IOException("Can't resolve address: " + address, e);
    } catch (IOException e) {
      channel.close();
      throw e;
    }
    String connectionId = generateConnectionId(channel);
    SelectionKey key = channel.register(this.nioSelector, SelectionKey.OP_CONNECT);
    Transmission transmission = null;
    try {
      transmission =
          TransmissionFactory.getTransmission(connectionId, channel, key, address.getHostName(), address.getPort(),
              time, metrics, portType, sslFactory, SSLFactory.Mode.CLIENT);
    } catch (IOException e) {
      logger.error("IOException on transmission creation " + e);
      channel.socket().close();
      channel.close();
      throw e;
    }
    key.attach(transmission);
    this.keyMap.put(connectionId, key);
    numActiveConnections.set(this.keyMap.size());
    return connectionId;
  }

  /**
   * Register the nioSelector with an existing channel
   * Use this on server-side, when a connection is accepted by a different thread but processed by the Selector
   * Note that we are not checking if the connection id is valid - since the connection already exists
   */
  public String register(SocketChannel channel, PortType portType) throws IOException {
    Socket socket = channel.socket();
    String connectionId = generateConnectionId(channel);
    SelectionKey key = channel.register(nioSelector, SelectionKey.OP_READ);
    Transmission transmission = null;
    try {
      transmission =
          TransmissionFactory.getTransmission(connectionId, channel, key, socket.getInetAddress().getHostAddress(),
              socket.getPort(), time, metrics, portType, sslFactory, SSLFactory.Mode.SERVER);
    } catch (IOException e) {
      logger.error("IOException on transmission creation " + e);
      socket.close();
      channel.close();
      throw e;
    }
    key.attach(transmission);
    this.keyMap.put(connectionId, key);
    numActiveConnections.set(this.keyMap.size());
    return connectionId;
  }

  /**
   * Disconnect any connections for the given id (if there are any). The disconnection is asynchronous and will not be
   * processed until the next {@link #poll(long) poll()} call.
   */
  @Override
  public void disconnect(String connectionId) {
    SelectionKey key = this.keyMap.get(connectionId);
    if (key != null) {
      key.cancel();
    }
  }

  /**
   * Interrupt the selector if it is blocked waiting to do I/O.
   */
  @Override
  public void wakeup() {
    nioSelector.wakeup();
  }

  /**
   * Close this selector and all associated connections
   */
  @Override
  public void close() {
    for (SelectionKey key : this.nioSelector.keys()) {
      close(key);
    }
    try {
      this.nioSelector.close();
    } catch (IOException e) {
      metrics.selectorNioCloseErrorCount.inc();
      logger.error("Exception closing nioSelector:", e);
    }
  }

  /**
   * Tells whether or not this selector is open.

   *
   * @return <tt>true</tt> if, and only if, this selector is open
   */
  @Override
  public boolean isOpen() {
    return nioSelector.isOpen();
  }

  /**
   * Queue the given request for sending in the subsequent {@poll(long)} calls
   * @param networkSend The NetworkSend that is ready to be sent
   */
  public void send(NetworkSend networkSend) {
    SelectionKey key = keyForId(networkSend.getConnectionId());
    if (key == null) {
      throw new IllegalStateException("Attempt to send data to a null key");
    }
    Transmission transmission = getTransmission(key);
    try {
      transmission.setNetworkSend(networkSend);
    } catch (CancelledKeyException e) {
      logger.debug("Ignoring response for closed socket.");
      close(key);
    }
  }

  /**
   * Do whatever I/O can be done on each connection without blocking. This includes completing connections, completing
   * disconnections, initiating new sends, or making progress on in-progress sends or receives.
   *

   *
   * When this call is completed the user can check for completed sends, receives, connections or disconnects using
   * {@link #completedSends()}, {@link #completedReceives()}, {@link #connected()}, {@link #disconnected()}. These
   * lists will be cleared at the beginning of each {@link #poll(long)} call and repopulated by the call if any
   * completed I/O.
   *
   * @param timeoutMs The amount of time to wait, in milliseconds. If negative, wait indefinitely.
   *
   * @throws IOException If a send is given for which we have no existing connection or for which there is
   *         already an in-progress send
   */
  @Override
  public void poll(long timeoutMs) throws IOException {
    poll(timeoutMs, null);
  }

  /**
   * Firstly initiate the provided sends. Then do whatever I/O can be done on each connection without blocking.
   * This includes completing connections, completing disconnections, initiating new sends,
   * or making progress on in-progress sends or receives.
   *

   *
   * When this call is completed the user can check for completed sends, receives, connections or disconnects using
   * {@link #completedSends()}, {@link #completedReceives()}, {@link #connected()}, {@link #disconnected()}. These
   * lists will be cleared at the beginning of each {@link #poll(long, List)} call and repopulated by the call if any
   * completed I/O.
   *
   * @param timeoutMs The amount of time to wait, in milliseconds. If negative, wait indefinitely.
   * @param sends The list of new sends to begin
   *
   * @throws IOException If a send is given for which we have no existing connection or for which there is
   *         already an in-progress send
   */
  @Override
  public void poll(long timeoutMs, List<NetworkSend> sends) throws IOException {
    clear();

    // register for write interest on any new sends
    if (sends != null) {
      for (NetworkSend networkSend : sends) {
        send(networkSend);
      }
    }

    // check ready keys
    long startSelect = time.milliseconds();
    int readyKeys = select(timeoutMs);
    long endSelect = time.milliseconds();
    this.metrics.selectorSelectTime.update(endSelect - startSelect);
    this.metrics.selectorSelectCount.inc();

    if (readyKeys > 0) {
      Set<SelectionKey> keys = nioSelector.selectedKeys();
      Iterator<SelectionKey> iter = keys.iterator();
      while (iter.hasNext()) {
        SelectionKey key = iter.next();
        iter.remove();

        Transmission transmission = getTransmission(key);
        try {
          if (key.isConnectable()) {
            transmission.finishConnect();
            if (transmission.ready()) {
              connected.add(transmission.getConnectionId());
              metrics.selectorConnectionCreated.inc();
            } else {
              unreadyConnections.add(transmission.getConnectionId());
            }
          }

          /* if channel is not ready, finish prepare */
          if (transmission.isConnected() && !transmission.ready()) {
            transmission.prepare();
            continue;
          }

          if (key.isReadable() && transmission.ready()) {
            read(key, transmission);
          } else if (key.isWritable() && transmission.ready()) {
            write(key, transmission);
          } else if (!key.isValid()) {
            close(key);
          }
        } catch (IOException e) {
          String socketDescription = socketDescription(channel(key));
          if (e instanceof EOFException || e instanceof ConnectException) {
            metrics.selectorDisconnectedErrorCount.inc();
            logger.error("Connection {} disconnected", socketDescription, e);
          } else {
            metrics.selectorIOErrorCount.inc();
            logger.warn("Error in I/O with connection to {}", socketDescription, e);
          }
          close(key);
        } catch (Exception e) {
          metrics.selectorKeyOperationErrorCount.inc();
          logger.error("closing key on exception remote host {}", channel(key).socket().getRemoteSocketAddress(), e);
          close(key);
        }
      }
      checkUnreadyConnectionsStatus();
      this.metrics.selectorIOCount.inc();
    }
    disconnected.addAll(closedConnections);
    closedConnections.clear();
    long endIo = time.milliseconds();
    this.metrics.selectorIOTime.update(endIo - endSelect);
  }

  /**
   * Check readiness for unready connections and add to completed list if ready
   */
  private void checkUnreadyConnectionsStatus() {
    Iterator<String> iterator = unreadyConnections.iterator();
    while (iterator.hasNext()) {
      String connId = iterator.next();
      if (isChannelReady(connId)) {
        connected.add(connId);
        iterator.remove();
        metrics.selectorConnectionCreated.inc();
      }
    }
  }

  /**
   * Generate the description for a SocketChannel
   */
  private String socketDescription(SocketChannel channel) {
    Socket socket = channel.socket();
    if (socket == null) {
      return "[unconnected socket]";
    } else if (socket.getInetAddress() != null) {
      return socket.getInetAddress().toString();
    } else {
      return socket.getLocalAddress().toString();
    }
  }

  /**
   * Returns {@code true} if channel is ready to send or receive data, {@code false} otherwise
   * @param connectionId upon which readiness is checked for
   * @return true if channel is ready to accept reads/writes, false otherwise
   */
  public boolean isChannelReady(String connectionId) {
    Transmission transmission = getTransmission(keyForId(connectionId));
    return transmission.ready();
  }

  @Override
  public List<NetworkSend> completedSends() {
    return this.completedSends;
  }

  @Override
  public List<NetworkReceive> completedReceives() {
    return this.completedReceives;
  }

  @Override
  public List<String> disconnected() {
    return this.disconnected;
  }

  @Override
  public List<String> connected() {
    return this.connected;
  }

  public long getNumActiveConnections() {
    return numActiveConnections.get();
  }

  /**
   * Clear the results from the prior poll
   */
  private void clear() {
    completedSends.clear();
    completedReceives.clear();
    connected.clear();
    disconnected.clear();
  }

  /**
   * Check for data, waiting up to the given timeout.
   *
   * @param ms Length of time to wait, in milliseconds. If negative, wait indefinitely.
   * @return The number of keys ready
   * @throws IOException
   */
  private int select(long ms) throws IOException {
    if (ms == 0L) {
      return this.nioSelector.selectNow();
    } else if (ms < 0L) {
      return this.nioSelector.select();
    } else {
      return this.nioSelector.select(ms);
    }
  }

  /**
   * Begin closing this connection by given connection id
   */
  @Override
  public void close(String connectionId) {
    SelectionKey key = keyForId(connectionId);
    if (key == null) {
      metrics.selectorCloseKeyErrorCount.inc();
      logger.error("Attempt to close socket for which there is no open connection. Connection id {}", connectionId);
    } else {
      close(key);
    }
  }

  /**
   * Begin closing this connection by given key
   */
  private void close(SelectionKey key) {
    Transmission transmission = getTransmission(key);
    if (transmission != null) {
      logger.debug("Closing connection from {}", transmission.getConnectionId());
      closedConnections.add(transmission.getConnectionId());
      keyMap.remove(transmission.getConnectionId());
      numActiveConnections.set(keyMap.size());
      unreadyConnections.remove(transmission.getConnectionId());
      try {
        transmission.close();
      } catch (IOException e) {
        logger.error("IOException thrown during closing of transmission with connectionId {} :",
            transmission.getConnectionId(), e);
      }
    } else {
      key.attach(null);
      key.cancel();
      SocketAddress address = null;
      try {
        SocketChannel socketChannel = channel(key);
        address = socketChannel.socket().getRemoteSocketAddress();
        socketChannel.socket().close();
        socketChannel.close();
      } catch (IOException e) {
        metrics.selectorCloseSocketErrorCount.inc();
        logger.error("Exception closing connection to remote host {} :", address, e);
      }
    }
    this.metrics.selectorConnectionClosed.inc();
  }

  /**
   * Get the selection key associated with this numeric id
   */
  private SelectionKey keyForId(String id) {
    return this.keyMap.get(id);
  }

  /**
   * Process reads from ready sockets
   */
  private void read(SelectionKey key, Transmission transmission) throws IOException {
    long startTimeToReadInMs = time.milliseconds();
    try {
      boolean readComplete = transmission.read();
      if (readComplete) {
        this.completedReceives.add(transmission.getNetworkReceive());
        transmission.onReceiveComplete();
        transmission.clearReceive();
      }
    } finally {
      long readTime = time.milliseconds() - startTimeToReadInMs;
      logger.trace("SocketServer time spent on read per key {} = {}", transmission.getConnectionId(), readTime);
    }
  }

  /**
   * Process writes to ready sockets
   */
  private void write(SelectionKey key, Transmission transmission) throws IOException {
    long startTimeToWriteInMs = time.milliseconds();
    try {
      boolean sendComplete = transmission.write();
      if (sendComplete) {
        logger.trace("Finished writing, registering for read on connection {}", transmission.getRemoteSocketAddress());
        transmission.onSendComplete();
        this.completedSends.add(transmission.getNetworkSend());
        metrics.sendInFlight.dec();
        transmission.clearSend();
        key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE | SelectionKey.OP_READ);
      }
    } finally {
      long writeTime = time.milliseconds() - startTimeToWriteInMs;
      logger.trace("SocketServer time spent on write per key {} = {}", transmission.getConnectionId(), writeTime);
    }
  }

  /**
   * Get the Transmission for the given connection
   */
  private Transmission getTransmission(SelectionKey key) {
    return (Transmission) key.attachment();
  }

  /**
   * Get the socket channel associated with this selection key
   */
  private SocketChannel channel(SelectionKey key) {
    return (SocketChannel) key.channel();
  }
}


text:
project_path: /web/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: Web'e, küçük ekranli telefonlardan genis ekranli televizyonlara kadar çok çesitli cihazlardan erisilebilir. Tüm bu cihazlarda iyi bir sekilde çalisacak bir siteyi nasil olusturacaginizi ögrenin.

{# wf_updated_on: 2014-01-05 #}
{# wf_published_on: 2013-12-31 #}

# Ilk Çoklu Cihaz Siteniz {: .page-title }

{% include "web/_shared/contributors/paulkinlan.html" %}

Çoklu cihaz deneyimleri olusturmak sanildigi kadar zor degildir. Bu kilavuzu izleyerek CS256 Mobil Web Gelistirme kursumuz için farkli cihaz türlerinin tümünde iyi sekilde çalisan bir örnek ürün açilis sayfasi olusturacagiz.

Farkli yeteneklere, oldukça farkli ekran boyutlarina ve etkilesim yöntemlerine sahip birden çok cihaz için olusturma, baslangiçta imkansiz gibi görünmese de göz korkutucu gelebilir.

Tamamiyla duyarli siteler olusturmak düsündügünüz kadar zor degildir ve size göstermek için bu kilavuzda, baslarken kullanabileceginiz adimlar ayrintili bir sekilde açiklanmaktadir.  Bunu iki basit adima ayirdik:

1.  Sayfanin bilgi mimarisini (genellikle IA olarak bilinir) ve yapisini tanimlama, 2.  Sayfanin duyarli olmasi ve tüm cihazlarda iyi görünmesi için tasarim ögeleri ekleme.

## Içeriginizi ve Yapinizi Olusturma

Içerik, bir sitenin en önemli ögesidir. O zaman, içerige göre tasarim yapip tasarimin içerige hükmetmesine izin vermeyelim. Bu kilavuzda, öncelikle ihtiyacimiz olan içerigi tanimlayacagiz, bu içerige dayali bir sayfa yapisi olusturacagiz ve daha sonra, sayfayi, dar ve genis görüntü alanlarinda düzgün çalisan basit bir dogrusal yerlesimde sunacagiz.

### Sayfa yapisini olusturma

Asagidakilere ihtiyacimiz oldugunu belirledik:

1.  Yüksek bir düzeyde ürünümüz olan `CS256: Mobil web gelistirme` kursunu açiklayan bir alan
2.  Ürünümüzle ilgilenen kullanicilardan bilgi toplamak için bir form
3.  Ayrintili bir açiklama ve video
4.  Ürününün eylem halindeyken resimleri
5.  Iddialari destekleyen bilgilerin bulundugu bir veri tablosu

### TL;DR {: .hide-from-toc }
- Öncelikle ihtiyaciniz olan içerigi tanimlayin.
- Dar ve genis görüntü alanlari için Bilgi Mimarisi`ni (IA) tasarlayin.
- Stil olmadan, içerikle birlikte sayfanin bir iskelet görünümünü olusturun.

Ayrica, hem dar hem de genis görüntü alanlari için kaba bir bilgi mimarisi ve yerlesim de olusturduk.

Bu, projenin geri kalaninda kullanacagimiz iskelet sayfanin kaba bölümlerine kolayca dönüstürülebilir.

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/addstructure.html" region_tag="structure" adjust_indentation="auto" %}

### Sayfaya içerik ekleme

Sitenin temel yapisi tamamlandi. Ihtiyacimiz olan bölümleri, bu bölümlerde görüntülenecek içerigi ve genel bilgi mimarisi içinde bunu nereye yerlestirecegimizi biliyoruz. Artik sitemizi olusturmaya baslayabiliriz.

Note: Stil daha sonra gelecektir

#### Baslik ve formu olusturma

Baslik ve istek bildirim formu, sayfamizin önemli bilesenleridir. Bunlarin kullaniciya hemen sunulmasi gerekir.

Basliga, kursu açiklamak için basit bir metin ekleyin:

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/addheadline.html" region_tag="headline" adjust_indentation="auto" %}

Formu da doldurmamiz gerekiyor.
Bu, kullanicilarin adlarini, telefon numaralarini ve onlari geri aramak için uygun olduklari zaman bilgisini toplayan basit bir form olacak.

Kullanicilarin ögelere kolayca odaklanmalarini, içinde ne olmasi gerektigini anlamalarini kolaylastirmak ve ayrica, erisilebilirlik araçlarinin formun yapisini anlamasina yardimci olmak için tüm formlarin etiketleri ve yer tutuculari olmalidir.  Ad özelligi yalnizca form degerini sunucuya göndermekle kalmaz, ayni zamanda tarayiciya, formu kullanici adina otomatik olarak nasil dolduracagiyla ilgili önemli ipuçlari da verir.

Kullanicilarin bir mobil cihazda içerigi hizli ve basit bir sekilde girebilmelerini saglamak için anlamsal türler ekleyecegiz.  Örnegin, bir telefon numarasi girerken kullanicinin yalnizca bir tus takimi görmesi gerekir.

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/addform.html" region_tag="form" adjust_indentation="auto" %}

{# include shared/related_guides.liquid inline=true list=page.related-guides.create-amazing-forms #}

#### Video ve Bilgi bölümünü olusturma

Içerigin Video ve Bilgi bölümü biraz daha derinlige sahiptir.
Ürünlerimizin özelliklerinin madde imli bir listesini ve ayrica, bir kullaniciyi ürünümüzü kullanirken gösteren bir video yer tutucusunu içerir.

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/addcontent.html" region_tag="section1" adjust_indentation="auto" %}

Videolar genellikle içerigi daha etkilesimli bir sekilde açiklamak ve siklikla bir ürünün veya kavramin tanitim gösterisini göstermek için kullanilir.

En iyi uygulamalari izleyerek videoyu sitenize kolayca entegre edebilirsiniz:

*  Kullanicilarin videoyu oynatmalarini kolaylastirmak için bir `controls` özelligi ekleyin.
*  Kullanicilara içerigin bir önizlemesini saglamak için bir `poster` resmi ekleyin.
*  Desteklenen video biçimlerine göre birden çok `<source>` ögesi ekleyin.
*  Kullanicilarin videoyu pencerede oynatamamalari durumunda indirebilmelerini saglamak için yedek metin ekleyin.

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/addvideo.html" region_tag="video"   adjust_indentation="auto" %}

{# include shared/related_guides.liquid inline=true list=page.related-guides.video #}

#### Resimler Bölümünü Olusturma

Resim bulunmayan siteler biraz sikici olabilir. Iki tür resim vardir:

*  Içerik resimleri: Dokümanla ayni dogrultuda olan ve içerikle ilgili fazladan bilgileri aktarmak için kullanilan resimler.
*  Biçimsel resimler: Sitenin daha iyi görünmesi için kullanilan resimler; bunlar genellikle arka plan resimleri, kaliplar ve renk geçisleri seklindedir.  Bu konuyu [sonraki makale](#) baslikli makalede ele alacagiz.

Sayfamizdaki Resimler bölümü, içerik resimlerinden olusan bir koleksiyondur.

Içerik resimleri, sayfanin anlamini aktarma açisindan önemlidir. Bunlari, gazete makalelerinde kullanilan resimler gibi düsünebilirsiniz. Kullandigimiz resimler, projenin egitmenleri olan Chris Wilson, Peter Lubbers ve Sean Bennet'in resimleridir.

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/addimages.html" region_tag="images"   adjust_indentation="auto" %}

Resimler, ekran genisliginin %100 ölçegine ayarlanmistir. Bu, dar görüntü alani olan cihazlarda iyi bir sekilde çalisir, ancak genis görüntü alanina sahip cihazlarda (masaüstü bilgisayarlar gibi) çok iyi görünmez.  Bunu, duyarli tasarim bölümünde ele alacagiz.

{# include shared/related_guides.liquid inline=true list=page.related-guides.images #}

Birçok kisi, resimleri görüntüleyemez ve genellikle, sayfadaki verileri ayristiran ve bunu kullaniciya sözlü olarak aktaran ekran okuyucu gibi bir yardimci teknoloji kullanir.  Tüm içerik resimlerinizde, ekran okuyucunun resmi kullaniciya açiklayabilmesi için bir tanimlayici `alt` etiketinin bulundugundan emin olun.

`alt` etiketlerini eklerken, resmi tam olarak açiklamak için alt metnini mümkün oldugunca kisa tuttugunuzdan emin olun.  Örnegin, demomuzda özelligi `Ad: Rol` olacak sekilde biçimlendiriyoruz. Bu, kullanicinin bu bölümün yazarlar ve yazarlarin isleriyle ilgili oldugunu anlamasi için yeterli bilgi sunmaktadir.

#### Tablolastirilmis Veri Bölümünü Ekleme

Son bölüm, ürünle ilgili belirli ürün verilerini göstermek için kullanilan basit bir tablodur.

Tablolar yalnizca bilgi matrisleri gibi tablo seklindeki veriler için kullanilmalidir.

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/addcontent.html" region_tag="section3" adjust_indentation="auto" %}

#### Altbilgi Ekleme

Çogu sitenin Sartlar ve Kosullar, sorumlulugun reddi beyanlari gibi içerigi ve sayfanin ana gezinme veya ana içerik alaninda bulunmamasi gereken baska içerikleri görüntülemek için bir altbilgiye ihtiyaci vardir.

Bizim sitemizde, yalnizca Sartlar ve Kosullar'a, bir Iletisim sayfasina ve sosyal medya profillerimize baglanti verecegiz.

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/addcontent.html" region_tag="footer" adjust_indentation="auto" %}

### Özet

Sitenin ana hatlarini olusturduk ve ana yapisal ögelerin tümünü tanimladik.  Ayrica, ilgili tüm içerigin is gereksinimlerimizi karsilamak üzere hazir ve yerinde oldugundan emin olduk.

       Içerik ve yapi

       Son site

Sayfanin su anda kötü göründügünü fark etmissinizdir; bunu bilinçli olarak böyle yaptik.
Içerik, bir sitenin en önemli ögesidir ve saglam bir bilgi mimarisine ve yogunluga sahip oldugumuzdan emin olmamiz gerekiyordu. Bu kilavuz, bize dayanabilecegimiz harika bir temel verdi. Sonraki kilavuzda içerigimizi biçimlendirecegiz.

## Duyarli Olmasini Saglayin

Web'e, küçük ekranli telefonlardan genis ekranli televizyonlara kadar çok çesitli cihazlardan erisilebilir. Her bir cihaz kendi benzersiz avantajlarina, ayni zamanda kisitlamalarina sahiptir. Bir web gelistiricisi olarak tüm cihazlari desteklemeniz beklenir.

Birden çok ekran boyutunda ve cihaz türünde çalisacak bir site olusturuyoruz. [Önceki makale](#) baslikli makalede, sayfanin Bilgi Mimarisi'ni isledik ve bir temel yapi olusturduk.
Bu kilavuzda, içerikle temel yapimizi alip çok sayida ekran boyutuna duyarli güzel bir sayfaya dönüstürecegiz.

       Içerik ve yapi

       Son site

Önce Mobil Cihazlar web gelistirme ilkelerini izleyerek bir cep telefonuna benzeyen, dar bir görüntü alaniyla basliyoruz ve önce bu deneyimi olusturuyoruz.
Daha sonra, deneyimi daha genis cihaz siniflarina ölçekliyoruz.
Bunu, görüntü alanimizi genisleterek ve tasarim ile yerlesimin düzgün görünüp görünmedigine karar vererek yapabiliriz.

Daha önce, içerigimizin nasil görünmesi gerektigine dair farkli, üst düzey birkaç tasarim olusturmustuk. Simdi sayfamizin bu farkli yerlesimlere uyarlanmasini saglamamiz gerekiyor.
Bunu, içerigi ekran boyutuna sigdirma yöntemimize göre kesme noktalarimizi nereye yerlestirecegimize karar vererek yapiyoruz. Kesme noktalari, yerlesim ve stil degisikliginin gerçeklestigi noktalardir.

### TL;DR {: .hide-from-toc }
- Her zaman bir görüntü alani kullanin.
- Her zaman önce dar bir görüntü alaniyla baslayip daha sonra bunu genisletin.
- Içerigi uyarlamaniz gerektiginde bunu kesme noktalariniza dayandirin.
- Ana kesme noktalarinizdan yerlesiminizin bir üst düzey görüntüsünü olusturun.

### Bir görüntü alani ekle

Temel bir sayfa için bile her zaman bir görüntü alani meta etiketi **kullanmaniz gerekir**.
Görüntü alani, birden çok cihaz deneyimi olusturmak için ihtiyaciniz olan en önemli bilesendir.
Bu olmadan, siteniz bir mobil cihazda düzgün çalismaz.

Görüntü alani, tarayiciya sayfanin ekrana sigmasi için ölçeklenmesi gerektigini bildirir.  Görüntü alaninizin sayfanin görüntüsünü kontrol etmesi için belirtebileceginiz birçok farkli yapilandirma vardir.  Varsayilan olarak sunlari öneririz:

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/viewport.html" region_tag="viewport" adjust_indentation="auto" %}

Görüntü alani, dokümanin basinda yer alir ve yalnizca bir kez açiklanmasi gerekir.

{# include shared/related_guides.liquid inline=true list=page.related-guides.responsive #}

### Basit stil uygula

Ürünümüzün ve sirketimizin bir stil kilavuzunda saglanmis çok özel marka bilinci olusturma ve yazi tipi yönergeleri zaten vardir.

#### Stil kilavuzu

Stil kilavuzu, sayfanin görsel gösterimini bir üst düzeyde anlamanin yararli bir yoludur ve tasarim genelinde tutarli oldugunuzdan emin olmaniza yardimci olur.

##### Renkler

#39b1a4

#ffffff

#f5f5f5

#e9e9e9

#dc4d38

#### Biçimsel resimler eklemek

Önceki kilavuzda, "içerik resimleri" adli resimleri ekledik.  Bunlar, ürünümüzün anlatilmasi açisindan önemli resimlerdi.  Biçimsel resimler, temel içerigin parçasi olarak ihtiyaç duyulmayan, ancak görsel gösteris ekleyen veya kullanicinin dikkatini belirli bir içerik parçasina yönlendirmeye yardimci olan resimlerdir.

Buna iyi bir örnek, "ekranin üst kismi"ndaki içerik için bir manset resmi kullanilmasi olabilir. Genellikle, kullaniciyi ürünle ilgili daha fazla bilgi okumaya ikna etmek için kullanilir.

Eklenmeleri çok basit olabilir. Bizim örnegimizde, bu basligin arka plani olacaktir ve bazi basit CSS'ler araciligiyla uygulanacaktir.

    #headline {
      padding: 0.8em;
      color: white;
      font-family: Roboto, sans-serif;
      background-image: url(backgroundimage.jpg);
      background-size: cover;
    }

Dikkati içerikten uzaklastirmamasi için bulaniklastirilmis, basit bir arka plan resmi seçtik ve bunu tüm ögeyi `kaplayacak` sekilde ayarladik; böylece, dogru en boy oranini korurken her zaman uzatilir.

### İlk kesme noktamizi ayarlayın

Tasarim, yaklasik 600 piksel genisliginde kötü görünmeye basliyor.  Bizim örnegimizde, satirin uzunlugu 10 kelimenin üzerine çikiyor (en uygun okuma uzunlugu) ve bu noktada, bunu degistirmek istiyoruz.

<video controls poster="images/firstbreakpoint.png" style="width: 100%;">
  <source src="videos/firstbreakpoint.mov" type="video/mov"></source>
  <source src="videos/firstbreakpoint.webm" type="video/webm"></source>

Maalesef tarayiciniz videoyu desteklemiyor.
     Videoyu indirin.

</video>

600 piksel, ilk kesme noktamizi olusturmak için iyi bir yer gibi görünüyor. Bu, ögeleri ekrana daha iyi sigmalari amaciyla yeniden konumlandirmamiz için gereken alani saglayacak.  Bunu, [Medya Sorgulari](/web/fundamentals/design-and-ux/responsive/#use-css-media-queries-for-responsiveness) adli bir teknolojiyi kullanarak yapabiliriz.

    @media (min-width: 600px) {

    }

Daha genis bir ekranda daha fazla alan vardir, dolayisiyla içerigin nasil görüntülenebilecegi konusunda daha esnek olunabilir.

Note: Tüm ögeleri ayni anda tasimaniz gerekmez, gerektikçe küçük ayarlamalar yapabilirsiniz.

Ürün sayfamiz baglaminda görünüse göre sunlari yapmamiz gerekecek:

*  Tasarimin maksimum genisligini sinirlama.
*  Ögelerin dolgusunu degistirme ve metin boyutunu küçültme.
*  Formu, baslik içerigiyle hizali bir sekilde hareket etmesi için tasima.
*  Videonun içerik çevresinde hareket etmesini saglama.
*  Resimlerin boyutunu küçültme ve daha hos bir tabloda görünmelerini saglama.

{# include shared/related_guides.liquid inline=true list=page.related-guides.first-break-point #}

### Tasarimin maksimum genisligini sinirlama

Yalnizca iki ana yerlesimimizin olmasini seçtik: dar bir görüntü alani ve genis bir görüntü alani. Bu seçimimiz, olusturma sürecimizi büyük ölçüde basitlestirecek.

Ayrica, dar görüntü alaninda kenarliksiz bölümler olusturmaya ve bu bölümlerin, genis görüntü alaninda kenarliksiz kalmasina karar verdik.  Bu, metin ve paragraflarin ultra genis ekranlarda tek, uzun bir satira uzamamasi için ekranin maksimum genisligini sinirlamamiz gerektigi anlamina gelir.  Bu noktanin yaklasik 800 pikselde olmasini seçtik.

Bunu gerçeklestirmek için genisligi sinirlandirmamiz ve ögeleri ortalamamiz gerekir.  Her bir ana bölümün çevresinde bir kapsayici olusturup bir `margin: auto` kodu uygulamaliyiz. Bu, ekranin büyümesine, ancak içerigin ortalanmis bir sekilde ve maksimum 800 piksel boyutta kalmasina olanak taniyacak.

Kapsayici, asagidaki biçimde basit bir `div` ögesi olacak:

    ...

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/fixingfirstbreakpoint.html" region_tag="containerhtml"   adjust_indentation="auto" %}

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/fixingfirstbreakpoint.html" region_tag="container"   adjust_indentation="auto" %}

### Dolguyu degistirme ve metin boyutunu küçültme

Dar görüntü alaninda, içerigi görüntülemek için çok fazla alanimiz olmadigindan tipografinin boyutu ve agirligi, ekrana sigmasi için çogunlukla önemli ölçüde küçültülür.

Daha genis bir görüntü alanimiz oldugunda kullanicinin daha genis bir ekranda, ancak ekrandan biraz daha uzakta bulunma olasiligini göz önünde bulundurmamiz gerekir.  Içerigin okunabilirligini artirmak için tipografinin boyutunu ve agirligini artirabilir ve ayri alanlari daha da ayirmak için dolguyu degistirebiliriz.

Ürün sayfamizda, bölüm ögelerinin dolgusunu genisligin %5'inde kalacak sekilde ayarlayarak dolguyu artiracagiz.  Ayrica, her bir bölümün basliklarinin boyutunu da artiracagiz.

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/fixingfirstbreakpoint.html" region_tag="padding"   adjust_indentation="auto" %}

### Ögeleri genis görüntü alanina uyarlama

Dar görüntü alanimiz, yigin seklinde dogrusal bir görüntüydü.  Her bir ana bölüm ve içindeki içerik, yukaridan asagiya dogru görüntüleniyordu.

Genis görüntü alani, bize içerigi ilgili ekran için en uygun sekilde görüntülemek üzere kullanabilecegimiz fazladan alan verir.  Ürün sayfamiz için bu, IA'miza göre asagidakileri yapabilecegimiz anlamina gelir:

*  Formu, baslik bilgileri çevresinde hareket ettirme.
*  Videoyu, önemli noktalarin sagina yerlestirme.
*  Resimleri döseme.
*  Tabloyu genisletme.

#### Form ögesini hareket ettirme

Dar görüntü alani, ögeleri ekrana rahatça yerlestirmek için çok daha az bir yatay alani kullanabilecegimiz anlamina gelir.

Yatay ekran alanini daha etkili kullanmak için basligin dogrusal akisindan çikmamiz ve form ile listeyi yan yana olacaklari sekilde tasimamiz gerekir.

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/fixingfirstbreakpoint.html" region_tag="formfloat"   adjust_indentation="auto" %}

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/fixingfirstbreakpoint.html" region_tag="padding"   adjust_indentation="auto" %}

<video controls poster="images/floatingform.png" style="width: 100%;">
  <source src="videos/floatingform.mov" type="video/mov"></source>
  <source src="videos/floatingform.webm" type="video/webm"></source>

Maalesef tarayiciniz videoyu desteklemiyor.
     Videoyu indirin.

</video>

#### Video ögesini hareket ettirme

Dar görüntü alani arayüzündeki video, ekranin tam genisligini kaplayacak ve önemli özellikler listesinden sonre yerlestirilecek sekilde tasarlanmistir. Genis bir görüntü alaninda, video çok genisleyecek sekilde ölçeklenir ve özellik listemizin yanina yerlestirildiginde yanlis görünür.

Video ögesinin, dar görüntü alaninin dikey akisinin disina tasinmasi ve genis bir görüntü alaninda içerigin madde imli listesiyle yan yana görüntülenmesi gerekir.

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/fixingfirstbreakpoint.html" region_tag="floatvideo"   adjust_indentation="auto" %}

#### Resimleri Döseme

Dar görüntü alani arayüzündeki resimler (çogunlukla mobil cihazlar), ekranin tam genisligini kaplayacak ve dikey olarak yigilacak sekilde ayarlanir.  Bu, genis görüntü alaninda iyi bir sekilde ölçeklenmez.

Resimlerin genis bir görüntü alaninda dogru görünmesini saglamak için kapsayici genisliginin %30'una ölçeklenirler ve (dar görüntü alanindaki gibi dikey yerlestirilmeleri yerine) yatay olarak yerlestirilirler. Ayrica, resimleri daha çekici hale getirmek için biraz sinir yariçapi ve kutu gölgesi de ekleyecegiz.

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/fixingfirstbreakpoint.html" region_tag="tileimages"   adjust_indentation="auto" %}

#### Resimleri DPI'ya duyarli yapma

Resimleri kullanirken, görüntü alaninin boyutunu ve ekranin yogunlugunu dikkate alin.

Web baslangiçta 96 dpi degerindeki ekranlar için olusturulmustu.  Mobil cihazlarin kullanilmaya baslanmasiyla ekranlarin piksel yogunlugunda büyük bir artis gördük; dizüstü bilgisayarlarin Retina sinifi ekranlarindan hiç söz etmiyoruz bile.  Bunun gibi, 96 dpi degerine kodlanan resimler genellikle yüksek dpi degerine sahip bir cihazda berbat görünür.

Bunun için henüz yaygin bir sekilde benimsenmemis bir çözümümüz var.
Bunu destekleyen tarayicilarda, yüksek yogunluga sahip bir ekranda yüksek yogunluga sahip bir resim görüntüleyebilirsiniz.

{# include shared/related_guides.liquid inline=true list=page.related-guides.images #}

#### Tablolar

Tablolarin, dar görüntü alani olan cihazlarda dogru bir sekilde görüntülenmesi çok zordur ve bunlara özel olarak dikkat edilmesi gerekir.

Dar bir görüntü alaninda tablonuzu iki satirdan olusturmanizi, bir satirdaki baslik ve hücrelerin sirasini degistirerek sütunlu görünümü elde etmenizi öneririz.

<video controls poster="images/responsivetable.png" style="width: 100%;">
  <source src="videos/responsivetable.mov" type="video/mov"></source>
  <source src="videos/responsivetable.webm" type="video/webm"></source>

Maalesef tarayiciniz videoyu desteklemiyor.
     Videoyu indirin.

</video>

Sitemizde, yalnizca tablo içerigi için fazladan bir kesme noktasi olusturmamiz gerekiyordu.
Önce bir mobil cihaz için olusturdugunuzda, uygulanan stilleri geri almak daha zor olacagindan, dar görüntü alani tablosu CSS'sini genis görüntü alani  CSS'sinden ayirmamiz gerekir.
Bu, bize net ve tutarli bir kesme saglar.

{% includecode content_path="web/fundamentals/codelabs/your-first-multi-screen-site/_code/content-with-styles.html" region_tag="table-css"   adjust_indentation="auto" %}

### Özet

**TEBRIKLER.** Bunu okurken, çok sayida cihazda, biçim katsayisinda ve ekran boyutunda çalisan ilk basit ürün açilis sayfanizi olusturmus olacaksiniz.

Bu yönergeleri uygularsaniz iyi bir baslangiç yaparsiniz:

1.  Bir temel IA olusturun ve kodlamadan önce içeriginizi anlayin.
2.  Her zaman bir görüntü alani ayarlayin.
3.  Temel deneyiminizi önce mobil cihazlar yaklasimiyla olusturun.
4.  Mobil deneyiminizi olusturduktan sonra, görüntünün genisligini görüntü bozulmaya baslayana kadar artirin ve kesme noktanizi buraya ayarlayin.
5.  Bunu tekrarlamaya devam edin.


text:
<?php

namespace Abc\Bundle\SupervisorBundle\Tests\Functional\Controller;

use Abc\Bundle\SupervisorBundle\Supervisor\SupervisorManager;
use Abc\Bundle\SupervisorBundle\Test\WebTestCase;

/**
 * @author Hannes Schulz <hannes.schulz@aboutcoders.com>
 */
class ProcessControllerTest extends WebTestCase
{
    /**
     * @var SupervisorManager|\PHPUnit_Framework_MockObject_MockObject
     */
    private $manager;

    /**
     * {@inheritdoc}
     */
    public function setUp()
    {
        $this->manager = $this->createMock(SupervisorManager::class);
    }

    public function testListAction()
    {
        $url = '/api/supervisors/localhost/processes';

        $client = static::createClient();

        $this->manager->expects($this->once())
            ->method('findById')
            ->willReturn(null);

        $this->mockServices(['abc.supervisor.manager' => $this->manager]);

        $client->request('GET', $url);

        $this->assertEquals(404, $client->getResponse()->getStatusCode());
    }

    public function testStartAction()
    {
        $url = '/api/supervisors/localhost/processes/foobar/start';

        $client = static::createClient();

        $this->manager->expects($this->once())
            ->method('findById')
            ->willReturn(null);

        $this->mockServices(['abc.supervisor.manager' => $this->manager]);

        $client->request('POST', $url);

        $this->assertEquals(404, $client->getResponse()->getStatusCode());
    }

    public function testStopAction()
    {
        $url = '/api/supervisors/localhost/processes/foobar/stop';

        $client = static::createClient();

        $this->manager->expects($this->once())
            ->method('findById')
            ->willReturn(null);

        $this->mockServices(['abc.supervisor.manager' => $this->manager]);

        $client->request('POST', $url);

        $this->assertEquals(404, $client->getResponse()->getStatusCode());
    }
}


text:
@implementation SFAppIdentity

- (NSURL *)rateURL {
	return [NSURL URLWithString:[NSString stringWithFormat:@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@", [SFAppIdentity iTunesAppId]]];
}

- (NSString *)storeURL {
	return [NSString stringWithFormat:@"http://itunes.apple.com/app/sonarflow/id%@", [SFAppIdentity iTunesAppId]];
}

- (NSString *)storeURLForCrossPromo {
	return [NSString stringWithFormat:@"http://itunes.apple.com/app/sonarflow/id%@", [SFAppIdentity iTunesAppIdForCrossPromo]];
}

+ (NSString *)iTunesAppId {
#if defined(SF_FREE)
	return [self iTunesAppIdFree];
#elif defined(SF_PRO)
	return [self iTunesAppIdPro];
#else
	return [self iTunesAppIdSpot];
#endif
}

+ (NSString *)iTunesAppIdForCrossPromo {
#if defined(SF_SPOTIFY)
	return [self iTunesAppIdFree];
#else
	return [self iTunesAppIdSpot];
#endif
}

+ (NSString *)iTunesAppIdFree {
	return @"382049291";
}

+ (NSString *)iTunesAppIdPro {
	return @"407248118";
}

+ (NSString *)iTunesAppIdSpot {
	return @"535452166";
}

- (NSString *)facebookAppId {
	const char *appIdCStr = FACEBOOK_APP_ID_STR;
	return [NSString stringWithUTF8String:appIdCStr];
}

@end


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Diy_customer_type extends MX_Controller
{
    function __construct() {
        parent::__construct();
    }

    function index(){
        $groups = $this->get('id')->result();
	echo '<pre>';
        var_dump($groups);
        echo '</pre>';

    }

    function get($order_by) {
        $this->load->model('mdl_diy_customer_type');
        $query = $this->mdl_diy_customer_type->get($order_by);
        return $query;
    }

    function get_with_limit($limit, $offset, $order_by) {
        $this->load->model('mdl_diy_customer_type');
        $query = $this->mdl_diy_customer_type->get_with_limit($limit, $offset, $order_by);
        return $query;
    }

    function get_where($id) {
        $this->load->model('mdl_diy_customer_type');
        $query = $this->mdl_diy_customer_type->get_where($id);
        return $query;
    }

    function get_where_custom($col, $value) {
        $this->load->model('mdl_diy_customer_type');
        $query = $this->mdl_diy_customer_type->get_where_custom($col, $value);
        return $query;
    }

    function _insert($data) {
        $this->load->model('mdl_diy_customer_type');
        $this->mdl_diy_customer_type->_insert($data);
    }

    function _update($id, $data) {
        $this->load->model('mdl_diy_customer_type');
        $this->mdl_diy_customer_type->_update($id, $data);
    }

    function _delete($id) {
        $this->load->model('mdl_diy_customer_type');
        $this->mdl_diy_customer_type->_delete($id);
    }

    function count_where($column, $value) {
        $this->load->model('mdl_diy_customer_type');
        $count = $this->mdl_diy_customer_type->count_where($column, $value);
        return $count;
    }

    function get_max() {
        $this->load->model('mdl_diy_customer_type');
        $max_id = $this->mdl_diy_customer_type->get_max();
        return $max_id;
    }

    function _custom_query($mysql_query) {
        $this->load->model('mdl_diy_customer_type');
        $query = $this->mdl_diy_customer_type->_custom_query($mysql_query);
        return $query;
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 6: 122 (1888)

#### Original name
Bjerkandera subsericella P. Karst., 1884

### Remarks
null


text:
# 0.2.0 (2015-12-15)

## Features
- **segmentProvider:** Contain segMap and shapes of each segment part as a default config
- **angular:** Support angular version 1.5.0-rc.0

## Breaking Changes
- **segGroup:**
    - Move properties 'height', 'width' from 'segOptions' attr to 'segDigitOptions' attr
    - Modify a mechanism to match a pattern
    - Therefore, be able to set custom segment patterns

- **segDigit:**
    - Delete \<defs> and \<use> tags in the digit template. Replace them with ng-repeat of \<polyline>
    - Modify a mechanism to render a digit
    - Therefore, be able to set custom segment shape

- **segMap:** Depressed

# 0.1.0 (2015-12-09)

## Breaking changes
- **segUtil:** Depressed
- **segmentProvider:**
    - Contain methods of segUtil
    - Hold default configs for segment-group and segment-digit
    - Modify default configs wherever you want

- **segGroup:**
    - Accept attribute 'seg-digit-options' to be passed segDigit

- **segDigit:**
    - Allow to set 'digit-class' and 'on-class' by inserting 'seg-digit-options' at segGroup directive
    - Set background-color, light-off part color with 'digit-class'
    - Set light-on part color with 'on-class'


text:
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace htslCore.Internal.Converters
{
    /// <summary>
    /// Html converter helper
    /// </summary>
    internal class HtmlConverterHelper
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="HtmlConverterHelper"/> class.
        /// </summary>
        public HtmlConverterHelper()
        {
        }

        /// <summary>
        /// Gets the new HTML document.
        /// </summary>
        /// <returns>Html Document</returns>
        public HtmlDocument GetNewHtmlDocument(string htmlString)
        {
            var htmlDoc = new HtmlDocument { OptionUseIdAttribute = true };
            htmlDoc.LoadHtml(htmlString);
            return htmlDoc;
        }
    }
}


text:
package wikidata.hashtaginclude.com.wikidataexplorer.ui.main.drawer;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import java.util.List;

import wikidata.hashtaginclude.com.wikidataexplorer.R;

/**
 * Created by matthewmichaud on 1/17/15.
 */
public class DrawerAdapter extends ArrayAdapter<DrawerItem> {

    public DrawerAdapter(Context context, List<DrawerItem> objects) {
        super(context, R.layout.adapter_list_item, objects);
    }

    @Override
    public int getViewTypeCount() {
        return DrawerItem.RowType.values().length;

    }

    @Override
    public int getItemViewType(int position) {
        return getItem(position).getViewType();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getItem(position).getView(LayoutInflater.from(getContext()), convertView);
    }
}


text:
package example.springdata.geode.client.security.server;

import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

/**
 * @author Patrick Johnson
 */
@SpringBootApplication
public class SecurityEnabledServer {

	public static void main(String[] args) {
		new SpringApplicationBuilder(SecurityEnabledServer.class).web(WebApplicationType.NONE).build().run(args);
	}

}


text:
import java.util.Scanner;

public class ChangeToUppercase {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        String text = console.nextLine();
        int startIndex = text.indexOf("<upcase>");
        int endIndex = text.indexOf("</upcase>");
        String upperText = "";
        String replacement = "";

        while (startIndex != -1) {
            upperText = text.substring(startIndex + 8, endIndex).toUpperCase();
            replacement = text.substring(startIndex, endIndex + 9);
            text = text.replace(replacement, upperText);
            startIndex = text.indexOf("<upcase>");
            endIndex = text.indexOf("</upcase>");
        }

        System.out.println(text);
    }
}


text:
Draw using generative patterns - Android

Project from last summer, some features include:

- Draw using a Tree Pattern, 'Seeker', Particle, and Diffusion-Limited-Aggregation
- Lots of options for each pattern
- Save the drawing as a PNG or JPEG
- Option to flatten the drawing canvas down for performance

Looking to migrate away from using the surface view and drawing thread and implementing the same features with libgdx.

##Screenshots
![Image](http://i.imgur.com/SfT2lqK.png)
![Image](http://i.imgur.com/q0t7v0X.png)
![Image](http://i.imgur.com/9DKCcJ1.png)
![Image](http://i.imgur.com/6HnHBfQ.png)


text:
A java client for InfluxDB v0.9.3+

### Usage
#### Create the client:
```java
InfluxDbClient client = new InfluxDbHttpClient("http://localhost:8086");
```
Or, if the InfluxDB server has auth enabled:
```java
InfluxDbClient client = new InfluxDbHttpClient("http://localhost:8086", "username", "password");
```

#### Write data:
```java
// Create the point.
DataPoint point = new DataPoint.Builder("measurementName")
        .withField("someStringField", "someStringValue")
        .withField("someBooleanField", true)
        .withField("someIntField", 1234)
        .withField("someFloatField", 1234.4321)
        .withTag("tagName", "tagValue")
        .withTimestamp(1444940098741L, TimestampPrecision.MILLISECONDS)
        .build();

// Write the point.
client.writePoint("databaseName", "retentionPolicy", point);
```
This will result in the following request being made:
```
--> POST /write?db=databaseName&rp=retentionPolicy&precision=ms HTTP/1.1
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Content-Type: text/plain; charset=utf-8
Content-Length: 145
Host: localhost:8086
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/2.5.0

measurementName,tagName=tagValue someStringField="someStringValue",someBooleanField=true,someIntField=1234,someFloatField=1234.4321 1444940098741
--> END POST (145-byte body)
```
If the write is executed successfully, the following response will be returned by the InfluxDB server:
```
<-- HTTP/1.1 204 No Content (7ms)
Content-Encoding: gzip
Request-Id: c37c2801-7381-11e5-8012-000000000000
X-Influxdb-Version: 0.9.2
Date: Thu, 15 Oct 2015 21:14:47 GMT
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1444943687231
OkHttp-Received-Millis: 1444943687238
<-- END HTTP (0-byte body)
```
Note: You can also write multiple points in a single request using the `InfluxDbClient.writePoints` method.

#### Query:
```java
List<QueryResult> results = client.executeQuery("databaseName", "SELECT * FROM measurementName GROUP BY tagName");
```
This will result in the following request being made:
```
--> GET /query?db=databaseName&q=select%20*%20from%20measurementName HTTP/1.1
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Host: localhost:8086
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/2.5.0
--> END GET
```
If the query is executed successfully, a response with the following body will be returned by the InfluxDB server
(example is of response containing point written in the write example):
```json
{
    "results": [
        {
            "series": [
                {
                    "columns": [
                        "time",
                        "someBooleanField",
                        "someFloatField",
                        "someIntField",
                        "someStringField"
                    ],
                    "name": "measurementName",
                    "tags": {
                        "tagName": "tagValue"
                    },
                    "values": [
                        [
                            "2015-10-15T20:14:58.741Z",
                            true,
                            1234.4321,
                            1234,
                            "someStringValue"
                        ]
                    ]
                }
            ]
        }
    ]
}
```
For more information about the format of JSON returned by InfluxDB, see
https://influxdb.com/docs/v0.9/guides/querying_data.html#querying-data-using-the-http-api.