text:
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Testing;

namespace EFCore3NetFramework.Migrations
{
    [DbContext(typeof(AllFeatureModel))]
    [Migration("20201129233738_Initial")]
    partial class Initial
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasDefaultSchema("dbo")
                .HasAnnotation("ProductVersion", "3.1.1")
                .HasAnnotation("Relational:MaxIdentifierLength", 128)
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("Testing.AllPropertyTypesOptional", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<int>("Id1")
                        .HasColumnType("int");

                    b.Property<byte[]>("BinaryAttr")
                        .HasColumnType("varbinary(max)");

                    b.Property<bool?>("BooleanAttr")
                        .HasColumnType("bit");

                    b.Property<byte?>("ByteAttr")
                        .HasColumnType("tinyint");

                    b.Property<DateTime?>("DateTimeAttr")
                        .HasColumnType("datetime2");

                    b.Property<DateTimeOffset?>("DateTimeOffsetAttr")
                        .HasColumnType("datetimeoffset");

                    b.Property<decimal?>("DecimalAttr")
                        .HasColumnType("decimal(18,2)");

                    b.Property<double?>("DoubleAttr")
                        .HasColumnType("float");

                    b.Property<Guid?>("GuidAttr")
                        .HasColumnType("uniqueidentifier");

                    b.Property<short?>("Int16Attr")
                        .HasColumnType("smallint");

                    b.Property<int?>("Int32Attr")
                        .HasColumnType("int");

                    b.Property<long?>("Int64Attr")
                        .HasColumnType("bigint");

                    b.Property<float?>("SingleAttr")
                        .HasColumnType("real");

                    b.Property<string>("StringAttr")
                        .HasColumnType("nvarchar(max)");

                    b.Property<TimeSpan?>("TimeAttr")
                        .HasColumnType("time");

                    b.Property<byte[]>("Timestamp")
                        .IsConcurrencyToken()
                        .ValueGeneratedOnAddOrUpdate()
                        .HasColumnType("rowversion");

                    b.HasKey("Id", "Id1");

                    b.ToTable("AllPropertyTypesOptionals");
                });

            modelBuilder.Entity("Testing.AllPropertyTypesRequired", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<byte[]>("BinaryAttr")
                        .IsRequired()
                        .HasColumnType("varbinary(max)");

                    b.Property<bool>("BooleanAttr")
                        .HasColumnType("bit");

                    b.Property<byte>("ByteAttr")
                        .HasColumnType("tinyint");

                    b.Property<DateTime>("DateTimeAttr")
                        .HasColumnType("datetime2");

                    b.Property<DateTimeOffset>("DateTimeOffsetAttr")
                        .HasColumnType("datetimeoffset");

                    b.Property<decimal>("DecimalAttr")
                        .HasColumnType("decimal(18,2)");

                    b.Property<double>("DoubleAttr")
                        .HasColumnType("float");

                    b.Property<Guid>("GuidAttr")
                        .HasColumnType("uniqueidentifier");

                    b.Property<short>("Int16Attr")
                        .HasColumnType("smallint");

                    b.Property<int>("Int32Attr")
                        .HasColumnType("int");

                    b.Property<long>("Int64Attr")
                        .HasColumnType("bigint");

                    b.Property<float>("SingleAttr")
                        .HasColumnType("real");

                    b.Property<string>("StringAttr")
                        .IsRequired()
                        .HasColumnType("nvarchar(max)");

                    b.Property<TimeSpan>("TimeAttr")
                        .HasColumnType("time");

                    b.HasKey("Id");

                    b.ToTable("AllPropertyTypesRequireds");
                });

            modelBuilder.Entity("Testing.BChild", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<int?>("BParentOptional_1Id")
                        .HasColumnType("int");

                    b.Property<int?>("BParentOptional_2Id")
                        .HasColumnType("int");

                    b.Property<int?>("BParentRequiredId")
                        .IsRequired()
                        .HasColumnType("int");

                    b.Property<int?>("BParentRequired_1Id")
                        .HasColumnType("int");

                    b.Property<int?>("BParentRequired_2Id")
                        .IsRequired()
                        .HasColumnType("int");

                    b.HasKey("Id");

                    b.HasIndex("BParentOptional_1Id");

                    b.HasIndex("BParentOptional_2Id")
                        .IsUnique()
                        .HasFilter("[BParentOptional_2Id] IS NOT NULL");

                    b.HasIndex("BParentRequiredId")
                        .IsUnique();

                    b.HasIndex("BParentRequired_1Id")
                        .IsUnique()
                        .HasFilter("[BParentRequired_1Id] IS NOT NULL");

                    b.HasIndex("BParentRequired_2Id");

                    b.ToTable("BChilds");
                });

            modelBuilder.Entity("Testing.BParentCollection", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<int?>("BChildOptionalId")
                        .HasColumnType("int");

                    b.Property<int?>("BChildRequiredId")
                        .HasColumnType("int");

                    b.HasKey("Id");

                    b.HasIndex("BChildOptionalId");

                    b.HasIndex("BChildRequiredId");

                    b.ToTable("BParentCollections");
                });

            modelBuilder.Entity("Testing.BParentOptional", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<int?>("BChildRequiredId")
                        .HasColumnType("int");

                    b.HasKey("Id");

                    b.HasIndex("BChildRequiredId")
                        .IsUnique()
                        .HasFilter("[BChildRequiredId] IS NOT NULL");

                    b.ToTable("BParentOptionals");
                });

            modelBuilder.Entity("Testing.BParentRequired", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.HasKey("Id");

                    b.ToTable("BParentRequireds");
                });

            modelBuilder.Entity("Testing.BaseClassWithRequiredProperties", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<string>("Discriminator")
                        .IsRequired()
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("Property0")
                        .IsRequired()
                        .HasColumnType("nvarchar(max)");

                    b.HasKey("Id");

                    b.ToTable("BaseClassWithRequiredProperties");

                    b.HasDiscriminator<string>("Discriminator").HasValue("BaseClassWithRequiredProperties");
                });

            modelBuilder.Entity("Testing.Child", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<int?>("Master_Children_Id")
                        .IsRequired()
                        .HasColumnType("int");

                    b.Property<int?>("ParentId")
                        .IsRequired()
                        .HasColumnType("int");

                    b.HasKey("Id");

                    b.HasIndex("Master_Children_Id");

                    b.HasIndex("ParentId");

                    b.ToTable("Children");
                });

            modelBuilder.Entity("Testing.HiddenEntity", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<string>("Discriminator")
                        .IsRequired()
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("Property1")
                        .HasColumnType("nvarchar(max)");

                    b.HasKey("Id");

                    b.ToTable("HiddenEntities");

                    b.HasDiscriminator<string>("Discriminator").HasValue("HiddenEntity");
                });

            modelBuilder.Entity("Testing.Master", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.HasKey("Id");

                    b.ToTable("Masters");
                });

            modelBuilder.Entity("Testing.ParserTest", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<string>("name")
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("name1")
                        .HasColumnType("nvarchar(max)");

                    b.Property<int?>("name11")
                        .HasColumnType("int");

                    b.Property<int?>("name12")
                        .HasColumnType("int");

                    b.Property<int?>("name13")
                        .HasColumnType("int");

                    b.Property<int?>("name14")
                        .HasColumnType("int");

                    b.Property<string>("name15")
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("name16")
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("name17")
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("name18")
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("name2")
                        .HasColumnType("nvarchar(max)");

                    b.Property<int?>("name3")
                        .HasColumnType("int");

                    b.Property<int?>("name4")
                        .HasColumnType("int");

                    b.Property<int?>("name5")
                        .HasColumnType("int");

                    b.Property<int?>("name6")
                        .HasColumnType("int");

                    b.Property<string>("name7")
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("name8")
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("name9")
                        .HasColumnType("nvarchar(max)");

                    b.HasKey("Id");

                    b.ToTable("ParserTests");
                });

            modelBuilder.Entity("Testing.RenamedColumn", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnName("Foo")
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.HasKey("Id");

                    b.ToTable("RenamedColumns");
                });

            modelBuilder.Entity("Testing.UChild", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<int?>("UParentOptional_UChildCollection_Id")
                        .HasColumnType("int");

                    b.Property<int?>("UParentOptional_UChildOptional_Id")
                        .HasColumnType("int");

                    b.Property<int?>("UParentRequired_UChildCollection_Id")
                        .IsRequired()
                        .HasColumnType("int");

                    b.Property<int?>("UParentRequired_UChildOptional_Id")
                        .IsRequired()
                        .HasColumnType("int");

                    b.Property<int?>("UParentRequired_UChildRequired_Id")
                        .HasColumnType("int");

                    b.HasKey("Id");

                    b.HasIndex("UParentOptional_UChildCollection_Id");

                    b.HasIndex("UParentOptional_UChildOptional_Id")
                        .IsUnique()
                        .HasFilter("[UParentOptional_UChildOptional_Id] IS NOT NULL");

                    b.HasIndex("UParentRequired_UChildCollection_Id");

                    b.HasIndex("UParentRequired_UChildOptional_Id")
                        .IsUnique();

                    b.HasIndex("UParentRequired_UChildRequired_Id")
                        .IsUnique()
                        .HasFilter("[UParentRequired_UChildRequired_Id] IS NOT NULL");

                    b.ToTable("UChilds");
                });

            modelBuilder.Entity("Testing.UParentCollection", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<int?>("UChildOptionalId")
                        .HasColumnType("int");

                    b.Property<int?>("UChildRequiredId")
                        .HasColumnType("int");

                    b.HasKey("Id");

                    b.HasIndex("UChildOptionalId");

                    b.HasIndex("UChildRequiredId");

                    b.ToTable("UParentCollections");
                });

            modelBuilder.Entity("Testing.UParentRequired", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.HasKey("Id");

                    b.ToTable("UParentRequireds");
                });

            modelBuilder.Entity("Testing.AbstractBaseClass", b =>
                {
                    b.HasBaseType("Testing.BaseClassWithRequiredProperties");

                    b.HasDiscriminator().HasValue("AbstractBaseClass");
                });

            modelBuilder.Entity("Testing.BaseClass", b =>
                {
                    b.HasBaseType("Testing.BaseClassWithRequiredProperties");

                    b.HasDiscriminator().HasValue("BaseClass");
                });

            modelBuilder.Entity("Testing.UParentOptional", b =>
                {
                    b.HasBaseType("Testing.HiddenEntity");

                    b.Property<string>("PropertyInChild")
                        .HasColumnType("nvarchar(max)");

                    b.Property<int?>("UChildRequiredId")
                        .HasColumnType("int");

                    b.HasIndex("UChildRequiredId")
                        .IsUnique()
                        .HasFilter("[UChildRequiredId] IS NOT NULL");

                    b.HasDiscriminator().HasValue("UParentOptional");
                });

            modelBuilder.Entity("Testing.ConcreteDerivedClass", b =>
                {
                    b.HasBaseType("Testing.AbstractBaseClass");

                    b.Property<string>("Property1")
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("PropertyInChild")
                        .HasColumnType("nvarchar(max)");

                    b.HasDiscriminator().HasValue("ConcreteDerivedClass");
                });

            modelBuilder.Entity("Testing.ConcreteDerivedClassWithRequiredProperties", b =>
                {
                    b.HasBaseType("Testing.AbstractBaseClass");

                    b.Property<string>("Property1")
                        .IsRequired()
                        .HasColumnName("ConcreteDerivedClassWithRequiredProperties_Property1")
                        .HasColumnType("nvarchar(max)");

                    b.HasDiscriminator().HasValue("ConcreteDerivedClassWithRequiredProperties");
                });

            modelBuilder.Entity("Testing.DerivedClass", b =>
                {
                    b.HasBaseType("Testing.BaseClass");

                    b.Property<string>("Property1")
                        .HasColumnName("DerivedClass_Property1")
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("PropertyInChild")
                        .HasColumnName("DerivedClass_PropertyInChild")
                        .HasColumnType("nvarchar(max)");

                    b.HasDiscriminator().HasValue("DerivedClass");
                });

            modelBuilder.Entity("Testing.AllPropertyTypesOptional", b =>
                {
                    b.OwnsOne("Testing.OwnedType", "OwnedType", b1 =>
                        {
                            b1.Property<int>("AllPropertyTypesOptionalId")
                                .ValueGeneratedOnAdd()
                                .HasColumnType("int")
                                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                            b1.Property<int>("AllPropertyTypesOptionalId1")
                                .HasColumnType("int");

                            b1.Property<float?>("SingleAttr")
                                .HasColumnType("real");

                            b1.HasKey("AllPropertyTypesOptionalId", "AllPropertyTypesOptionalId1");

                            b1.ToTable("AllPropertyTypesOptionals");

                            b1.WithOwner()
                                .HasForeignKey("AllPropertyTypesOptionalId", "AllPropertyTypesOptionalId1");
                        });
                });

            modelBuilder.Entity("Testing.BChild", b =>
                {
                    b.HasOne("Testing.BParentOptional", "BParentOptional_1")
                        .WithMany("BChildCollection")
                        .HasForeignKey("BParentOptional_1Id")
                        .OnDelete(DeleteBehavior.NoAction);

                    b.HasOne("Testing.BParentOptional", "BParentOptional_2")
                        .WithOne("BChildOptional")
                        .HasForeignKey("Testing.BChild", "BParentOptional_2Id")
                        .OnDelete(DeleteBehavior.NoAction);

                    b.HasOne("Testing.BParentRequired", "BParentRequired")
                        .WithOne("BChildOptional")
                        .HasForeignKey("Testing.BChild", "BParentRequiredId")
                        .OnDelete(DeleteBehavior.NoAction)
                        .IsRequired();

                    b.HasOne("Testing.BParentRequired", "BParentRequired_1")
                        .WithOne("BChildRequired")
                        .HasForeignKey("Testing.BChild", "BParentRequired_1Id")
                        .OnDelete(DeleteBehavior.NoAction);

                    b.HasOne("Testing.BParentRequired", "BParentRequired_2")
                        .WithMany("BChildCollection")
                        .HasForeignKey("BParentRequired_2Id")
                        .OnDelete(DeleteBehavior.NoAction)
                        .IsRequired();
                });

            modelBuilder.Entity("Testing.BParentCollection", b =>
                {
                    b.HasOne("Testing.BChild", "BChildOptional")
                        .WithMany("BParentCollection_2")
                        .HasForeignKey("BChildOptionalId")
                        .OnDelete(DeleteBehavior.NoAction);

                    b.HasOne("Testing.BChild", "BChildRequired")
                        .WithMany("BParentCollection")
                        .HasForeignKey("BChildRequiredId")
                        .OnDelete(DeleteBehavior.NoAction);
                });

            modelBuilder.Entity("Testing.BParentOptional", b =>
                {
                    b.HasOne("Testing.BChild", "BChildRequired")
                        .WithOne("BParentOptional")
                        .HasForeignKey("Testing.BParentOptional", "BChildRequiredId")
                        .OnDelete(DeleteBehavior.NoAction);
                });

            modelBuilder.Entity("Testing.Child", b =>
                {
                    b.HasOne("Testing.Master", null)
                        .WithMany("Children")
                        .HasForeignKey("Master_Children_Id")
                        .OnDelete(DeleteBehavior.NoAction)
                        .IsRequired();

                    b.HasOne("Testing.Child", "Parent")
                        .WithMany("Children")
                        .HasForeignKey("ParentId")
                        .OnDelete(DeleteBehavior.Cascade)
                        .IsRequired();
                });

            modelBuilder.Entity("Testing.UChild", b =>
                {
                    b.HasOne("Testing.UParentOptional", null)
                        .WithMany("UChildCollection")
                        .HasForeignKey("UParentOptional_UChildCollection_Id")
                        .OnDelete(DeleteBehavior.NoAction);

                    b.HasOne("Testing.UParentOptional", null)
                        .WithOne("UChildOptional")
                        .HasForeignKey("Testing.UChild", "UParentOptional_UChildOptional_Id")
                        .OnDelete(DeleteBehavior.NoAction);

                    b.HasOne("Testing.UParentRequired", null)
                        .WithMany("UChildCollection")
                        .HasForeignKey("UParentRequired_UChildCollection_Id")
                        .OnDelete(DeleteBehavior.NoAction)
                        .IsRequired();

                    b.HasOne("Testing.UParentRequired", null)
                        .WithOne("UChildOptional")
                        .HasForeignKey("Testing.UChild", "UParentRequired_UChildOptional_Id")
                        .OnDelete(DeleteBehavior.NoAction)
                        .IsRequired();

                    b.HasOne("Testing.UParentRequired", null)
                        .WithOne("UChildRequired")
                        .HasForeignKey("Testing.UChild", "UParentRequired_UChildRequired_Id")
                        .OnDelete(DeleteBehavior.NoAction);
                });

            modelBuilder.Entity("Testing.UParentCollection", b =>
                {
                    b.HasOne("Testing.UChild", "UChildOptional")
                        .WithMany()
                        .HasForeignKey("UChildOptionalId")
                        .OnDelete(DeleteBehavior.NoAction);

                    b.HasOne("Testing.UChild", "UChildRequired")
                        .WithMany()
                        .HasForeignKey("UChildRequiredId");
                });

            modelBuilder.Entity("Testing.UParentOptional", b =>
                {
                    b.HasOne("Testing.UChild", "UChildRequired")
                        .WithOne()
                        .HasForeignKey("Testing.UParentOptional", "UChildRequiredId")
                        .OnDelete(DeleteBehavior.NoAction);
                });
#pragma warning restore 612, 618
        }
    }
}


text:
package org.drools.core.util;

import org.junit.Test;
import static org.junit.Assert.*;

public class ClassUtilsTest {

    @Test
    public void testCanonicalNameSimpleClass() {
        String name = ClassUtils.canonicalName( ClassUtilsTest.class );
        assertEquals( "org.drools.core.util.ClassUtilsTest",
                      name );
    }

    @Test
    public void testCanonicalNameInnerClass() {
        String name = ClassUtils.canonicalName( A.class );
        assertEquals( "org.drools.core.util.ClassUtilsTest.A",
                      name );
    }

    @Test
    public void testCanonicalNameInnerInnerClass() {
        String name = ClassUtils.canonicalName( A.B.class );
        assertEquals( "org.drools.core.util.ClassUtilsTest.A.B",
                      name );
    }

    @Test
    public void testCanonicalNameArray() {
        String name = ClassUtils.canonicalName( Object[].class );
        assertEquals( "java.lang.Object[]",
                      name );
    }

    @Test
    public void testCanonicalNameMultiIndexArray() {
        String name = ClassUtils.canonicalName( Object[][][].class );
        assertEquals( "java.lang.Object[][][]",
                      name );
    }

    @Test
    public void testCanonicalNameMultiIndexArrayInnerClass() {
        String name = ClassUtils.canonicalName( A.B[][][].class );
        assertEquals( "org.drools.core.util.ClassUtilsTest.A.B[][][]",
                      name );
    }

    @Test
    public void testCanonicalNameMultiIndexArrayPrimitives() {
        String name = ClassUtils.canonicalName( long[][][].class );
        assertEquals( "long[][][]",
                      name );
    }

    public static class A {
        public static class B {
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package dhcp

import (
	"encoding/binary"
	"net"
	"time"
)

// IPRange returns how many ips in the ip range from start to stop (inclusive)
func IPRange(start, stop net.IP) int {
	//return int(Uint([]byte(stop))-Uint([]byte(start))) + 1
	return int(binary.BigEndian.Uint32(stop.To4())) - int(binary.BigEndian.Uint32(start.To4())) + 1
}

// IPAdd returns a copy of start + add.
// IPAdd(net.IP{192,168,1,1},30) returns net.IP{192.168.1.31}
func IPAdd(start net.IP, add int) net.IP { // IPv4 only
	start = start.To4()
	//v := Uvarint([]byte(start))
	result := make(net.IP, 4)
	binary.BigEndian.PutUint32(result, binary.BigEndian.Uint32(start)+uint32(add))
	//PutUint([]byte(result), v+uint64(add))
	return result
}

// IPLess returns where IP a is less than IP b.
func IPLess(a, b net.IP) bool {
	b = b.To4()
	for i, ai := range a.To4() {
		if ai != b[i] {
			return ai < b[i]
		}
	}
	return false
}

// IPInRange returns true if ip is between (inclusive) start and stop.
func IPInRange(start, stop, ip net.IP) bool {
	return !(IPLess(ip, start) || IPLess(stop, ip))
}

// OptionsLeaseTime - converts a time.Duration to a 4 byte slice, compatible
// with OptionIPAddressLeaseTime.
func OptionsLeaseTime(d time.Duration) []byte {
	leaseBytes := make([]byte, 4)
	binary.BigEndian.PutUint32(leaseBytes, uint32(d/time.Second))
	//PutUvarint(leaseBytes, uint64(d/time.Second))
	return leaseBytes
}

// JoinIPs returns a byte slice of IP addresses, one immediately after the other
// This may be useful for creating multiple IP options such as OptionRouter.
func JoinIPs(ips []net.IP) (b []byte) {
	for _, v := range ips {
		b = append(b, v.To4()...)
	}
	return
}


text:
layout: post
title: Asymmetric distribution of lunar impact basins
type: article
---

>Miljkovic, et al., Science. 342, 724-726 (2013). [[PDF]](/papers/Miljkovic+2013.pdf)
See also this related study: [Laneuville+2013]({% post_url 2013-06-18-asymmetric-lunar-evolution %})

Maps of crustal thickness derived from NASA's Gravity Recovery and Interior Laboratory (GRAIL)
mission revealed more large impact basins on the nearside hemisphere of the Moon than on its
farside. The enrichment in heat-producing elements and prolonged volcanic activity on the lunar
nearside hemisphere indicate that the temperature of the nearside crust and upper mantle was hotter
than that of the farside at the time of basin formation. Using the iSALE-2D hydrocode to model
impact basin formation, we found that impacts on the hotter nearside would have formed basins with
up to twice the diameter of similar impacts on the cooler farside hemisphere. The size distribution
of lunar impact basins is thus not representative of the earliest inner solar system impact
bombardment.

![Impact Basins](/images/asymmetricImpactBasins.png)


text:
import React, { PropTypes } from 'react';
import { Link } from 'react-router';

const CourseRow = ({ course }) => {
    return (

            Watch
            <Link to={`/course/${course.id}`}>{course.title}</Link>
            {course.authorId}
            {course.category}
            {course.length}

    );
};

CourseRow.propTypes = {
    course: PropTypes.object.isRequired
};

export default CourseRow;


text:
"""Semaphores and concurrency primitives."""
from __future__ import absolute_import, unicode_literals

from collections import deque

from kombu.five import python_2_unicode_compatible

__all__ = ('DummyLock', 'LaxBoundedSemaphore')

@python_2_unicode_compatible
class LaxBoundedSemaphore(object):
    """Asynchronous Bounded Semaphore.

    Lax means that the value will stay within the specified
    range even if released more times than it was acquired.

    Example:
        >>> from future import print_statement as printf
        # ^ ignore: just fooling stupid pyflakes

        >>> x = LaxBoundedSemaphore(2)

        >>> x.acquire(printf, 'HELLO 1')
        HELLO 1

        >>> x.acquire(printf, 'HELLO 2')
        HELLO 2

        >>> x.acquire(printf, 'HELLO 3')
        >>> x._waiters   # private, do not access directly
        [print, ('HELLO 3',)]

        >>> x.release()
        HELLO 3
    """

    def __init__(self, value):
        self.initial_value = self.value = value
        self._waiting = deque()
        self._add_waiter = self._waiting.append
        self._pop_waiter = self._waiting.popleft

    def acquire(self, callback, *partial_args, **partial_kwargs):
        """Acquire semaphore.

        This will immediately apply ``callback`` if
        the resource is available, otherwise the callback is suspended
        until the semaphore is released.

        Arguments:
            callback (Callable): The callback to apply.
            *partial_args (Any): partial arguments to callback.
        """
        value = self.value
        if value <= 0:
            self._add_waiter((callback, partial_args, partial_kwargs))
            return False
        else:
            self.value = max(value - 1, 0)
            callback(*partial_args, **partial_kwargs)
            return True

    def release(self):
        """Release semaphore.

        Note:
            If there are any waiters this will apply the first waiter
            that is waiting for the resource (FIFO order).
        """
        try:
            waiter, args, kwargs = self._pop_waiter()
        except IndexError:
            self.value = min(self.value + 1, self.initial_value)
        else:
            waiter(*args, **kwargs)

    def grow(self, n=1):
        """Change the size of the semaphore to accept more users."""
        self.initial_value += n
        self.value += n
        [self.release() for _ in range(n)]

    def shrink(self, n=1):
        """Change the size of the semaphore to accept less users."""
        self.initial_value = max(self.initial_value - n, 0)
        self.value = max(self.value - n, 0)

    def clear(self):
        """Reset the semaphore, which also wipes out any waiting callbacks."""
        self._waiting.clear()
        self.value = self.initial_value

    def __repr__(self):
        return '<{0} at {1:#x} value:{2} waiting:{3}>'.format(
            self.__class__.__name__, id(self), self.value, len(self._waiting),
        )

class DummyLock(object):
    """Pretending to be a lock."""

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        pass


text:
Extract academic citations from Wikipedia
=========================================
This project contains a utility for extracting academic citation identifiers.

**NOTE:** As one of its dependencies (`Mediawiki-Utilities <https://github.com/halfak/Mediawiki-Utilities>`_) requires
Python 3 so does mwcites.

``pip install mwcites``

Usage
-----
There's really only one utility in this package called ``mwcitations``.

::

    $ mwcitations extract enwiki-20150112-pages-meta-history*.xml*.bz2 > citations.tsv

Documentation
-------------
Documentation is provided ``$ mwcitations extract -h``.

::

    Extracts academic citations from articles from the history of Wikipedia
    articles by processing a pages-meta-history XML dump and matching regular
    expressions to revision content.

    Currently supported identifiers include:

     * PubMed
     * DOI
     * ISBN
     * arXiv
     * ISSN

    Outputs a TSV file with the following fields:

     * page_id: The identifier of the Wikipedia article (int), e.g. 1325125
     * page_title: The title of the Wikipedia article (utf-8), e.g. Club cell
     * rev_id: The Wikipedia revision where the citation was first added (int),
               e.g. 282470030
     * timestamp: The timestamp of the revision where the citation was first
                  added. (ISO 8601 datetime), e.g. 2009-04-08T01:52:20Z
     * type: The type of identifier, e.g. pmid, pmcid, doi, isbn or arxiv
     * id: The id of the cited scholarly article (utf-8),
           e.g 10.1183/09031936.00213411

    Usage:
        mwcites extract -h | --help
        mwcites extract <dump_file>...

    Options:
        -h --help        Shows this documentation


text:
package i5.las2peer.services.cdService.data.simulation;

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;

public class MetaData implements Serializable {

	private static final long serialVersionUID = 1L;

	long seriesId;

	private Parameters parameters;
	private Evaluation evaluation;

	public MetaData() {

	}

	public MetaData(SimulationSeries series) {

		this.seriesId = series.getId();
		this.parameters = series.getParameters();
		this.evaluation = series.getCooperationEvaluation();
	}

	////// Getter //////

	@JsonProperty
	public long getSeriesId() {
		return seriesId;
	}

	@JsonProperty
	public Parameters getParameters() {
		return parameters;
	}

	@JsonProperty
	public Evaluation getEvaluation() {
		return evaluation;
	}

	////// Setter //////
	@JsonSetter
	public void setSeriesId(long seriesId) {
		this.seriesId = seriesId;
	}

	@JsonSetter
	public void setParameters(Parameters parameters) {
		this.parameters = parameters;
	}

	@JsonSetter
	public void setEvaluation(Evaluation evaluation) {
		this.evaluation = evaluation;
	}

}


text:
require 'shellwords'

installvars  = node[cookbook_name]['install']
configvars   = node[cookbook_name]['config']
configyml    = "#{installvars['conf_dir']}/config.yml"
sentryconfpy = "#{installvars['conf_dir']}/sentry.conf.py"

directory installvars['conf_dir'] do
  owner     installvars['user']
  group     installvars['group']
  recursive true
end

template configyml do
  owner     installvars['user']
  group     installvars['group']
  cookbook  configvars['config.yml']['cookbook']
  notifies  :run, 'ruby_block[populate_secret_key]', :immediately
  variables(
    :vars => configvars['config.yml']['vars']
  )
end

template sentryconfpy do
  owner     installvars['user']
  group     installvars['group']
  cookbook  configvars['sentry.conf.py']['cookbook']
  variables(
    :vars => configvars['sentry.conf.py']['vars']
  )
end

suuser    = "su #{installvars['user']} -l -c"
sentrycom = "#{configvars['sentry_bin']} --config #{installvars['conf_dir']}"
gensecret = "#{suuser} '#{sentrycom} config generate-secret-key'"

ruby_block 'populate_secret_key' do
  block do
    text  = ::File.read(configyml)
    text2 = text.gsub(/SECRET_KEY/, %x( #{gensecret} ).strip)

    ::File.open(configyml, 'w') { |file| file.puts text2 }
  end
  action :nothing
end

envvars = {
  'PATH' =>      configvars['sentry_env']['path'],
  'NODE_PATH' => configvars['sentry_env']['node_path'],
  'HOME' =>      installvars['home'],
  'USER' =>      installvars['user'],
  'LOGNAME' =>   installvars['user'],
  'LANG' =>      'en_US.UTF-8'
}

bash 'sentry_upgrade' do
  user  installvars['user']
  group installvars['group']
  code  "#{sentrycom} upgrade --noinput | tee -a /tmp/sentry_upgrade.output"
  environment envvars
end

adminuserflag = "#{installvars['conf_dir']}/.admin_user"
supertext = configvars['admin_superuser'] ? "--superuser " : "--no-superuser"

bash 'sentry_createuser' do
  user  installvars['user']
  group installvars['group']
  code  "#{sentrycom} createuser --no-input #{supertext} "\
        "--email #{configvars['admin_email'].shellescape} "\
        "--password #{configvars['admin_pass'].shellescape} "\
        "| tee -a /tmp/sentry_createuser.output"

  not_if      { ::File.exist?(adminuserflag) }
  notifies    :create, "file[#{adminuserflag}]"
  environment envvars
end

file adminuserflag do
  content configvars['admin_email']
  action  :nothing
end


text:
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string_regex.hpp>
#include <boost/format.hpp>
#include <boost/tokenizer.hpp>
#include <boost/regex.hpp>

#include "UDPServer.h"
#include "utils/Logging.h"
#include "net/NetworkManager.h"

namespace flint {

UDPServer::UDPServer(boost::asio::io_service &ioService,
		const std::string &listenIp, int listenPort) :
		timer_(ioService), socket_(ioService), listenIp_(listenIp), listenPort_(
				listenPort) {
	// TODO Auto-generated constructor stub
}

UDPServer::~UDPServer() {
	// TODO Auto-generated destructor stub
}

void UDPServer::init() {
//	LOG_INFO << "UDPServer init!!! -> " << listenIp_ << ":" << listenPort_;
	boost::asio::ip::address address = boost::asio::ip::address::from_string(
			"0.0.0.0");
	boost::asio::ip::udp::endpoint endpoint(address, listenPort_);

	// open
	socket_.open(endpoint.protocol());

	// reuse address, must set before binding!!!
	boost::asio::ip::udp::socket::reuse_address reuse_option(true);
	socket_.set_option(reuse_option);

	// set ttl
	boost::asio::ip::multicast::hops ttl(1);
	socket_.set_option(ttl);

	// enable loopback
	boost::asio::ip::multicast::enable_loopback loopback(true);
	socket_.set_option(loopback);

	// close quickly
	boost::asio::socket_base::linger linger_option(true, 0);
	socket_.set_option(linger_option);

	try {
		// bind
		socket_.bind(endpoint);
	} catch (boost::system::system_error &e) {
		LOG_ERROR << "UDPServer bind: " << e.what();
	}

	// join the multicast group.
	boost::asio::ip::address multicastAddress =
			boost::asio::ip::address::from_string(listenIp_);
	try {
		std::string ip = NetworkManager::getInstance()->getIpAddr();
		if (boost::iequals(ip, "")) {
//			LOG_INFO << "join group: " << multicastAddress.to_string();
			socket_.set_option(
					boost::asio::ip::multicast::join_group(multicastAddress));
		} else {
//			LOG_INFO << "join group: " << multicastAddress.to_string() << " | "
//					<< ip;
			socket_.set_option(
					boost::asio::ip::multicast::join_group(
							multicastAddress.to_v4(),
							boost::asio::ip::address::from_string(ip).to_v4()));
		}
	} catch (boost::system::system_error &e) {
		LOG_ERROR << "UDPServer join group: " << e.what();
	}
//	LOG_DEBUG << "UDPServer init!!!- end";
}

void UDPServer::onStart() {
//	LOG_INFO << "UDPServer start!!! -> " << listenIp_ << ":" << listenPort_;
	init();
	wait_packet();
}

void UDPServer::onStop() {
	socket_.close();
	timer_.cancel();
}

void UDPServer::wait_packet() {
//	LOG_DEBUG << "UDPServer wait packet!!!";
	recv_buffer_.fill(0);
	socket_.async_receive_from(boost::asio::buffer(recv_buffer_),
			client_endpoint_,
			boost::bind(&UDPServer::handle_packet, this,
					boost::asio::placeholders::error,
					boost::asio::placeholders::bytes_transferred));
//	LOG_DEBUG << "UDPServer wait packet!!! end";
}

void UDPServer::handle_packet(const boost::system::error_code& error,
		std::size_t len) {
//	LOG_DEBUG << "UDPServer handle packet!!!";
	if (!error || error == boost::asio::error::message_size) {
		if (len > 0) {
//			std::string message;
//			message.assign(recv_buffer_.data(), len);
			parseMessage(client_endpoint_.address().to_string(),
					client_endpoint_.port(), recv_buffer_.data(), len);
		}
		wait_packet();
	}
//	LOG_DEBUG << "UDPServer handle packet!!! end";
}

} /* namespace flint */


text:
/**
 * 聊天业务操作
 */

const chatModel = require('./../models/chat')

const chatService = {

  /**
   * 创建用户
   * @param  {object} chat   聊天记录对象
   * @return {object}        创建结果
   */
  async create (chat) {
    let result = await chatModel.create(chat)
    return result
  },

  /**
   * 获取用户的所有聊天记录
   * @param {object} formData 查询条件
   */
  async getChatlogs (formData) {
    let resultData = await chatModel.getChatlogs(formData)
    return resultData
  },

  /**
   * 查询两个制定用户的消息
   * @param {object} formData 查询表单
   */
  async getChatByFromAndTo (formData) {
    let resultData = await chatModel.getChatByFromAndTo(formData)
    return resultData
  }

}

module.exports = chatService


text:
#include <ApplicationServices/ApplicationServices.h>
#include <objc/objc.h>

#ifdef __OBJC__
#include <Foundation/Foundation.h>
@class NSString;
#else
typedef struct NSString NSString;
#endif

#ifdef __cplusplus
extern "C" {
#endif

BOOL stringIsCaseInsensitiveEqualToString(NSString *first, NSString *second);
BOOL hasCaseInsensitiveSuffix(NSString *string, NSString *suffix);
BOOL hasCaseInsensitiveSubstring(NSString *string, NSString *substring);
NSString *filenameByFixingIllegalCharacters(NSString *string);
CFStringEncoding stringEncodingForResource(Handle resource);

#ifdef __cplusplus
}
#endif


text:
template<typename T,typename Alloc>
class vector
{
    public:
    typedef T value_type;
    typedef Alloc alloc_type;
    typedef value_type & reference;
    typedef value_type * pointer;
    typedef const value_type & const_reference;
    typedef const value_type * const_pointer;
    typedef value_type * iterator;
    typedef const value_type * const_iterator;
    typedef std::reverse_iterator<iterator> reverse_iterator;
    typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
    typedef std::size_t size_type;
    typedef ptrdiff_t difference_type;

    vector()
    {

    }
    explicit vector(const alloc_type &)
    {

    }
    explicit vector(size_type,const alloc_type & = alloc_type() )
    {

    }
    vector(size_type,const value_type v,const alloc_type &=alloc_type() )
    {

    }
    template <typename InputIter>
    vector(InputIter begin,InputIter end,const alloc_type & = alloc_type() )
    {

    }
    template<typename U>
    vector(std::initialize_list<U>,const alloc_type & = alloc_type() )
    {

    }
    vector(const vector &)
    {

    }
    vector(const vector &,const alloc_type &)
    {

    }
    vector(vector &&)
    {

    }
    vector(vector &&,const alloc_type &)
    {

    }
    ~vector()
    {

    }

    iterator begin()
    {

    }
    const_iterator begin()const
    {

    }
    iterator end()
    {

    }
    const_iterator end()const
    {

    }
    reverse_iterator rbegin()
    {

    }
    const_reverse_iterator rbegin()const
    {

    }
    reverse_iterator rend()
    {

    }
    const_reverse_iterator rend()const
    {

    }

    const_iterator cbegin()const
    {

    }
    const_iterator cend()const
    {

    }
    const_reverse_iterator crbegin()const
    {

    }
    const_reverse_iterator crend()const
    {

    }
    reference front()
    {

    }
    const_reference front()const
    {

    }

    reference back()
    {

    }

    const_reference back()const
    {

    }

    pointer data()
    {

    }

    const_pointer data()const
    {

    }

    reference operator[](size_type ) const
    {

    }

    const_reference operator[](size_type ) const
    {

    }

    reference at(size_type )
    {

    }

    const_reference at(size_type )const
    {

    }
    void swap(vector &)noexcept
    {
    }

};


text:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class SchoolSystem {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n = Integer.parseInt(scanner.nextLine());

		String name;
		String subject;

		String[] tokens = new String[4];
		List<Double> grades = new ArrayList<>();
		Map<String, TreeMap<String, List<Double>>> students = new TreeMap<>();
		for (int i = 0; i < n; i++) {
			tokens = scanner.nextLine().split("\\s+");
			name = tokens[0] + " " + tokens[1];
			subject = tokens[2];
			grades.add(Double.parseDouble(tokens[3]));

			if (students.containsKey(name)) {
				if (students.get(name).containsKey(subject)) {
					grades.addAll(students.get(name).get(subject));
				}
			}
			else {
				students.put(name, new TreeMap<>());
			}

			students.get(name).put(subject, grades);
			grades = new ArrayList<>();
		}

		List<String> subjects = new ArrayList<>();
		for (Map.Entry<String, TreeMap<String, List<Double>>> studentsEntry : students.entrySet()) {
			System.out.printf("%s: [", studentsEntry.getKey());

			for (Map.Entry<String, List<Double>> subjectsEntry : studentsEntry.getValue().entrySet()) {
				subjects.add(String.format("%s - %.2f", subjectsEntry.getKey(), getAvarageGrade(subjectsEntry.getValue())));
			}
			System.out.printf("%s]%n", String.join(", ", subjects));
			subjects.clear();
		}
	}

	private static double getAvarageGrade(List<Double> grades) {
		double gradesSum = 0.0;
		for (int i = 0; i <grades.size(); i++) {
			gradesSum += grades.get(i);
		}

		return gradesSum / grades.size();
	}
}


text:
<?php

namespace LeadThread\Bitly\Exceptions;

class BitlyAuthException extends BitlyException
{
    public function __construct($message = "INVALID_LOGIN", $code = 0, Exception $previous = null){
        parent::__construct($message, $code, $previous);
    }
}


text:
import pytest
from _pytest._io.saferepr import _pformat_dispatch
from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE
from _pytest._io.saferepr import saferepr

def test_simple_repr():
    assert saferepr(1) == "1"
    assert saferepr(None) == "None"

def test_maxsize():
    s = saferepr("x" * 50, maxsize=25)
    assert len(s) == 25
    expected = repr("x" * 10 + "..." + "x" * 10)
    assert s == expected

def test_no_maxsize():
    text = "x" * DEFAULT_REPR_MAX_SIZE * 10
    s = saferepr(text, maxsize=None)
    expected = repr(text)
    assert s == expected

def test_maxsize_error_on_instance():
    class A:
        def __repr__(self):
            raise ValueError("...")

    s = saferepr(("*" * 50, A()), maxsize=25)
    assert len(s) == 25
    assert s[0] == "(" and s[-1] == ")"

def test_exceptions() -> None:
    class BrokenRepr:
        def __init__(self, ex):
            self.ex = ex

        def __repr__(self):
            raise self.ex

    class BrokenReprException(Exception):
        __str__ = None  # type: ignore[assignment]
        __repr__ = None  # type: ignore[assignment]

    assert "Exception" in saferepr(BrokenRepr(Exception("broken")))
    s = saferepr(BrokenReprException("really broken"))
    assert "TypeError" in s
    assert "TypeError" in saferepr(BrokenRepr("string"))

    none = None
    try:
        none()  # type: ignore[misc]
    except BaseException as exc:
        exp_exc = repr(exc)
    obj = BrokenRepr(BrokenReprException("omg even worse"))
    s2 = saferepr(obj)
    assert s2 == (
        "<[unpresentable exception ({!s}) raised in repr()] BrokenRepr object at 0x{:x}>".format(
            exp_exc, id(obj)
        )
    )

def test_baseexception():
    """Test saferepr() with BaseExceptions, which includes pytest outcomes."""

    class RaisingOnStrRepr(BaseException):
        def __init__(self, exc_types):
            self.exc_types = exc_types

        def raise_exc(self, *args):
            try:
                self.exc_type = self.exc_types.pop(0)
            except IndexError:
                pass
            if hasattr(self.exc_type, "__call__"):
                raise self.exc_type(*args)
            raise self.exc_type

        def __str__(self):
            self.raise_exc("__str__")

        def __repr__(self):
            self.raise_exc("__repr__")

    class BrokenObj:
        def __init__(self, exc):
            self.exc = exc

        def __repr__(self):
            raise self.exc

        __str__ = __repr__

    baseexc_str = BaseException("__str__")
    obj = BrokenObj(RaisingOnStrRepr([BaseException]))
    assert saferepr(obj) == (
        "<[unpresentable exception ({!r}) "
        "raised in repr()] BrokenObj object at 0x{:x}>".format(baseexc_str, id(obj))
    )
    obj = BrokenObj(RaisingOnStrRepr([RaisingOnStrRepr([BaseException])]))
    assert saferepr(obj) == (
        "<[{!r} raised in repr()] BrokenObj object at 0x{:x}>".format(
            baseexc_str, id(obj)
        )
    )

    with pytest.raises(KeyboardInterrupt):
        saferepr(BrokenObj(KeyboardInterrupt()))

    with pytest.raises(SystemExit):
        saferepr(BrokenObj(SystemExit()))

    with pytest.raises(KeyboardInterrupt):
        saferepr(BrokenObj(RaisingOnStrRepr([KeyboardInterrupt])))

    with pytest.raises(SystemExit):
        saferepr(BrokenObj(RaisingOnStrRepr([SystemExit])))

    with pytest.raises(KeyboardInterrupt):
        print(saferepr(BrokenObj(RaisingOnStrRepr([BaseException, KeyboardInterrupt]))))

    with pytest.raises(SystemExit):
        saferepr(BrokenObj(RaisingOnStrRepr([BaseException, SystemExit])))

def test_buggy_builtin_repr():
    # Simulate a case where a repr for a builtin raises.
    # reprlib dispatches by type name, so use "int".

    class int:
        def __repr__(self):
            raise ValueError("Buggy repr!")

    assert "Buggy" in saferepr(int())

def test_big_repr():
    from _pytest._io.saferepr import SafeRepr

    assert len(saferepr(range(1000))) <= len("[" + SafeRepr(0).maxlist * "1000" + "]")

def test_repr_on_newstyle() -> None:
    class Function:
        def __repr__(self):
            return "<%s>" % (self.name)  # type: ignore[attr-defined]

    assert saferepr(Function())

def test_unicode():
    val = "£€"
    reprval = "'£€'"
    assert saferepr(val) == reprval

def test_pformat_dispatch():
    assert _pformat_dispatch("a") == "'a'"
    assert _pformat_dispatch("a" * 10, width=5) == "'aaaaaaaaaa'"
    assert _pformat_dispatch("foo bar", width=5) == "('foo '\n 'bar')"

def test_broken_getattribute():
    """saferepr() can create proper representations of classes with
    broken __getattribute__ (#7145)
    """

    class SomeClass:
        def __getattribute__(self, attr):
            raise RuntimeError

        def __repr__(self):
            raise RuntimeError

    assert saferepr(SomeClass()).startswith(
        "<[RuntimeError() raised in repr()] SomeClass object at 0x"
    )


text:
project_path: /web/_project.yaml
book_path: /web/shows/_book.yaml
description: HTTP 203 - Where do we start. In each show Jake and Paul pick a hot topic in the world of web development and discuss the various aspects of it, meanwhile dropping in lifehacks, lessons and some rather honest truths.

{# wf_updated_on: 2016-08-24 #}
{# wf_published_on: 2016-08-24 #}

# HTTP 203 {: .page-title }

<img src="../imgs/http203_rect.jpg" class="attempt-right">

**Where do we start?** In each show Jake and Paul pick a hot topic in the
world of web development and discuss the various aspects of it, meanwhile
dropping in lifehacks, lessons and some rather honest truths.

[YouTube](https://www.youtube.com/playlist?list=PLNYkxOF6rcIAKIQFsNbV0JDws_G_bnNo9)

[Podcast](podcast/)


text:
<?php

namespace console\models\tvcatchup;

use Yii;

/**
 * This is the model class for table "{{%field_data_field_channel_date}}".
 *
 * @property string $entity_type
 * @property string $bundle
 * @property integer $deleted
 * @property string $entity_id
 * @property string $revision_id
 * @property string $language
 * @property string $delta
 * @property string $field_channel_date_value
 * @property string $field_channel_date_format
 */
class FieldDataFieldChannelDate extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%field_data_field_channel_date}}';
    }

    /**
     * @return \yii\db\Connection the database connection used by this AR class.
     */
    public static function getDb()
    {
        return Yii::$app->get('db_tvcatchup');
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['entity_type', 'deleted', 'entity_id', 'language', 'delta'], 'required'],
            [['deleted', 'entity_id', 'revision_id', 'delta'], 'integer'],
            [['entity_type', 'bundle'], 'string', 'max' => 128],
            [['language'], 'string', 'max' => 32],
            [['field_channel_date_value'], 'string', 'max' => 10],
            [['field_channel_date_format'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'entity_type' => 'Entity Type',
            'bundle' => 'Bundle',
            'deleted' => 'Deleted',
            'entity_id' => 'Entity ID',
            'revision_id' => 'Revision ID',
            'language' => 'Language',
            'delta' => 'Delta',
            'field_channel_date_value' => 'Field Channel Date Value',
            'field_channel_date_format' => 'Field Channel Date Format',
        ];
    }
}


text:
require "rails_helper"

RSpec.describe PropertiesController, type: :routing do
  describe "routing" do

    it "routes to #index" do
      expect(:get => "/properties").to route_to("properties#index")
    end

    it "routes to #new" do
      expect(:get => "/properties/new").to route_to("properties#new")
    end

    it "routes to #show" do
      expect(:get => "/properties/1").to route_to("properties#show", id: '1')
    end

    it "routes to #edit" do
      expect(:get => "/properties/1/edit").to route_to("properties#edit", id: '1')
    end

    it "routes to #create" do
      expect(:post => "/properties").to route_to("properties#create")
    end

    it "routes to #update via PUT" do
      expect(:put => "/properties/1").to route_to("properties#update", id: '1')
    end

    it "routes to #update via PATCH" do
      expect(patch: "/properties/1").to route_to("properties#update", id: '1')
    end

    it "routes to #destroy" do
      expect(:delete => "/properties/1").to route_to("properties#destroy", id: '1')
    end

  end
end


text:
require 'spec_helper'

module Refinery
  module Stylesheets
    describe Stylesheet do
      describe "validations" do
        subject { Stylesheet.new(style_type: nil) }
        %w(name content style_type).each do |attribute|
          it "should validate presence of #{attribute}" do
            subject.should have(1).errors_on(attribute)
          end
        end
      end

      describe '.find_by_param' do
        let(:stylesheet) { FactoryGirl.create(:stylesheet, content: '// comments' ) }
        it 'should find stylesheet by selecting the id out of param' do
           Stylesheet.find_by_param(stylesheet.to_param).should == stylesheet
        end
      end

      describe '#to_param' do
        let(:now) { Time.now }
        subject { FactoryGirl.create(:stylesheet, content: '// comments', updated_at: now) }

        it 'should return id and timestamp of updated at' do
          subject.to_param.should == "#{subject.id}-#{now.to_i}"
        end
      end
    end
  end
end


text:
#ifndef STATIC_REGION_H
#define STATIC_REGION_H

#include "Static.Global.h"

namespace GleeBug
{
    /**
    \brief An immutable region object. Used to indicate a region of data in a vector.
    \tparam T Type of the data in the region.
    */
    template<typename T>
    class Region
    {
    public:
        /**
        \brief Default constructor (constructs an invalid region).
        */
        explicit Region()
            : Region(nullptr, INVALID_VALUE, INVALID_VALUE)
        {
        }

        /**
        \brief Constructor (constructs a valid region).
        \param [in] data Pointer to the vector that holds the actual data. Use nullptr to create an invalid region.
        \param offset The offset. Use INVALID_VALUE to create an invalid region.
        \param count (Optional) Number of Ts in the region. Use INVALID_VALUE to create an invalid region.
        */
        explicit Region(std::vector<uint8>* data, uint32 offset, uint32 count = 1)
            : mData(data),
              mOffset(offset),
              mCount(count)
        {
        }

        /**
        \brief Clears and invalidates this region.
        */
        void Clear()
        {
            *this = Region<T>();
        }

        /**
        \brief Returns a pointer inside the data to the start of this region.
        \return nullptr if the region is invalid, a pointer to the data otherwise.
        */
        T* Data() const
        {
            if(!Valid())
                return nullptr;
            return (T*)(mData->data() + mOffset);
        }

        /**
        \brief Gets the offset in the data of this region.
        */
        uint32 Offset() const
        {
            return mOffset;
        }

        /**
        \brief Gets the number of Ts in this region.
        */
        uint32 Count() const
        {
            return mCount;
        }

        /**
        \brief Gets the size of this region in bytes. Basically: sizeof(T) * Count().
        */
        uint32 Size() const
        {
            return Valid() ? mCount * sizeof(T) : INVALID_VALUE;
        }

        /**
        \brief Returns if this region is valid.
        */
        bool Valid() const
        {
            return mOffset != INVALID_VALUE &&
                   mCount != INVALID_VALUE &&
                   mData && mData->data() &&
                   mOffset + mCount * sizeof(T) <= mData->size();
        }

        /**
        \brief Returns if this region is empty (has no data).
        */
        bool Empty() const
        {
            return Size() == 0;
        }

        /**
        \brief Returns Valid().
        */
        operator bool() const
        {
            return Valid();
        }

        /**
        \brief Returns Data().
        */
        T* operator()() const
        {
            return Data();
        }

        T* operator ->() const
        {
            return Data();
        }

        const T & operator[](uint32 index) const
        {
            return Data()[index];
        }

        T & operator[](uint32 index)
        {
            return Data()[index];
        }

    protected:
        std::vector<uint8>* mData;
        uint32 mOffset;
        uint32 mCount;
    };
};

#endif //STATIC_REGION_H


text:
Article 730
----
La preuve de la qualité d'héritier s'établit par tous moyens.

Il n'est pas dérogé aux dispositions ni aux usages concernant la délivrance de
certificats de propriété ou d'hérédité par des autorités judiciaires ou
administratives.


text:
package slogo.model;

import generic.Pair;

/**
 * A factory for creating Function objects.
 */
public class FunctionFactory {

	private static final String METHOD_LOCATION = "slogo.model.";
	private final static String METHOD_MAKER_CLASS = "STOREDMETHOD";
    private static final String VARIABLE_SYNTAX_ERROR = "VariableSyntaxError";
    private static final String NO_SUCH_FUNCTION_ERROR = "NoSuchFunctionError";
    private static final String METHOD_PREFIX = "SLCommand_";

	/**
	 * Creates and returns the function specified by
	 * functionType using reflection.
	 *
	 * @param functionType the function type
	 * @param m the m
	 * @return the function
	 */
	public IFunction getFunction(String functionType, IMemory m){
		IFunction myInstance = null;
		String functionTypeUpper = functionType.toUpperCase();

		try {
			if(m.getStorageMemory().readMethod(functionType)!=null){functionTypeUpper = METHOD_MAKER_CLASS;}
			myInstance = (IFunction) Class.forName(METHOD_LOCATION+METHOD_PREFIX+functionTypeUpper).newInstance();
			return myInstance;
		}
		catch (InstantiationException e) {
			e.printStackTrace();
		}
		catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		catch (ClassNotFoundException e) {
			if(m.getStorageMemory().readVariable(functionType)!=null){functionError(VARIABLE_SYNTAX_ERROR,"");}
			functionError(NO_SUCH_FUNCTION_ERROR, functionType);
		}

		return myInstance;
	}

	/**
	 * Function error.
	 *
	 * @param errorType the error type
	 * @param specificMessage the specific message
	 */
	private void functionError(String errorType, String specificMessage){
		throw new SlogoException(new Pair<String, String>(errorType,specificMessage));
	}
}


text:
package org.apache.jmeter.report.processor;

/**
 * A factory for creating PercentileAggregator with index of percentile fixed to
 * value 50.
 *
 * @since 3.0
 */
public class MedianAggregatorFactory extends AbstractAggregatorFactory {

    /*
     * (non-Javadoc)
     *
     * @see
     * org.apache.jmeter.report.core.AbstractAggregatorFactory#createAggregator
     * ()
     */
    @Override
    protected Aggregator createAggregator() {
        return new PercentileAggregator(50);
    }

}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;

namespace Vulnerator.ViewModel
{
    public class AsyncObservableCollection<T> : ObservableCollection<T>
    {
        private readonly SynchronizationContext _synchronizationContext = SynchronizationContext.Current;

        public AsyncObservableCollection()
        {
        }

        public AsyncObservableCollection(IEnumerable<T> list)
            : base(list)
        {
        }

        private void ExecuteOnSyncContext(Action action)
        {
            if (SynchronizationContext.Current == _synchronizationContext)
            {
                action();
            }
            else
            {
                _synchronizationContext.Send(_ => action(), null);
            }
        }

        protected override void InsertItem(int index, T item)
        {
            ExecuteOnSyncContext(() => base.InsertItem(index, item));
        }

        protected override void RemoveItem(int index)
        {
            ExecuteOnSyncContext(() => base.RemoveItem(index));
        }

        protected override void SetItem(int index, T item)
        {
            ExecuteOnSyncContext(() => base.SetItem(index, item));
        }

        protected override void MoveItem(int oldIndex, int newIndex)
        {
            ExecuteOnSyncContext(() => base.MoveItem(oldIndex, newIndex));
        }

        protected override void ClearItems()
        {
            ExecuteOnSyncContext(() => base.ClearItems());
        }
    }
}


text:
#import "SCLSwitchView.h"
#import "SCLMacros.h"

@interface SCLSwitchView ()

@property (strong, nonatomic) UISwitch *switchKnob;
@property (strong, nonatomic) UILabel *switchLabel;

@end

#pragma mark

@implementation SCLSwitchView

#pragma mark - Constructors

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        [self setup];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setup];
    }
    return self;
}

#pragma mark - Initialization

- (void)setup
{
    // Add switch knob
    self.switchKnob = [[UISwitch alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, 0.f)];
    [self addSubview:self.switchKnob];

    // Add switch label
    CGFloat x, width, height;
    x = self.switchKnob.frame.size.width + 8.0f;
    width = self.frame.size.width - self.switchKnob.frame.size.width - 8.0f;
    height = self.switchKnob.frame.size.height;

    self.switchLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, 0.0f, width, height)];

    NSString *switchFontFamily = @"HelveticaNeue-Bold";
    CGFloat switchFontSize = 12.0f;

    self.switchLabel.numberOfLines = 1;
    self.switchLabel.textAlignment = NSTextAlignmentLeft;
    self.switchLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    self.switchLabel.adjustsFontSizeToFitWidth = YES;
    self.switchLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
    self.switchLabel.minimumScaleFactor = 0.5f;
    self.switchLabel.font = [UIFont fontWithName:switchFontFamily size:switchFontSize];
    self.switchLabel.textColor = UIColorFromHEX(0x4D4D4D);

    [self addSubview:self.switchLabel];
}

#pragma mark - Getters

- (UIColor *)tintColor {
    return self.switchKnob.tintColor;
}

- (UIColor *)labelColor {
    return self.switchLabel.textColor;
}

- (UIFont *)labelFont {
    return self.switchLabel.font;
}

- (NSString *)labelText {
    return self.switchLabel.text;
}

- (BOOL)isSelected {
    return self.switchKnob.isOn;
}

#pragma mark - Setters

- (void)setTintColor:(UIColor *)tintColor {
    self.switchKnob.onTintColor = tintColor;
}

- (void)setLabelColor:(UIColor *)labelColor {
    self.switchLabel.textColor = labelColor;
}

- (void)setLabelFont:(UIFont *)labelFont {
    self.switchLabel.font = labelFont;
}

- (void)setLabelText:(NSString *)labelText {
    self.switchLabel.text = labelText;
}

@end


text:
//
//  RTScene.h
//  RealTimesSDK
//
//  Created by Ante Trbojevic 1 on 15/06/15.
//  Copyright (c) 2015 RealNetworks. All rights reserved.
//

#import <Foundation/Foundation.h>

@class RTMediaItem;

/** An instance of a [RTScene](RTScene.html) describes a single scene in a story. A scene has a time range and a reference to the media item from which the scene was created.

 For video items the time range specifies the start time and duration of the section of the video that is played for this scene. For photos the time range is always (0, 0).
 */
@interface RTScene : NSObject

/** @name Constructors */

/** Creates a scene from the given RTMediaItem.

 @param item The media item.
 @param startTime The start time in seconds.
 @param duration The duration time in seconds.
 */
- (id)initWithMediaItem:(RTMediaItem *)item startTime:(NSTimeInterval)startTime duration:(NSTimeInterval)duration;

/** @name Properties */

/** Gets the media item. */
@property (readonly, nonatomic) RTMediaItem *mediaItem;

/** Gets the start time. */
@property (readonly, nonatomic) NSTimeInterval startTime;

/** Gets the duration. */
@property (readonly, nonatomic) NSTimeInterval duration;

/** Gets or sets if the scene is selected. */
@property (assign, nonatomic) BOOL isSelected;

@end


text:
package com.github.gquintana.beepbeep.config;

import com.github.gquintana.beepbeep.pipeline.PipelineBuilder;
import com.github.gquintana.beepbeep.pipeline.Pipelines;
import com.github.gquintana.beepbeep.util.Converters;
import com.github.gquintana.beepbeep.util.Strings;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.time.Duration;
import java.time.temporal.TemporalAmount;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.github.gquintana.beepbeep.util.Maps.flatten;
import static java.util.Arrays.asList;

public class ConfigurationLoader {
    private final Yaml yaml = new Yaml();

    public PipelineBuilder loadFile(Path configurationFile) {
        try (FileInputStream inputStream = new FileInputStream(configurationFile.toFile())) {
            return load(inputStream);
        } catch (IOException e) {
            throw new ConfigurationException("Failed to read configuration " + configurationFile);
        }
    }

    public PipelineBuilder loadResource(String resource) {
        try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource)) {
            if (inputStream == null) {
                throw new FileNotFoundException("Resource not found");
            }
            return load(inputStream);
        } catch (IOException e) {
            throw new ConfigurationException("Failed to read configuration " + resource, e);
        }
    }

    public PipelineBuilder load(InputStream inputStream) {
        @SuppressWarnings("unchecked")
        Map<String, Object> map = yaml.loadAs(inputStream, Map.class);
        String type = Converters.convertToString(map.get("type"));
        PipelineBuilder pipelineBuilder = Pipelines.create(type);
        for (Map.Entry<String, Object> keyValue : map.entrySet()) {
            String key = Strings.toCamelCase(keyValue.getKey());
            switch (key) {
                case "Type":
                    // Skip
                    break;
                case "Scripts":
                    applyWithScriptScanner(pipelineBuilder, keyValue.getValue());
                    break;
                case "Variables":
                    applyWithVariables(pipelineBuilder, flatten(keyValue.getValue(), null));
                    break;
                case "ScriptStore":
                    applyWithScriptStore(pipelineBuilder, key, keyValue.getValue());
                    break;
                default:
                    applyWith(pipelineBuilder, keyValue.getKey(), keyValue.getValue());
                    break;
            }
        }
        return pipelineBuilder;
    }

    /**
     * Inject script score configuration in PipelineBuilder
     */
    private void applyWithScriptStore(PipelineBuilder pipelineBuilder, String key, Object value) {
        if (value instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> valueMap = (Map<String, Object>) value;
            Object storeName = valueMap.remove("name");
            if (storeName != null) {
                applyWith(pipelineBuilder, key, storeName);
            }
            for (Map.Entry<String, Object> mapEntry : valueMap.entrySet()) {
                applyWith(pipelineBuilder, key + "." + mapEntry.getKey(), mapEntry.getValue());
            }
        } else {
            applyWith(pipelineBuilder, key, value);
        }
    }

    /**
     * Inject script scanners configuration in PipelineBuilder
     */
    private void applyWithScriptScanner(PipelineBuilder pipelineBuilder, Object value) {
        if (value instanceof List) {
            List scripts = (List) value;
            PipelineBuilder.CompositeScriptScannerBuilder compositeBuilder = pipelineBuilder.withCompositeScriptScanner();
            for (Object script : scripts) {
                compositeBuilder.schemes(Converters.convertToString(script));
            }
            compositeBuilder.end();
        } else {
            pipelineBuilder.withFilesScriptScanner(Converters.convertToString(value));
        }
    }

    /**
     * Inject variables in PipelineBuilder
     */
    @SuppressWarnings("unchecked")
    private void applyWithVariables(PipelineBuilder pipelineBuilder, Object value) {
        if (value instanceof Map) {
            pipelineBuilder.withVariables((Map) value);
        }
    }

    /**
     * Call withXXX method on PipelineBuilder
     */
    private void applyWith(PipelineBuilder pipelineBuilder, String key, Object value) {
        String setterName = "with" + Strings.toCamelCase(key);
        Class clazz = pipelineBuilder.getClass();
        List<Method> methods = Arrays.stream(clazz.getMethods())
            .filter(m -> isMethod(m, setterName))
            .collect(Collectors.toList());
        if (methods.isEmpty()) {
            throw new ConfigurationException("Invalid configuration " + key);
        }
        Method method = methods.get(0);
        value = convert(value, method.getParameterTypes()[0]);
        try {
            method.invoke(pipelineBuilder, value);
        } catch (ReflectiveOperationException e) {
            throw new ConfigurationException("Failed to invoke " + method.getName(), e);
        }
    }

    private static final Set<Class> SUPPORTED_PARAMETER_TYPES = new HashSet<>(asList(String.class, Boolean.class, Boolean.TYPE, Charset.class, TemporalAmount.class, Duration.class));

    /**
     * Find withXXX method on PipelineBuilder
     */
    private static boolean isMethod(Method method, String setterName) {
        if (method.getParameterCount() != 1) {
            return false;
        }
        Class parameterClass = method.getParameterTypes()[0];
        if (!SUPPORTED_PARAMETER_TYPES.contains(parameterClass)) {
            return false;
        }
        return method.getName().equals(setterName);
    }

    /**
     * Convert withXXX method parameter to appropriate type
     */
    private <T> T convert(Object object, Class<T> clazz) {
        return Converters.convert(object, clazz);
    }
}


text:
// MESG_CAPABILITIES_ID (0x54) (Ant Message Protocol and Usage - Page 52)

typedef struct {
	UCHAR maxChannels;
	UCHAR maxNetworks;
	UCHAR stdOptions;
	UCHAR advOptions[2];
	UCHAR maxDataChannels;
} cfg_capabilities;

int ANT_init(char *devname);
int ANT_send(int args, ... );
int ANT_sendStr(int len, UCHAR *data);
int ANT_tx(int fd, UCHAR *data, int length);

int ANT_cfgCapabilties(UCHAR *data, cfg_capabilities *cfg, UCHAR size);

int hstr2hex(UCHAR *hex, char *hexstr, int size);
UCHAR checkSum(UCHAR *data, int length);

#endif


text:
:- module(tipc_linda,
          [
           linda/0,                  %
           linda/1,                  % +Term
           linda_client/1,           % +Address
           close_client/0,           %
           linda_timeout/1,          % +Number
           linda_timeout/2,          % ?Number, ?Number
           out/1,                    % +Term
           in/1,                     % ?Term
           in_noblock/1,             % ?Term
           in/2,                     % +List, ?Term
           rd/1,                     % ?Term
           rd_noblock/1,             % ?Term
           rd/2,                     % +List, ?Term
           bagof_rd_noblock/3,       % +Template, ?Term, -Bag
           bagof_in_noblock/3,       % +Template, ?Term, -Bag
           linda_eval/1,             % :Head
           linda_eval/2,             % ?Head, :Body
           linda_eval_detached/1,    % :Head
           linda_eval_detached/2,    % ?Head, :Body
           tuple/1,                  % :Goal
           tuple/2,                  % ?Head, :Body
           tipc_linda_server/0,      %
           tipc_initialize/0
          ]).
:- use_module(library(tipc/tipc),[tipc_initialize/0]).
:- autoload(library(broadcast),
	    [listen/3,broadcast_request/1,broadcast/1,unlisten/3]).
:- autoload(library(debug),[assertion/1]).
:- autoload(library(error),[must_be/2]).
:- autoload(library(lists),[member/2]).

/** <module> A Process Communication Interface

Linda is a framework for building systems  that are composed of programs
that cooperate among themselves in order  to   realize  a larger goal. A
Linda application is  composed  of  two   or  more  processes  acting in
concert. One process acts as a  server   and  the others act as clients.
Fine-grained communications between client and server is provided by way
of message passing over sockets and   support  networks, TIPC sockets in
this case. Clients interact indirectly by way  of the server. The server
is in principle an eraseable blackboard that   clients  can use to write
(out/1), read (rd/1) and remove (in/1)  messages called _|tuples.|_ Some
predicates will fail if  a  requested  tuple   is  not  present  on  the
blackboard. Others will block until a  tuple instance becomes available.
Tuple instances are made available to  clients   by  writing them on the
blackboard using out/1.

In TIPC Linda, there is a  subtle   difference  between the =in= and the
=rd= predicates that is  worth  noting.   The  =in=  predicates  succeed
exactly once for each tuple placed  in   the  tuple  space. The tuple is
provided to exactly one  requesting  client.   Clients  can  contend for
tuples in this way, thus  enabling   multi-server  operations.  The =rd=
predicates succeed nondeterministically, providing   all matching tuples
in the tuple space at a given time to the requesting client as a choice
point without disturbing them.

TIPC Linda is inspired by and adapted   from the SICStus Prolog API. But
unlike SICStus TCP Linda, TIPC  Linda   is  connectionless.  There is no
specific session between client and  server.   The  server  receives and
responds to datagrams originated by clients in an epiperiodic manner.

Example: A simple producer-consumer.

In client 1:
==
init_producer :-
       linda_client(global),
       producer.

producer :-
       produce(X),
       out(p(X)),
       producer.

produce(X) :- .....
==
In client 2:
==
init_consumer :-
        linda_client(global),
        consumer.

consumer :-
       in(p(A)),
       consume(A),
       consumer.

consume(A) :- .....
==

Example: Synchronization
==
       ...,
       in(ready),  %Waits here until someone does out(ready)
       ...,
==
Example: A critical region
==
       ...,
       in(region_free),  % wait for region to be free
       critical_part,
       out(region_free), % let next one in
       ...,
==
Example: Reading global data
==
       ...,
       rd(data(Data)),
       ...,
==
or, without blocking:
==
       ...,
       (rd_noblock(data(Data)) ->
             do_something(Data)
       ;     write('Data not available!'),nl
       ),
       ...,
==

Example: Waiting for any one of several events
==
       ...,
       in([e(1),e(2),...,e(n)], E),
%  Here is E instantiated to the first tuple that became available
       ...,
==

Example: Producers and Consumers in the same process using =linda_eval=
threads and/or =tuple= predicates

==
  consumer1 :-
        repeat,
        in([p(_), quit], Y),
        (   Y = p(Z) -> writeln(consuming(Z)); !),
        fail.

  producer1 :-
        forall(between(1,40, X), out(p(X))).

  producer_consumer1 :-
        linda_eval(consumer1),
        call_cleanup(producer1, out(quit)), !.
%
%
  consumer2 :-
       between(1,4,_),
       in_noblock(p(X)), !,
       writeln(consuming(X)),
       consumer2.

  producer2 :-
        linda_eval(p(X), between(1,40, X)).

  producer_consumer2 :-
        producer2,
        linda_eval(consumer2), !.
%
%
  consumer3 :-
        forall(rd_noblock(p(X)), writeln(consuming(X))).

  producer3 :-
        tuple(p(X), between(1,40, X)).

  producer_consumer3 :-
        producer3,
        linda_eval(done, consumer3),
        in(done), !.
==

##  Servers {#tipc-linda-servers}

   The server is the process running the "blackboard process". It is
   part of TIPC Linda. It is a collection of predicates that are
   registered as tipc_broadcast listeners. The server process can be run
   on a separate machine if necessary.

   To load the package, enter the query:
   ==
   ?- use_module(library(tipc/tipc_linda)).

   ?- linda.
      TIPC Linda server now listening at: port_id('<1.1.1:3200515722>')
      true.
   ==

## Clients {#tipc-linda-clients}

   The clients are one or more Prolog processes that have connection(s)
   to the server.

   To load the package, enter the query:
   ==
   ?- use_module(library(tipc/tipc_linda)).

   ?- linda_client(global).
      TIPC Linda server listening at: port_id('<1.1.1:3200515722>')
      true.
   ==

@see Nicholas Carriero and David Gelernter. _|How to Write Parallel
Programs: A First Course.|_ The MIT Press, Cambridge, MA, 1990.

@author Jeffrey A. Rosenwald

@compat SWI-Prolog for Linux only
@compat tipc_broadcast library
*/

:- meta_predicate eventually_implies(0,0), ~>(0,0), safely(0).

safely(Goal) :-
    catch(Goal, Err, (print_message(error, Err), fail)).

eventually_implies(P, Q) :-
    setup_call_cleanup(P, (Foo = true; Foo = false), assertion(Q)),
    Foo == true.

:- op(950, xfy, ~>).

~>(P, Q) :- eventually_implies(P, Q).

:- dynamic(linda_data/1).

%
%    This is the backend state machine
%

linda_action(rd(listening)) :- !.

linda_action(in(TupleList, Tuple)) :-
    member(Tuple, TupleList),
    retract(linda_data(Tuple)),
    !.

linda_action(in(Tuple)) :-
    retract(linda_data(Tuple)),
    !.

linda_action(out(Tuple)) :-
    assert(linda_data(Tuple)).

linda_action(rd(TupleList, Tuple)) :-
    member(Tuple, TupleList),
    linda_data(Tuple).

linda_action(rd(Tuple)) :-
    linda_data(Tuple).

linda_action(bagof_rd_noblock(Template, Var^Tuple, Bag)) :-
    !, bagof(Template, Var^linda_data(Tuple), Bag).

linda_action(bagof_rd_noblock(Template, Tuple, Bag)) :-
    !, bagof(Template, linda_data(Tuple), Bag).

linda_action(bagof_in_noblock(Template, Var^Tuple, Bag)) :-
    Datum = linda_data(Tuple),
    !, bagof(Template, Var^(Datum, retract(Datum)), Bag).

linda_action(bagof_in_noblock(Template, Tuple, Bag)) :-
    !, bagof(Template, retract(linda_data(Tuple)), Bag).

%
%    This is the user interface
%

%!  linda is det.
%!  linda(:Goal) is det.
%   Starts a Linda-server in this process. The
%   network address is written to current output stream as a TIPC
%   port_id/2 reference (e.g. port_id('<1.1.1:3200515722>') ). This
%   predicates looks to see if a server is already listening on the
%   cluster. If so, it reports the address of the existing server.
%   Otherwise, it registers a new server and reports its address.
%
% ==
% ?- linda.
%    TIPC Linda server now listening at: port_id('<1.1.1:3200515722>')
%    true.
%
% ?- linda.
%    TIPC Linda server still listening at: port_id('<1.1.1:3200515722>')
%    true.
% ==
%
%  The following will call my_init/0 in the current module after the
%  server is successfully started or is found already listening.
%  my_init/0 could start client-processes, initialize the tuple space,
%  etc.
%
% ==
% ?- linda(my_init).
% ==
%

linda_listening(Addr) :-
    basic_request(rd(listening), Addr),
    !.

linda :-
    linda_listening(Addr),
    !,
    format('TIPC Linda server still listening at: ~p~n', [Addr]).

linda :-
    listen(tipc_linda, '$linda'(Action), linda_action(Action)),
    linda_listening(Addr),
    !,
    format('TIPC Linda server now listening at: ~p~n', [Addr]).

:- meta_predicate linda(0).

linda(Hook) :-
    linda,
    call(Hook).

%!  linda_client(+Domain) is semidet.
%
%    Establishes a connection to a Linda-server  providing a named tuple
%    space. Domain is  an  atom   specifying  a  particular tuple-space,
%    selected from a universe of tuple-spaces.  At present however, only
%    one tuple-space, =global=, is supported. A client may interact with
%    any server reachable on the TIPC  cluster. This predicate will fail
%    if no server is reachable for that tuple space.
%

linda_client(global) :-
    linda_listening(Addr),
    !,
    format('TIPC Linda server listening at: ~p~n', [Addr]).

%!  close_client is det.
%
% Closes the connection to  the  Linda-server.   Causes  the  server  to
% release resources associated with this client.

close_client :- true.   % Presently a noop

%!  linda_timeout(?OldTime, ?NewTime) is semidet.
%
% Controls Linda's message-passing timeout. It specifies the time window
% where clients will accept server replies in  response to =in= and =rd=
% requests.  Replies  arriving  outside  of  this  window  are  silently
% ignored. OldTime is unified with the old   timeout and then timeout is
% set to NewTime.  NewTime  is  of   the  form  Seconds:Milliseconds.  A
% non-negative real number, seconds, is also  recognized. The default is
% 0.250 seconds. This timeout is thread local and is _not_  inherited
% from its parent. New threads are initialized to the default.
%
% *|Note:|* The synchronous behavior  afforded by in/1 and rd/1
% is implemented by periodically polling the   server.  The poll rate is
% set according to this timeout. Setting the timeout too small may
% result in substantial network traffic that is of little value.
%
% @throws error(feature_not_supported). SICStus Linda can
% disable the timeout by specifying =off= as NewTime. This feature does
% not exist for safety reasons.
%

:- thread_local linda_time_out/1.

linda_timeout(Time, Time) :-
    linda_time_out(Time),
    !.

linda_timeout(_OldTime, NewTime) :-
    NewTime == off,
    throw(error(feature_not_supported)).

linda_timeout(OldTime, NewTime) :-
    ground(NewTime),
    NewTime = Seconds:Milliseconds,
    NewTime1 is float(Seconds + (Milliseconds / 1000.0)),
    linda_timeout(OldTime, NewTime1),
    !.

linda_timeout(OldTime, NewTime) :-
    ground(NewTime),
    NewTime >= 0.020,
    clause(linda_time_out(OldTime), true, Ref),
    asserta(linda_time_out(NewTime)) -> erase(Ref),
    !.

linda_timeout(0.250, NewTime) :-
    NewTime >= 0.020,
    asserta(linda_time_out(NewTime)).

%!  linda_timeout(+NewTime) is semidet.
%
% Temporarily sets Linda's timeout. Internally,  the original timeout is
% saved and then the timeout is set  to NewTime. NewTime is as described
% in linda_timeout/2. The original timeout  is restored automatically on
% cut of choice points, failure on backtracking, or uncaught exception.
%

linda_timeout(NewTime) :-
    linda_timeout(OldTime, NewTime) ~>
        linda_timeout(NewTime, OldTime).

basic_request(Action) :-
    basic_request(Action, _Addr).

basic_request(Action, Addr) :-
    linda_timeout(Time, Time),
    broadcast_request(tipc_cluster('$linda'(Action):Addr, Time)).

%!  out(+Tuple) is det.
%
%    Places a Tuple in Linda's tuple-space.
%

out(Tuple) :-
    broadcast(tipc_cluster('$linda'(out(Tuple)))),
    !.

%!  in(?Tuple) is det.
%
%    Atomically removes the tuple Tuple from   Linda's tuple-space if it
%    is there. The tuple will be returned   to exactly one requestor. If
%    no tuple is available, the predicate   blocks until it is available
%    (that is, someone performs an out/1).

in(Tuple) :-
    repeat,
    in_noblock(Tuple),
    !.

%!  in_noblock(?Tuple) is semidet.
%
%    Atomically removes the tuple Tuple from   Linda's tuple-space if it
%    is there. If not, the predicate fails.  This predicate can fail due
%    to a timeout.

in_noblock(Tuple) :-
    basic_request(in(Tuple)),
    !.

%!  in(+TupleList, -Tuple) is det.
%
%    As in/1 but succeeds when any  one   of  the tuples in TupleList is
%    available. Tuple is unified with the fetched tuple.

in(TupleList, Tuple) :-
    must_be(list, TupleList),
    repeat,
    basic_request(in(TupleList, Tuple)),
    !.

%!  rd(?Tuple) is nondet.
%
%    Succeeds  nondeterministically  if  Tuple  is    available  in  the
%    tuple-space, suspends otherwise until it is available. Compare this
%    with in/1: the tuple is not removed.

rd(Tuple) :-
    repeat,
    rd_noblock(Tuple).

%!  rd_noblock(?Tuple) is nondet.
%
%    Succeeds  nondeterministically  if  Tuple  is    available  in  the
%    tuple-space, fails otherwise. This predicate  can   fail  due  to a
%    timeout.

rd_noblock(Tuple) :-
    basic_request(rd(Tuple)).

%!  rd(?TupleList, -Tuple) is nondet.
%
%    As in/2 but provides a  choice  point   that  does  not  remove any
%    tuples.

rd(TupleList, Tuple) :-
    must_be(list, TupleList),
    repeat,
    basic_request(rd(TupleList, Tuple)).

%!  bagof_in_noblock(?Template, ?Tuple, -Bag) is nondet.
%!  bagof_rd_noblock(?Template, ?Tuple, -Bag) is nondet.
%
%    Bag is the list of all instances of Template such that Tuple exists
%    in the tuple-space. The behavior of variables in Tuple and Template
%    is as in bagof/3. The variables   could be existentially quantified
%    with ^/2 as in bagof/3. The  operation   is  performed as an atomic
%    operation. This predicate can  fail  due   to  a  timeout. Example:
%    Assume that only one client is connected to the server and that the
%    tuple-space initially is empty.
%
%  ==
%    ?- out(x(a,3)), out(x(a,4)), out(x(b,3)), out(x(c,3)).
%
%    true.
%    ?- bagof_rd_noblock(C-N, x(C,N), L).
%
%    L = [a-3,a-4,b-3,c-3] .
%
%    true.
%    ?- bagof_rd_noblock(C, N^x(C,N), L).
%
%    L = [a,a,b,c] .
%
%    true.
%  ==

bagof_rd_noblock(Template,  Tuple, Bag) :-
    !, basic_request(bagof_rd_noblock(Template, Tuple, Bag)).

bagof_in_noblock(Template,  Tuple, Bag) :-
    !, basic_request(bagof_in_noblock(Template, Tuple, Bag)).

:- meta_predicate
      linda_eval(?, 0),
      linda_eval(0),
      linda_eval_detached(?, 0),
      linda_eval_detached(0).

%!  linda_eval(:Goal) is det.
%!  linda_eval(?Head, :Goal) is det.
%!  linda_eval_detached(:Goal) is det.
%!  linda_eval_detached(?Head, :Goal) is det.
%
%  Causes Goal to be evaluated in parallel  with a parent predicate. The
%  child  thread  is  a  full-fledged    client,   possessing  the  same
%  capabilities as the  parent.  Upon   successful  completion  of Goal,
%  unbound variables are unified and the  result   is  sent to the Linda
%  server via out/1, where  it  is   made  available  to  others. linda_eval/2
%  evaluates Goal, then unifies the result  with Head, providing a means
%  of customizing the resulting output structure.   In linda_eval/1, Head, and
%  Goal are identical, except that the module  name for Head is stripped
%  before output. If the child fails  or receives an uncaught exception,
%  no such output occurs.
%
%  *|Joining Threads:|* Threads created using linda_eval/(1-2) are not allowed
%  to linger. They are joined (blocking  the parent, if necessary) under
%  three conditions: backtracking on failure into an linda_eval/(1-2), receipt
%  of an uncaught  exception,  and  cut   of  choice-points.  Goals  are
%  evaluated   using   forall/2.   They   are    expected   to   provide
%  nondeterministic behavior. That is they  may   succeed  zero  or more
%  times on backtracking. They must however,  eventually fail or succeed
%  deterministically.  Otherwise,  the  thread  will  hang,  which  will
%  eventually hang the parent  thread.  Cutting   choice  points  in the
%  parent's body has the effect of joining   all children created by the
%  parent. This provides a  barrier  that   guarantees  that  all  child
%  instances of Goal have run to completion before the parent proceeds.
%  Detached threads behave as above, except that they operate
%  independently and cannot be joined. They will continue to run while
%  the host process continues to run.
%
% Here is an example of a parallel quicksort:
%
% ==
% qksort([], []).
%
% qksort([X | List], Sorted) :-
%       partition(@>(X), List, Less, More),
%       linda_eval(qksort(More, SortedMore)),
%       qksort(Less, SortedLess), !,
%       in_noblock(qksort(More, SortedMore)),
%       append(SortedLess, [X | SortedMore], Sorted).
% ==
%
linda_eval(Head) :-
    linda_eval(Head, Head).

linda_eval(Head, Body) :-
    must_be(callable, Body),
    strip_module(Head, _Module, Plain),
    thread_create(forall(Body, out(Plain)), Id, []) ~>
       thread_join(Id, true).

linda_eval_detached(Head) :-
    linda_eval_detached(Head, Head).

linda_eval_detached(Head, Body) :-
    must_be(callable, Body),
    strip_module(Head, _Module, Plain),
    thread_create(forall(Body, out(Plain)), _Id, [detached(true)]).

%!  tuple(:Goal) is det.
%!  tuple(?Head, :Goal) is det.
%
%  registers Head as a virtual tuple  in   TIPC  Linda's tuple space. On
%  success, any client on the  cluster   may  reference the tuple, Head,
%  using rd/1 or rd_noblock/1.  On  reference,   Goal  is  executed by a
%  separate thread of execution in the host client's Prolog process. The
%  result is unified with Head, which  is   then  returned  to the guest
%  client. As in linda_eval/(1-2) above, Goal is evaluated using forall/2. The
%  virtual tuple is unregistered  on   backtracking  into a tuple/(1-2),
%  receipt of uncaught exception, or cut   of choice-points. In tuple/1,
%  Head and Goal are identical, except that  the module name is stripped
%  from Head.
%
%  *|Note:|* A virtual tuple is an extension  of the server. Even though
%  it is operating in the client's  Prolog environment, it is restricted
%  in the server operations that it may   perform.  It is generally safe
%  for tuple predicates to perform out/1   operations,  but it is unsafe
%  for them to perform any variant of   =in= or =rd=, either directly or
%  indirectly. This restriction is however, relaxed   if  the server and
%  client are operating in separate  heavyweight processes (not threads)
%  on the node or cluster. This is   most  easily achieved by starting a
%  stand-alone   Linda   server   somewhere   on    the   cluster.   See
%  tipc_linda_server/0, below.
%
:- meta_predicate tuple(?, 0), tuple(0).

tuple(Head) :-
    tuple(Head, Head).

tuple(Head, Body) :-
    must_be(callable, Body),
    strip_module(Head, _Module, Plain),
    listen(user, '$linda'(rd(Plain)), Body) ~>
        unlisten(user, '$linda'(rd(Plain)), Body).

%% tipc_linda_server is nondet.
%
%   Acts as a stand-alone Linda server.   This predicate initializes the
%   TIPC stack and then starts a Linda  server in the current thread. If
%   a client performs  an  =|out(server_quit)|=,   the  server's  Prolog
%   process will exit via halt/1. It is intended for use in scripting as
%   follows:
%
%   ==
%   swipl -q -g 'use_module(library(tipc/tipc_linda)),
%          tipc_linda_server' -t 'halt(1)'
%   ==
%
%   See also manual section 2.10.2.1 Using PrologScript.
%
%   *|Note:|*  Prolog  will  return  a  non-zero  exit  status  if  this
%   predicate is executed on  a  cluster   that  already  has  an active
%   server. An exit status of zero is returned on graceful shutdown.
%
%   @throws error(permission_error(halt,thread,2),context(halt/1,Only
%   from thread 'main')), if this predicate is executed in a thread
%   other than =main=.
%
%
wait_for_quit :-
    linda_timeout(6.0),
    in(server_quit),
    halt(0).

tipc_linda_server :-
%   detach_IO,               % become a daemon
            tipc_initialize,
            (   linda_client(global) -> true; linda(wait_for_quit)).

%!  tipc_initialize is semidet.
%
%   See tipc:tipc_initialize/0.
%


text:
import React from 'react'
import { Segment } from 'shengnian-ui-react'

const SegmentExampleVeryPadded = () => (
  <Segment padded='very'>
    Very padded content.
  </Segment>
)

export default SegmentExampleVeryPadded


text:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

use PHPImageWorkshop\ImageWorkshop as ImageWorkshop;

require(dirname(__dir__, 2).'/vendor/autoload.php');
// require_once('PHPImageWorkshop/autoload.php');

class Myimage extends ImageWorkshop {
//	function __construct() {
		// Call parent constructor
//		parent::__construct();

//		$CI =& get_instance();
//	}
}
?>