text:
package integration

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
	"time"

	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/client-go/rest"
	api "k8s.io/kubernetes/pkg/apis/core"
	"k8s.io/kubernetes/pkg/apis/policy"
	clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"

	"github.com/openshift/library-go/pkg/crypto"
	"github.com/openshift/origin/pkg/cmd/server/admin"
	testutil "github.com/openshift/origin/test/util"
	testserver "github.com/openshift/origin/test/util/server"
)

// If this test fails make sure to update it with contents from
// vendor/k8s.io/kubernetes/test/integration/auth/node_test.go#TestNodeAuthorizer
func TestNodeAuthorizer(t *testing.T) {
	masterConfig, err := testserver.DefaultMasterOptions()
	if err != nil {
		t.Fatal(err)
	}
	defer testserver.CleanupMasterEtcd(t, masterConfig)

	clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterConfig)
	if err != nil {
		t.Fatal(err)
	}
	clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
	if err != nil {
		t.Fatal(err)
	}
	superuserClient, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig)
	if err != nil {
		t.Fatal(err)
	}

	clientConfig := rest.AnonymousClientConfig(clusterAdminClientConfig)

	caDir := filepath.Dir(masterConfig.ServingInfo.ClientCA)
	signer := &admin.SignerCertOptions{
		CertFile:   filepath.Join(caDir, "ca.crt"),
		KeyFile:    filepath.Join(caDir, "ca.key"),
		SerialFile: filepath.Join(caDir, "ca.serial.txt"),
	}

	certDir, err := ioutil.TempDir("", "nodeauthorizer")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(certDir)

	nodeanonClient := makeNodeClientset(t, signer, certDir, "unknown", clientConfig)
	node1Client := makeNodeClientset(t, signer, certDir, "system:node:node1", clientConfig)
	node2Client := makeNodeClientset(t, signer, certDir, "system:node:node2", clientConfig)

	// Prep namespace
	if _, err := superuserClient.Core().Namespaces().Create(&api.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "ns"}}); err != nil {
		t.Fatal(err)
	}
	wait.Poll(time.Second, time.Minute, func() (bool, error) {
		sa, err := superuserClient.Core().ServiceAccounts("ns").Get("default", metav1.GetOptions{})
		if err != nil || len(sa.Secrets) == 0 {
			return false, nil
		}
		return true, nil
	})

	// Create objects
	if _, err := superuserClient.Core().Secrets("ns").Create(&api.Secret{ObjectMeta: metav1.ObjectMeta{Name: "mysecret"}}); err != nil {
		t.Fatal(err)
	}
	if _, err := superuserClient.Core().Secrets("ns").Create(&api.Secret{ObjectMeta: metav1.ObjectMeta{Name: "mypvsecret"}}); err != nil {
		t.Fatal(err)
	}
	if _, err := superuserClient.Core().ConfigMaps("ns").Create(&api.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "myconfigmap"}}); err != nil {
		t.Fatal(err)
	}
	if _, err := superuserClient.Core().PersistentVolumeClaims("ns").Create(&api.PersistentVolumeClaim{
		ObjectMeta: metav1.ObjectMeta{Name: "mypvc"},
		Spec: api.PersistentVolumeClaimSpec{
			AccessModes: []api.PersistentVolumeAccessMode{api.ReadOnlyMany},
			Resources:   api.ResourceRequirements{Requests: api.ResourceList{api.ResourceStorage: resource.MustParse("1")}},
		},
	}); err != nil {
		t.Fatal(err)
	}
	if _, err := superuserClient.Core().PersistentVolumes().Create(&api.PersistentVolume{
		ObjectMeta: metav1.ObjectMeta{Name: "mypv"},
		Spec: api.PersistentVolumeSpec{
			AccessModes:            []api.PersistentVolumeAccessMode{api.ReadOnlyMany},
			Capacity:               api.ResourceList{api.ResourceStorage: resource.MustParse("1")},
			ClaimRef:               &api.ObjectReference{Namespace: "ns", Name: "mypvc"},
			PersistentVolumeSource: api.PersistentVolumeSource{AzureFile: &api.AzureFilePersistentVolumeSource{ShareName: "default", SecretName: "mypvsecret"}},
		},
	}); err != nil {
		t.Fatal(err)
	}

	getSecret := func(client clientset.Interface) func() error {
		return func() error {
			_, err := client.Core().Secrets("ns").Get("mysecret", metav1.GetOptions{})
			return err
		}
	}
	getPVSecret := func(client clientset.Interface) func() error {
		return func() error {
			_, err := client.Core().Secrets("ns").Get("mypvsecret", metav1.GetOptions{})
			return err
		}
	}
	getConfigMap := func(client clientset.Interface) func() error {
		return func() error {
			_, err := client.Core().ConfigMaps("ns").Get("myconfigmap", metav1.GetOptions{})
			return err
		}
	}
	getPVC := func(client clientset.Interface) func() error {
		return func() error {
			_, err := client.Core().PersistentVolumeClaims("ns").Get("mypvc", metav1.GetOptions{})
			return err
		}
	}
	getPV := func(client clientset.Interface) func() error {
		return func() error {
			_, err := client.Core().PersistentVolumes().Get("mypv", metav1.GetOptions{})
			return err
		}
	}

	createNode2NormalPod := func(client clientset.Interface) func() error {
		return func() error {
			_, err := client.Core().Pods("ns").Create(&api.Pod{
				ObjectMeta: metav1.ObjectMeta{Name: "node2normalpod"},
				Spec: api.PodSpec{
					NodeName:   "node2",
					Containers: []api.Container{{Name: "image", Image: "busybox"}},
					Volumes: []api.Volume{
						{Name: "secret", VolumeSource: api.VolumeSource{Secret: &api.SecretVolumeSource{SecretName: "mysecret"}}},
						{Name: "cm", VolumeSource: api.VolumeSource{ConfigMap: &api.ConfigMapVolumeSource{LocalObjectReference: api.LocalObjectReference{Name: "myconfigmap"}}}},
						{Name: "pvc", VolumeSource: api.VolumeSource{PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{ClaimName: "mypvc"}}},
					},
				},
			})
			return err
		}
	}
	updateNode2NormalPodStatus := func(client clientset.Interface) func() error {
		return func() error {
			startTime := metav1.NewTime(time.Now())
			_, err := client.Core().Pods("ns").UpdateStatus(&api.Pod{
				ObjectMeta: metav1.ObjectMeta{Name: "node2normalpod"},
				Status:     api.PodStatus{StartTime: &startTime},
			})
			return err
		}
	}
	deleteNode2NormalPod := func(client clientset.Interface) func() error {
		return func() error {
			zero := int64(0)
			return client.Core().Pods("ns").Delete("node2normalpod", &metav1.DeleteOptions{GracePeriodSeconds: &zero})
		}
	}

	createNode2MirrorPod := func(client clientset.Interface) func() error {
		return func() error {
			_, err := client.Core().Pods("ns").Create(&api.Pod{
				ObjectMeta: metav1.ObjectMeta{
					Name:        "node2mirrorpod",
					Annotations: map[string]string{api.MirrorPodAnnotationKey: "true"},
				},
				Spec: api.PodSpec{
					NodeName:   "node2",
					Containers: []api.Container{{Name: "image", Image: "busybox"}},
				},
			})
			return err
		}
	}
	deleteNode2MirrorPod := func(client clientset.Interface) func() error {
		return func() error {
			zero := int64(0)
			return client.Core().Pods("ns").Delete("node2mirrorpod", &metav1.DeleteOptions{GracePeriodSeconds: &zero})
		}
	}

	createNode2 := func(client clientset.Interface) func() error {
		return func() error {
			_, err := client.Core().Nodes().Create(&api.Node{ObjectMeta: metav1.ObjectMeta{Name: "node2"}})
			return err
		}
	}
	updateNode2Status := func(client clientset.Interface) func() error {
		return func() error {
			_, err := client.Core().Nodes().UpdateStatus(&api.Node{
				ObjectMeta: metav1.ObjectMeta{Name: "node2"},
				Status:     api.NodeStatus{},
			})
			return err
		}
	}
	deleteNode2 := func(client clientset.Interface) func() error {
		return func() error {
			return client.Core().Nodes().Delete("node2", nil)
		}
	}
	createNode2NormalPodEviction := func(client clientset.Interface) func() error {
		return func() error {
			return client.Policy().Evictions("ns").Evict(&policy.Eviction{
				TypeMeta: metav1.TypeMeta{
					APIVersion: "policy/v1beta1",
					Kind:       "Eviction",
				},
				ObjectMeta: metav1.ObjectMeta{
					Name:      "node2normalpod",
					Namespace: "ns",
				},
			})
		}
	}
	createNode2MirrorPodEviction := func(client clientset.Interface) func() error {
		return func() error {
			return client.Policy().Evictions("ns").Evict(&policy.Eviction{
				TypeMeta: metav1.TypeMeta{
					APIVersion: "policy/v1beta1",
					Kind:       "Eviction",
				},
				ObjectMeta: metav1.ObjectMeta{
					Name:      "node2mirrorpod",
					Namespace: "ns",
				},
			})
		}
	}

	// nodeanonClient := clientsetForToken(tokenNodeUnknown, clientConfig)
	// node1Client := clientsetForToken(tokenNode1, clientConfig)
	// node2Client := clientsetForToken(tokenNode2, clientConfig)

	// all node requests from node1 and unknown node fail
	expectForbidden(t, getSecret(nodeanonClient))
	expectForbidden(t, getPVSecret(nodeanonClient))
	expectForbidden(t, getConfigMap(nodeanonClient))
	expectForbidden(t, getPVC(nodeanonClient))
	expectForbidden(t, getPV(nodeanonClient))
	expectForbidden(t, createNode2NormalPod(nodeanonClient))
	expectForbidden(t, createNode2MirrorPod(nodeanonClient))
	expectForbidden(t, deleteNode2NormalPod(nodeanonClient))
	expectForbidden(t, deleteNode2MirrorPod(nodeanonClient))
	expectForbidden(t, createNode2MirrorPodEviction(nodeanonClient))
	expectForbidden(t, createNode2(nodeanonClient))
	expectForbidden(t, updateNode2Status(nodeanonClient))
	expectForbidden(t, deleteNode2(nodeanonClient))

	expectForbidden(t, getSecret(node1Client))
	expectForbidden(t, getPVSecret(node1Client))
	expectForbidden(t, getConfigMap(node1Client))
	expectForbidden(t, getPVC(node1Client))
	expectForbidden(t, getPV(node1Client))
	expectForbidden(t, createNode2NormalPod(nodeanonClient))
	expectForbidden(t, createNode2MirrorPod(node1Client))
	expectNotFound(t, deleteNode2MirrorPod(node1Client))
	expectNotFound(t, createNode2MirrorPodEviction(node1Client))
	expectForbidden(t, createNode2(node1Client))
	expectForbidden(t, updateNode2Status(node1Client))
	expectForbidden(t, deleteNode2(node1Client))

	// related object requests from node2 fail
	expectForbidden(t, getSecret(node2Client))
	expectForbidden(t, getPVSecret(node2Client))
	expectForbidden(t, getConfigMap(node2Client))
	expectForbidden(t, getPVC(node2Client))
	expectForbidden(t, getPV(node2Client))
	expectForbidden(t, createNode2NormalPod(nodeanonClient))
	// mirror pod and self node lifecycle is allowed
	expectAllowed(t, createNode2MirrorPod(node2Client))
	expectAllowed(t, deleteNode2MirrorPod(node2Client))
	expectAllowed(t, createNode2MirrorPod(node2Client))
	expectAllowed(t, createNode2MirrorPodEviction(node2Client))
	expectAllowed(t, createNode2(node2Client))
	expectAllowed(t, updateNode2Status(node2Client))
	expectAllowed(t, deleteNode2(node2Client))

	// create a pod as an admin to add object references
	expectAllowed(t, createNode2NormalPod(superuserClient))

	// unidentifiable node and node1 are still forbidden
	expectForbidden(t, getSecret(nodeanonClient))
	expectForbidden(t, getPVSecret(nodeanonClient))
	expectForbidden(t, getConfigMap(nodeanonClient))
	expectForbidden(t, getPVC(nodeanonClient))
	expectForbidden(t, getPV(nodeanonClient))
	expectForbidden(t, createNode2NormalPod(nodeanonClient))
	expectForbidden(t, updateNode2NormalPodStatus(nodeanonClient))
	expectForbidden(t, deleteNode2NormalPod(nodeanonClient))
	expectForbidden(t, createNode2NormalPodEviction(nodeanonClient))
	expectForbidden(t, createNode2MirrorPod(nodeanonClient))
	expectForbidden(t, deleteNode2MirrorPod(nodeanonClient))
	expectForbidden(t, createNode2MirrorPodEviction(nodeanonClient))

	expectForbidden(t, getSecret(node1Client))
	expectForbidden(t, getPVSecret(node1Client))
	expectForbidden(t, getConfigMap(node1Client))
	expectForbidden(t, getPVC(node1Client))
	expectForbidden(t, getPV(node1Client))
	expectForbidden(t, createNode2NormalPod(node1Client))
	expectForbidden(t, updateNode2NormalPodStatus(node1Client))
	expectForbidden(t, deleteNode2NormalPod(node1Client))
	expectForbidden(t, createNode2NormalPodEviction(node1Client))
	expectForbidden(t, createNode2MirrorPod(node1Client))
	expectNotFound(t, deleteNode2MirrorPod(node1Client))
	expectNotFound(t, createNode2MirrorPodEviction(node1Client))

	// node2 can get referenced objects now
	expectAllowed(t, getSecret(node2Client))
	expectAllowed(t, getPVSecret(node2Client))
	expectAllowed(t, getConfigMap(node2Client))
	expectAllowed(t, getPVC(node2Client))
	expectAllowed(t, getPV(node2Client))
	expectForbidden(t, createNode2NormalPod(node2Client))
	expectAllowed(t, updateNode2NormalPodStatus(node2Client))
	expectAllowed(t, deleteNode2NormalPod(node2Client))
	expectAllowed(t, createNode2MirrorPod(node2Client))
	expectAllowed(t, deleteNode2MirrorPod(node2Client))
	// recreate as an admin to test eviction
	expectAllowed(t, createNode2NormalPod(superuserClient))
	expectAllowed(t, createNode2MirrorPod(superuserClient))
	expectAllowed(t, createNode2NormalPodEviction(node2Client))
	expectAllowed(t, createNode2MirrorPodEviction(node2Client))
}

func makeNodeClientset(t *testing.T, signer *admin.SignerCertOptions, certDir string, username string, anonymousConfig *rest.Config) clientset.Interface {
	clientCertOptions := &admin.CreateClientCertOptions{
		SignerCertOptions: signer,
		CertFile:          admin.DefaultCertFilename(certDir, username),
		KeyFile:           admin.DefaultKeyFilename(certDir, username),
		ExpireDays:        crypto.DefaultCertificateLifetimeInDays,
		User:              username,
		Groups:            []string{"system:nodes"},
		Overwrite:         true,
	}
	if err := clientCertOptions.Validate(nil); err != nil {
		t.Fatal(err)
	}
	if _, err := clientCertOptions.CreateClientCert(); err != nil {
		t.Fatal(err)
	}

	configCopy := *anonymousConfig
	configCopy.TLSClientConfig.CertFile = clientCertOptions.CertFile
	configCopy.TLSClientConfig.KeyFile = clientCertOptions.KeyFile

	c, err := clientset.NewForConfig(&configCopy)
	if err != nil {
		t.Fatal(err)
	}
	return c
}

// expect executes a function a set number of times until it either returns the
// expected error or executes too many times. It returns if the retries timed
// out and the last error returned by the method.
func expect(t *testing.T, f func() error, wantErr func(error) bool) (timeout bool, lastErr error) {
	t.Helper()
	err := wait.PollImmediate(time.Second, 30*time.Second, func() (bool, error) {
		t.Helper()
		lastErr = f()
		if wantErr(lastErr) {
			return true, nil
		}
		t.Logf("unexpected response, will retry: %v", lastErr)
		return false, nil
	})
	return err == nil, lastErr
}

func expectForbidden(t *testing.T, f func() error) {
	t.Helper()
	if ok, err := expect(t, f, errors.IsForbidden); !ok {
		t.Errorf("Expected forbidden error, got %v", err)
	}
}

func expectNotFound(t *testing.T, f func() error) {
	t.Helper()
	if ok, err := expect(t, f, errors.IsNotFound); !ok {
		t.Errorf("Expected notfound error, got %v", err)
	}
}

func expectAllowed(t *testing.T, f func() error) {
	t.Helper()
	if ok, err := expect(t, f, func(e error) bool { return e == nil }); !ok {
		t.Errorf("Expected no error, got %v", err)
	}
}


text:
@interface ILSwapPickKindActionSheet : UIActionSheet
{
	NSString* sendingType;
}

- (id) initWithSendingType:(NSString*) sendingType;
@property(readonly) NSString* sendingType;

@end

@implementation ILSwapPickKindActionSheet

- (id) initWithSendingType:(NSString*) t;
{
	if (!(self = [super init]))
		return nil;

	sendingType = [t copy];

	self.title = [NSString stringWithFormat:
			   NSLocalizedString(@"Choose what to send as an item of type '%@':", @"Format for item kind action sheet title"), t];

	// kILSwapSendText
	[self addButtonWithTitle:NSLocalizedString(@"Text (NSString)", @"Text button in item kind action sheet")];

	// kILSwapSendImagePNG
	[self addButtonWithTitle:NSLocalizedString(@"Image (NSData, PNG)", @"Image (PNG) button in item kind action sheet")];

	self.cancelButtonIndex = [self addButtonWithTitle:NSLocalizedString(@"Cancel", @"Cancel button")];

	return self;
}

@synthesize sendingType;

- (void) dealloc
{
	[sendingType release];
	[super dealloc];
}

@end

@interface ILSwapAppPane () <ABPeoplePickerNavigationControllerDelegate>

- (UITableViewCell*) valueOnlyCellWithText:(NSString*) text fromTable:(UITableView*) tv identifier:(NSString*) ident;
- (UITableViewCell*) noValuesCellForTable:(UITableView*) tv identifier:(NSString*) ident;
- (UITableViewCell*) cellForType:(NSString*) type fromTable:(UITableView*) tv identifier:(NSString*) ident;

@end

enum {
	kILSwapAppSectionInfo,
	kILSwapAppSectionActions,
	kILSwapAppSectionTypes,
};

enum {
	kILSwapSendText,
	kILSwapSendImagePNG,
};

static NSArray* ILSwapAppPaneCanonicalOrderOfRegistrationKeys() {
	static NSArray* a = nil; if (!a) {
		a = [[NSArray alloc] initWithObjects:
			 kILAppIdentifier,
			 kILAppVisibleName,
			 kILAppVersion,
			 kILAppReceiveItemURLScheme,
			 kILAppSupportsReceivingMultipleItems,
			 kILAppRegistrationUUID,
			 nil];
	}

	return a;
}

static NSString* ILSwapAppPaneLabelForRegistrationKey(NSString* key) {
	static NSDictionary* a = nil; if (!a) {
		a = [[NSDictionary alloc] initWithObjectsAndKeys:
			 NSLocalizedString(@"ID", @"kILAppIdentifier label"), kILAppIdentifier,
			 NSLocalizedString(@"name", @"kILAppVisibleName label"), kILAppVisibleName,
			 NSLocalizedString(@"version", @"kILAppVersion label"), kILAppVersion,
			 NSLocalizedString(@"URL", @"kILAppReceiveItemURLScheme label"), kILAppReceiveItemURLScheme,
			 NSLocalizedString(@"actions", @"kILAppSupportedActions label"), kILAppSupportedActions,
			 NSLocalizedString(@"UTIs", @"kILAppSupportedReceivedItemsUTIs label"), kILAppSupportedReceivedItemsUTIs,
			 NSLocalizedString(@"multiple?", @"kILAppSupportsReceivingMultipleItems label"), kILAppSupportsReceivingMultipleItems,
			 NSLocalizedString(@"UUID", @"kILAppRegistrationUUID label"), kILAppRegistrationUUID,
			 nil];
	}

	NSString* label = [a objectForKey:key];
	if (!label)
		label = key;
	return label;
}

static NSComparisonResult ILSwapAppPaneCompareRegistrationKeys(id a, id b, void* context) {
	if ([a isEqual:b])
		return NSOrderedSame;

	NSArray* order = ILSwapAppPaneCanonicalOrderOfRegistrationKeys();

	NSInteger indexOfA = [order indexOfObject:a];
	NSInteger indexOfB = [order indexOfObject:b];

	BOOL hasA = indexOfA != NSNotFound;
	BOOL hasB = indexOfB != NSNotFound;

	if (hasA && !hasB)
		return NSOrderedAscending;
	else if (!hasA && hasB)
		return NSOrderedDescending;
	else if (!hasA && !hasB)
		return NSOrderedSame;
	else
		return indexOfA > indexOfB? NSOrderedDescending : NSOrderedAscending;
}

@implementation ILSwapAppPane

- (id) initWithApplicationRegistrationRecord:(NSDictionary*) r;
{
	if (!(self = [self initWithNibName:@"ILSwapAppPane" bundle:nil]))
		return nil;

	record = [r copy];

	NSMutableArray* k = [NSMutableArray arrayWithArray:[r allKeys]];
	[k removeObject:kILAppSupportedActions];
	[k removeObject:kILAppSupportedReceivedItemsUTIs];
	[k sortUsingFunction:&ILSwapAppPaneCompareRegistrationKeys context:NULL];

	NSMutableArray* v = [NSMutableArray arrayWithCapacity:[k count]];
	for (NSString* key in k)
		[v addObject:[r objectForKey:key]];

	keys = [k copy];
	values = [v copy];

	actions = [L0As(NSArray, [r objectForKey:kILAppSupportedActions]) mutableCopy];
	types = [L0As(NSArray, [r objectForKey:kILAppSupportedReceivedItemsUTIs]) mutableCopy];

	self.title = [r objectForKey:kILAppVisibleName];

	if (ILSwapIsiPad())
		self.navigationItem.titleView = ILSwapCatalogNavigationBarTitleViewForString(self.title);

	return self;
}

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation;
{
	return UIInterfaceOrientationIsPortrait(toInterfaceOrientation) || [ILSwapCatalogApp() shouldSupportAdditionalOrientation:toInterfaceOrientation forViewController:self];
}

- (void) dealloc
{
	[record release];

	[keys release];
	[values release];
	[actions release];
	[types release];

	[super dealloc];
}

- (void) viewWillAppear:(BOOL)animated;
{
	[super viewWillAppear:animated];
	NSIndexPath* p = [self.tableView indexPathForSelectedRow];
	if (p)
		[self.tableView deselectRowAtIndexPath:p animated:animated];
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
		case kILSwapAppSectionInfo:
			return [keys count];

		case kILSwapAppSectionActions:
			return actions && [actions count] != 0? [actions count] : 1;

		case kILSwapAppSectionTypes:
			return types && [types count] != 0? [types count] : 1;

		default:
			return 0;
	}

}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString* kILSwapAppKeyValueCell = @"keyValueCell";
    static NSString* kILSwapAppValueOnlyCell = @"valueOnlyCell";
    static NSString* kILSwapAppNoValuesCell = @"noValuesCell";

	if ([indexPath section] == kILSwapAppSectionInfo) {

		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kILSwapAppKeyValueCell];
		if (cell == nil) {
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:kILSwapAppKeyValueCell] autorelease];
		}

		NSString* key = ILSwapAppPaneLabelForRegistrationKey([keys objectAtIndex:[indexPath row]]);
		NSString* value = [[values objectAtIndex:[indexPath row]] description];
		cell.textLabel.text = key;
		cell.detailTextLabel.text = value;
		cell.detailTextLabel.adjustsFontSizeToFitWidth = YES;
		cell.selectionStyle = UITableViewCellSelectionStyleNone;

		return cell;

	} else {

		switch ([indexPath section]) {
			case kILSwapAppSectionActions:
				if (!actions || [actions count] == 0)
					return [self noValuesCellForTable:tableView identifier:kILSwapAppNoValuesCell];
				else {
					id obj = [actions objectAtIndex:[indexPath row]];
					return [self valueOnlyCellWithText:[obj description] fromTable:tableView identifier:kILSwapAppValueOnlyCell];
				}

			case kILSwapAppSectionTypes:
				if (!types || [types count] == 0)
					return [self noValuesCellForTable:tableView identifier:kILSwapAppNoValuesCell];
				else {
					id obj = [types objectAtIndex:[indexPath row]];
					return [self cellForType:[obj description] fromTable:tableView identifier:kILSwapAppValueOnlyCell];
				}

			default:
				return nil; // Unsupported section
		}

	}
}

- (UITableViewCell*) valueOnlyCellWithText:(NSString*) text fromTable:(UITableView*) tv identifier:(NSString*) ident;
{
	UITableViewCell* cell = [tv dequeueReusableCellWithIdentifier:ident];

	if (!cell)
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident] autorelease];

	cell.textLabel.text = text;
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	cell.accessoryType = UITableViewCellAccessoryNone;

	return cell;
}

- (UITableViewCell*) cellForType:(NSString*) type fromTable:(UITableView*) tv identifier:(NSString*) ident;
{
	UITableViewCell* cell = [self valueOnlyCellWithText:type fromTable:tv identifier:ident];

	if ([type isEqual:(id) kUTTypeUTF8PlainText] ||
		[type isEqual:(id) kUTTypePNG] ||
		[type isEqual:kMvrContactAsPropertyListType])
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

	cell.selectionStyle = UITableViewCellSelectionStyleBlue;
	return cell;
}

- (UITableViewCell*) noValuesCellForTable:(UITableView*) tv identifier:(NSString*) ident;
{
	UITableViewCell* cell = [tv dequeueReusableCellWithIdentifier:ident];

	if (!cell)
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident] autorelease];

	cell.textLabel.text = NSLocalizedString(@"No values", @"No values cell label");
	cell.textLabel.textColor = [UIColor grayColor];
	cell.textLabel.textAlignment = UITextAlignmentCenter;
	cell.selectionStyle = UITableViewCellSelectionStyleNone;

	return cell;
}

- (NSString*) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
{
	switch (section) {
		case 1:
			return NSLocalizedString(@"Actions", @"Actions section in app pane");
		case 2:
			return NSLocalizedString(@"Accepted types", @"UTI section in app pane");

		default:
			return nil;
	}
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
	if ([indexPath section] == kILSwapAppSectionTypes) {
		if ([types count] == 0)
			return;

		NSString* obj = L0As(NSString, [types objectAtIndex:[indexPath row]]);

		if ([obj isEqual:(id) kUTTypeUTF8PlainText]) {

			ILSwapSendText* t = [[[ILSwapSendText alloc] initWithApplicationIdentifier:[record objectForKey:kILAppIdentifier] type:obj target:self didFinishSelector:@selector(didFinishSendingText:)] autorelease];
			[ILSwapCatalogApp() displaySendViewController:t];

		} else if ([obj isEqual:(id) kUTTypePNG]) {

			ILSwapSendImage* i = [[ILSwapSendImage new] autorelease];
			i.type = obj;
			i.actualImageType = (id) kUTTypePNG;
			i.application = record;
			i.delegate = self;

			UIView* v = [self.tableView cellForRowAtIndexPath:indexPath];
			if (!v)
				v = self.tableView;

			[i sendFromView:v inViewController:self];

		} else if ([obj isEqual:kMvrContactAsPropertyListType]) {

			ABPeoplePickerNavigationController* peoplePicker = [[ABPeoplePickerNavigationController new] autorelease];
			peoplePicker.peoplePickerDelegate = self;

			if (ILSwapIsiPad() && [peoplePicker respondsToSelector:@selector(modalPresentationStyle)])
				peoplePicker.modalPresentationStyle = UIModalPresentationFormSheet;
			else
				peoplePicker.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;

			[self presentModalViewController:peoplePicker animated:YES];

		} else if (obj) {
			ILSwapPickKindActionSheet* s = [[[ILSwapPickKindActionSheet alloc] initWithSendingType:obj] autorelease];
			s.delegate = self;

			UIView* c = [tableView cellForRowAtIndexPath:indexPath].contentView;
			if (!c)
				c = tableView;

			[ILSwapCatalogApp() showActionSheet:s invokedByView:c];
		}
	}
}

- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex;
{
	ILSwapPickKindActionSheet* a = (ILSwapPickKindActionSheet*) actionSheet;
	BOOL deselect = YES;

	switch (buttonIndex) {
		case kILSwapSendText: {
			ILSwapSendText* t = [[[ILSwapSendText alloc] initWithApplicationIdentifier:[record objectForKey:kILAppIdentifier] type:a.sendingType target:self didFinishSelector:@selector(didFinishSendingText:)] autorelease];
			[ILSwapCatalogApp() displaySendViewController:t];
		}
			break;

		case kILSwapSendImagePNG: {
			ILSwapSendImage* i = [[ILSwapSendImage new] autorelease];
			i.type = a.sendingType;
			i.actualImageType = (id) kUTTypePNG;
			i.application = record;
			i.delegate = self;

			NSIndexPath* p = [self.tableView indexPathForSelectedRow];
			UIView* v = p? [self.tableView cellForRowAtIndexPath:p] : nil;
			if (!v)
				v = self.tableView;

			[i sendFromView:v inViewController:self];
			deselect = NO;
			break;
		}

		default:
			break;
	}

	NSIndexPath* p = [self.tableView indexPathForSelectedRow];
	if (p && deselect)
		[self.tableView deselectRowAtIndexPath:p animated:YES];
}

- (void) didFinishPickingImage:(ILSwapSendImage *)i;
{
	NSIndexPath* p = [self.tableView indexPathForSelectedRow];
	if (p)
		[self.tableView deselectRowAtIndexPath:p animated:YES];
}

#pragma mark People picking

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker;
{
	NSIndexPath* p = [self.tableView indexPathForSelectedRow];
	if (p)
		[self.tableView deselectRowAtIndexPath:p animated:YES];
	[peoplePicker dismissModalViewControllerAnimated:YES];
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person;
{
	[peoplePicker dismissModalViewControllerAnimated:YES];

	ILSwapItem* i = [ILSwapItem moverContactItemFromPersonRecord:person];
	[[ILSwapService sharedService] sendItem:i forAction:nil toApplicationWithIdentifier:[record objectForKey:kILAppIdentifier]];

	return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier;
{
	return NO;
}

#pragma mark Sending text finish selector

- (void) didFinishSendingText:(ILSwapSendText*) t;
{
	NSIndexPath* p = [self.tableView indexPathForSelectedRow];
	if (p)
		[self.tableView deselectRowAtIndexPath:p animated:YES];
}

@end

redpajama_set_name: RedPajamaGithub


text:
const attr = 'info' in console ? 'info' : "log"
const pad = num => ('0' + num).slice(-2)

const timeStore = {}
const getTime = typeof performance !== 'undefined' && performance.now
	? () => performance.now()
	: () => new Date().getTime()

const createLogger = ({ scope="ROOT", debug }) => {
	const logger = {
		DISPATCH: data => {
			timeStore[data.key] = getTime()
			return data
		},
		DID_UPDATE: data => {
			let { key, value, currentState, nextState } = data
			const time = new Date()
			const formattedTime = `${ time.getHours() }:${ pad(time.getMinutes()) }:${ pad(time.getSeconds()) }`
			const takeTime = (getTime() - timeStore[key]).toFixed(2)
			const message = `${ scope }: action [${ key }] end at ${ formattedTime }, take ${ takeTime }ms`

			try {
				console.groupCollapsed(message)
			} catch (e) {
				try {
					console.group(message)
				} catch (e) {
					console.log(message)
				}
			}

			if (attr === 'log') {
				console[attr](value)
				console[attr](currentState)
				console[attr](nextState)
			} else {
				console[attr](`%c value`, `color: #03A9F4; font-weight: bold`, value)
				console[attr](`%c prev state`, `color: #9E9E9E; font-weight: bold`, currentState)
				console[attr](`%c next state`, `color: #4CAF50; font-weight: bold`, nextState)
			}

			try {
				console.groupEnd()
			} catch (e) {
				console.log('-- log end --')
			}

			return data
		},
		THROW_ERROR: error => {
			if (debug) {
				throw error
			}
			return error
		}
	}
	return logger
}

export default createLogger


text:
package nl.nn.adapterframework.util;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import nl.nn.adapterframework.core.INamedObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.logging.log4j.Logger;

/**
 * Base class for items of global lists.
 * The list itself is contained as a static field.
 * New items are registerd using registerItem().
 * Typical use: SapSystem.getSystem(name).<method to execute>
 * <br/>
 * @author Gerrit van Brakel
 */
public class GlobalListItem implements INamedObject {
	protected Logger log = LogUtil.getLogger(this);

	private static Hashtable<String, GlobalListItem> items = new Hashtable<>();
	private String name;
	private String aliasFor;

	/**
	 * configure() will be called once for each item registered, except for the aliasses.
	 */
	protected void configure() {
	}

	/**
	 * Get an item by Name. Descender classes should implement a similar method,
	 * that returns an object of its own type.
	 */
	protected static GlobalListItem getItem(String itemName) {
		GlobalListItem result = null;

		result = items.get(itemName);
		if (result==null) {
			throw new NullPointerException("no list item found for name ["+itemName+"]");
		}
		if (!StringUtils.isEmpty(result.getAliasFor())) {
			String aliasName = result.getAliasFor();
			result=getItem(aliasName);
			if (result==null) {
				throw new NullPointerException("no alias ["+aliasName+"] list item found for name ["+itemName+"] ");
			}
		}
		return result;
	}

	/**
	 * Get the system names as an Iterator, alphabetically sorted
	 *
	 * @return Iterator with the realm names, alphabetically sorted
	 */
	public static Iterator<String> getRegisteredNames() {
		SortedSet<String> sortedKeys = new TreeSet<>(items.keySet());
		return sortedKeys.iterator();
	}

	/**
	 * Gets a list with system names.
	 */
	public static List<String> getRegisteredNamesAsList() {
		Iterator<String> it = getRegisteredNames();
		List<String> result = new ArrayList<>();
		while(it.hasNext()) {
			result.add(it.next());
		}
		return result;
	}

	/**
	 * Register an item in the list
	 */
	public void registerItem(Object dummyParent) {
		if(StringUtils.isEmpty(getAliasFor())) {
			configure();
		}
		items.put(getName(), this);
		log.debug("globalItemList registered item [" + toString() + "]");
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

	/**
	 * The name under which the item can be retrieved.
	 */
	@Override
	public void setName(String string) {
		name = string;
	}
	@Override
	public String getName() {
		return name;
	}

	/**
	 * If this attribute is set, the item is only an alias for another item.
	 */
	public void setAliasFor(String string) {
		aliasFor = string;
	}
	public String getAliasFor() {
		return aliasFor;
	}

}


text:
class Resource
{
  public:
    Resource(std::string n);
    ~Resource(void);
    std::string getName() const { return name; }
  private:
    std::string name;
};
#endif


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace SomeTechie.RoundRobinScheduleGenerator
{
    [XmlType()]
    public class Game
    {
        protected RoundRobinTeamData _team1Data;
        [XmlIgnore()]
        public RoundRobinTeamData Team1Data
        {
            get
            {
                return _team1Data;
            }
        }

        [XmlIgnore()]
        protected string _vsID;
        public string vsID
        {
            get
            {
                return CalculateVsId(Team1, Team2);
            }
        }

        protected static int _idPos = 0;
        protected int _id = _idPos++;
        [XmlAttribute("Id")]
        public int Id
        {
            get
            {
                return _id;
            }
            set
            {
                _id = value;
                if (value > _idPos) _idPos = value;
            }
        }

        protected int _scheduleVersion = 0;
        [XmlAttribute("ScheduleVersion")]
        public int ScheduleVersion
        {
            get
            {
                return _scheduleVersion;
            }
            set
            {
                _scheduleVersion = value;
            }
        }

        [XmlIgnore()]
        public Team Team1
        {
            get
            {
                if (Team1Data != null)
                {
                    return Team1Data.Team;
                }
                else
                {
                    return null;
                }
            }
        }

        protected RoundRobinTeamData _team2Data;
        [XmlIgnore()]
        public RoundRobinTeamData Team2Data
        {
            get
            {
                return _team2Data;
            }
        }

        [XmlIgnore()]
        public Team Team2
        {
            get
            {
                if (Team2Data != null)
                {
                    return Team2Data.Team;
                }
                else
                {
                    return null;
                }
            }
        }

        [XmlIgnore()]
        Team[] _teams = null;
        public Team[] Teams
        {
            get
            {
                return _teams;
            }
        }

        [XmlIgnore()]
        Division _division = null;
        public Division Division
        {
            get
            {
                return _division;
            }
        }

        [XmlIgnore()]
        public int NumTeams
        {
            get
            {
                return 2;
            }
        }

        [XmlIgnore()]
        public List<RoundRobinTeamData> TeamDatas
        {
            get
            {
                List<RoundRobinTeamData> teamDatas = new List<RoundRobinTeamData>();
                teamDatas.Add(Team1Data);
                teamDatas.Add(Team2Data);
                return teamDatas;
            }
            set
            {
                if (value.Count >= 2)
                {
                    _team1Data = value[0];
                    _team2Data = value[1];
                    _teams = new Team[] { Team1, Team2 };
                    _division = Team1.Division;
                }
            }
        }

        protected Dictionary<string, TeamGameResult> _teamGameResults = new Dictionary<string, TeamGameResult>();
        [XmlIgnore()]
        public Dictionary<string, TeamGameResult> TeamGameResults
        {
            get
            {
                return _teamGameResults;
            }
            set
            {
                _teamGameResults = value;
            }
        }

        [XmlIgnore()]
        public Nullable<bool> IsLogicalResult
        {
            get
            {
                if (WinningTeam == null) return null;

                int winningScore = TeamGameResults[WinningTeam.Id].NumPoints;

                foreach(KeyValuePair<string,TeamGameResult> result in TeamGameResults){
                    if (result.Value.NumPoints > winningScore)
                    {
                        // The winning team didn't get the most points
                        return false;
                    }
                }

                return true;
            }
        }

        [XmlArray("TeamGameResults"), XmlArrayItem("TeamGameResult")]
        public SerializableKeyValuePair<string, TeamGameResult>[] XmlTeamGameResults
        {
            get
            {
                List<SerializableKeyValuePair<string, TeamGameResult>> xmlResults = new List<SerializableKeyValuePair<string, TeamGameResult>>();
                string[] keys = new string[TeamGameResults.Count];
                TeamGameResults.Keys.CopyTo(keys,0);
                TeamGameResult[] values = new TeamGameResult[TeamGameResults.Count];
                TeamGameResults.Values.CopyTo(values,0);

                for (int i = 0; i < TeamGameResults.Count; i++)
                {
                    xmlResults.Add(new SerializableKeyValuePair<string, TeamGameResult>(keys[i], values[i]));
                }
                return xmlResults.ToArray();
            }
            set
            {
                _teamGameResults.Clear();
                foreach (SerializableKeyValuePair<string, TeamGameResult> pair in value)
                {
                    _teamGameResults.Add(pair.Key, pair.Value);
                }
            }
        }

        protected List<string> _xmlTeams;
        [XmlArray("Teams"), XmlArrayItem("Team")]
        public string[] XmlSerializerTeams
        {
            get
            {
                List<string> xmlTeams = new List<string>();
                foreach (Team team in Teams)
                {
                    if (team != null)
                    {
                        xmlTeams.Add(team.Id);
                    }
                    else
                    {
                        xmlTeams.Add(null);
                    }
                }
                return xmlTeams.ToArray();
            }
            set
            {
                _xmlTeams = new List<string>(value);
            }
        }
        [XmlIgnore()]
        public string[] XmlTeamsIn
        {
            get
            {
                return _xmlTeams.ToArray();
            }
        }

        [XmlIgnore()]
        protected ScoreKeeper _scoreKeeper;
        public ScoreKeeper ScoreKeeper
        {
            get
            {
                Controller controller = Controller.GetController();
                if (controller.ScoreKeepersAssignment.ContainsKey(GamePosition)) return controller.ScoreKeepersAssignment[GamePosition];
                else return null;
            }
        }

        [XmlIgnore()]
        public GamePosition GamePosition
        {
            get
            {
                return GamePosition.GetGamePosition(CourtRoundNum, CourtNumber);
            }
        }

        [XmlIgnore()]
        public bool IsBye
        {
            get
            {
                return Team1Data.IsBye || Team2Data.IsBye;
            }
        }

        [XmlIgnore()]
        public bool IsInProgress
        {
            get
            {
                if (IsCompleted)
                {
                    return false;
                }

                foreach (KeyValuePair<string, TeamGameResult> teamResult in TeamGameResults)
                {
                    if (teamResult.Value.NumPoints > 0)return true;
                }
                return false;
            }
        }

        protected int _courtRoundNum;
        [XmlAttribute("CourtRoundNum")]
        public int CourtRoundNum
        {
            get
            {
                return _courtRoundNum;
            }
            set
            {
                _courtRoundNum = value;
            }
        }

        protected int _robinRoundNum;
        [XmlAttribute("RobinRoundNum")]
        public int RobinRoundNum
        {
            get
            {
                return _robinRoundNum;
            }
            set
            {
                _robinRoundNum = value;
            }
        }

        protected int _courtNumber;
        [XmlAttribute("CourtNumber")]
        public int CourtNumber
        {
            get
            {
                return _courtNumber;
            }
            set
            {
                _courtNumber = value;
            }
        }

        protected bool _isConfirmed = true;
        [XmlAttribute("IsConfirmed")]
        public bool IsConfirmed
        {
            get
            {
                return _isConfirmed;
            }
            set
            {
                _isConfirmed = value;
            }
        }

        [XmlIgnore()]
        public bool IsCompleted
        {
            get
            {
                return _winningTeam != null;
            }
        }

        protected bool _enabled = true;
        [XmlAttribute("Enabled")]
        public bool Enabled
        {
            get
            {
                return _enabled;
            }
            set
            {
                _enabled = value;

                // Reset tracking of played games
                if (!value)
                {
                    foreach (RoundRobinTeamData teamData in TeamDatas)
                    {
                        if (teamData != null)
                        {
                            teamData.removePlayedGame(this);
                        }
                    }
                }
                else
                {

                    foreach (RoundRobinTeamData teamData in TeamDatas)
                    {
                        if (teamData != null && !(new List<Game>(teamData.PlayedGames).Contains(this)))
                        {
                            teamData.addPlayedGame(this);
                        }
                    }
                }
            }
        }

        protected Team _winningTeam = null;
        [XmlIgnore()]
        public Team WinningTeam
        {
            get
            {
                return _winningTeam;
            }
            set
            {
                _winningTeam = value;
                if (_winningTeam == null)
                {
                    foreach (RoundRobinTeamData teamData in TeamDatas)
                    {
                        teamData.removePlayedGame(this);
                    }
                }
                else
                {
                    foreach (RoundRobinTeamData teamData in TeamDatas)
                    {
                        if (!(new List<Game>(teamData.PlayedGames).Contains(this)))
                        {
                            teamData.addPlayedGame(this);
                        }
                    }
                }
            }
        }

        protected string _xmlWinningTeam = null;
        [XmlAttribute("WinningTeam")]
        public string XmSerializerWinningTeam
        {
            get
            {
                if (WinningTeam != null)
                {
                    return WinningTeam.Id;
                }
                else
                {
                    return null;
                }
            }
            set
            {
                _xmlWinningTeam = value;
            }
        }
        public string XmlWinningTeamIn
        {
            get
            {
                return _xmlWinningTeam;
            }
        }

        public Game(RoundRobinTeamData team1Data, RoundRobinTeamData team2Data)
        {
            if (team1Data.Team.Division != team2Data.Team.Division) throw new Exception("Teams must be in the same division");
            _team1Data = team1Data;
            _team2Data = team2Data;
            _division = Team1.Division;
            _teams = new Team[] { Team1, Team2 };
            foreach (RoundRobinTeamData teamData in TeamDatas)
            {
                _teamGameResults.Add(teamData.Team.Id, new TeamGameResult(teamData));
            }
        }

        public void resetTeams(RoundRobinTeamData team1Data, RoundRobinTeamData team2Data)
        {
            // Remove old team data
            RoundRobinTeamData[] oldTeamDatas = TeamDatas.ToArray();

            // Set up new team
            if (team1Data.Team.Division != team2Data.Team.Division) throw new Exception("Teams must be in the same division");
            _team1Data = team1Data;
            _team2Data = team2Data;
            _division = Team1.Division;
            _teams = new Team[] { Team1, Team2 };
            _teamGameResults.Clear();
            foreach (RoundRobinTeamData teamData in TeamDatas)
            {
                _teamGameResults.Add(teamData.Team.Id, new TeamGameResult(teamData));
            }

            // Reset tracking of played games for both old and new teams
            if (_winningTeam != null)
            {
                foreach (RoundRobinTeamData teamData in oldTeamDatas)
                {
                    teamData.removePlayedGame(this);
                }

                foreach (RoundRobinTeamData teamData in TeamDatas)
                {
                    if (!(new List<Game>(teamData.PlayedGames).Contains(this)))
                    {
                        teamData.addPlayedGame(this);
                    }
                }
            }
        }

        protected Game()
        {
        }

        public override string ToString()
        {
            return string.Format("{0} vs {1}", Team1.ToString(), Team2.ToString());
        }

        public static string CalculateVsId(Team team1, Team team2)
        {
            return team1.NumId.ToString() + "," + team2.NumId.ToString();
        }

        public Game Clone()
        {
            Game game = new Game(Team1Data, Team2Data);
            game.RobinRoundNum = RobinRoundNum;
            game.CourtRoundNum = CourtRoundNum;

            return game;
        }
    }
}


text:
package com.vaadin.client.ui;

import com.google.gwt.core.client.GWT;

public class UnknownComponentConnector extends AbstractComponentConnector {

    @Override
    public boolean delegateCaptionHandling() {
        return false;
    }

    @Override
    public VUnknownComponent getWidget() {
        return (VUnknownComponent) super.getWidget();
    }

    public void setServerSideClassName(String serverClassName) {
        getWidget()
                .setCaption(
                        "Widgetset '"
                                + GWT.getModuleName()
                                + "' does not contain implementation for "
                                + serverClassName
                                + ". Check its component connector's @Connect mapping, widgetsets "
                                + "GWT module description file and re-compile your"
                                + " widgetset. In case you have downloaded a vaadin"
                                + " add-on package, you might want to refer to "
                                + "add-on "
                                + "instructions.");
    }
}


text:
using System;
using System.Collections.Generic;
using FubuMVC.Core;
using FubuMVC.Core.Behaviors;
using FubuMVC.Core.Runtime;
using Valcon.HelloWorld.Models;

namespace Valcon.HelloWorld.Configuration.Behaviors
{
    public class CrudErrorWrapperBehavior : BasicBehavior
    {
        private readonly IFubuRequest _fubuRequest;
        private readonly IPartialFactory _partialFactory;
        public CrudErrorWrapperBehavior(IFubuRequest fubuRequest, IPartialFactory partialFactory)
            : base(PartialBehavior.Executes)
        {
            _partialFactory = partialFactory;
            _fubuRequest = fubuRequest;
        }

        protected override DoNext performInvoke()
        {
            if(InsideBehavior != null)
            {
                try
                {
                    InsideBehavior.InvokePartial();
                }
                catch (Exception exc)
                {
                    var response = new AjaxResponse
                                        {
                                            Success = false,
                                            Errors = new List<string> { exc.Message }
                                        };
                    _fubuRequest.Set(response);

                    _partialFactory
                        .BuildPartial(response.GetType())
                        .Invoke();
                }

            }

            return DoNext.Stop;
        }
    }
}


text:
<?php

App::uses('AppModel', 'Model');
class ConfigAppModel extends AppModel {
}


text:
package sample;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.togglz.core.Feature;
import org.togglz.core.manager.FeatureManager;
import org.togglz.core.util.NamedFeature;

@RestController
public class HelloWorldController {

    private static final String GREETING = "Greetings from Spring Boot!";

    private final FeatureManager manager;

    public static final Feature HELLO_WORLD = new NamedFeature("HELLO_WORLD");

    public static final Feature REVERSE_GREETING = new NamedFeature("REVERSE_GREETING");

    public HelloWorldController(FeatureManager manager) {
		this.manager = manager;
	}

	@RequestMapping("/")
    public ResponseEntity<?> index() {
        if (manager.isActive(HELLO_WORLD)) {
            StringBuilder sb = new StringBuilder(GREETING);
            if (manager.isActive(REVERSE_GREETING)) {
                sb.reverse();
            }
            return ResponseEntity.ok().body(sb.toString());
        }
        return ResponseEntity.notFound().build();
    }
}


text:
/**
 * Onshape REST API
 * The Onshape REST API consumed by all clients.
 *
 * OpenAPI spec version: 1.93
 * Contact: api-support@onshape.zendesk.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

export class BTDocumentLabelParams {
    'name'?: string;
    'documentIds'?: Array<string>;
    'ownerId'?: string;
    'parentLabelId'?: string;

    static discriminator: string | undefined = undefined;

    static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [
        {
            "name": "name",
            "baseName": "name",
            "type": "string"
        },
        {
            "name": "documentIds",
            "baseName": "documentIds",
            "type": "Array<string>"
        },
        {
            "name": "ownerId",
            "baseName": "ownerId",
            "type": "string"
        },
        {
            "name": "parentLabelId",
            "baseName": "parentLabelId",
            "type": "string"
        }    ];

    static getAttributeTypeMap() {
        return BTDocumentLabelParams.attributeTypeMap;
    }
}


text:
package org.apache.shindig.gadgets.oauth;

import org.apache.shindig.auth.SecurityToken;
import org.apache.shindig.gadgets.GadgetException;
import org.apache.shindig.gadgets.GadgetSpecFactory;
import org.apache.shindig.gadgets.oauth.AccessorInfo.HttpMethod;
import org.apache.shindig.gadgets.oauth.AccessorInfo.OAuthParamLocation;
import org.apache.shindig.gadgets.oauth.OAuthStore.ConsumerInfo;
import org.apache.shindig.gadgets.oauth.OAuthStore.TokenInfo;
import org.apache.shindig.gadgets.spec.GadgetSpec;
import org.apache.shindig.gadgets.spec.OAuthService;
import org.apache.shindig.gadgets.spec.OAuthSpec;
import org.apache.shindig.gadgets.spec.OAuthService.Location;
import org.apache.shindig.gadgets.spec.OAuthService.Method;

import com.google.inject.Inject;

import net.oauth.OAuthServiceProvider;

import org.apache.commons.lang.StringUtils;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * Higher-level interface that allows callers to store and retrieve
 * OAuth-related data directly from {@code GadgetSpec}s, {@code GadgetContext}s,
 * etc. See {@link OAuthStore} for a more detailed explanation of the OAuth
 * Data Store.
 */
public class GadgetOAuthTokenStore {

  private final OAuthStore store;
  private final GadgetSpecFactory specFactory;

  /**
   * Public constructor.
   *
   * @param store an {@link OAuthStore} that can store and retrieve OAuth
   *              tokens, as well as information about service providers.
   */
  @Inject
  public GadgetOAuthTokenStore(OAuthStore store, GadgetSpecFactory specFactory) {
    this.store = store;
    this.specFactory = specFactory;
  }

  /**
   * Retrieve an AccessorInfo and OAuthAccessor that are ready for signing OAuthMessages.  To do
   * this, we need to figure out:
   *
   * - what consumer key/secret to use for signing.
   * - if an access token should be used for the request, and if so what it is.   *
   * - the OAuth request/authorization/access URLs.
   * - what HTTP method to use for request token and access token requests
   * - where the OAuth parameters are located.
   *
   * Note that most of that work gets skipped for signed fetch, we just look up the consumer key
   * and secret for that.  Signed fetch always sticks the parameters in the query string.
   */
  public AccessorInfo getOAuthAccessor(SecurityToken securityToken,
      OAuthArguments arguments, OAuthClientState clientState) throws GadgetException {

    AccessorInfoBuilder accessorBuilder = new AccessorInfoBuilder();

    // Does the gadget spec tell us any details about the service provider, like where to put the
    // OAuth parameters and what methods to use for their URLs?
    OAuthServiceProvider provider = null;
    if (arguments.mayUseToken()) {
      provider = lookupSpecInfo(securityToken, arguments, accessorBuilder);
    } else {
      // This is plain old signed fetch.
      accessorBuilder.setParameterLocation(AccessorInfo.OAuthParamLocation.URI_QUERY);
    }

    // What consumer key/secret should we use?
    ConsumerInfo consumer = store.getConsumerKeyAndSecret(
        securityToken, arguments.getServiceName(), provider);
    accessorBuilder.setConsumer(consumer);

    // Should we use the OAuth access token?  We never do this unless the client allows it, and
    // if owner == viewer.
    if (arguments.mayUseToken()
        && securityToken.getOwnerId() != null
        && securityToken.getViewerId().equals(securityToken.getOwnerId())) {
      lookupToken(securityToken, consumer, arguments, clientState, accessorBuilder);
    }

    return accessorBuilder.create();
  }

  /**
   * Lookup information contained in the gadget spec.
   */
  private OAuthServiceProvider lookupSpecInfo(SecurityToken securityToken, OAuthArguments arguments,
      AccessorInfoBuilder accessorBuilder) throws GadgetException {
    GadgetSpec spec = findSpec(securityToken, arguments);
    OAuthSpec oauthSpec = spec.getModulePrefs().getOAuthSpec();
    if (oauthSpec == null) {
      throw oauthNotFoundEx(securityToken);
    }
    OAuthService service = oauthSpec.getServices().get(arguments.getServiceName());
    if (service == null) {
      throw serviceNotFoundEx(securityToken, oauthSpec, arguments.getServiceName());
    }
    // In theory some one could specify different parameter locations for request token and
    // access token requests, but that's probably not useful.  We just use the request token
    // rules for everything.
    accessorBuilder.setParameterLocation(getStoreLocation(service.getRequestUrl().location));
    accessorBuilder.setMethod(getStoreMethod(service.getRequestUrl().method));
    OAuthServiceProvider provider = new OAuthServiceProvider(
        service.getRequestUrl().url.toJavaUri().toASCIIString(),
        service.getAuthorizationUrl().toJavaUri().toASCIIString(),
        service.getAccessUrl().url.toJavaUri().toASCIIString());
    return provider;
  }

  /**
   * Figure out the OAuth token that should be used with this request.  We check for this in three
   * places.  In order of priority:
   *
   * 1) From information we cached on the client.
   *    We encrypt the token and cache on the client for performance.
   *
   * 2) From information we have in our persistent state.
   *    We persist the token server-side so we can look it up if necessary.
   *
   * 3) From information the gadget developer tells us to use (a preapproved request token.)
   *    Gadgets can be initialized with preapproved request tokens.  If the user tells the service
   *    provider they want to add a gadget to a gadget container site, the service provider can
   *    create a preapproved request token for that site and pass it to the gadget as a user
   *    preference.
   * @throws GadgetException
   */
  private void lookupToken(SecurityToken securityToken, ConsumerInfo consumerInfo,
      OAuthArguments arguments, OAuthClientState clientState, AccessorInfoBuilder accessorBuilder)
      throws GadgetException {
    if (clientState.getRequestToken() != null) {
      // We cached the request token on the client.
      accessorBuilder.setRequestToken(clientState.getRequestToken());
      accessorBuilder.setTokenSecret(clientState.getRequestTokenSecret());
    } else if (clientState.getAccessToken() != null) {
      // We cached the access token on the client
      accessorBuilder.setAccessToken(clientState.getAccessToken());
      accessorBuilder.setTokenSecret(clientState.getAccessTokenSecret());
      accessorBuilder.setSessionHandle(clientState.getSessionHandle());
      accessorBuilder.setTokenExpireMillis(clientState.getTokenExpireMillis());
    } else {
      // No useful client-side state, check persistent storage
      TokenInfo tokenInfo = store.getTokenInfo(securityToken, consumerInfo,
          arguments.getServiceName(), arguments.getTokenName());
      if (tokenInfo != null && tokenInfo.getAccessToken() != null) {
        // We have an access token in persistent storage, use that.
        accessorBuilder.setAccessToken(tokenInfo.getAccessToken());
        accessorBuilder.setTokenSecret(tokenInfo.getTokenSecret());
        accessorBuilder.setSessionHandle(tokenInfo.getSessionHandle());
        accessorBuilder.setTokenExpireMillis(tokenInfo.getTokenExpireMillis());
      } else {
        // We don't have an access token yet, but the client sent us a (hopefully) preapproved
        // request token.
        accessorBuilder.setRequestToken(arguments.getRequestToken());
        accessorBuilder.setTokenSecret(arguments.getRequestTokenSecret());
      }
    }
  }

  private OAuthParamLocation getStoreLocation(Location location) throws GadgetException {
    switch(location) {
    case HEADER:
      return OAuthParamLocation.AUTH_HEADER;
    case URL:
      return OAuthParamLocation.URI_QUERY;
    case BODY:
      return OAuthParamLocation.POST_BODY;
    }
    throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR,
        "Unknown parameter location " + location);
  }

  private HttpMethod getStoreMethod(Method method) throws GadgetException {
    switch(method) {
    case GET:
      return HttpMethod.GET;
    case POST:
      return HttpMethod.POST;
    }
    throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR,
        "Unknown method " + method);
  }

  private GadgetSpec findSpec(SecurityToken securityToken, OAuthArguments arguments)
      throws GadgetException {
    try {
      return specFactory.getGadgetSpec(
          new URI(securityToken.getAppUrl()),
          arguments.getBypassSpecCache());
    } catch (URISyntaxException e) {
      throw new UserVisibleOAuthException("could not fetch gadget spec, gadget URI invalid", e);
    }
  }

  private GadgetException serviceNotFoundEx(SecurityToken securityToken, OAuthSpec oauthSpec,
      String serviceName) {
    StringBuilder message = new StringBuilder()
        .append("Spec for gadget ")
        .append(securityToken.getAppUrl())
        .append(" does not contain OAuth service ")
        .append(serviceName)
        .append(".  Known services: ")
        .append(StringUtils.join(oauthSpec.getServices().keySet(), ','));
    return new UserVisibleOAuthException(message.toString());
  }

  private GadgetException oauthNotFoundEx(SecurityToken securityToken) {
    StringBuilder message = new StringBuilder()
        .append("Spec for gadget ")
        .append(securityToken.getAppUrl())
        .append(" does not contain OAuth element.");
    return new UserVisibleOAuthException(message.toString());
  }

  /**
   * Store an access token for the given user/gadget/service/token name
   */
  public void storeTokenKeyAndSecret(SecurityToken securityToken, ConsumerInfo consumerInfo,
      OAuthArguments arguments, TokenInfo tokenInfo) throws GadgetException {
    store.setTokenInfo(securityToken, consumerInfo, arguments.getServiceName(),
        arguments.getTokenName(), tokenInfo);
  }

  /**
   * Remove an access token for the given user/gadget/service/token name
   */
  public void removeToken(SecurityToken securityToken, ConsumerInfo consumerInfo,
      OAuthArguments arguments) throws GadgetException {
    store.removeToken(securityToken, consumerInfo, arguments.getServiceName(),
        arguments.getTokenName());
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--Generated by crowdin.com-->
<resources>
  <string-array name="pref_volumeButtonNavigation_labels">
    <item>"Moet nie gebruik vir navigasie"</item>
    <item>Navigeer verse</item>
    <item>Navigeer Hoofstukke</item>
  </string-array>
</resources>


text:
package fakes

import (
	"io"
	"sync"
)

type BOSHCommand struct {
	GetBOSHPathCall struct {
		CallCount int
		Returns   struct {
			Path  string
			Error error
		}
	}

	RunStub        func(stdout io.Writer, workingDirectory string, args []string) error
	runMutex       sync.RWMutex
	runArgsForCall []struct {
		stdout           io.Writer
		workingDirectory string
		args             []string
	}
	runReturns struct {
		result1 error
	}
	runReturnsOnCall map[int]struct {
		result1 error
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *BOSHCommand) GetBOSHPath() (string, error) {
	fake.GetBOSHPathCall.CallCount++

	return fake.GetBOSHPathCall.Returns.Path, fake.GetBOSHPathCall.Returns.Error
}

func (fake *BOSHCommand) Run(stdout io.Writer, workingDirectory string, args []string) error {
	var argsCopy []string
	if args != nil {
		argsCopy = make([]string, len(args))
		copy(argsCopy, args)
	}
	fake.runMutex.Lock()
	ret, specificReturn := fake.runReturnsOnCall[len(fake.runArgsForCall)]
	fake.runArgsForCall = append(fake.runArgsForCall, struct {
		stdout           io.Writer
		workingDirectory string
		args             []string
	}{stdout, workingDirectory, argsCopy})
	fake.recordInvocation("Run", []interface{}{stdout, workingDirectory, argsCopy})
	fake.runMutex.Unlock()

	if fake.RunStub != nil {
		return fake.RunStub(stdout, workingDirectory, args)
	}
	if specificReturn {
		return ret.result1
	}
	return fake.runReturns.result1
}

func (fake *BOSHCommand) RunCallCount() int {
	fake.runMutex.RLock()
	defer fake.runMutex.RUnlock()
	return len(fake.runArgsForCall)
}

func (fake *BOSHCommand) RunArgsForCall(i int) (io.Writer, string, []string) {
	fake.runMutex.RLock()
	defer fake.runMutex.RUnlock()
	return fake.runArgsForCall[i].stdout, fake.runArgsForCall[i].workingDirectory, fake.runArgsForCall[i].args
}

func (fake *BOSHCommand) RunReturns(result1 error) {
	fake.RunStub = nil
	fake.runReturns = struct {
		result1 error
	}{result1}
}

func (fake *BOSHCommand) RunReturnsOnCall(i int, result1 error) {
	fake.RunStub = nil
	if fake.runReturnsOnCall == nil {
		fake.runReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.runReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *BOSHCommand) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.runMutex.RLock()
	defer fake.runMutex.RUnlock()
	return fake.invocations
}

func (fake *BOSHCommand) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
AASP Contributions Series (Dallas) 39: 218 (2000)

#### Original name
Staphlosporonites siwalikus R.K. Saxena & A.P. Bhattach.

### Remarks
null


text:
package ninja;

import ninja.conf.*;
import ninja.utils.NinjaPropertiesImpl;
import com.google.inject.AbstractModule;
import ninja.utils.NinjaProperties;

/**
 * The basic configuration of the main ninja framework.
 */
public class BaseAndClassicModules extends AbstractModule {

    private final NinjaPropertiesImpl ninjaProperties;

    public BaseAndClassicModules(NinjaPropertiesImpl ninjaProperties) {
        this.ninjaProperties = ninjaProperties;
    }

    @Override
    public void configure() {
        install(new NinjaBaseModule(ninjaProperties));
        install(new NinjaClassicModule((NinjaProperties)ninjaProperties));
    }

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="bc.css">

### RvtSamples 2019

I already described how I installed Revit 2019,
[compiled the Revit 2019 SDK samples](http://thebuildingcoder.typepad.com/blog/2018/04/compiling-the-revit-2019-sdk-samples.html),
migrated [RevitLookup to the new version](http://thebuildingcoder.typepad.com/blog/2018/04/revitlookup-2019-and-new-sdk-samples.html),
[The Building Coder samples](http://thebuildingcoder.typepad.com/blog/2018/04/forge-rvt-to-ifc-adn-xtra-tbc-and-adnrme-updates.html#2),
[the AdnRme MEP HVAC and electrical samples](http://thebuildingcoder.typepad.com/blog/2018/04/forge-rvt-to-ifc-adn-xtra-tbc-and-adnrme-updates.html#3) and
the [AdnRevitApiLabsXtra training labs](http://thebuildingcoder.typepad.com/blog/2018/04/forge-rvt-to-ifc-adn-xtra-tbc-and-adnrme-updates.html#4).

In the course of the last post, I forgot to mention setting up RvtSamples.

Just like the migration to previous versions, this is not a trivial undertaking.

Here are the discussions of the previous migrations to
the [Revit 2017 SDK](http://thebuildingcoder.typepad.com/blog/2016/04/rvtsamples-for-revit-2017.html) and
the [Revit 2018](http://thebuildingcoder.typepad.com/blog/2017/05/sdk-update-rvtsamples-and-modifying-grid-end-point.html#3).

To curt a long story short and simply share my current working RvtSamples source code for the Revit 2019 SDK, here
is [RvtSamples_2019.zip](zip/RvtSamples_2019.zip) containing my modified files.
It also includes some of the originals renamed by adding the suffix `original`.

I hope you find this useful.

Please let me know if you find anything is missing.

Todo: I have not even checked yet whether
the [new Revit 2019 SDK samples](http://thebuildingcoder.typepad.com/blog/2018/04/revitlookup-2019-and-new-sdk-samples.html#3) have
been included yet.

I strongly suspect not, sorry to say... stay tuned...


text:
package FacebookPrep;

public class _0158ReadNCharactersGivenRead4IICallMultipleTimes {

	public static void main(String[] args) {

	}

	abstract class Reader4 {
		abstract int read4(char[] buf4);
	}

	public class Solution extends Reader4 {

		@Override
		int read4(char[] buf4) {
			// TODO Auto-generated method stub
			return 0;
		}

		/**
		 * @param buf Destination buffer
		 * @param n   Number of characters to read
		 * @return The number of actual characters read
		 */
		public int read(char[] buf, int n) {

		}

	}
}


text:
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:true, indent:4, maxerr:100, plusplus:false, devel:true, nomen:false */
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4 */
/*global define, exports, require */

/**
 * Provides jsonlint results via the core linting extension point
 */
/*global exports, require, Buffer*/
/*jshint -W097, -W098, -W079 */
"use strict";

if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

define(function (require, exports, module) {
    var jsonlint;
    if (typeof window === "undefined") {
        jsonlint = require("thirdparty/jsonlint/jsonlint");
    } else {
        require("thirdparty/jsonlint/jsonlint");
        jsonlint = window.jsonlint;
    }

    var re = /(\d+)/;

    function convertToBetterErrorMessage(errStr, message) {
        var errorMessage = message;

        switch (message) {
            case "Expecting 'EOF', '}', ':', ',', ']', got 'STRING'":
                errorMessage = "Probably missing a semi colon, comma or }/]";
                break;
            default:
                break;
        }
        return errorMessage;
    }

    function closestMatch(strA, strB, threshold) {
        var pos = -1,
            startPos = 0,
            i;

        if (threshold === undefined) {
            threshold = 2;
        }

        for(i = strB.length, startPos = 0; i >= 0; i--) {
            var searchString = strB.substring(0, i);
            pos = strA.indexOf(searchString, startPos);

            if(pos !== -1) {
                if (threshold > searchString.length) {
                    pos = -1;
                }

                break;
            }
        }

        return pos;
    }

    function getPosition(errorLine, text, errorText, marker) {
        var lines = text.split("\n");

        // errorText = "...[Line Content]"
        // length("-----------------------^") - length("...")
        var problem = errorText.substring(marker.length - 1);
        // this could need some improvement...
        var l = closestMatch(lines[errorLine], problem, 2);

        return l;
    }

    /**
     * Run jsonlint on the current document. Reports results to the main UI. Displays
     * a gold star when no errors are found.
     */
    function lintOneFile(text, fullPath) {
        try {
            jsonlint.parse(text);
        } catch (e) {
    //            ["Parse error on line 347:", "...      "newFeatures" [            {    ", "-----------------------^", "Expecting 'EOF', '}', ':', ',', ']', got '['"]
            var parts = e.message.split("\n"),
                line = re.exec(parts[0]);

            if (line) {
                var t = convertToBetterErrorMessage(line, parts[3]);
                var errorLine = line[0] - 1;
                var position = getPosition(errorLine, text, parts[1], parts[2]);
                var error = {
                    pos:     {line: errorLine, ch: position},
                    message: t,
                    type:    "problem_type_error" // dependency to CodeInspection is not helpful here
                };

                return {errors: [error]};
            }
        }

        return null;
    }

    // Testing API
    exports.lintOneFile   = lintOneFile;
    exports.closestMatch  = closestMatch;
    module.exports        = exports;
});


text:
CREATE DATABASE  IF NOT EXISTS `pdv` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `pdv`;
-- MySQL dump 10.13  Distrib 5.6.13, for osx10.6 (i386)
--
-- Host: 127.0.0.1    Database: pdv
-- ------------------------------------------------------
-- Server version	5.6.13

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `movimiento`
--

DROP TABLE IF EXISTS `movimiento`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `movimiento` (
  `idMovimiento` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `idItem` bigint(20) unsigned NOT NULL,
  `cantidad` decimal(10,2) unsigned DEFAULT NULL,
  `pu` decimal(10,2) unsigned DEFAULT NULL,
  `fecha` timestamp NULL DEFAULT NULL,
  `aplicado` char(1) DEFAULT 'N',
  PRIMARY KEY (`idMovimiento`),
  KEY `index2` (`idItem`),
  CONSTRAINT `fk_movimiento_item` FOREIGN KEY (`idItem`) REFERENCES `item` (`idItem`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `movimiento`
--

LOCK TABLES `movimiento` WRITE;
/*!40000 ALTER TABLE `movimiento` DISABLE KEYS */;
/*!40000 ALTER TABLE `movimiento` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2015-07-28  7:34:28


text:
Kills the currently executing Lua script, assuming no write operation was yet
performed by the script.

This command is mainly useful to kill a script that is running for too much
time(for instance because it entered an infinite loop because of a bug).
The script will be killed and the client currently blocked into EVAL will see
the command returning with an error.

If the script already performed write operations it can not be killed in this
way because it would violate Lua script atomicity contract.
In such a case only `SHUTDOWN NOSAVE` is able to kill the script, killing
the Redis process in an hard way preventing it to persist with half-written
information.

Please refer to the `EVAL` documentation for detailed information about Redis
Lua scripting.

@return

@simple-string-reply


text:
▲

▼

				✐

				By:

					<input type="button" value="Save" ng-click="vm.onArticleSaveEditClick(article)" />
					<input type="button" value="Cancel" ng-click="vm.onArticleCancelEditClick(article)" />


text:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.appbar.MaterialToolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/centeredToolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="center"
tools:viewBindingIgnore="true">

<TextView
    android:id="@+id/centeredToolbarTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:ellipsize="end"
    android:maxLines="1"
    android:textAppearance="@style/StepikToolbarTextAppearance"/>

</com.google.android.material.appbar.MaterialToolbar>


text:
<?php

namespace Illuminate\Database\Schema;

use Illuminate\Support\Fluent;

/**
 * @method ForeignKeyDefinition deferrable(bool $value = true) Set the foreign key as deferrable (PostgreSQL)
 * @method ForeignKeyDefinition initiallyImmediate(bool $value = true) Set the default time to check the constraint (PostgreSQL)
 * @method ForeignKeyDefinition on(string $table) Specify the referenced table
 * @method ForeignKeyDefinition onDelete(string $action) Add an ON DELETE action
 * @method ForeignKeyDefinition onUpdate(string $action) Add an ON UPDATE action
 * @method ForeignKeyDefinition references(string|array $columns) Specify the referenced column(s)
 */
class ForeignKeyDefinition extends Fluent
{
    /**
     * Indicate that deletes should cascade.
     *
     * @return $this
     */
    public function cascadeOnDelete()
    {
        return $this->onDelete('cascade');
    }
}


text:
'''Module for getting stats from WES Entropy Daemon'''
import argparse
import ast
import errno
import logging
import select
import socket
from WesEntropy.Engine.interface import WesClientConfig
from WesEntropy.Engine.utilities import WesConfig, DaemonMsg

class WesEntropyStats(object):
    '''Object for getting stats from WES Entropy Daemon'''

    RECEIVE_SIZE = 4096
    TIMEOUT = 1

    def __init__(self, config):
        if config is None or isinstance(config, str):
            self.config = WesClientConfig(config)
        else:
            assert isinstance(config, WesConfig)
            self.config = config
        self.server_address = self.config.socket_path
        self.socket = None

    def connect(self):
        """Set up socket"""
        try:
            logging.debug("Attempt to connect to daemon: %s",
                          self.server_address)
            self.socket = socket.socket(socket.AF_UNIX,
                                        socket.SOCK_STREAM)
            self.socket.connect(self.server_address)

        except IOError:
            self.destroy()

        if self.socket is None:
            logging.warning("Failed to connect to daemon.")

        return self.socket is not None

    def request_stats(self):
        """Request stats from server."""
        success = False
        if self.socket is None:
            return success

        logging.debug("Request stats")
        request = DaemonMsg.construct_stats_request()

        bytes_written = 0
        try:
            bytes_written = self.socket.send(request)
        except IOError as error:
            logging.error("Error on send (error: %s)",
                          errno.errorcode[error.errno])

        if bytes_written == len(request):
            logging.debug("Requested stats")

            success = True
        else:
            logging.error("Failed to write all bytes: wrote %i",
                          bytes_written)
            self.destroy()
        return success

    def get_waiting_data(self):
        """Get data waiting in socket, after select says it is ready to read"""
        data = ""
        if self.socket is None:
            return data
        try:
            data = self.socket.recv(WesEntropyStats.RECEIVE_SIZE)
            if len(data) > 0:
                logging.debug(
                    "Received stats data")
            else:
                logging.error("Hangup on recv")
                self.destroy()
        except IOError as error:
            logging.error("Error on recv (error: %s)",
                          errno.errorcode[error.errno])
            self.destroy()
        return data

    def get_data(self):
        '''Get data in socket'''
        if self.socket is None:
            return ""

        readable = []
        try:
            readable, _, _ = select.select(
                [self.socket.fileno()], [], [], WesEntropyStats.TIMEOUT)
        except IOError as error:
            logging.error("Error on select (error: %s)",
                          errno.errorcode[error.errno])

        if readable:
            return self.get_waiting_data()

        logging.debug("No waiting data")
        self.destroy()
        return ""

    def destroy(self):
        """Destroy WES Socket"""
        if self.socket is not None:
            try:
                self.socket.close()
            except IOError as error:
                logging.error("Error on socket close (error: %s)",
                              errno.errorcode[error.errno])
            logging.debug("Closed connection to server: %s",
                          self.server_address)
        self.socket = None

    def get_stats(self):
        """Get stats from daemon"""
        self.connect()
        self.request_stats()
        msg = self.get_data()
        stats = None

        if msg != '':
            try:
                stats = ast.literal_eval(msg)
            except ValueError:
                logging.debug('Invalid stats msg: %s', msg)
        self.destroy()
        return stats

def time_string(uptime):
    '''Convert seconds to pretty string'''
    days, remainder = divmod(int(uptime), 24 * 60 * 60)
    hours, remainder = divmod(remainder, 60 * 60)
    minutes, seconds = divmod(remainder, 60)
    return ("%i days, %i hours, %i minutes,  %i seconds" %
            (days, hours, minutes, seconds))

def print_stats(stats_dict):
    '''Pretty print statistics to screen'''
    if stats_dict is None:
        print "No data received from daemon"
        return
    if 'info' in stats_dict:
        print "General Information:"
        if 'version' in stats_dict['info']:
            print "    WES Version:    %s" % stats_dict['info']['version']
        if 'daemon_uptime' in stats_dict['info']:
            print("    Daemon uptime:  %s" %
                  time_string(stats_dict['info']['daemon_uptime']))
            print
        if 'stream' in stats_dict['info']:
            print "    Stream source: %s" % stats_dict['info']['stream']
        if 'drbg' in stats_dict['info']:
            print "    DRBG:          %s" % stats_dict['info']['drbg']
        if 'seed' in stats_dict['info']:
            print "    Seed source:   %s" % stats_dict['info']['seed']
        print
    if 'consumed' in stats_dict:
        print "Randomness consumed:"
        for key, value in stats_dict['consumed'].iteritems():
            print "    %s: %i bytes" % (key, value)
        print
    if 'produced' in stats_dict:
        print "Randomness produced:"
        print "    %i bytes" % stats_dict['produced']

    print ("\nVisit www.whitewoodencryption.com to "
           "harness the power of great entropy.")

def main():
    """Main method"""
    parser = argparse.ArgumentParser(
        description='Get entropy from WES Entropy Daemon')
    parser.add_argument('-d', '--debug', action='store_true',
                        dest='debug', help='Enter debugger')
    parser.add_argument('-c', '--config', dest='config',
                        default=None,
                        help='location of config file, default: ' +
                        '/etc/wesentropy/client.conf')
    parser.add_argument('-v', '--verbose', action='store_true',
                        dest='verbose', help="run with verbose logging")

    args = parser.parse_args()

    if args.debug:
        import ipdb
        ipdb.set_trace()

    if args.verbose:
        logging.basicConfig(format='%(levelname)s: %(message)s',
                            level=logging.DEBUG)
    else:
        logging.basicConfig(format='%(levelname)s: %(message)s')

    stats = WesEntropyStats(args.config)
    stats_dict = stats.get_stats()
    print_stats(stats_dict)

if __name__ == '__main__':
    main()