text:
package netty.framework.dao.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;

public class IDQuery {

	public static int queryMaxID(String tableName) {

		final String sql = "SELECT Max(id) FROM " + tableName;
		ResultSet result = DataBase.INSTANCE.query(sql);
		if(result == null) {
			throw new RuntimeException(tableName + " table not exist!!!");
		} else {
			try {
				if(result.next()) {
					return result.getInt(1);
				} else {
					throw new RuntimeException(tableName + " have no vales!!!");
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		throw new RuntimeException(tableName + " query id error!!!");

	}
}


text:
<project name="webstart">
	<target name="webstart_demo" depends="jars">
		<antcall target="-webstart_demo">
		    <param name="keystore" value="applet/lwjglkeystore"/>
			<param name="alias" value="lwjgl"/>
			<param name="password" value="123456"/>
		  </antcall>
	</target>

	<target name="webstart_demo-release">
		<input 	message="Please type the password for the keystore" addproperty="sign.pwd"/>

		<antcall target="-webstart_demo">
		    <param name="keystore" value="signing/lwjgl.jks"/>
			<param name="alias" value="lwjgl"/>
			<param name="password" value="${sign.pwd}"/>
		  </antcall>
	</target>

	<!-- Create webstart demo and extension from release files -->
	<target name="-webstart_demo" description="Using released files, creates the necessary files used for jnlp demos">

		<!-- delete existing temp -->
		<delete dir="${lwjgl.temp}"/>

		<!-- unzip release to temp dir -->
		<unzip src="${lwjgl.dist}/lwjgl-${lwjgl.version}.zip" dest="${lwjgl.temp}/webstart/temp" overwrite="true"/>

		<!-- DEMO SECTION -->
		<move file="${lwjgl.temp}/webstart/temp/lwjgl-${lwjgl.version}/jar/lwjgl_test.jar" tofile="${lwjgl.temp}/webstart/lwjgl_test.jar"/>
		<jar destfile="${lwjgl.temp}/webstart/lwjgl_test.jar" update="true">
			<manifest>
				<attribute name="Sealed" value="true"/>
			</manifest>
		</jar>
		<jar destfile="${lwjgl.temp}/webstart/media.jar" basedir="${lwjgl.res}">
			<manifest>
				<attribute name="Sealed" value="true"/>
			</manifest>
		</jar>

		<!-- EXTENSION SECTION -->
		<move todir="${lwjgl.temp}/webstart/${lwjgl.version}/" flatten="true">
			<fileset dir="${lwjgl.temp}/webstart/temp">
				<include name="**/jinput.jar"/>
				<include name="**/lwjgl*.jar"/>
				<exclude name="**/lwjgl_util_applet.jar"/>
				<exclude name="**/lwjgl-debug.jar"/>
			</fileset>
		</move>

		<jar destfile="${lwjgl.temp}/webstart/${lwjgl.version}/lwjgl.jar" update="true">
			<manifest>
				<attribute name="Specification-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Specification-Version" 		value="${lwjgl.version}"/>
				<attribute name="Specification-Vendor" 			value="lwjgl.org"/>
				<attribute name="Implementation-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Implementation-Version" 		value="${lwjgl.version}"/>
				<attribute name="Implementation-Vendor" 		value="lwjgl.org"/>
				<attribute name="Implementation-Vendor-Id" 	value="org.lwjgl"/>
				<attribute name="Extension-Name" 						value="org.lwjgl"/>
				<attribute name="Sealed" value="true"/>
				<attribute name="Trusted-Library" value="true"/>
			</manifest>
		</jar>

		<jar destfile="${lwjgl.temp}/webstart/${lwjgl.version}/jinput.jar" update="true">
			<manifest>
				<attribute name="Specification-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Specification-Version" 		value="${lwjgl.version}"/>
				<attribute name="Specification-Vendor" 			value="lwjgl.org"/>
				<attribute name="Implementation-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Implementation-Version" 		value="${lwjgl.version}"/>
				<attribute name="Implementation-Vendor" 		value="lwjgl.org"/>
				<attribute name="Implementation-Vendor-Id" 	value="org.lwjgl"/>
				<attribute name="Extension-Name" 						value="org.lwjgl"/>
				<attribute name="Sealed" value="true"/>
				<attribute name="Trusted-Library" value="true"/>
			</manifest>
		</jar>

		<jar destfile="${lwjgl.temp}/webstart/${lwjgl.version}/lwjgl_util.jar" update="true">
			<manifest>
				<attribute name="Specification-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Specification-Version" 		value="${lwjgl.version}"/>
				<attribute name="Specification-Vendor" 			value="lwjgl.org"/>
				<attribute name="Implementation-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Implementation-Version" 		value="${lwjgl.version}"/>
				<attribute name="Implementation-Vendor" 		value="lwjgl.org"/>
				<attribute name="Implementation-Vendor-Id" 	value="org.lwjgl"/>
				<attribute name="Extension-Name" 						value="org.lwjgl"/>
				<attribute name="Sealed" value="true"/>
				<attribute name="Trusted-Library" value="true"/>
			</manifest>
		</jar>

		<!-- create native jars -->
		<jar destfile="${lwjgl.temp}/webstart/${lwjgl.version}/native_windows.jar" basedir="${lwjgl.temp}/webstart/temp/lwjgl-${lwjgl.version}/native/windows">
			<manifest>
				<attribute name="Specification-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Specification-Version" 		value="${lwjgl.version}"/>
				<attribute name="Specification-Vendor" 			value="lwjgl.org"/>
				<attribute name="Implementation-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Implementation-Version" 		value="${lwjgl.version}"/>
				<attribute name="Implementation-Vendor" 		value="lwjgl.org"/>
				<attribute name="Implementation-Vendor-Id" 	value="org.lwjgl"/>
				<attribute name="Extension-Name" 						value="org.lwjgl"/>
				<attribute name="Sealed" value="true"/>
				<attribute name="Trusted-Library" value="true"/>
			</manifest>
		</jar>

		<jar destfile="${lwjgl.temp}/webstart/${lwjgl.version}/native_linux.jar" basedir="${lwjgl.temp}/webstart/temp/lwjgl-${lwjgl.version}/native/linux">
			<manifest>
				<attribute name="Specification-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Specification-Version" 		value="${lwjgl.version}"/>
				<attribute name="Specification-Vendor" 			value="lwjgl.org"/>
				<attribute name="Implementation-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Implementation-Version" 		value="${lwjgl.version}"/>
				<attribute name="Implementation-Vendor" 		value="lwjgl.org"/>
				<attribute name="Implementation-Vendor-Id" 	value="org.lwjgl"/>
				<attribute name="Extension-Name" 						value="org.lwjgl"/>
				<attribute name="Sealed" value="true"/>
				<attribute name="Trusted-Library" value="true"/>
			</manifest>
		</jar>

		<jar destfile="${lwjgl.temp}/webstart/${lwjgl.version}/native_macosx.jar" basedir="${lwjgl.temp}/webstart/temp/lwjgl-${lwjgl.version}/native/macosx">
			<manifest>
				<attribute name="Specification-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Specification-Version" 		value="${lwjgl.version}"/>
				<attribute name="Specification-Vendor" 			value="lwjgl.org"/>
				<attribute name="Implementation-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Implementation-Version" 		value="${lwjgl.version}"/>
				<attribute name="Implementation-Vendor" 		value="lwjgl.org"/>
				<attribute name="Implementation-Vendor-Id" 	value="org.lwjgl"/>
				<attribute name="Extension-Name" 						value="org.lwjgl"/>
				<attribute name="Sealed" value="true"/>
				<attribute name="Trusted-Library" value="true"/>
			</manifest>
		</jar>

		<jar destfile="${lwjgl.temp}/webstart/${lwjgl.version}/native_solaris.jar" basedir="${lwjgl.temp}/webstart/temp/lwjgl-${lwjgl.version}/native/solaris">
			<manifest>
				<attribute name="Specification-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Specification-Version" 		value="${lwjgl.version}"/>
				<attribute name="Specification-Vendor" 			value="lwjgl.org"/>
				<attribute name="Implementation-Title" 			value="LWJGL ${lwjgl.version}"/>
				<attribute name="Implementation-Version" 		value="${lwjgl.version}"/>
				<attribute name="Implementation-Vendor" 		value="lwjgl.org"/>
				<attribute name="Implementation-Vendor-Id" 	value="org.lwjgl"/>
				<attribute name="Extension-Name" 						value="org.lwjgl"/>
				<attribute name="Sealed" value="true"/>
				<attribute name="Trusted-Library" value="true"/>
			</manifest>
		</jar>

		<!-- sign 'em -->
		<signjar jar="${lwjgl.temp}/webstart/${lwjgl.version}/lwjgl.jar" 						alias="${alias}" keystore="${keystore}" storepass="${password}"/>
		<signjar jar="${lwjgl.temp}/webstart/${lwjgl.version}/lwjgl_util.jar" 			alias="${alias}" keystore="${keystore}" storepass="${password}"/>
		<signjar jar="${lwjgl.temp}/webstart/${lwjgl.version}/jinput.jar" 					alias="${alias}" keystore="${keystore}" storepass="${password}"/>
		<signjar jar="${lwjgl.temp}/webstart/${lwjgl.version}/native_solaris.jar" 	alias="${alias}" keystore="${keystore}" storepass="${password}"/>
		<signjar jar="${lwjgl.temp}/webstart/${lwjgl.version}/native_linux.jar" 		alias="${alias}" keystore="${keystore}" storepass="${password}"/>
		<signjar jar="${lwjgl.temp}/webstart/${lwjgl.version}/native_macosx.jar" 		alias="${alias}" keystore="${keystore}" storepass="${password}"/>
		<signjar jar="${lwjgl.temp}/webstart/${lwjgl.version}/native_windows.jar" 	alias="${alias}" keystore="${keystore}" storepass="${password}"/>

		<!-- copy over extension jnlp file -->
		<copy todir="${lwjgl.temp}/webstart/${lwjgl.version}">
    	<fileset dir="${lwjgl.web}/webstart">
    		<include name="extension.jnlp"/>
    	</fileset>
    	<filterset>
      	<filter token="LWJGL_VERSION" value="${lwjgl.version}"/>
    	</filterset>
  	</copy>

		<!-- nuke extracted dir -->
		<delete dir="${lwjgl.temp}/webstart/temp"/>

	</target>
</project>

redpajama_set_name: RedPajamaGithub


text:
<p id="haine_denis" data-toggle="tooltip" title="">
    Denis Haine
    is a veterinarian and PhD candidate in veterinary epidemiology at
    the Université de Montréal, QC. For the last 10
    years he has held several positions, as epidemiology and biostats
    consultant, director of biostatistics in a CRO and scientific
    assistant in a NSERC research centre.


text:
package compute

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"google.golang.org/api/option"

	"cloud.google.com/go/internal/testutil"
	"cloud.google.com/go/internal/uid"
	"google.golang.org/api/iterator"
	computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
	"google.golang.org/protobuf/proto"
)

var projectId = testutil.ProjID()
var defaultZone = "us-central1-a"
var image = "projects/debian-cloud/global/images/family/debian-10"

func TestCreateGetPutPatchListInstance(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping smoke test in short mode")
	}
	space := uid.NewSpace("gogapic", nil)
	name := space.New()
	ctx := context.Background()
	c, err := NewInstancesRESTClient(ctx)
	if err != nil {
		t.Fatal(err)
	}
	createRequest := &computepb.InsertInstanceRequest{
		Project: projectId,
		Zone:    defaultZone,
		InstanceResource: &computepb.Instance{
			Name:        &name,
			Description: proto.String("тест"),
			MachineType: proto.String(fmt.Sprintf("https://www.googleapis.com/compute/v1/projects/%s/zones/%s/machineTypes/n1-standard-1", projectId, defaultZone)),
			Disks: []*computepb.AttachedDisk{
				{
					AutoDelete: proto.Bool(true),
					Boot:       proto.Bool(true),
					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
					InitializeParams: &computepb.AttachedDiskInitializeParams{
						SourceImage: proto.String(image),
					},
				},
			},
			NetworkInterfaces: []*computepb.NetworkInterface{
				{
					AccessConfigs: []*computepb.AccessConfig{
						{
							Name: proto.String("default"),
						},
					},
				},
			},
		},
	}

	insert, err := c.Insert(ctx, createRequest)
	if err != nil {
		t.Fatal(err)
	}

	err = insert.Wait(ctx)
	defer ForceDeleteInstance(ctx, name, c)
	if err != nil {
		t.Fatal(err)
	}

	getRequest := &computepb.GetInstanceRequest{
		Project:  projectId,
		Zone:     defaultZone,
		Instance: name,
	}
	get, err := c.Get(ctx, getRequest)
	if err != nil {
		t.Fatal(err)
	}
	if get.GetName() != name {
		t.Fatalf("expected instance name: %s, got: %s", name, get.GetName())
	}
	if get.GetDescription() != "тест" {
		t.Fatalf("expected instance description: %s, got: %s", "тест", get.GetDescription())
	}
	if secureBootEnabled := get.GetShieldedInstanceConfig().GetEnableSecureBoot(); secureBootEnabled {
		t.Fatalf("expected instance secure boot: %t, got: %t", false, get.GetShieldedInstanceConfig().GetEnableSecureBoot())
	}

	get.Description = proto.String("updated")
	updateRequest := &computepb.UpdateInstanceRequest{
		Instance:         name,
		InstanceResource: get,
		Project:          projectId,
		Zone:             defaultZone,
	}
	updateOp, err := c.Update(ctx, updateRequest)
	if err != nil {
		t.Error(err)
	}

	err = updateOp.Wait(ctx)
	if err != nil {
		t.Fatal(err)
	}

	patchReq := &computepb.UpdateShieldedInstanceConfigInstanceRequest{
		Instance: name,
		Project:  projectId,
		Zone:     defaultZone,
		ShieldedInstanceConfigResource: &computepb.ShieldedInstanceConfig{
			EnableSecureBoot: proto.Bool(true),
		},
	}
	patchOp, err := c.UpdateShieldedInstanceConfig(ctx, patchReq)
	if err != nil {
		return
	}

	err = patchOp.Wait(ctx)
	if err != nil {
		t.Fatal(err)
	}

	fetched, err := c.Get(ctx, getRequest)
	if err != nil {
		t.Fatal(err)
	}
	if fetched.GetDescription() != "updated" {
		t.Fatal(fmt.Sprintf("expected instance description: %s, got: %s", "updated", fetched.GetDescription()))
	}
	if secureBootEnabled := fetched.GetShieldedInstanceConfig().GetEnableSecureBoot(); !secureBootEnabled {
		t.Fatal(fmt.Sprintf("expected instance secure boot: %t, got: %t", true, secureBootEnabled))
	}
	listRequest := &computepb.ListInstancesRequest{
		Project: projectId,
		Zone:    defaultZone,
	}

	itr := c.List(ctx, listRequest)
	if err != nil {
		t.Fatal(err)
	}
	found := false
	element, err := itr.Next()
	for err == nil {
		if element.GetName() == name {
			found = true
		}
		element, err = itr.Next()
	}
	if err != nil && err != iterator.Done {
		t.Fatal(err)
	}
	if !found {
		t.Error("Couldn't find the instance in list response")
	}

	deleteInstanceRequest := &computepb.DeleteInstanceRequest{
		Project:  projectId,
		Zone:     defaultZone,
		Instance: name,
	}
	_, err = c.Delete(ctx, deleteInstanceRequest)
	if err != nil {
		t.Error(err)
	}
}

func ForceDeleteInstance(ctx context.Context, name string, client *InstancesClient) {
	deleteInstanceRequest := &computepb.DeleteInstanceRequest{
		Project:  projectId,
		Zone:     defaultZone,
		Instance: name,
	}
	client.Delete(ctx, deleteInstanceRequest)
}

func TestCreateGetRemoveSecurityPolicies(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping smoke test in short mode")
	}
	space := uid.NewSpace("gogapic", nil)
	name := space.New()
	ctx := context.Background()
	c, err := NewSecurityPoliciesRESTClient(ctx)
	if err != nil {
		t.Fatal(err)
	}
	action := "allow"
	matcher := &computepb.SecurityPolicyRuleMatcher{
		Config: &computepb.SecurityPolicyRuleMatcherConfig{
			SrcIpRanges: []string{
				"*",
			},
		},
		VersionedExpr: proto.String(computepb.SecurityPolicyRuleMatcher_SRC_IPS_V1.String()),
	}
	securityPolicyRule := &computepb.SecurityPolicyRule{
		Action:      &action,
		Priority:    proto.Int32(0),
		Description: proto.String("test rule"),
		Match:       matcher,
	}
	securityPolicyRuleDefault := &computepb.SecurityPolicyRule{
		Action:      &action,
		Priority:    proto.Int32(2147483647),
		Description: proto.String("default rule"),
		Match:       matcher,
	}
	insertRequest := &computepb.InsertSecurityPolicyRequest{
		Project: projectId,
		SecurityPolicyResource: &computepb.SecurityPolicy{
			Name: &name,
			Rules: []*computepb.SecurityPolicyRule{
				securityPolicyRule,
				securityPolicyRuleDefault,
			},
		},
	}
	insert, err := c.Insert(ctx, insertRequest)
	if err != nil {
		t.Fatal(err)
	}

	err = insert.Wait(ctx)
	defer ForceDeleteSecurityPolicy(ctx, name, c)
	if err != nil {
		t.Fatal(err)
	}

	removeRuleRequest := &computepb.RemoveRuleSecurityPolicyRequest{
		Priority:       proto.Int32(0),
		Project:        projectId,
		SecurityPolicy: name,
	}

	rule, err := c.RemoveRule(ctx, removeRuleRequest)
	if err != nil {
		t.Error(err)
	}
	err = rule.Wait(ctx)
	if err != nil {
		t.Fatal(err)
	}

	getRequest := &computepb.GetSecurityPolicyRequest{
		Project:        projectId,
		SecurityPolicy: name,
	}
	get, err := c.Get(ctx, getRequest)
	if err != nil {
		t.Error(err)
	}
	if len(get.GetRules()) != 1 {
		t.Fatalf("expected count for rules: %d, got: %d", 1, len(get.GetRules()))
	}

	deleteRequest := &computepb.DeleteSecurityPolicyRequest{
		Project:        projectId,
		SecurityPolicy: name,
	}
	_, err = c.Delete(ctx, deleteRequest)
	if err != nil {
		t.Error(err)
	}
}

func ForceDeleteSecurityPolicy(ctx context.Context, name string, client *SecurityPoliciesClient) {
	deleteRequest := &computepb.DeleteSecurityPolicyRequest{
		Project:        projectId,
		SecurityPolicy: name,
	}
	client.Delete(ctx, deleteRequest)
}

func TestPaginationWithMaxRes(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping smoke test in short mode")
	}
	ctx := context.Background()
	c, err := NewAcceleratorTypesRESTClient(ctx)
	if err != nil {
		t.Fatal(err)
	}
	req := &computepb.ListAcceleratorTypesRequest{
		Project:    projectId,
		Zone:       defaultZone,
		MaxResults: proto.Uint32(1),
	}
	itr := c.List(ctx, req)

	found := false
	element, err := itr.Next()
	for err == nil {
		if element.GetName() == "nvidia-tesla-t4" {
			found = true
			break
		}
		element, err = itr.Next()
	}
	if err != nil && err != iterator.Done {
		t.Fatal(err)
	}
	if !found {
		t.Error("Couldn't find the accelerator in the response")
	}
}

func TestPaginationDefault(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping smoke test in short mode")
	}
	ctx := context.Background()
	c, err := NewAcceleratorTypesRESTClient(ctx)
	if err != nil {
		t.Fatal(err)
	}
	req := &computepb.ListAcceleratorTypesRequest{
		Project: projectId,
		Zone:    defaultZone,
	}
	itr := c.List(ctx, req)

	found := false
	element, err := itr.Next()
	for err == nil {
		if element.GetName() == "nvidia-tesla-t4" {
			found = true
			break
		}
		element, err = itr.Next()
	}
	if err != nil && err != iterator.Done {
		t.Fatal(err)
	}
	if !found {
		t.Error("Couldn't find the accelerator in the response")
	}
}

func TestPaginationMapResponse(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping smoke test in short mode")
	}
	ctx := context.Background()
	c, err := NewAcceleratorTypesRESTClient(ctx)
	if err != nil {
		t.Fatal(err)
	}
	req := &computepb.AggregatedListAcceleratorTypesRequest{
		Project: projectId,
	}
	itr := c.AggregatedList(ctx, req)

	found := false
	element, err := itr.Next()
	for err == nil {
		if element.Key == "zones/us-central1-a" {
			types := element.Value.GetAcceleratorTypes()
			for _, item := range types {
				if item.GetName() == "nvidia-tesla-t4" {
					found = true
					break
				}
			}
		}
		element, err = itr.Next()
	}
	if err != iterator.Done {
		t.Fatal(err)
	}
	if !found {
		t.Error("Couldn't find the accelerator in the response")
	}
}

func TestPaginationMapResponseMaxRes(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping smoke test in short mode")
	}
	ctx := context.Background()
	c, err := NewAcceleratorTypesRESTClient(ctx)
	if err != nil {
		t.Fatal(err)
	}
	req := &computepb.AggregatedListAcceleratorTypesRequest{
		Project:    projectId,
		MaxResults: proto.Uint32(10),
	}
	itr := c.AggregatedList(ctx, req)
	found := false
	element, err := itr.Next()
	for err == nil {
		if element.Key == "zones/us-central1-a" {
			types := element.Value.GetAcceleratorTypes()
			for _, item := range types {
				if item.GetName() == "nvidia-tesla-t4" {
					found = true
					break
				}
			}
		}
		element, err = itr.Next()
	}
	if err != iterator.Done {
		t.Fatal(err)
	}
	if !found {
		t.Error("Couldn't find the accelerator in the response")
	}
}

func TestHeaders(t *testing.T) {
	ctx := context.Background()

	svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		contentType := r.Header.Get("Content-Type")
		xGoog := r.Header.Get("X-Goog-Api-Client")
		if contentType != "application/json" {
			t.Fatalf("Content-Type header was %s, expected `application/json`.", contentType)
		}
		if !strings.Contains(xGoog, "rest/") {
			t.Fatal("X-Goog-Api-Client header doesn't contain `rest/`")
		}
	}))
	defer svr.Close()
	opts := []option.ClientOption{
		option.WithEndpoint(svr.URL),
		option.WithoutAuthentication(),
	}
	c, err := NewAcceleratorTypesRESTClient(ctx, opts...)
	if err != nil {
		t.Fatal(err)
	}
	_, err = c.Get(ctx, &computepb.GetAcceleratorTypeRequest{
		AcceleratorType: "test",
		Project:         "test",
		Zone:            "test",
	})
	if err != nil {
		return
	}
}

func TestInstanceGroupResize(t *testing.T) {
	// we test a required query-param field set to 0
	if testing.Short() {
		t.Skip("skipping smoke test in short mode")
	}
	ctx := context.Background()
	instanceTemplatesClient, err := NewInstanceTemplatesRESTClient(ctx)
	if err != nil {
		t.Fatal(err)
	}
	instanceGroupManagersClient, err := NewInstanceGroupManagersRESTClient(ctx)
	if err != nil {
		t.Fatal(err)
	}
	space := uid.NewSpace("gogapic", nil)
	templateName := space.New()
	managerName := space.New()
	templateResource := &computepb.InstanceTemplate{
		Name: proto.String(templateName),
		Properties: &computepb.InstanceProperties{
			MachineType: proto.String("n2-standard-2"),
			Disks: []*computepb.AttachedDisk{
				{
					AutoDelete: proto.Bool(true),
					Boot:       proto.Bool(true),
					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
					InitializeParams: &computepb.AttachedDiskInitializeParams{
						SourceImage: proto.String(image),
					},
				},
			},
			NetworkInterfaces: []*computepb.NetworkInterface{
				{
					AccessConfigs: []*computepb.AccessConfig{
						{
							Name: proto.String("default"),
							Type: proto.String(computepb.AccessConfig_ONE_TO_ONE_NAT.String()),
						},
					},
				},
			},
		},
	}
	insertOp, err := instanceTemplatesClient.Insert(
		ctx,
		&computepb.InsertInstanceTemplateRequest{
			Project:                  projectId,
			InstanceTemplateResource: templateResource,
		})
	if err != nil {
		t.Fatal(err)
	}
	err = insertOp.Wait(ctx)
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		_, err = instanceTemplatesClient.Delete(
			ctx,
			&computepb.DeleteInstanceTemplateRequest{
				Project:          projectId,
				InstanceTemplate: templateName,
			})
		if err != nil {
			t.Error(err)
		}
	}()

	igmResource := &computepb.InstanceGroupManager{
		BaseInstanceName: proto.String("gogapic"),
		TargetSize:       proto.Int32(1),
		InstanceTemplate: proto.String(insertOp.Proto().GetTargetLink()),
		Name:             proto.String(managerName),
	}

	insertOp, err = instanceGroupManagersClient.Insert(
		ctx,
		&computepb.InsertInstanceGroupManagerRequest{
			Project:                      projectId,
			Zone:                         defaultZone,
			InstanceGroupManagerResource: igmResource,
		},
	)
	if err != nil {
		t.Fatal(err)
	}
	err = insertOp.Wait(ctx)
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
		defer cancel()
		deleteOp, err := instanceGroupManagersClient.Delete(
			timeoutCtx,
			&computepb.DeleteInstanceGroupManagerRequest{
				Zone:                 defaultZone,
				Project:              projectId,
				InstanceGroupManager: managerName,
			})
		if err != nil {
			t.Error(err)
		}
		if err := deleteOp.Wait(ctx); err != nil {
			t.Error(err)
		}
	}()
	fetched, err := instanceGroupManagersClient.Get(
		ctx,
		&computepb.GetInstanceGroupManagerRequest{
			Project:              projectId,
			Zone:                 defaultZone,
			InstanceGroupManager: managerName,
		})
	if err != nil {
		t.Fatal(err)
	}
	if fetched.GetTargetSize() != 1 {
		t.Fatalf("expected target size: %d, got: %d", 1, fetched.GetTargetSize())
	}
	resizeOperation, err := instanceGroupManagersClient.Resize(
		ctx,
		&computepb.ResizeInstanceGroupManagerRequest{
			Project:              projectId,
			Size:                 0,
			Zone:                 defaultZone,
			InstanceGroupManager: managerName,
		})
	if err != nil {
		t.Fatal(err)
	}
	err = resizeOperation.Wait(ctx)
	if err != nil {
		t.Fatal(err)
	}
	fetched, err = instanceGroupManagersClient.Get(
		ctx,
		&computepb.GetInstanceGroupManagerRequest{
			Project:              projectId,
			Zone:                 defaultZone,
			InstanceGroupManager: managerName,
		})
	if err != nil {
		t.Fatal(err)
	}
	if fetched.GetTargetSize() != 0 {
		t.Fatalf("expected target size: %d, got: %d", 0, fetched.GetTargetSize())
	}
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once

#include <vespa/vespalib/util/alloc.h>
#include <vespa/vespalib/util/array.h>
#include <vector>
#include <mutex>

namespace vespalib {

/**
 * This is a backing store intended for small size variable length data elemets.
 * It has the important property that once an object has been allocated it does not move in memory.
 * It will start of by allocating one backing buffer and items stored will be appended here.
 * When limit is exceeded a new buffer is allocated with twice the size of the previous and so it goes.
 **/
class MemoryDataStore {
public:
    class Reference {
    public:
        Reference(void * data_) : _data(data_) { }
        void * data() { return _data; }
        const char * c_str() const { return static_cast<const char *>(_data); }
    private:
        void   * _data;
    };
    MemoryDataStore(alloc::Alloc && initialAlloc=alloc::Alloc::alloc(256), std::mutex * lock=nullptr);
    MemoryDataStore(const MemoryDataStore &) = delete;
    MemoryDataStore & operator = (const MemoryDataStore &) = delete;
    ~MemoryDataStore();
    /**
     * Will allocate space and copy the data in. The returned pointer will be valid
     * for the lifetime of this object.
     * @return A pointer/reference to the freshly stored object.
     */
    Reference push_back(const void * data, const size_t sz);
    void swap(MemoryDataStore & rhs) { _buffers.swap(rhs._buffers); }
    void clear() {
        _buffers.clear();
    }
private:
    std::vector<alloc::Alloc> _buffers;
    size_t _writePos;
    std::mutex * _lock;
};

class VariableSizeVector
{
public:
    class Reference {
    public:
        Reference(void * data_, size_t sz) : _data(data_), _sz(sz) { }
        void * data() { return _data; }
        const char * c_str() const { return static_cast<const char *>(_data); }
        size_t size() const { return _sz; }
    private:
        void   * _data;
        size_t   _sz;
    };
    class iterator {
    public:
        iterator(vespalib::Array<Reference> & v, size_t index) : _vector(&v), _index(index) {}
        Reference & operator  * () const { return (*_vector)[_index]; }
        Reference * operator -> () const { return &(*_vector)[_index]; }
        iterator & operator ++ () {
            _index++;
            return *this;
        }
        iterator operator ++ (int) {
            iterator prev = *this;
            ++(*this);
            return prev;
        }
        bool operator==(const iterator& rhs) const { return (_index == rhs._index); }
        bool operator!=(const iterator& rhs) const { return (_index != rhs._index); }
    private:
        vespalib::Array<Reference> * _vector;
        size_t _index;
    };
    class const_iterator {
    public:
        const_iterator(const vespalib::Array<Reference> & v, size_t index) : _vector(&v), _index(index) {}
        const Reference & operator  * () const { return (*_vector)[_index]; }
        const Reference * operator -> () const { return &(*_vector)[_index]; }
        const_iterator & operator ++ () {
            _index++;
            return *this;
        }
        const_iterator operator ++ (int) {
            const_iterator prev = *this;
            ++(*this);
            return prev;
        }
        bool operator==(const const_iterator& rhs) const { return (_index == rhs._index); }
        bool operator!=(const const_iterator& rhs) const { return (_index != rhs._index); }
    private:
        const vespalib::Array<Reference> * _vector;
        size_t _index;
    };
    VariableSizeVector(const VariableSizeVector &) = delete;
    VariableSizeVector & operator = (const VariableSizeVector &) = delete;
    VariableSizeVector(size_t initialCount, size_t initialBufferSize);
    ~VariableSizeVector();
    iterator begin() { return iterator(_vector, 0); }
    iterator end() { return iterator(_vector, size()); }
    const_iterator begin() const { return const_iterator(_vector, 0); }
    const_iterator end() const { return const_iterator(_vector, size()); }
    Reference push_back(const void * data, const size_t sz);
    Reference operator [] (uint32_t index) const { return _vector[index]; }
    size_t size() const { return _vector.size(); }
    bool empty() const { return _vector.empty(); }
    void swap(VariableSizeVector & rhs) {
        _vector.swap(rhs._vector);
        _store.swap(rhs._store);
    }
    void clear() {
        _vector.clear();
        _store.clear();
    }
private:
    vespalib::Array<Reference> _vector;
    MemoryDataStore _store;
};

} // namespace vespalib


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>A-Index</title>
<meta name="date" content="2013-07-28">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L M N O P R S T U V W

A

add(byte[], int) - Method in class com.physicaloid.misc.RingBuffer

Adds byte array to ring buffer

addReadListener(ReadLisener) - Method in class com.physicaloid.lib.framework.SerialCommunicator

Adds read listener

addReadListener(ReadLisener) - Method in class com.physicaloid.lib.Physicaloid

Adds read listener

addReadListener(ReadLisener) - Method in class com.physicaloid.lib.usb.driver.uart.UartCdcAcm

addReadListener(ReadLisener) - Method in class com.physicaloid.lib.usb.driver.uart.UartFtdi

ALTERA_FPGA_RBF - Static variable in class com.physicaloid.lib.Boards.UploadProtocols

app_name - Static variable in class com.physicaloid.R.string

AppBaseTheme - Static variable in class com.physicaloid.R.style

Base application theme, dependent on API level.

AppTheme - Static variable in class com.physicaloid.R.style

Application theme.

ATMEGA32U4 - Static variable in class com.physicaloid.lib.Boards.ChipTypes

AutoCommunicator - Class in com.physicaloid.lib.framework

AutoCommunicator() - Constructor for class com.physicaloid.lib.framework.AutoCommunicator

AVR - Static variable in class com.physicaloid.lib.usb.UsbIds.Vid

AVR109 - Static variable in class com.physicaloid.lib.Boards.UploadProtocols

AvrConf - Class in com.physicaloid.lib.programmer.avr

AvrConf(Boards) - Constructor for class com.physicaloid.lib.programmer.avr.AvrConf

AvrUploader - Class in com.physicaloid.lib.programmer.avr

AvrUploader(SerialCommunicator) - Constructor for class com.physicaloid.lib.programmer.avr.AvrUploader

A B C D E F G H I L M N O P R S T U V W

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
Autenticazione SPID per Ruby on Rails.
Questa gemma si appoggia alla gemma [ruby-saml](https://github.com/onelogin/ruby-saml).

## Cosa c'è e cosa manca
- [x] Creazione gemma
- [x] Applicazione demo funzionante con login tramite il server test idp.spid.gov.it
repository: https://github.com/rubynetti/rubynetti-rails
- [x] Login tramite redirect
- [ ] Login tramite post
- [X] Sistema di testing automatico
- [X] Sistema di configurazione
- [ ] Integrazione con omniauth
- [ ] Integrazione o esempio di integrazione con devise
- [ ] Configurazione richiesta attributi utente

## Installazione
All'interno del Gemfile indicare questa gemma:

```ruby
gem 'spid-rails'
```

Eseguire

```bash
$ bundle
```

## Come si usa?
La gemma può essere aggiunta a qualunque applicazione Rails al fine di utilizzare il sistema di login Spid.
Il metadata generato può essere utilizzato per farsi accreditare e in seguito dialogare con qualunque Identity Provider Spid accreditato.

### Configurazione

Per creare il file di configurazione:

```bash
$ rails g spid:rails:config
```

Il file viene aggiunto agli initializer dell'applicazione e permette il settaggio personalizzato del mount-point dell'engine e i relativi end-point per le procedure Spid di login, logout e visualizzazione del metadata del Service Provider.

Le restanti impostazioni permettono di configurare il percorso di sistema dove reperire la coppia chiave privata/certificato e il livello di crittografia per l'eventuale signature.

```ruby
# config/initializers/spid-rails.rb

# Impostazioni di default dello Spid Engine

Spid::Rails.tap do |config|

  # Mount point di Spid sull'applicazione
  # default: 'spid'
  # config.mount_point = 'spid'

  # Url alla quale e' disponibile il metadata del provider
  # default: 'metadata'
  # config.metadata_path = 'metadata'

  # Url alla quale ricevere le risposte di autenticazione Saml
  # default: 'sso'
  # config.sso_path = 'sso'

  # Url alla quale ricevere le risposte di logout Saml
  # default: 'slo'
  # config.slo_path = 'slo'

  # Percorso relativo alla root dell'app
  # al quale reperire la coppia chiave privata - certificato
  # default: 'lib/.keys'
  # config.keys_path = 'lib/.keys/'

  # Livello di crittografia SHA per la generazione delle signature
  # default: 256
  # config.sha = 256

end
```

Per utilizzare Identity provider custom o modificare quelli presenti:

```bash
$ rails g spid:rails:idp_importer
```

Il file viene aggiunto alla cartella _config/spid-rails_ e permette di specificare idp per i diversi ambienti dell'applicazione.

```YAML
# app/config/spid-rails/idp_import.yml

shared: &shared
  local_test:
    metadata_url: 'https://localhost:8080'
    validate_cert: false

development:
  <<: *shared
  agid:
    metadata_url: 'https://idp.spid.gov.it:8080/assets/idp-metadata.xml'
    validate_cert: false

test:
  <<: *shared
```

### Nelle view

Una volta installata la gemma, verranno creati una serie di helper utilizzabili nelle view e nei controller.

```spid_rails.metadata_path``` e ```spid_rails.metadata_url``` restituiscono il percorso al quale è reperibile il metadata del Service Provider.
```ruby
# Esempio di link al metadata del ServiceProvider
link_to "Metadata SP", spid_rails.metadata_path
```

```spid_rails.new_sso_path``` e ```spid_rails.new_sso_url``` restituiscono il percorso tramite il quale inizializzare una richiesa di autenticazione all'Identity Provider.
È necessario fornire come parametro l'Idp cui indirizzare la richiesta, facoltativo il livello di autenticazione Spid (default: '1') e i bindings della richiesta all' Idp (default: ['redirect']).
```ruby
# Esempio di link al login tramite l'Idp di test https:://idp.spid.gov.it
link_to "Login con Spid", spid_rails.new_sso_path(sso: { idp: :agid_test, spid_level: 2 })
```

Gli Identity Provider attualmente supportati sono:
- 'aruba'      : servizio Idp di Aruba Pec S.p.A.
- 'infocert'   : servizio Idp di Infocert S.p.A
- 'namirial'   : servizio Idp di Namirial S.p.A.
- 'poste'      : servizio Idp di Poste Italiane S.p.A.
- 'spiditalia' : servizio Idp di REGISTER.IT S.p.A.
- 'sielte'     : servizio Idp di Sielte S.p.A.
- 'tim'        : servizio Idp di TI Trust Technologies S.r.l.
- 'agid_test'  : servizio idp di test di Agid
- 'poste_test' : servizio Idp di test di Poste Italiane S.p.A.

```spid_rails.new_slo_path``` e ```spid_rails.new_slo_url``` infine restituiscono il percorso tramite il quale inizializzare una richiesa di logout all'Identity Provider che ha autenticato la sessione corrente.
```ruby
# Esempio di link al logout
link_to "Logout", spid_rails.new_slo_path
```

### Nei controller

Dopo l'autenticazione e fino al logout vengono aggiunte alla sessione le seguenti variabili:

```session[:sso_params]``` che restituisce i parametri coi quali è stata effettuata l'ultima richiesta di autenticazione, in particolare l'idp

```session[:spid_index]``` che restituisce l'identificativo dell'attuale sessione Spid e viene utilizzato nella procedura di logout

```session[:spid_login_time]``` che restituisce il _time_ in cui è avvenuto il login

È inoltre possibile settare la variabile ```session[:spid_relay_state]```, contenente l'indirizzo al quale si vuole essere reindirizzati in caso l'autenticazione abbia successo

Un esempio rudimentale di verifica del login dell'utente all'interno di un'azione del controller potrebbe essere il seguente
```ruby
# app/controllers/my_controller.rb
class MyController < Application controller
  before_action :validate_spid_session

  ...

  private

  def validate_spid_session
    if session[:spid_index].blank?
      session[:spid_relay_state] = request.path
      redirect_to login_path
    end
  end

end
```

dove _login_path_ indirizza alla pagina in cui è posizionato il pulsante Spid.

## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
layout: post
title: 'TIP: Partial screenshots made easy'
date: 2015-01-26 17:17:16.000000000 -06:00
categories:
- TIP
tags: []
status: publish
type: post
published: true
meta:
  _edit_last: '1'
author:
  login: gibble
  email: chad.hurd@gcsquared.com
  display_name: caffgeek
  first_name: Chad
  last_name: Hurd

---
I have to take partial screenshots when creating emails or documentation almost every day. I'm not a fan of installing extra tools unless they're simple, and truly save me time. A few seconds isn't enough. This is one of those cases, typically I'll just take the screenshot with PrintScreen, or Alt-PrintScreen, paste it into mspaint, select and copy the part I need, and move on.

However, windows already has a tool for taking partial snapshots of the screen, it's called "[Snipping Tool](http://windows.microsoft.com/en-CA/windows7/products/features/snipping-tool)". It works for most cases, and that's enough for me.

We just need a quick way to open it. So, hit the windows key to open the start menu and type Snipping Tool, right click on it, and select properties. Focus in Shortcut key, and hit a key combination to open it. Mac has a similar tool already bound to Cmd-Shift-4, so I bound the snippet tool to Ctrl-Shift-4.

[![SnippingTool](/assets/SnippingTool-212x300.png)](/assets/SnippingTool-212x300.png)

Now, I just hit Ctrl-Shift-4, and the screen goes partially opaque. I highlight a section of the screen, and it's automatically put in my clipboard. It's also opened in the snipping tool, but I just close it without saving changes (Alt-F4). Then paste the partial screenshot in my email or document.

Simple.


text:
package org.eclipse.rdf4j.federated.repository;

import java.util.Collections;
import java.util.Set;

import org.eclipse.rdf4j.federated.FederationContext;
import org.eclipse.rdf4j.federated.structures.FedXBooleanQuery;
import org.eclipse.rdf4j.federated.structures.FedXGraphQuery;
import org.eclipse.rdf4j.federated.structures.FedXTupleQuery;
import org.eclipse.rdf4j.federated.structures.QueryType;
import org.eclipse.rdf4j.federated.util.FedXUtil;
import org.eclipse.rdf4j.query.MalformedQueryException;
import org.eclipse.rdf4j.query.Operation;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.Update;
import org.eclipse.rdf4j.query.parser.ParsedDescribeQuery;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.eclipse.rdf4j.repository.sail.SailBooleanQuery;
import org.eclipse.rdf4j.repository.sail.SailGraphQuery;
import org.eclipse.rdf4j.repository.sail.SailQuery;
import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection;
import org.eclipse.rdf4j.repository.sail.SailTupleQuery;
import org.eclipse.rdf4j.sail.SailConnection;

import com.google.common.collect.Sets;

/**
 * A special {@link SailRepositoryConnection} which adds the original query string as binding to the returned query. The
 * binding name is defined by {@link #BINDING_ORIGINAL_QUERY} and is added to all query instances returned by the
 * available prepare methods.
 *
 * @author Andreas Schwarte
 *
 */
public class FedXRepositoryConnection extends SailRepositoryConnection {

	/**
	 * We add a binding to each parsed query mapping the original query in order to send the original query to the
	 * endpoint if there is only a single federation member is relevant for this query.
	 */
	public static final String BINDING_ORIGINAL_QUERY = "__originalQuery";
	public static final String BINDING_ORIGINAL_BASE_URI = "__originalBaseURI";
	public static final String BINDING_ORIGINAL_QUERY_TYPE = "__originalQueryType";
	public static final String BINDING_ORIGINAL_MAX_EXECUTION_TIME = "__originalQueryMaxExecutionTime";

	/**
	 * The number of bindings in the external binding set that are added by FedX.
	 *
	 * @see #BINDING_ORIGINAL_QUERY
	 * @see #BINDING_ORIGINAL_QUERY_TYPE
	 * @see #BINDING_ORIGINAL_MAX_EXECUTION_TIME
	 */
	public static final Set<String> FEDX_BINDINGS = Collections.unmodifiableSet(
			Sets.newHashSet(BINDING_ORIGINAL_QUERY, BINDING_ORIGINAL_BASE_URI, BINDING_ORIGINAL_QUERY_TYPE,
					BINDING_ORIGINAL_MAX_EXECUTION_TIME));

	private final FederationContext federationContext;

	protected FedXRepositoryConnection(FedXRepository repository,
			SailConnection sailConnection) {
		super(repository, sailConnection);
		this.federationContext = repository.getFederationContext();
	}

	@Override
	public SailQuery prepareQuery(QueryLanguage ql, String queryString,
			String baseURI) throws MalformedQueryException {
		SailQuery q = super.prepareQuery(ql, queryString, baseURI);
		if (q instanceof SailTupleQuery) {
			insertOriginalQueryString(q, queryString, baseURI, QueryType.SELECT);
			q = new FedXTupleQuery((SailTupleQuery) q);
		} else if (q instanceof SailGraphQuery) {
			insertOriginalQueryString(q, queryString, baseURI, determineGraphQueryType((SailGraphQuery) q));
			q = new FedXGraphQuery((SailGraphQuery) q);
		} else if (q instanceof SailBooleanQuery) {
			insertOriginalQueryString(q, queryString, baseURI, QueryType.ASK);
			q = new FedXBooleanQuery((SailBooleanQuery) q);
		}
		setIncludeInferredDefault(q);
		return q;
	}

	@Override
	public FedXTupleQuery prepareTupleQuery(QueryLanguage ql,
			String queryString, String baseURI) throws MalformedQueryException {
		SailTupleQuery q = super.prepareTupleQuery(ql, queryString, baseURI);
		insertOriginalQueryString(q, queryString, baseURI, QueryType.SELECT);
		setIncludeInferredDefault(q);
		return new FedXTupleQuery(q);
	}

	@Override
	public FedXGraphQuery prepareGraphQuery(QueryLanguage ql,
			String queryString, String baseURI) throws MalformedQueryException {
		SailGraphQuery q = super.prepareGraphQuery(ql, queryString, baseURI);
		insertOriginalQueryString(q, queryString, baseURI, determineGraphQueryType(q));
		setIncludeInferredDefault(q);
		return new FedXGraphQuery(q);
	}

	@Override
	public SailBooleanQuery prepareBooleanQuery(QueryLanguage ql,
			String queryString, String baseURI) throws MalformedQueryException {
		SailBooleanQuery q = super.prepareBooleanQuery(ql, queryString, baseURI);
		insertOriginalQueryString(q, queryString, baseURI, QueryType.ASK);
		setIncludeInferredDefault(q);
		return new FedXBooleanQuery(q);
	}

	@Override
	public Update prepareUpdate(QueryLanguage ql, String updateString, String baseURI)
			throws RepositoryException, MalformedQueryException {
		Update update = super.prepareUpdate(ql, updateString, baseURI);
		insertOriginalQueryString(update, updateString, baseURI, QueryType.UPDATE);
		return update;
	}

	private void setIncludeInferredDefault(SailQuery query) {
		query.setIncludeInferred(federationContext.getConfig().getIncludeInferredDefault());
	}

	private void insertOriginalQueryString(Operation query, String queryString, String baseURI, QueryType qt) {
		if (baseURI != null) {
			query.setBinding(BINDING_ORIGINAL_BASE_URI, FedXUtil.literal(baseURI));
		}
		query.setBinding(BINDING_ORIGINAL_QUERY, FedXUtil.literal(queryString));
		query.setBinding(BINDING_ORIGINAL_QUERY_TYPE, FedXUtil.literal(qt.name()));
	}

	private QueryType determineGraphQueryType(SailGraphQuery q) {
		if (q.getParsedQuery() instanceof ParsedDescribeQuery) {
			return QueryType.DESCRIBE;
		}
		return QueryType.CONSTRUCT;
	}
}


text:
import java.io.PrintStream;
import java.util.Scanner;

public class Spavanac {
	public static final int MINUTES_EARLIER = 45;
	public static final int MINUTES_IN_HOUR = 60;
	public static final int HOURS_IN_DAY = 24;

	PrintStream out;
	Scanner in;
	int newMinutes;
	int newHours;

	Spavanac(){
		out = new PrintStream(System.out);
		in = new Scanner(System.in);
	}

	void start(){
		int hours = in.nextInt();
		int minutes = in.nextInt();

		newMinutes = minutes - MINUTES_EARLIER;
		newHours = hours;

		if (newMinutes < 0){
			int negativeMinutes = newMinutes;

			newMinutes = MINUTES_IN_HOUR + negativeMinutes;
			newHours -= 1;
		}

		if (newHours < 0){
			int negativeHours = newHours;

			newHours = HOURS_IN_DAY + negativeHours;
		}

		out.printf("%d %d", newHours, newMinutes);
	}

	public static void main(String[] argv){
		new Spavanac().start();
	}
}


text:
<!doctype HTML public "-//W3C//DTD HTML 4.0 Frameset//EN">

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Labelled Block Until Done</title>

About
 the Labelled Block Until Done Tool:

The Labelled Block Until Done Tool stops downstream processing until the very last record  has arrived.  On output, it writes all records first to output1 before then starting writing all records to output2.

Configuration Properties:

There is no configuration properties to the tool.

Version History:

Version 1.0  - Initial release.

Version 2.0 - Updated to Alteryx 9.0 macro interface.

___________________________________________________________________________________

www.ChaosReignsWithin.com


text:
package com.interview.array;

/**
 * Date 10/08/2016
 * @author Tushar Roy
 *
 * Given a sorted array of integers nums and integer values a, b and c.
 * Apply a function of the form f(x) = ax2 + bx + c to each element x in the array.
 *
 * Time complexity O(n)
 *
 * https://leetcode.com/problems/sort-transformed-array/
 */
public class SortedArrayTransformation {
    public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
        int start = 0;
        int end = nums.length - 1;
        int[] result = new int[nums.length];
        int index = (a >= 0 ? nums.length - 1 : 0);
        while (start <= end) {
            int x = apply(nums[start], a, b, c);
            int y = apply(nums[end], a, b, c);
            boolean condition = (a >= 0 ? x >= y : x <= y);
            if (condition) {
                result[index] = x;
                start++;
            } else {
                result[index] = y;
                end--;
            }
            index = index + (a >= 0 ? -1 : 1);
        }
        return result;
    }

    private int apply(int x, int a, int b, int c) {
        return a*x*x + b * x + c;
    }
}


text:
using AutoMapper;
using Todo.QueryStack.Model;

namespace Todo.QueryStack.Mappers
{
    class NotifierMapperProfile : Profile
    {
        protected override void Configure()
        {
            CreateMap<ToDoList, NotifiedToDoList>()
                .ForMember(dest => dest.Items, opt => opt.Ignore());
            CreateMap<ToDoItem, NotifiedToDoItem>();
        }
    }
}


text:
<?php
if(isset($list)) echo json_encode($list);
else echo json_encode($error);


text:
package com.marcobehler.saito.core.pagination;

import com.google.common.collect.Lists;
import lombok.Getter;

import java.util.List;

/**
 * @author Marco Behler <marco@marcobehler.com>
 */
@Getter
public class PaginationException extends RuntimeException {

    private final int pages;

    private final int pageSize;

    private final List<Object> data;

    public PaginationException(int pages, int pageSize, List<Object> data) {
        this.pages = pages;
        this.pageSize = pageSize;
        this.data = data;
    }

    public List<List<Object>> getPartitions() {
        return Lists.partition(data, pageSize);
    }

    public Page toPage(int page) {
        List<Object> data = getPartitions().get(page - 1);
        return new Page(data, page);
    }

}


text: Pace.on('hide',function(){jQuery("#wpace-hidden-all").remove();});


text:
`skopeo` may already be packaged in your distribution. This document lists the
installation steps for many distros, along with their information and support links.

### Fedora

```sh
sudo dnf -y install skopeo
```

[Package Info](https://src.fedoraproject.org/rpms/skopeo) and
[Bugzilla](https://bugzilla.redhat.com/buglist.cgi?bug_status=__open__&classification=Fedora&component=skopeo&product=Fedora)

Fedora bugs can be reported on the Skopeo GitHub [Issues](https://github.com/containers/skopeo/issues) page.

### RHEL / CentOS Stream ≥ 8

```sh
sudo dnf -y install skopeo
```

If you are a RHEL customer, please reach out through the official RHEL support
channels for any issues.

CentOS Stream 9: [Package Info](https://gitlab.com/redhat/centos-stream/rpms/skopeo/-/tree/c9s) and
[Bugzilla](https://bugzilla.redhat.com/buglist.cgi?bug_status=__open__&classification=Red%20Hat&component=skopeo&product=Red%20Hat%20Enterprise%20Linux%209&version=CentOS%20Stream)

CentOS Stream 8: [Package Info](https://git.centos.org/rpms/skopeo/tree/c8s-stream-rhel8) and
[Bugzilla](https://bugzilla.redhat.com/buglist.cgi?bug_status=__open__&classification=Red%20Hat&component=skopeo&product=Red%20Hat%20Enterprise%20Linux%208&version=CentOS%20Stream)

### RHEL/CentOS ≤ 7.x

```sh
sudo yum -y install skopeo
```

CentOS 7: [Package Repo](https://git.centos.org/rpms/skopeo/tree/c7-extras)

### openSUSE

```sh
sudo zypper install skopeo
```

[Package Info](https://software.opensuse.org/package/skopeo)

### Alpine

```sh
sudo apk add skopeo
```

[Package Info](https://pkgs.alpinelinux.org/packages?name=skopeo)

### macOS

```sh
brew install skopeo
```

### Nix / NixOS
```sh
$ nix-env -i skopeo
```

[Package Info](https://search.nixos.org/packages?&show=skopeo&query=skopeo)

### Debian

The skopeo package is available on [Bullseye](https://packages.debian.org/bullseye/skopeo),
and Debian Testing and Unstable.

```bash
# Debian Bullseye, Testing or Unstable/Sid
sudo apt-get update
sudo apt-get -y install skopeo
```

[Package Info](https://packages.debian.org/stable/skopeo)

### Raspberry Pi OS arm64 (beta)

Raspberry Pi OS uses the standard Debian's repositories,
so it is fully compatible with Debian's arm64 repository.
You can simply follow the [steps for Debian](#debian) to install Skopeo.

### Ubuntu

The skopeo package is available in the official repositories for Ubuntu 20.10
and newer.

```bash
# Ubuntu 20.10 and newer
sudo apt-get -y update
sudo apt-get -y install skopeo
```

[Package Info](https://packages.ubuntu.com/jammy/skopeo)

### Windows
Skopeo has not yet been packaged for Windows. There is an [open feature
request](https://github.com/containers/skopeo/issues/715) and contributions are
always welcome.

## Container Images

Skopeo container images are available at `quay.io/skopeo/stable:latest`.
For example,

```bash
podman run docker://quay.io/skopeo/stable:latest copy --help
```

[Read more](./contrib/skopeoimage/README.md).

## Building from Source

Otherwise, read on for building and installing it from source:

To build the `skopeo` binary you need at least Go 1.12.

There are two ways to build skopeo: in a container, or locally without a
container. Choose the one which better matches your needs and environment.

### Building without a container

Building without a container requires a bit more manual work and setup in your
environment, but it is more flexible:

- It should work in more environments (e.g. for native macOS builds)
- It does not require root privileges (after dependencies are installed)
- It is faster, therefore more convenient for developing `skopeo`.

Install the necessary dependencies:

```bash
# Fedora:
sudo dnf install gpgme-devel libassuan-devel btrfs-progs-devel device-mapper-devel
```

```bash
# Ubuntu (`libbtrfs-dev` requires Ubuntu 18.10 and above):
sudo apt install libgpgme-dev libassuan-dev libbtrfs-dev libdevmapper-dev pkg-config
```

```bash
# macOS:
brew install gpgme
```

```bash
# openSUSE:
sudo zypper install libgpgme-devel device-mapper-devel libbtrfs-devel glib2-devel
```

Make sure to clone this repository in your `GOPATH` - otherwise compilation fails.

```bash
git clone https://github.com/containers/skopeo $GOPATH/src/github.com/containers/skopeo
cd $GOPATH/src/github.com/containers/skopeo && make bin/skopeo
```

By default the `make` command (make all) will build bin/skopeo and the documentation locally.

Building of documentation requires `go-md2man`. On systems that do not have this tool, the
document generation can be skipped by passing `DISABLE_DOCS=1`:
```
DISABLE_DOCS=1 make
```

### Building documentation

To build the manual you will need go-md2man.

```bash
# Debian:
sudo apt-get install go-md2man
```

```
# Fedora:
sudo dnf install go-md2man
```

```
# MacOS:
brew install go-md2man
```

Then

```bash
make docs
```

### Building in a container

Building in a container is simpler, but more restrictive:

- It requires the `podman` command and the ability to run Linux containers.
- The created executable is a Linux executable, and depends on dynamic libraries
  which may only be available only in a container of a similar Linux
  distribution.

```bash
$ make binary
```

### Shell completion scripts

Skopeo has shell completion scripts for bash, zsh, fish and powershell. They are installed as part of `make install`.
You may have to restart your shell in order for them to take effect.

For instructions to manually generate and load the scripts please see `skopeo completion --help`.

### Installation

Finally, after the binary and documentation is built:

```bash
sudo make install
```

### Building a static binary

There have been efforts in the past to produce and maintain static builds, but the maintainers prefer to run Skopeo using distro packages or within containers. This is because static builds of Skopeo tend to be unreliable and functionally restricted. Specifically:
- Some features of Skopeo depend on non-Go libraries like `libgpgme` and `libdevmapper`.
- Generating static Go binaries uses native Go libraries, which don't support e.g. `.local` or LDAP-based name resolution.

That being said, if you would like to build Skopeo statically, you might be able to do it by combining all the following steps.
- Export environment variable `CGO_ENABLED=0` (disabling CGO causes Go to prefer native libraries when possible, instead of dynamically linking against system libraries).
- Set the `BUILDTAGS=containers_image_openpgp` Make variable (this remove the dependency on `libgpgme` and its companion libraries).
- Clear the `GO_DYN_FLAGS` Make variable (which otherwise seems to force the creation of a dynamic executable).

The following command implements these steps to produce a static binary in the `bin` subdirectory of the repository:

```bash
docker run -v $PWD:/src -w /src -e CGO_ENABLED=0 golang \
make BUILDTAGS=containers_image_openpgp GO_DYN_FLAGS=
```

Keep in mind that the resulting binary is unsupported and might crash randomly. Only use if you know what you're doing!

For more information, history, and context about static builds, check the following issues:

- [#391] - Consider distributing statically built binaries as part of release
- [#669] - Static build fails with segmentation violation
- [#670] - Fixing static binary build using container
- [#755] - Remove static and in-container targets from Makefile
- [#932] - Add nix derivation for static builds
- [#1336] - Unable to run skopeo on Fedora 30 (due to dyn lib dependency)
- [#1478] - Publish binary releases to GitHub (request+discussion)

[#391]: https://github.com/containers/skopeo/issues/391
[#669]: https://github.com/containers/skopeo/issues/669
[#670]: https://github.com/containers/skopeo/issues/670
[#755]: https://github.com/containers/skopeo/issues/755
[#932]: https://github.com/containers/skopeo/issues/932
[#1336]: https://github.com/containers/skopeo/issues/1336
[#1478]: https://github.com/containers/skopeo/issues/1478


text:
#ifndef QmitkBinaryThresholdULToolGUI_h_Included
#define QmitkBinaryThresholdULToolGUI_h_Included

#include "QmitkToolGUI.h"
#include "SegmentationUIExports.h"
#include "mitkBinaryThresholdULTool.h"
#include "ctkRangeWidget.h"

/**
  \ingroup org_mitk_gui_qt_interactivesegmentation_internal
  \brief GUI for mitk::BinaryThresholdTool.

  This GUI shows a slider to change the tool's threshold and an OK button to accept a preview for actual thresholding.

  Last contributor: $Author$
*/
class SegmentationUI_EXPORT QmitkBinaryThresholdULToolGUI : public QmitkToolGUI
{
  Q_OBJECT

  public:

    mitkClassMacro(QmitkBinaryThresholdULToolGUI, QmitkToolGUI);
    itkNewMacro(QmitkBinaryThresholdULToolGUI);

    void OnThresholdingIntervalBordersChanged(double lower, double upper);
    void OnThresholdingValuesChanged(mitk::ScalarType lower, mitk::ScalarType upper);

  signals:

  public slots:

  protected slots:

    void OnNewToolAssociated(mitk::Tool*);

    void OnAcceptThresholdPreview();

    void OnThresholdsChanged(double min, double max);

  protected:
    QmitkBinaryThresholdULToolGUI();
    virtual ~QmitkBinaryThresholdULToolGUI();

    ctkRangeWidget* m_DoubleThresholdSlider;

    mitk::BinaryThresholdULTool::Pointer m_BinaryThresholdULTool;
};

#endif


text:
Simple gmetad client that creates alerts by mail and/or SMS.
Created for a friend who needed such a tool and because the existing ganglia-alert is written in Perl.


text:
package org.apache.maven.execution;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toSet;

/**
 * Container for storing the request from the user to activate or deactivate certain projects and optionally fail the
 * build if those projects do not exist.
 */
public class ProjectActivation
{
    private static class ProjectActivationSettings
    {
        /**
         * The selector of a project. This can be the project directory, [groupId]:[artifactId] or :[artifactId].
         */
        final String selector;

        /**
         * This describes how/when to active or deactivate the project.
         */
        final ActivationSettings activationSettings;

        ProjectActivationSettings( String selector, ActivationSettings activationSettings )
        {
            this.selector = selector;
            this.activationSettings = activationSettings;
        }
    }

    /**
     * List of activated and deactivated projects.
     */
    private final List<ProjectActivationSettings> activations = new ArrayList<>();

    /**
     * Adds a project activation to the request.
     * @param selector The selector of the project.
     * @param active Should the project be activated?
     * @param optional Can the build continue if the project does not exist?
     */
    public void addProjectActivation( String selector, boolean active, boolean optional )
    {
        final ActivationSettings settings = ActivationSettings.of( active, optional );
        this.activations.add( new ProjectActivationSettings( selector, settings ) );
    }

    private Stream<ProjectActivationSettings> getProjects( final Predicate<ActivationSettings> predicate )
    {
        return this.activations.stream()
                .filter( activation -> predicate.test( activation.activationSettings ) );
    }

    private Set<String> getProjectSelectors( final Predicate<ActivationSettings> predicate )
    {
        return getProjects( predicate )
                .map( activation -> activation.selector )
                .collect( toSet() );
    }

    /**
     * @return Required active project selectors, never {@code null}.
     */
    public Set<String> getRequiredActiveProjectSelectors()
    {
        return getProjectSelectors( pa -> !pa.optional && pa.active );
    }

    /**
     * @return Optional active project selectors, never {@code null}.
     */
    public Set<String> getOptionalActiveProjectSelectors()
    {
        return getProjectSelectors( pa -> pa.optional && pa.active );
    }

    /**
     * @return Required inactive project selectors, never {@code null}.
     */
    public Set<String> getRequiredInactiveProjectSelectors()
    {
        return getProjectSelectors( pa -> !pa.optional && !pa.active );
    }

    /**
     * @return Optional inactive project selectors, never {@code null}.
     */
    public Set<String> getOptionalInactiveProjectSelectors()
    {
        return getProjectSelectors( pa -> pa.optional && !pa.active );
    }

    /**
     * Mimics the pre-Maven 4 "selected projects" list.
     * @deprecated Use {@link #getRequiredActiveProjectSelectors()} and {@link #getOptionalActiveProjectSelectors()}
     * instead.
     */
    @Deprecated
    public List<String> getSelectedProjects()
    {
        return Collections.unmodifiableList( new ArrayList<>( getProjectSelectors( pa -> pa.active ) ) );
    }

    /**
     * Mimics the pre-Maven 4 "excluded projects" list.
     * @deprecated Use {@link #getRequiredInactiveProjectSelectors()} and {@link #getOptionalInactiveProjectSelectors()}
     * instead.
     */
    @Deprecated
    public List<String> getExcludedProjects()
    {
        return Collections.unmodifiableList( new ArrayList<>( getProjectSelectors( pa -> !pa.active ) ) );
    }

    /**
     * Overwrites the active projects based on a pre-Maven 4 "active projects" list.
     * @param activeProjectSelectors A {@link List} of project selectors that must be activated.
     * @deprecated Use {@link #activateOptionalProject(String)} or {@link #activateRequiredProject(String)} instead.
     */
    @Deprecated
    public void overwriteActiveProjects( List<String> activeProjectSelectors )
    {
        List<ProjectActivationSettings> projects = getProjects( pa -> pa.active ).collect( Collectors.toList() );
        this.activations.removeAll( projects );
        activeProjectSelectors.forEach( this::activateOptionalProject );
    }

    /**
     * Overwrites the inactive projects based on a pre-Maven 4 "inactive projects" list.
     * @param inactiveProjectSelectors A {@link List} of project selectors that must be deactivated.
     * @deprecated Use {@link #deactivateOptionalProject(String)} or {@link #deactivateRequiredProject(String)} instead.
     */
    @Deprecated
    public void overwriteInactiveProjects( List<String> inactiveProjectSelectors )
    {
        List<ProjectActivationSettings> projects = getProjects( pa -> !pa.active ).collect( Collectors.toList() );
        this.activations.removeAll( projects );
        inactiveProjectSelectors.forEach( this::deactivateOptionalProject );
    }

    /**
     * Mark a project as required and activated.
     * @param selector The selector of the project.
     */
    public void activateRequiredProject( String selector )
    {
        this.activations.add( new ProjectActivationSettings( selector, ActivationSettings.ACTIVATION_REQUIRED ) );
    }

    /**
     * Mark a project as optional and activated.
     * @param selector The selector of the project.
     */
    public void activateOptionalProject( String selector )
    {
        this.activations.add( new ProjectActivationSettings( selector, ActivationSettings.ACTIVATION_OPTIONAL ) );
    }

    /**
     * Mark a project as required and deactivated.
     * @param selector The selector of the project.
     */
    public void deactivateRequiredProject( String selector )
    {
        this.activations.add( new ProjectActivationSettings( selector, ActivationSettings.DEACTIVATION_REQUIRED ) );
    }

    /**
     * Mark a project as optional and deactivated.
     * @param selector The selector of the project.
     */
    public void deactivateOptionalProject( String selector )
    {
        this.activations.add( new ProjectActivationSettings( selector, ActivationSettings.DEACTIVATION_OPTIONAL ) );
    }

    public boolean isEmpty()
    {
        return this.activations.isEmpty();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Hibernate Validator, declare and validate application constraints
  ~
  ~ License: Apache License, Version 2.0
  ~ See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
  -->
<constraint-mappings xmlns="https://jakarta.ee/xml/ns/validation/mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="https://jakarta.ee/xml/ns/validation/mapping https://jakarta.ee/xml/ns/validation/validation-mapping-3.0.xsd"
        version="3.0">
    <default-package>java.lang</default-package>
    <bean class="Double" ignore-annotations="true">
        <class>
            <constraint annotation="org.hibernate.validator.test.internal.xml.MyConstraint">
                <message>Error</message>
                <element name="additionalConstraints">
                    <annotation>
                        <element name="message">Missing firstName</element>
                        <element name="constraint"></element>
                    </annotation>
                </element>
            </constraint>
        </class>
    </bean>
</constraint-mappings>


text:
using System;

namespace Tiger.Build.Compiler.Ast
{
    public class BoolLiteral : Expression
    {
        private readonly bool _value;

        public BoolLiteral(bool value)
        {
            _value = value;
        }

        public override Type Type
        {
            get { return typeof (bool); }
        }

        protected internal override System.Linq.Expressions.Expression Transform()
        {
            return System.Linq.Expressions.Expression.Constant(_value);
        }
    }
}


text:
#include "condor_common.h"
#include "condor_attributes.h"
#include "condor_string.h"
#include "util_lib_proto.h"
#include "my_popen.h"

//
// Local DAGMan includes
//
#include "dagman_main.h"
#include "dag.h"
#include "submit.h"
#include "util.h"
#include "debug.h"
#include "tmp_dir.h"
#include "write_user_log.h"

typedef bool (* parse_submit_fnc)( const char *buffer, int &jobProcCount,
			int &cluster );

	// Get the event mask for the workflow/default log file.
const char *getEventMask();

//-------------------------------------------------------------------------
/** Parse output from condor_submit, determine the number of job procs
    and the cluster.
	@param buffer containing the line to be parsed
	@param integer to be filled in with the number of job procs generated
	       by the condor_submit
	@param integer to be filled in with the cluster ID
	@return true iff the line was correctly parsed
*/
static bool
parse_condor_submit( const char *buffer, int &jobProcCount, int &cluster )
{
  // The initial space is to make the sscanf match zero or more leading
  // whitespace that may exist in the buffer.
  if ( 2 != sscanf( buffer, " %d job(s) submitted to cluster %d",
  			&jobProcCount, &cluster) ) {
	debug_printf( DEBUG_QUIET, "ERROR: parse_condor_submit failed:\n\t%s\n",
				buffer );
    return false;
  }

  return true;
}

//-------------------------------------------------------------------------
/** Parse output from stork_submit, determine the number of job procs
    and the cluster.
	@param buffer containing the line to be parsed
	@param integer to be filled in with the number of job procs generated
	       by the stork_submit
	@param integer to be filled in with the cluster ID
	@return true iff the line was correctly parsed
*/
static bool
parse_stork_submit( const char *buffer, int &jobProcCount, int &cluster )
{
  // The initial space is to make the sscanf match zero or more leading
  // whitespace that may exist in the buffer.
  if ( 1 != sscanf( buffer, " Request assigned id: %d", &cluster) ) {
	debug_printf( DEBUG_QUIET, "ERROR: parse_stork_submit failed:\n\t%s\n",
				buffer );
    return false;
  }

  jobProcCount = 1;
  return true;
}

//-------------------------------------------------------------------------
static bool
submit_try( ArgList &args, CondorID &condorID, Job::job_type_t type,
			bool prohibitMultiJobs )
{
  MyString cmd; // for debug output
  args.GetArgsStringForDisplay( &cmd );

  FILE * fp = my_popen( args, "r", TRUE );
  if (fp == NULL) {
    debug_printf( DEBUG_NORMAL,
		  "ERROR: my_popen(%s) in submit_try() failed!\n",
		  cmd.Value() );
    return false;
  }

  //----------------------------------------------------------------------
  // Parse submit command output for a Condor/Stork job ID.  This
  // desperately needs to be replaced by Condor/Stork submit APIs.
  //
  // Typical condor_submit output for Condor v6 looks like:
  //
  //   Submitting job(s).
  //   Logging submit event(s).
  //   1 job(s) submitted to cluster 2267.
  //----------------------------------------------------------------------

  char buffer[UTIL_MAX_LINE_LENGTH];
  buffer[0] = '\0';

  	// Configure what we look for in the command output according to
	// which type of job we have.
  const char *marker = NULL;
  parse_submit_fnc parseFnc = NULL;

  if ( type == Job::TYPE_CONDOR ) {
    marker = " submitted to cluster ";

	  // Note: we *could* check how many jobs got submitted here, and
	  // correlate that with how many submit events we see later on.
	  // I'm not worrying about that for now...  wenger 2006-02-07.
	  // We also have to check the number of jobs to get an accurate
	  // count of submitted jobs to report in the dagman.out file.

	  // We should also check whether we got more than one cluster, and
	  // either deal with it correctly or generate an error message.
	parseFnc = parse_condor_submit;
  } else if ( type == Job::TYPE_STORK ) {
    marker = "assigned id";
	parseFnc = parse_stork_submit;
  } else {
	debug_printf( DEBUG_QUIET, "Illegal job type: %d\n", type );
	ASSERT(false);
  }

  // Take all of the output (both stdout and stderr) from condor_submit
  // or stork_submit, and echo it to the dagman.out file.  Look for
  // the line (if any) containing the word "cluster" (Condor) or
  // "assigned id" (Stork).  If we don't find such a line, something
  // went wrong with the submit, so we return false.  The caller of this
  // function can retry the submit by repeatedly calling this function.

  MyString  command_output("");
  MyString keyLine("");
  while (fgets(buffer, UTIL_MAX_LINE_LENGTH, fp)) {
    MyString buf_line = buffer;
	buf_line.chomp();
	debug_printf(DEBUG_VERBOSE, "From submit: %s\n", buf_line.Value());
	command_output += buf_line;
    if (strstr(buffer, marker) != NULL) {
	  keyLine = buf_line;
	}
  }

  { // Relocated this curly bracket to its previous position to hopefully
    // fix Coverity warning.  Not sure why these curly brackets are here
	// at all...  wenger 2013-06-12
    int status = my_pclose(fp) & 0xff;

    if (keyLine == "") {
      debug_printf(DEBUG_NORMAL, "failed while reading from pipe.\n");
      debug_printf(DEBUG_NORMAL, "Read so far: %s\n", command_output.Value());
      return false;
    }

    if (status != 0) {
		debug_printf(DEBUG_NORMAL, "Read from pipe: %s\n",
					 command_output.Value());
		debug_printf( DEBUG_QUIET, "ERROR while running \"%s\": "
					  "my_pclose() failed with status %d (errno %d, %s)!\n",
					  cmd.Value(), status, errno, strerror( errno ) );
		return false;
    }
  }

  int	jobProcCount;
  if ( !parseFnc( keyLine.Value(), jobProcCount, condorID._cluster) ) {
		// We are going forward (do not return false here)
		// Expectation is that higher levels will catch that we
		// did not get a cluster initialized properly here, fail,
		// and write a rescue DAG. gt3658 2013-06-03
		//
		// This is better than the old failure that would submit
		// DAGMAN_MAX_SUBMIT_ATTEMPT copies of the same job.
      debug_printf( DEBUG_NORMAL, "WARNING: submit returned 0, but "
        "parsing submit output failed!\n" );
		// Returning here so we don't try to process invalid values
		// below.  (This should really return something like "submit failed
		// don't retry" -- see gittrac #3685.)
  	  return true;
  }

  // Stork job specs have only 1 dimension.  The Stork user log forces the proc
  // and sub-proc ids to "-1", so do the same here for the returned submit id.
  if ( type == Job::TYPE_STORK ) {
	  condorID._proc = -1;
	  condorID._subproc = -1;
  }

  	// Check for multiple job procs if configured to disallow that.
  if ( prohibitMultiJobs && (jobProcCount > 1) ) {
	debug_printf( DEBUG_NORMAL, "Submit generated %d job procs; "
				"disallowed by DAGMAN_PROHIBIT_MULTI_JOBS setting\n",
				jobProcCount );
	main_shutdown_rescue( EXIT_ERROR, Dag::DAG_STATUS_ERROR );
  }

  return true;
}

//-------------------------------------------------------------------------
// NOTE: this and submit_try should probably be merged into a single
// method -- submit_batch_job or something like that.  wenger/pfc 2006-04-05.
static bool
do_submit( ArgList &args, CondorID &condorID, Job::job_type_t jobType,
			bool prohibitMultiJobs )
{
	MyString cmd; // for debug output
	args.GetArgsStringForDisplay( &cmd );
	debug_printf( DEBUG_VERBOSE, "submitting: %s\n", cmd.Value() );

	bool success = false;

	success = submit_try( args, condorID, jobType, prohibitMultiJobs );

	if( !success ) {
	    debug_printf( DEBUG_QUIET, "ERROR: submit attempt failed\n" );
		debug_printf( DEBUG_QUIET, "submit command was: %s\n", cmd.Value() );
	}

	return success;
}

//-------------------------------------------------------------------------
bool
condor_submit( const Dagman &dm, const char* cmdFile, CondorID& condorID,
			   const char* DAGNodeName, MyString &DAGParentNodeNames,
			   List<Job::NodeVar> *vars, int retry,
			   const char* directory, const char *workflowLogFile,
			   bool prohibitMultiJobs, bool hold_claim )
{
	TmpDir		tmpDir;
	MyString	errMsg;
	if ( !tmpDir.Cd2TmpDir( directory, errMsg ) ) {
		debug_printf( DEBUG_QUIET,
				"Could not change to node directory %s: %s\n",
				directory, errMsg.Value() );
		return false;
	}

	if ( prohibitMultiJobs ) {
		MyString	errorMsg;
		int queueCount = MultiLogFiles::getQueueCountFromSubmitFile(
					MyString( cmdFile ), MyString( directory ),
					errorMsg );
		if ( queueCount == -1 ) {
			debug_printf( DEBUG_QUIET, "ERROR in "
						"MultiLogFiles::getQueueCountFromSubmitFile(): %s\n",
						errorMsg.Value() );
				// We don't just return false here because that would
				// cause us to re-try the submit, which would obviously
				// just fail again.
			main_shutdown_rescue( EXIT_ERROR, Dag::DAG_STATUS_ERROR );
			return false; // We won't actually get to here.
		} else if ( queueCount != 1 ) {
			debug_printf( DEBUG_QUIET, "ERROR: node %s job queues %d "
						"job procs, but DAGMAN_PROHIBIT_MULTI_JOBS is "
						"set\n", DAGNodeName, queueCount );
				// We don't just return false here because that would
				// cause us to re-try the submit, which would obviously
				// just fail again.
			main_shutdown_rescue( EXIT_ERROR, Dag::DAG_STATUS_ERROR );
			return false; // We won't actually get to here.
		}
	}

	ArgList args;

	// construct arguments to condor_submit to add attributes to the
	// job classad which identify the job's node name in the DAG, the
	// node names of its parents in the DAG, and the job ID of DAGMan
	// itself; then, define submit_event_notes to print the job's node
	// name inside the submit event in the userlog

	// NOTE: we specify the job ID of DAGMan using only its cluster ID
	// so that it may be referenced by jobs in their priority
	// attribute (which needs an int, not a string).  Doing so allows
	// users to effectively "batch" jobs by DAG so that when they
	// submit many DAGs to the same schedd, all the ready jobs from
	// one DAG complete before any jobs from another begin.

	args.AppendArg( dm.condorSubmitExe );

	args.AppendArg( "-a" );
	MyString nodeName = MyString(ATTR_DAG_NODE_NAME_ALT) + " = " + DAGNodeName;
	args.AppendArg( nodeName.Value() );

		// append a line adding the parent DAGMan's cluster ID to the job ad
	args.AppendArg( "-a" );
	MyString dagJobId = MyString( "+" ) + ATTR_DAGMAN_JOB_ID + " = " +
				dm.DAGManJobId._cluster;
	args.AppendArg( dagJobId.Value() );

		// now we append a line setting the same thing as a submit-file macro
		// (this is necessary so the user can reference it in the priority)
	args.AppendArg( "-a" );
	MyString dagJobIdMacro = MyString( "" ) + ATTR_DAGMAN_JOB_ID + " = " +
				dm.DAGManJobId._cluster;
	args.AppendArg( dagJobIdMacro.Value() );

	args.AppendArg( "-a" );
	MyString submitEventNotes = MyString(
				"submit_event_notes = DAG Node: " ) + DAGNodeName;
	args.AppendArg( submitEventNotes.Value() );

		// workflowLogFile is non-null here if we need to tell the schedd to
		// use that file as the default/workflow log for this node.
	if ( workflowLogFile ) {
			// We need to append the DAGman default log file to
			// the log file list
		args.AppendArg( "-a" );
		std::string dlog( "dagman_log = " );
		dlog += workflowLogFile;
		args.AppendArg( dlog.c_str() );
		debug_printf( DEBUG_VERBOSE, "Adding a DAGMan workflow log %s\n",
					workflowLogFile );

			// Now append the mask
		debug_printf( DEBUG_VERBOSE, "Masking the events recorded in the DAGMAN workflow log\n" );
		args.AppendArg( "-a" );
		std::string dmask("+");
		dmask += ATTR_DAGMAN_WORKFLOW_MASK;
		dmask += " = \"";
		const char *eventMask = getEventMask();
		debug_printf( DEBUG_VERBOSE, "Mask for workflow log is %s\n",
					eventMask );
		dmask += eventMask;
		dmask += "\"";
		args.AppendArg( dmask.c_str() );
	}

	ArgList parentNameArgs;
	parentNameArgs.AppendArg( "-a" );
	MyString parentNodeNames = MyString( "+DAGParentNodeNames = " ) +
	                        "\"" + DAGParentNodeNames + "\"";
	parentNameArgs.AppendArg( parentNodeNames.Value() );

		// set any VARS specified in the DAG file
	MyString anotherLine;
	ListIterator<Job::NodeVar> varsIter(*vars);
	Job::NodeVar nodeVar;
	while ( varsIter.Next(nodeVar) ) {

			// Substitute the node retry count if necessary.  Note that
			// we can't do this in Job::ResolveVarsInterpolations()
			// because that's only called at parse time.
		MyString value = nodeVar._value;
		MyString retryStr( retry );
		value.replaceString( "$(RETRY)", retryStr.Value() );
		MyString varStr = nodeVar._name + " = " + value;

		args.AppendArg( "-a" );
		args.AppendArg( varStr.Value() );
	}

		// Set the special DAG_STATUS variable (mainly for use by
		// "final" nodes).
	args.AppendArg( "-a" );
	MyString var = "DAG_STATUS = ";
	var += dm.dag->_dagStatus;
	args.AppendArg( var.Value() );

		// Set the special FAILED_COUNT variable (mainly for use by
		// "final" nodes).
	args.AppendArg( "-a" );
	var = "FAILED_COUNT = ";
	var += dm.dag->NumNodesFailed();
	args.AppendArg( var.Value() );

		// how big is the command line so far
	MyString display;
	args.GetArgsStringForDisplay( &display );
	int cmdLineSize = display.Length();

	parentNameArgs.GetArgsStringForDisplay( &display );
	int DAGParentNodeNamesLen = display.Length();
		// how many additional chars must we still add to command line
	        // NOTE: according to the POSIX spec, the args +
   	        // environ given to exec() cannot exceed
   	        // _POSIX_ARG_MAX, so we also need to calculate & add
   	        // the size of environ** to reserveNeeded
	int reserveNeeded = strlen( cmdFile );
	int maxCmdLine = _POSIX_ARG_MAX;

		// if we don't have room for DAGParentNodeNames, leave it unset
	if( cmdLineSize + reserveNeeded + DAGParentNodeNamesLen > maxCmdLine ) {
		debug_printf( DEBUG_NORMAL, "Warning: node %s has too many parents "
					  "to list in its classad; leaving its DAGParentNodeNames "
					  "attribute undefined\n", DAGNodeName );
		check_warning_strictness( DAG_STRICT_3 );
	} else {
		args.AppendArgsFromArgList( parentNameArgs );
	}

	if( hold_claim ){
		args.AppendArg( "-a" );
		MyString holdit = MyString("+") + MyString(ATTR_JOB_KEEP_CLAIM_IDLE) + " = "
			+ dm._claim_hold_time;
		args.AppendArg( holdit.Value() );
	}

	if (dm._submitDagDeepOpts.suppress_notification) {
		args.AppendArg( "-a" );
		MyString notify = MyString("notification = never");
		args.AppendArg( notify.Value() );
	}

	args.AppendArg( cmdFile );

	bool success = do_submit( args, condorID, Job::TYPE_CONDOR,
				dm.prohibitMultiJobs );

	if ( !tmpDir.Cd2MainDir( errMsg ) ) {
		debug_printf( DEBUG_QUIET,
				"Could not change to original directory: %s\n",
				errMsg.Value() );
		success = false;
	}

	return success;
}

//-------------------------------------------------------------------------
bool
stork_submit( const Dagman &dm, const char* cmdFile, CondorID& condorID,
			   const char* DAGNodeName, const char* directory )
{
	TmpDir		tmpDir;
	MyString	errMsg;
	if ( !tmpDir.Cd2TmpDir( directory, errMsg ) ) {
		debug_printf( DEBUG_QUIET,
				"Could not change to DAG directory %s: %s\n",
				directory, errMsg.Value() );
		return false;
	}

  ArgList args;

  args.AppendArg( dm.storkSubmitExe );
  args.AppendArg( "-lognotes" );

  MyString logNotes = MyString( "DAG Node: " ) + DAGNodeName;
  args.AppendArg( logNotes.Value() );

  args.AppendArg( cmdFile );

  bool success = do_submit( args, condorID, Job::TYPE_STORK,
  			dm.prohibitMultiJobs );

	if ( !tmpDir.Cd2MainDir( errMsg ) ) {
		debug_printf( DEBUG_QUIET,
				"Could not change to original directory: %s\n",
				errMsg.Value() );
		success = false;
	}

  return success;
}

//-------------------------------------------------------------------------
// Subproc ID for "fake" events (for NOOP jobs).
static int _subprocID = 0;

//-------------------------------------------------------------------------
void
set_fake_condorID( int subprocID )
{
	_subprocID = subprocID;
}

int
get_fake_condorID()
{
	return _subprocID;
}
//-------------------------------------------------------------------------
bool
fake_condor_submit( CondorID& condorID, Job* job, const char* DAGNodeName,
			   const char* directory, const char *logFile, bool logIsXml )
{
	TmpDir		tmpDir;
	MyString	errMsg;
	if ( !tmpDir.Cd2TmpDir( directory, errMsg ) ) {
		debug_printf( DEBUG_QUIET,
				"Could not change to node directory %s: %s\n",
				directory, errMsg.Value() );
		return false;
	}

	_subprocID++;
		// Special CondorID for NOOP jobs -- actually indexed by
		// otherwise-unused subprocID.
	condorID._cluster = 0;
	condorID._proc = Job::NOOP_NODE_PROCID;
	condorID._subproc = _subprocID;

		// Make sure that this job gets marked as a NOOP
	if( job ) {
		job->SetCondorID( condorID );
	}

	WriteUserLog ulog;
	ulog.setEnableGlobalLog( false );
	ulog.setUseXML( logIsXml );
	ulog.initialize( std::vector<const char*>(1,logFile), condorID._cluster,
		condorID._proc, condorID._subproc, NULL );

	SubmitEvent subEvent;
	subEvent.cluster = condorID._cluster;
	subEvent.proc = condorID._proc;
	subEvent.subproc = condorID._subproc;

		// We need some value for submitHost for the event to be read
		// correctly.
	subEvent.setSubmitHost( "<dummy-submit-for-noop-job>" );

	MyString subEventNotes("DAG Node: " );
	subEventNotes += DAGNodeName;
		// submitEventLogNotes get deleted in SubmitEvent destructor.
	subEvent.submitEventLogNotes = strnewp( subEventNotes.Value() );

	if ( !ulog.writeEvent( &subEvent ) ) {
		EXCEPT( "Error: writing dummy submit event for NOOP node failed!\n" );
		return false;
	}

	JobTerminatedEvent termEvent;
	termEvent.cluster = condorID._cluster;
	termEvent.proc = condorID._proc;
	termEvent.subproc = condorID._subproc;
	termEvent.normal = true;
	termEvent.returnValue = 0;
	termEvent.signalNumber = 0;

	if ( !ulog.writeEvent( &termEvent ) ) {
		EXCEPT( "Error: writing dummy terminated event for NOOP node failed!\n" );
		return false;
	}

	return true;
}

bool writePreSkipEvent( CondorID& condorID, Job* job, const char* DAGNodeName,
			   const char* directory, const char *logFile, bool logIsXml )
{
	TmpDir tmpDir;
	MyString	errMsg;
	if ( !tmpDir.Cd2TmpDir( directory, errMsg ) ) {
		debug_printf( DEBUG_QUIET,
				"Could not change to node directory %s: %s\n",
				directory, errMsg.Value() );
		return false;
	}

		// Special CondorID for NOOP jobs -- actually indexed by
		// otherwise-unused subprocID.
	condorID._cluster = 0;
	condorID._proc = Job::NOOP_NODE_PROCID;

	condorID._subproc = 1+get_fake_condorID();
		// Increment this value
	set_fake_condorID(condorID._subproc);

	if( job ) {
		job->SetCondorID( condorID );
	}

	WriteUserLog ulog;
	ulog.setEnableGlobalLog( false );
	ulog.setUseXML( logIsXml );
	ulog.initialize( std::vector<const char*>(1,logFile), condorID._cluster,
		condorID._proc, condorID._subproc, NULL );

	PreSkipEvent pEvent;
	pEvent.cluster = condorID._cluster;
	pEvent.proc = condorID._proc;
	pEvent.subproc = condorID._subproc;

	MyString pEventNotes("DAG Node: " );
	pEventNotes += DAGNodeName;
		// skipEventLogNotes gets deleted in PreSkipEvent destructor.
	pEvent.skipEventLogNotes = strnewp( pEventNotes.Value() );

	if ( !ulog.writeEvent( &pEvent ) ) {
		EXCEPT( "Error: writing PRESKIP event failed!\n" );
		return false;
	}
	return true;
}

const char *
getEventMask()
{
	static std::string result("");
	static std::stringstream dmaskstrm("");

	if ( result == "" ) {
		//
		// IMPORTANT NOTE:  see all events that we deal with in
		// Dag::ProcessOneEvent() -- all of those need to be in the
		// event mask!! (wenger 2012-11-16)
		//
		int mask[] = {
			ULOG_SUBMIT,
			ULOG_EXECUTE,
			ULOG_EXECUTABLE_ERROR,
			ULOG_JOB_EVICTED,
			ULOG_JOB_TERMINATED,
			ULOG_SHADOW_EXCEPTION,
			ULOG_JOB_ABORTED,
			ULOG_JOB_SUSPENDED,
			ULOG_JOB_UNSUSPENDED,
			ULOG_JOB_HELD,
			ULOG_JOB_RELEASED,
			ULOG_POST_SCRIPT_TERMINATED,
			ULOG_GLOBUS_SUBMIT,			// For Pegasus
			ULOG_JOB_RECONNECT_FAILED,
			ULOG_GRID_SUBMIT,			// For Pegasus
			-1
		};

		for ( const int *p = &mask[0]; *p != -1; ++p ) {
			if ( p != &mask[0] ) {
				dmaskstrm << ",";
			}
			dmaskstrm << *p;
		}

		result = dmaskstrm.str();
	}

	return result.c_str();
}


text:
package org.la4j.linear;

import org.la4j.factory.Factory;
import org.la4j.matrix.Matrices;
import org.la4j.matrix.Matrix;
import org.la4j.matrix.functor.MatrixFunction;
import org.la4j.vector.Vector;

/**
 * This class represents Jacobi method for solving linear systems. More details
 *

 *  here.
 *

 */
public class JacobiSolver extends AbstractSolver implements LinearSystemSolver {

    private static final long serialVersionUID = 4071505L;

    private final Matrix aa;

    public JacobiSolver(Matrix a) {
        super(a);

        // We need a copy here, since we don't want to change source matrix
        this.aa = a.copy();

        for (int i = 0; i < aa.rows(); i++) {
            MatrixFunction divider = Matrices.asDivFunction(aa.get(i, i));
            for (int j = 0; j < aa.columns(); j++) {
                if (i != j) {
                    aa.update(i, j, divider);
                }
            }
        }
    }

    @Override
    public Vector solve(Vector b, Factory factory) {
        ensureRHSIsCorrect(b);

        Vector current = factory.createVector(unknowns());

        // while it is not a solution
        while (!a.multiply(current).equals(b)) {

            Vector next = current.blank();

            for (int i = 0; i < aa.rows(); i++) {

                double acc = b.get(i) / aa.get(i, i);
                for (int j = 0; j < aa.columns(); j++) {
                    if (i != j) {
                        acc -= aa.get(i, j) * current.get(j);
                    }
                }

                next.set(i, acc);
            }

            current = next;
        }

        return current;
    }

    @Override
    public boolean applicableTo(Matrix matrix) {
        return matrix.is(Matrices.DIAGONALLY_DOMINANT_MATRIX);
    }
}