text:
using System;
using System.Security;

namespace System.Diagnostics
{
    // We know of no way to achieve this on Unix, particularly providing the password
    // without a prompt. If we find a way, we should implement it. It may make more sense to provide
    // similar functionality through an API specific to Unix.
    public sealed partial class ProcessStartInfo
    {
        private const bool CaseSensitiveEnvironmentVariables = true;

        public string UserName
        {
            get { throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported); }
            set { throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported); }
        }

        public string PasswordInClearText
        {
            get { throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported); }
            set { throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported); }
        }

        public string Domain
        {
            get { throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported); }
            set { throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported); }
        }

        public bool LoadUserProfile
        {
            get { throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported); }
            set { throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported); }
        }

        public bool UseShellExecute { get; set; }

        public string[] Verbs => Array.Empty<string>();

        [CLSCompliant(false)]
        public SecureString Password
        {
            get { throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported); }
            set { throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported); }
        }
    }
}

redpajama_set_name: RedPajamaGithub


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

namespace LuckyLotto.Helpers
{
    public static class ColorHelpers
    {
        public static Color NextColor(this Random random)
        {
            return Color.FromArgb(255, (byte) random.Next(0, 255), (byte) random.Next(0, 255),
                (byte) random.Next(0, 255));
        }
    }
}


text:
import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import DataRoute from 'ember-data-route';

export default Ember.Route.extend(DataRoute, AuthenticatedRouteMixin, {
  model() {
    return this.get('store').createRecord('post');
  }
});


text:
"""
syslogmp.stream
~~~~~~~~~~~~~~~

Treat binary data as a stream and provide methods to read from it.

:Copyright: 2007-2021 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""

from itertools import islice, takewhile
from typing import Callable, Iterator

class Stream:
    def __init__(self, data: bytes) -> None:
        self.iterator = iter(data)

    def read(self, n: int) -> bytes:
        """Return the next `n` bytes."""
        return bytes(islice(self.iterator, n))

    def read_until(self, stop_byte: bytes) -> bytes:
        """Return bytes until the first occurrence of the stop byte.

        The stop byte is not returned, but silently dropped from the
        remaining stream data.
        """
        predicate = create_match_predicate(stop_byte)
        return bytes(takewhile(predicate, self.iterator))

    def read_until_inclusive(self, stop_byte: bytes) -> bytes:
        """Return bytes until, and including, the first occurrence of
        the stop byte.
        """

        def inner() -> Iterator[int]:
            predicate = create_match_predicate(stop_byte)
            for code_point in self.iterator:
                yield code_point
                if not predicate(code_point):
                    return

        return bytes(inner())

    def read_remainder(self) -> bytes:
        """Return all remaining bytes."""
        return bytes(self.iterator)

def create_match_predicate(value_to_match: bytes) -> Callable[[int], bool]:
    code_point = ord(value_to_match)
    return lambda cp: cp != code_point


text:
package org.hillview.table;

import org.hillview.table.api.ISubSchema;

public class FullSubSchema implements ISubSchema {
    @Override
    public boolean isColumnPresent(final String name) {
        return true;
    }
}


text:
package com.google.walkaround.slob.server;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.dev.LocalBlobstoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskHandle;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.tools.development.ApiProxyLocal;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalFileServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.apphosting.api.ApiProxy;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.walkaround.slob.server.MutationLog.DeltaIterator;
import com.google.walkaround.slob.shared.ChangeData;
import com.google.walkaround.slob.shared.ChangeRejected;
import com.google.walkaround.slob.shared.ClientId;
import com.google.walkaround.slob.shared.InvalidSnapshot;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.slob.shared.SlobModel;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedIterator;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedPreparedQuery;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.util.server.appengine.OversizedPropertyMover;
import com.google.walkaround.util.server.appengine.OversizedPropertyMover.MovableProperty;

import junit.framework.TestCase;

import org.waveprotocol.wave.model.util.Utf16Util;

import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.annotation.Nullable;

/**
 * @author ohler@google.com (Christian Ohler)
 */
public class MutationLogTest extends TestCase {

  @SuppressWarnings("unused")
  private static final Logger log = Logger.getLogger(MutationLogTest.class.getName());

  // NOTE(ohler): testSizeEstimates() does NOT pass regardless of what these
  // constants are.  It was off by one when I ran with other values.  Still good
  // enough, didn't investigate in detail.
  private static final String SNAPSHOT_STRING =
      "snapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshot"
      + "snapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshot";
  private static final String ROOT_ENTITY_KIND = "Wavelet";
  private static final String DELTA_ENTITY_KIND = "WaveletDelta";
  private static final String SNAPSHOT_ENTITY_KIND = "WaveletSnapshot";
  private static final String OBJECT_ID = "obj";

  private static class TestModel implements SlobModel {
    public class TestObject implements Slob {
      @Override @Nullable public String snapshot() {
        return snapshotString;
      }

      @Override public void apply(ChangeData<String> payload) throws ChangeRejected {
        // accept any payload, do nothing with it
      }
    }

    @Override
    public Slob create(@Nullable String snapshot) throws InvalidSnapshot {
      return new TestObject();
    }

    @Override
    public List<String> transform(List<ChangeData<String>> clientOps,
        List<ChangeData<String>> serverOps) throws ChangeRejected {
      throw new AssertionError("Not implemented");
    }

    private final String snapshotString;

    TestModel(String snapshotString) {
      this.snapshotString = checkNotNull(snapshotString, "Null snapshotString");
    }
  }

  private final LocalServiceTestHelper helper =
      new LocalServiceTestHelper(
          new LocalDatastoreServiceTestConfig()
              .setDefaultHighRepJobPolicyUnappliedJobPercentage(30),
          new LocalFileServiceTestConfig());
  private final CheckedDatastore datastore = new CheckedDatastore(
      DatastoreServiceFactory.getDatastoreService());

  @Override protected void setUp() throws Exception {
    super.setUp();
    helper.setUp();
    ApiProxyLocal proxy = (ApiProxyLocal) ApiProxy.getDelegate();
    // HACK(ohler): Work around "illegal blobKey" crash.
    proxy.setProperty(LocalBlobstoreService.NO_STORAGE_PROPERTY, "true");
  }

  @Override protected void tearDown() throws Exception {
    helper.tearDown();
    super.tearDown();
  }

  public void testSizeEstimates() throws Exception {
    CheckedTransaction tx = new CheckedTransaction() {
        @Override
        public Entity get(Key key) throws PermanentFailure, RetryableFailure {
          return null;
        }

        @Override
        public Map<Key, Entity> get(Iterable<Key> keys) throws PermanentFailure, RetryableFailure {
          throw new AssertionError("Not implemented");
        }

        @Override
        public CheckedPreparedQuery prepare(Query q) {
          return new CheckedPreparedQuery() {
            @Override public CheckedIterator asIterator(final FetchOptions options)
                throws PermanentFailure, RetryableFailure {
              return CheckedIterator.EMPTY;
            }

            @Override public List<Entity> asList(final FetchOptions options)
                throws PermanentFailure, RetryableFailure {
              return ImmutableList.of();
            }

            @Override public int countEntities(final FetchOptions options)
                throws PermanentFailure, RetryableFailure {
              throw new AssertionError("Not implemented");
            }

            @Override public Entity asSingleEntity() throws PermanentFailure, RetryableFailure {
              throw new AssertionError("Not implemented");
            }
          };
        }

        @Override
        public Key put(Entity e) throws PermanentFailure, RetryableFailure {
          throw new AssertionError("Not implemented");
        }

        @Override
        public List<Key> put(Iterable<Entity> e) throws PermanentFailure, RetryableFailure {
          throw new AssertionError("Not implemented");
        }

        @Override
        public void delete(Key... keys) throws PermanentFailure, RetryableFailure {
          throw new AssertionError("Not implemented");
        }

        @Override
        public TaskHandle enqueueTask(Queue queue, TaskOptions task)
            throws PermanentFailure, RetryableFailure {
          throw new AssertionError("Not implemented");
        }

        @Override
        public void rollback() {
          throw new AssertionError("Not implemented");
        }

        @Override
        public void commit() throws PermanentFailure, RetryableFailure {
          throw new AssertionError("Not implemented");
        }

        @Override
        public boolean isActive() {
          throw new AssertionError("Not implemented");
        }

        @Override
        public void close() {
          throw new AssertionError("Not implemented");
        }

        @Override
        public void runAfterCommit(Runnable r) {
          throw new AssertionError("Not implemented");
        }
      };

    SlobId objectId = new SlobId(OBJECT_ID);
    ClientId clientId = new ClientId("s");
    String payload = "{\"a\": 5}";

    // I didn't track down exactly where the 12 comes from.
    int encodingOverhead = 12;
    int idSize = ROOT_ENTITY_KIND.length() + OBJECT_ID.length() + encodingOverhead;
    int versionSize = 8;
    int deltaSize = idSize + DELTA_ENTITY_KIND.length() + versionSize
        + MutationLog.DELTA_CLIENT_ID_PROPERTY.length() + clientId.getId().length()
        + MutationLog.DELTA_OP_PROPERTY.length() + payload.length();
    int snapshotSize = idSize + SNAPSHOT_ENTITY_KIND.length() + versionSize
        + MutationLog.SNAPSHOT_DATA_PROPERTY.length() + SNAPSHOT_STRING.length();
    log.info("deltaSize=" + deltaSize
        + ", snapshotSize=" + snapshotSize);
    assertEquals(56, deltaSize);
    assertEquals(225, snapshotSize);
    ChangeData<String> delta = new ChangeData<String>(clientId, payload);

    MutationLog mutationLog =
        new MutationLog(datastore,
            ROOT_ENTITY_KIND, DELTA_ENTITY_KIND, SNAPSHOT_ENTITY_KIND,
            new MutationLog.DefaultDeltaEntityConverter(),
            tx, objectId, new TestModel(SNAPSHOT_STRING), new MutationLog.StateCache(1),
            OversizedPropertyMover.NULL_LISTENER);
    MutationLog.Appender appender = mutationLog.prepareAppender().getAppender();

    assertEquals(0, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals( 1 * deltaSize + 0 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals( 2 * deltaSize + 0 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals( 3 * deltaSize + 0 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals( 4 * deltaSize + 0 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals( 5 * deltaSize + 0 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals( 6 * deltaSize + 0 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals( 7 * deltaSize + 0 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals( 8 * deltaSize + 0 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals( 9 * deltaSize + 1 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals(10 * deltaSize + 1 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals(11 * deltaSize + 1 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals(12 * deltaSize + 1 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals(13 * deltaSize + 1 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals(14 * deltaSize + 2 * snapshotSize, appender.estimatedBytesStaged());
    appender.append(delta);
    assertEquals(15 * deltaSize + 2 * snapshotSize, appender.estimatedBytesStaged());
  }

  String makeMassiveString() {
    int numCodePoints = 1 << 19;
    StringBuilder b = new StringBuilder(
        // Overestimate.
        numCodePoints * 2);
    int nextCp = 0;
    for (int i = 0; i < numCodePoints; i++) {
      b.appendCodePoint(nextCp);
      if (i + 1 < numCodePoints && i % 80 == 79) {
        b.append("\n");
        i++;
      }
      nextCp = (nextCp + 1) & 0x10ffff;
      while (Utf16Util.isSurrogate(nextCp) || !Utf16Util.isCodePointValid(nextCp)) {
        //log.info("Skipping cp " + nextCp);
        nextCp = (nextCp + 1) & 0x10ffff;
      }
    }
    return "" + b;
  }

  public void testOversizedProperties() throws Exception {
    String massiveString = makeMassiveString();
    final List<String> movedProperties = Lists.newArrayList();
    SlobId objectId = new SlobId(OBJECT_ID);
    CheckedTransaction tx = datastore.beginTransaction();
    MutationLog mutationLog =
        new MutationLog(datastore,
            ROOT_ENTITY_KIND, DELTA_ENTITY_KIND, SNAPSHOT_ENTITY_KIND,
            new MutationLog.DefaultDeltaEntityConverter(),
            tx, objectId, new TestModel(massiveString), new MutationLog.StateCache(1),
            new OversizedPropertyMover.BlobWriteListener() {
              @Override public void blobCreated(
                  Key entityKey, MovableProperty property, BlobKey blobKey) {
                movedProperties.add(property.getPropertyName());
              }
              @Override public void blobDeleted(
                  Key entityKey, MovableProperty property, BlobKey blobKey) {
                throw new AssertionError();
              }
            });
    MutationLog.Appender appender = mutationLog.prepareAppender().getAppender();
    ClientId clientId = new ClientId("fake-clientid");
    // This will generate one snapshot.
    appender.appendAll(
        ImmutableList.of(
            new ChangeData<String>(clientId, "delta 0 " + massiveString),
            new ChangeData<String>(clientId, "delta 1 " + massiveString),
            new ChangeData<String>(clientId, "delta 2 " + massiveString)));
    // This will generate another snapshot.
    appender.append(new ChangeData<String>(clientId, "delta 3 " + massiveString));
    appender.finish();
    tx.commit();
    assertEquals(ImmutableList.of("op", "op", "op", "op", "Data", "Data"), movedProperties);

    CheckedTransaction tx2 = datastore.beginTransaction();
    MutationLog mutationLog2 =
        // TODO: eliminate code duplication
        new MutationLog(datastore,
            ROOT_ENTITY_KIND, DELTA_ENTITY_KIND, SNAPSHOT_ENTITY_KIND,
            new MutationLog.DefaultDeltaEntityConverter(),
            tx2, objectId, new TestModel(massiveString), new MutationLog.StateCache(1),
            new OversizedPropertyMover.BlobWriteListener() {
              @Override public void blobCreated(
                  Key entityKey, MovableProperty property, BlobKey blobKey) {
                throw new AssertionError();
              }
              @Override public void blobDeleted(
                  Key entityKey, MovableProperty property, BlobKey blobKey) {
                throw new AssertionError();
              }
            });
    DeltaIterator deltas = mutationLog2.forwardHistory(0, null);
    assertEquals("delta 0 " + massiveString, deltas.next().getPayload());
    assertEquals("delta 1 " + massiveString, deltas.next().getPayload());
    assertEquals("delta 2 " + massiveString, deltas.next().getPayload());
    assertEquals("delta 3 " + massiveString, deltas.next().getPayload());
    assertFalse(deltas.hasNext());
  }

}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
    ''' <summary>
    ''' Recommends the "Lib" keyword in external method declarations.
    ''' </summary>
    Friend Class LibKeywordRecommender
        Inherits AbstractKeywordRecommender

        Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword)
            If context.FollowsEndOfStatement Then
                Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
            End If

            If context.TargetToken.IsChildToken(Of DeclareStatementSyntax)(Function(declaration) declaration.Identifier) Then
                Return SpecializedCollections.SingletonEnumerable(New RecommendedKeyword("Lib", VBFeaturesResources.Introduces_a_clause_that_identifies_the_external_file_DLL_or_code_resource_containing_an_external_procedure))
            Else
                Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
            End If
        End Function
    End Class
End Namespace


text:
#ifndef _CORE_BLUETOOTH_H_
#warning Please do not import this header file directly. Use <CoreBluetooth/CoreBluetooth.h> instead.
#endif

#import <CoreBluetooth/CBDefines.h>

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

CB_EXTERN NSString * const CBErrorDomain;

/*!
 * @enum CBError
 *
 * @discussion The possible errors returned during LE transactions.
 */
typedef NS_ENUM(NSInteger, CBError) {
	CBErrorUnknown												= 0,
	CBErrorInvalidParameters NS_ENUM_AVAILABLE(NA, 6_0)			= 1,
	CBErrorInvalidHandle NS_ENUM_AVAILABLE(NA, 6_0)				= 2,
	CBErrorNotConnected NS_ENUM_AVAILABLE(NA, 6_0)				= 3,
	CBErrorOutOfSpace NS_ENUM_AVAILABLE(NA, 6_0)				= 4,
	CBErrorOperationCancelled NS_ENUM_AVAILABLE(NA, 6_0)		= 5,
	CBErrorConnectionTimeout NS_ENUM_AVAILABLE(NA, 6_0)			= 6,
	CBErrorPeripheralDisconnected NS_ENUM_AVAILABLE(NA, 6_0)	= 7,
	CBErrorUUIDNotAllowed NS_ENUM_AVAILABLE(NA, 6_0)			= 8,
	CBErrorAlreadyAdvertising NS_ENUM_AVAILABLE(NA, 6_0)		= 9,
	CBErrorConnectionFailed NS_ENUM_AVAILABLE(NA, 7_1)			= 10,
	CBErrorConnectionLimitReached NS_ENUM_AVAILABLE(NA, 9_0)	= 11
};

CB_EXTERN NSString * const CBATTErrorDomain;

typedef NS_ENUM(NSInteger, CBATTError) {
	CBATTErrorSuccess NS_ENUM_AVAILABLE(NA, 6_0)	= 0x00,
	CBATTErrorInvalidHandle							= 0x01,
	CBATTErrorReadNotPermitted						= 0x02,
	CBATTErrorWriteNotPermitted						= 0x03,
	CBATTErrorInvalidPdu							= 0x04,
	CBATTErrorInsufficientAuthentication			= 0x05,
	CBATTErrorRequestNotSupported					= 0x06,
	CBATTErrorInvalidOffset							= 0x07,
	CBATTErrorInsufficientAuthorization				= 0x08,
	CBATTErrorPrepareQueueFull						= 0x09,
	CBATTErrorAttributeNotFound						= 0x0A,
	CBATTErrorAttributeNotLong						= 0x0B,
	CBATTErrorInsufficientEncryptionKeySize			= 0x0C,
	CBATTErrorInvalidAttributeValueLength			= 0x0D,
	CBATTErrorUnlikelyError							= 0x0E,
	CBATTErrorInsufficientEncryption				= 0x0F,
	CBATTErrorUnsupportedGroupType					= 0x10,
	CBATTErrorInsufficientResources					= 0x11
};

NS_ASSUME_NONNULL_END


text:
package net.signalr.client;

import net.signalr.client.util.concurrent.promise.Promise;

/**
 * Represents the connecting connection state.
 */
final class ConnectingConnectionState implements ConnectionState {

    /**
     * The start result.
     */
    private final Promise<Void> _promise;

    /**
     * Initializes a new instance of the {@link ConnectingConnectionState} class.
     *
     * @param promise The start result.
     */
    public ConnectingConnectionState(final Promise<Void> promise) {
        if (promise == null) {
            throw new IllegalArgumentException("Promise must not be null");
        }

        _promise = promise;
    }

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

    @Override
    public void addHeader(final ConnectionContext context, final String name, final String value) {
        throw new IllegalStateException("Connection is connecting");
    }

    @Override
    public void addParameter(final ConnectionContext context, final String name, final String value) {
        throw new IllegalStateException("Connection is connecting");
    }

    @Override
    public void setConnectionData(final ConnectionContext context, final String connectionData) {
        throw new IllegalStateException("Connection is connecting");
    }

    @Override
    public void notifyConnectionListener(final ConnectionListener listener) {
        listener.onConnecting();
    }

    @Override
    public Promise<Void> connect(final ConnectionContext context) {
        return _promise;
    }

    @Override
    public Promise<Void> reconnect(final ConnectionContext context) {
        throw new IllegalStateException("Connection is connecting");
    }

    @Override
    public Promise<Void> disconnect(final ConnectionContext context) {
        throw new IllegalStateException("Connection is connecting");
    }

    @Override
    public Promise<Void> send(final ConnectionContext context, final String message) {
        throw new IllegalStateException("Connection is connecting");
    }
}


text:
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Skybrud.OpenGraph")]
[assembly: AssemblyDescription("Small library for generating Open Graph meta tags")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Skybrud.dk")]
[assembly: AssemblyProduct("Skybrud.OpenGraph")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("06138d2b-db8a-436e-a014-93e5a051405f")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]


text:
#include "Common.h"

///
/// EXTENSION CONSTRUCTOR/DESTRUCTOR
///

Extension::Extension(LPRDATA _rdPtr, LPEDATA edPtr, fpcob cobPtr)
    : rdPtr(_rdPtr), rhPtr(_rdPtr->rHo.hoAdRunHeader), Runtime(_rdPtr)
{
    /*
        Link all your action/condition/expression functions to their IDs to match the
        IDs in the JSON here
    */

	LinkAction(0, StartRecording);
	LinkAction(1, StopRecording);
	/*LinkAction(2, LogStream);
	LinkAction(3, LogData);*/

    LinkCondition(0, OnError);
	LinkCondition(1, IsConnected);

	LinkExpression(0, LastError);
	LinkExpression(1, Attention);
	LinkExpression(2, Meditation);
	LinkExpression(3, Delta);
	LinkExpression(4, Theta);
	LinkExpression(5, Alpha1);
	LinkExpression(6, Alpha2);
	LinkExpression(7, Beta1);
	LinkExpression(8, Beta2);
	LinkExpression(9, Gamma1);
	LinkExpression(10,Gamma2);
	LinkExpression(11,PoorSignal);
	LinkExpression(12,DllVersion);

    /*
        This is where you'd do anything you'd do in CreateRunObject in the original SDK

        It's the only place you'll get access to edPtr at runtime, so you should transfer
        anything from edPtr to the extension class here.

    */
	dllVersion=0;
	connectionId=0;
	errCode=0;
	_snprintf_s(comPortName, _countof(comPortName),_countof(comPortName),"\\\\.\\COM");
	_snwprintf_s(lastError, _countof(lastError),ERRORSIZE,ErrorS[noError]);
	_snwprintf_s(errorTemp, _countof(errorTemp),ERRORSIZE,ErrorS[noError]);
	isConnected = false;
	baudRate = BaudRateValues[edPtr->baudRateId];

	dllVersion = TG_GetDriverVersion();
	connectionId = TG_GetNewConnectionId();
}

Extension::~Extension()
{
    /*
        This is where you'd do anything you'd do in DestroyRunObject in the original SDK.
        (except calling destructors and other such atrocities, because that's automatic in Edif)
    */
	TG_FreeConnection( connectionId );

}

short Extension::Handle()
{
    /*
       If your extension will draw to the MMF window you should first
       check if anything about its display has changed :

           if (rdPtr->roc.rcChanged)
              return REFLAG_DISPLAY;
           else
              return 0;

       You will also need to make sure you change this flag yourself
       to 1 whenever you want to redraw your object

       If your extension won't draw to the window, but it still needs
       to do something every MMF loop use :

            return 0;

       If you don't need to do something every loop, use :

            return REFLAG_ONESHOT;

       This doesn't mean this function can never run again. If you want MMF
       to handle your object again (causing this code to run) use this function:

            Runtime.Rehandle();

       At the end of the loop this code will run

    */

	// Will not be called next loop
	return REFLAG_ONESHOT;
}

short Extension::Display()
{
    /*
       If you return REFLAG_DISPLAY in Handle() this routine will run.
    */

    // Ok
    return 0;
}

short Extension::Pause()
{

    // Ok
    return 0;
}

short Extension::Continue()
{

    // Ok
    return 0;
}

bool Extension::Save(HANDLE File)
{
	bool OK = false;

    #ifndef VITALIZE

	    // Save the object's data here

	    OK = true;

    #endif

	return OK;
}

bool Extension::Load(HANDLE File)
{
	bool OK = false;

    #ifndef VITALIZE

	    // Load the object's data here

	    OK = true;

    #endif

	return OK;
}

// These are called if there's no function linked to an ID

void Extension::Action(int ID, LPRDATA rdPtr, long param1, long param2)
{

}

long Extension::Condition(int ID, LPRDATA rdPtr, long param1, long param2)
{

    return false;
}

long Extension::Expression(int ID, LPRDATA rdPtr, long param)
{

    return 0;
}


text:
package org.apache.flink.runtime.scheduler.adaptive;

import org.apache.flink.api.common.JobStatus;
import org.apache.flink.runtime.checkpoint.CheckpointCoordinator;
import org.apache.flink.runtime.checkpoint.CheckpointScheduling;
import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
import org.apache.flink.runtime.executiongraph.ExecutionGraph;
import org.apache.flink.runtime.scheduler.ExecutionGraphHandler;
import org.apache.flink.runtime.scheduler.OperatorCoordinatorHandler;
import org.apache.flink.runtime.scheduler.exceptionhistory.ExceptionHistoryEntry;
import org.apache.flink.runtime.scheduler.stopwithsavepoint.StopWithSavepointStoppingException;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.concurrent.FutureUtils;

import org.slf4j.Logger;

import javax.annotation.Nullable;

import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledFuture;

/**
 * Tracks a "stop with savepoint" operation. The incoming "savepointFuture" is coming from the
 * {@link CheckpointCoordinator}, which takes care of triggering a savepoint, and then shutting down
 * the job (on success).
 *
 *
This state is tracking the future to act accordingly on it. The savepoint path (= the result
 * of the operation) is made available via the "operationFuture" to the user. This operation is only
 * considered successfully if the "savepointFuture" completed successfully, and the job reached the
 * terminal state FINISHED.
 *
 *
This state has to cover several failure scenarios, depending on whether the savepoint
 * succeeeds/fails and the job succeeds/fails/keeps running.
 *
 *

 *
Savepoint succeeds, job succeeds - The happy path we like to see.
 *
Savepoint fails, job fails - The generic failure case. Something happened during
 *       checkpointing on the TM side that also failed the task; fail the savepoint operation and
 *       restart the job.
 *
Savepoint succeeds, job fails - Some issue occurred in notifyCheckpointComplete or during
 *       the job shutdown. Fail the savepoint operation and job, but inform the user about the
 *       created savepoint.
 *
Savepoint fails, job keeps running - The savepoint failed due to an error on the JM side,
 *       before we ever triggered anything on the TM side. Fail the savepoint operation, but keep
 *       the job running.
 *

 *
 *
This is further complicated by this information being transmitted via 2 separate RPCs from
 * TM->JM, with the {@code savepointFuture} not being completed in the main thread, introducing
 * ordering/lateness issues. Be careful to not liberally use {@link Context#runIfState(State,
 * Runnable, Duration)} because it can result in a message being lost if multiple operations are
 * queued and the first initiates a state transition.
 */
class StopWithSavepoint extends StateWithExecutionGraph {

    private final Context context;
    /**
     * The result future of this operation, containing the path to the savepoint. This is the future
     * that other components (e.g., the REST API) wait for.
     *
     *
Must only be completed successfully if the savepoint was created and the job has FINISHED.
     */
    private final CompletableFuture<String> operationFuture;

    private final CheckpointScheduling checkpointScheduling;

    @Nullable private Throwable operationFailureCause;
    private boolean hasPendingStateTransition = false;

    // be careful when applying operations on this future that can trigger state transitions,
    // as several other methods do the same and we mustn't trigger multiple transitions!
    private final CompletableFuture<String> internalSavepointFuture = new CompletableFuture<>();

    StopWithSavepoint(
            Context context,
            ExecutionGraph executionGraph,
            ExecutionGraphHandler executionGraphHandler,
            OperatorCoordinatorHandler operatorCoordinatorHandler,
            CheckpointScheduling checkpointScheduling,
            Logger logger,
            ClassLoader userCodeClassLoader,
            CompletableFuture<String> savepointFuture,
            List<ExceptionHistoryEntry> failureCollection) {
        super(
                context,
                executionGraph,
                executionGraphHandler,
                operatorCoordinatorHandler,
                logger,
                userCodeClassLoader,
                failureCollection);
        this.context = context;
        this.checkpointScheduling = checkpointScheduling;
        this.operationFuture = new CompletableFuture<>();

        FutureUtils.assertNoException(
                internalSavepointFuture.exceptionally(
                        cause -> {
                            onSavepointFailure(cause);
                            return null;
                        }));

        // this is a roundabout way of splicing the completion of the future into the main thread.
        // allows other methods to apply synchronous operations on the future without having to
        // worry about the main thread.
        savepointFuture.handle(
                (savepoint, error) -> {
                    context.runIfState(
                            this,
                            () -> {
                                if (error != null) {
                                    internalSavepointFuture.completeExceptionally(error);
                                } else {
                                    internalSavepointFuture.complete(savepoint);
                                }
                            },
                            Duration.ZERO);
                    return null;
                });
    }

    @Override
    public void onLeave(Class<? extends State> newState) {
        this.operationFuture.completeExceptionally(
                new FlinkException(
                        "Stop with savepoint operation could not be completed.",
                        operationFailureCause));

        super.onLeave(newState);
    }

    /**
     * Cancel the job and fail the savepoint operation future.
     *
     *
We don't wait for the {@link #internalSavepointFuture} here so that users can still cancel
     * a job if the savepoint takes too long (or gets stuck).
     *
     *
Since we don't actually cancel the savepoint (for which there is no API to do so), there
     * is a small risk that the job is cancelled at the very moment that the savepoint completes,
     * causing it to not be reported to the user. See FLINK-28127.
     */
    @Override
    public void cancel() {
        operationFailureCause = new FlinkException("The job was cancelled.");
        context.goToCanceling(
                getExecutionGraph(),
                getExecutionGraphHandler(),
                getOperatorCoordinatorHandler(),
                getFailures());
    }

    @Override
    public JobStatus getJobStatus() {
        return JobStatus.RUNNING;
    }

    /**
     * Restarts the checkpoint scheduler and, if only the savepoint failed without a task failure /
     * job termination, transitions back to {@link Executing}.
     *
     *
This method must assume that {@link #onFailure}/{@link #onGloballyTerminalState} MAY
     * already be waiting for the savepoint operation to complete, itching to trigger a state
     * transition (hence the {@link #hasPendingStateTransition} check).
     *
     *
If the above is violated (e.g., by always transitioning into another state), then
     * depending on other implementation details something very bad will happen, like the scheduler
     * crashing the JVM because it attempted multiple state transitions OR effectively dropping the
     * onFailure/onGloballyTerminalState call OR we trigger state transitions while we are already
     * in another state.
     *
     *
For maintainability reasons this method should not mutate any state that affects state
     * transitions in other methods.
     */
    private void onSavepointFailure(Throwable cause) {
        // revert side-effect of Executing#stopWithSavepoint
        checkpointScheduling.startCheckpointScheduler();
        // a task failed concurrently; defer the error handling to onFailure()
        // otherwise we will attempt 2 state transitions, which is forbidden
        if (!hasPendingStateTransition) {
            operationFailureCause = cause;
            context.goToExecuting(
                    getExecutionGraph(),
                    getExecutionGraphHandler(),
                    getOperatorCoordinatorHandler(),
                    getFailures());
        }
    }

    @Override
    void onFailure(Throwable cause) {
        if (hasPendingStateTransition) {
            // the error handling remains the same independent of how many tasks have failed
            // we don't want to initiate the same state transition multiple times, so we exit early
            // this could also be achieved via Context#runIfState, but that'd spam the logs
            return;
        }
        hasPendingStateTransition = true;

        FutureUtils.assertNoException(
                internalSavepointFuture.handle(
                        (savepoint, savepointError) -> {
                            // if savepointError is null then the savepoint has been created
                            // successfully, but the job failed while committing side effects,
                            // so we enrich the exception for the user
                            final Throwable ex =
                                    savepointError != null
                                            ? cause
                                            : new StopWithSavepointStoppingException(
                                                    savepoint, getJobId(), cause);
                            operationFailureCause = ex;
                            FailureResultUtil.restartOrFail(
                                    context.howToHandleFailure(ex), context, this);
                            return null;
                        }));
    }

    @Override
    void onGloballyTerminalState(JobStatus globallyTerminalState) {
        if (globallyTerminalState == JobStatus.FINISHED) {
            // do not set this in other cases
            // handleGlobalFailure circles back to onFailure()
            hasPendingStateTransition = true;
            FutureUtils.assertNoException(
                    internalSavepointFuture.handle(
                            (savepoint, error) -> {
                                Preconditions.checkState(
                                        error == null,
                                        "A savepoint should never fail after a job has been terminated via stop-with-savepoint.");
                                completeOperationAndGoToFinished(savepoint);
                                return null;
                            }));
        } else {
            handleGlobalFailure(
                    new FlinkException(
                            "Job did not reach the FINISHED state while performing stop-with-savepoint."));
        }
    }

    private void completeOperationAndGoToFinished(String savepoint) {
        operationFuture.complete(savepoint);
        context.goToFinished(ArchivedExecutionGraph.createFrom(getExecutionGraph()));
    }

    CompletableFuture<String> getOperationFuture() {
        return operationFuture;
    }

    interface Context
            extends StateWithExecutionGraph.Context,
                    StateTransitions.ToCancelling,
                    StateTransitions.ToExecuting,
                    StateTransitions.ToFailing,
                    StateTransitions.ToRestarting {

        /**
         * Asks how to handle the failure.
         *
         * @param failure failure describing the failure cause
         * @return {@link FailureResult} which describes how to handle the failure
         */
        FailureResult howToHandleFailure(Throwable failure);

        /**
         * Runs the given action after the specified delay if the state is the expected state at
         * this time.
         *
         * @param expectedState expectedState describes the required state to run the action after
         *     the delay
         * @param action action to run if the state equals the expected state
         * @param delay delay after which the action should be executed
         * @return a ScheduledFuture representing pending completion of the task
         */
        ScheduledFuture<?> runIfState(State expectedState, Runnable action, Duration delay);
    }

    static class Factory implements StateFactory<StopWithSavepoint> {
        private final Context context;

        private final ExecutionGraph executionGraph;

        private final ExecutionGraphHandler executionGraphHandler;

        private final OperatorCoordinatorHandler operatorCoordinatorHandler;

        private final CheckpointScheduling checkpointScheduling;

        private final Logger logger;

        private final ClassLoader userCodeClassLoader;

        private final CompletableFuture<String> savepointFuture;

        private final List<ExceptionHistoryEntry> failureCollection;

        Factory(
                Context context,
                ExecutionGraph executionGraph,
                ExecutionGraphHandler executionGraphHandler,
                OperatorCoordinatorHandler operatorCoordinatorHandler,
                CheckpointScheduling checkpointScheduling,
                Logger logger,
                ClassLoader userCodeClassLoader,
                CompletableFuture<String> savepointFuture,
                List<ExceptionHistoryEntry> failureCollection) {
            this.context = context;
            this.executionGraph = executionGraph;
            this.executionGraphHandler = executionGraphHandler;
            this.operatorCoordinatorHandler = operatorCoordinatorHandler;
            this.checkpointScheduling = checkpointScheduling;
            this.logger = logger;
            this.userCodeClassLoader = userCodeClassLoader;
            this.savepointFuture = savepointFuture;
            this.failureCollection = failureCollection;
        }

        @Override
        public Class<StopWithSavepoint> getStateClass() {
            return StopWithSavepoint.class;
        }

        @Override
        public StopWithSavepoint getState() {
            return new StopWithSavepoint(
                    context,
                    executionGraph,
                    executionGraphHandler,
                    operatorCoordinatorHandler,
                    checkpointScheduling,
                    logger,
                    userCodeClassLoader,
                    savepointFuture,
                    failureCollection);
        }
    }
}


text:
package io.sweetheart.examples.chapter03.item08;

import java.util.concurrent.atomic.AtomicInteger;

public class CounterPoint extends Point {
    private static final AtomicInteger counter = new AtomicInteger();

    public CounterPoint(int x, int y) {
        super(x, y);
        counter.incrementAndGet();
    }

    public int numberCreated() {
        return counter.get();
    }
}


text:
package com.atlassian.plugins.codegen.modules.jira;

import com.atlassian.plugins.codegen.annotations.Dependencies;
import com.atlassian.plugins.codegen.annotations.Dependency;
import com.atlassian.plugins.codegen.annotations.JiraPluginModuleCreator;
import com.atlassian.plugins.codegen.modules.AbstractPluginModuleCreator;
import com.atlassian.plugins.codegen.modules.PluginModuleLocation;
import com.atlassian.plugins.codegen.modules.common.component.ComponentModuleCreator;
import com.atlassian.plugins.codegen.modules.common.component.ComponentProperties;

/**
 * @since 3.6
 */
@JiraPluginModuleCreator
@Dependencies({
        @Dependency(groupId = "org.mockito", artifactId = "mockito-all", version = "1.8.5", scope = "test")
        , @Dependency(groupId = "org.apache.httpcomponents", artifactId = "httpclient", version = "4.1.1", scope = "test")
})
public class RPCModuleCreator extends AbstractPluginModuleCreator<RPCProperties>
{

    public static final String MODULE_NAME = "RPC Endpoint Plugin";
    private static final String TEMPLATE_PREFIX = "templates/jira/rpc/";

    //stub
    private static final String CLASS_TEMPLATE = TEMPLATE_PREFIX + "RPCService.java.vtl";
    private static final String INTERFACE_TEMPLATE = TEMPLATE_PREFIX + "RPCServiceInterface.java.vtl";
    private static final String UNIT_TEST_TEMPLATE = "templates/generic/GenericTest.java.vtl";
    private static final String FUNC_TEST_TEMPLATE = TEMPLATE_PREFIX + "RPCServiceFuncTest.java.vtl";

    //examples
    private static final String EXAMPLE_CLASS_TEMPLATE = TEMPLATE_PREFIX + "Example" + CLASS_TEMPLATE;

    private static final String SOAP_PLUGIN_MODULE_TEMPLATE = TEMPLATE_PREFIX + "soap-rpc-plugin.xml.vtl";
    private static final String XML_PLUGIN_MODULE_TEMPLATE = TEMPLATE_PREFIX + "xml-rpc-plugin.xml.vtl";

    @Override
    public void createModule(PluginModuleLocation location, RPCProperties props) throws Exception
    {
        String packageName = props.getPackage();
        String classname = props.getClassname();
        String iClassname = props.getInterfaceClass();
        String iPackage = props.getInterfacePackage();

        if (props.includeExamples())
        {
            templateHelper.writeJavaClassFromTemplate(EXAMPLE_CLASS_TEMPLATE, classname, location.getSourceDirectory(), packageName, props);
        } else
        {

            //interface
            templateHelper.writeJavaClassFromTemplate(INTERFACE_TEMPLATE, iClassname, location.getSourceDirectory(), iPackage, props);

            //main class
            templateHelper.writeJavaClassFromTemplate(CLASS_TEMPLATE, classname, location.getSourceDirectory(), packageName, props);

            //unit test
            templateHelper.writeJavaClassFromTemplate(UNIT_TEST_TEMPLATE, testClassname(iClassname), location.getTestDirectory(), packageName, props);

        }

        //add the component element first
        ComponentProperties cProps = new ComponentProperties(props.getFullyQualifiedClassname());
        cProps.setFullyQualifiedInterface(props.getFullyQualifiedInterface());
        cProps.setModuleKey(props.getModuleKey() + "-component");
        cProps.setModuleName(props.getModuleName() + " Component");
        cProps.setDescription("Component For " + props.getModuleName());
        cProps.setDescriptionI18nKey(props.getDescriptionI18nKey() + ".component");
        cProps.setNameI18nKey(props.getNameI18nKey() + ".component");
        cProps.setGenerateClass(false);
        cProps.setGenerateInterface(false);
        cProps.setIncludeExamples(false);
        //

        ComponentModuleCreator componentCreator = new ComponentModuleCreator();
        componentCreator.createModule(location, cProps);

        //now add the rpc element
        if (props.isSoap())
        {
            addModuleToPluginXml(SOAP_PLUGIN_MODULE_TEMPLATE, location, props);
        } else
        {
            addModuleToPluginXml(XML_PLUGIN_MODULE_TEMPLATE, location, props);
        }

    }

    @Override
    public String getModuleName()
    {
        return MODULE_NAME;
    }
}


text:
module PostUserService
  def self.create(post_user)
    post_user.validate

    if post_user.post.try(:limited?)
      post_user.errors.add(:post, I18n.t('service.post_user.limited'))
      return false
    end

    post_user.save
  end
end


text:
import xadmin
from xadmin import views
from models import IDC, Host, MaintainLog, HostGroup, AccessRecord
from xadmin.layout import Main, TabHolder, Tab, Fieldset, Row, Col, AppendedText, Side
from xadmin.plugins.inline import Inline
from xadmin.plugins.batch import BatchChangeAction
from deploy.models import Deploy

class MainDashboard(object):
    widgets = [
        [
            {"type": "html", "title": "Test Widget", "content": "
 Welcome to ops system!

Join Online Group:
QQ xxxxxxx
"},
            {"type": "list", "model": "cmdb.host", 'params': {'o':'-create_time'}},
        ],
        [
            {"type": "qbutton", "title": "Quick Start", "btns": [{'model': Host}, {'model':IDC}, {'title': "baidu", 'url': "http://www.baidu.com"}]},
            {"type": "addform", "model": MaintainLog},
        ]
    ]
xadmin.sites.site.register(views.website.IndexView, MainDashboard)

class BaseSetting(object):
    enable_themes = False
    use_bootswatch = False
xadmin.sites.site.register(views.BaseAdminView, BaseSetting)

class GlobalSetting(object):
    site_title = 'hdfax运维管理平台'
    site_footer  = '2016恒大金服'
    global_search_models = [Host]
    global_models_icon = {
        Host: 'fa fa-laptop', IDC: 'fa fa-cloud', MaintainLog: 'fa fa-wrench'
    }
    def get_site_menu(self):
        return (
            {'title': '资产管理', 'perm': self.get_model_perm(Host, 'change'), 'menus':(
                {'title':'主机管理', 'icon': 'fa fa-laptop', 'url': self.get_model_url(Host, 'changelist')},
                {'title': '主机组管理',  'url': self.get_model_url(HostGroup, 'changelist')},
                {'title':'IDC管理', 'icon': 'fa fa-cloud', 'url': self.get_model_url(IDC, 'changelist')},
                {'title':'维修日志', 'icon': 'fa fa-wrench', 'url': self.get_model_url(MaintainLog, 'changelist')},
                {'title':'访问日志','url': self.get_model_url(AccessRecord, 'changelist')},
            )},
            {'title': '部署管理', 'perm': self.get_model_perm(Deploy, 'change'), 'menus':(
                {'title':'线上发布','url': self.get_model_url(Deploy, 'changelist')},
            )},
            {'title': '页面测试', 'perm': '', 'menus':(
                {'title':'ansible','url': "/ansible/"},
            )},
        )
    menu_style = 'default'#'accordion'
xadmin.sites.site.register(views.CommAdminView, GlobalSetting)

class MaintainInline(object):
    model = MaintainLog
    extra = 1
    style = 'accordion'

class IDCAdmin(object):
    list_display = ('name', 'address', 'description', 'create_time')
    list_display_links = ('name',)
    wizard_form_list = [
        ('First\'s Form', ('name', 'address')),
        ('Second Form', ('contact', 'telphone', 'qq', 'customer_id', 'description' )),
    ]

    search_fields = ['name']
    #relfield_style = 'fk-ajax'
    relfield_style = 'fk-select'
    reversion_enable = True

    actions = [BatchChangeAction, ]
    #batch_fields = ('contact', 'create_time')
    batch_fields = ('contact', 'groups')

class HostAdmin(object):
    #def open_web(self, instance):
    #    return "Open" % instance.ip
    #open_web.short_description = "Acts"
    #open_web.allow_tags = True
    #open_web.is_column = True

    list_display = ('name', 'mip', 'bip', 'vip', 'service_type',
                    'zone_type', 'status', 'description')
    list_display_links = ('name',)

    raw_id_fields = ('idc',)
    style_fields = {'system': "radio-inline"}

    search_fields = ['name', 'bip', 'mip', 'vip']
    list_filter = ['idc', 'status', 'core_num', 'hard_disk', 'memory', ('service_type',xadmin.filters.MultiSelectFieldListFilter), ('zone_type',xadmin.filters.MultiSelectFieldListFilter)]

    list_quick_filter = ['service_type', 'zone_type', {'field':'idc__name','limit':10}]
#    list_bookmarks = [{'title': "Need Guarantee", 'query': {'status__exact': 2}, 'order': ('-guarantee_date',), 'cols': ('brand', 'guarantee_date', 'service_type')}]

    show_detail_fields = ('idc',)
    list_editable = (
        'name', 'bip', 'mip', 'vip', 'service_type', 'zone_type', 'status', 'description')
    save_as = True

    #aggregate_fields = {"guarantee_date": "min"}
    grid_layouts = ('table', 'thumbnails')

    form_layout = (
        Main(
            TabHolder(
                Tab('Comm Fields',
                    Fieldset('主机信息',
                             Row('name', 'system'),
                             Row('bip', 'mip', 'vip'),
                             description=""
                             ),
                    Inline(MaintainLog),
                    ),
                Tab('Extend Fields',
                    Fieldset('扩展信息',
                             Row('idc', 'service_type', 'zone_type'),
                             Row('core_num', AppendedText(
                                 'hard_disk', 'G'), AppendedText('memory', "G")),
                             'status'
                             ),
                    ),
            ),
        ),
    )
    inlines = [MaintainInline]
    reversion_enable = True

#    data_charts = {
#        "host_service_type_counts": {'title': u"Host service type count", "x-field": "service_type", "y-field": ("service_type",),
#                              "option": {
#                                         "series": {"bars": {"align": "center", "barWidth": 0.8,'show':True}},
#                                         "xaxis": {"aggregate": "count", "mode": "categories"},
#                                         },
#                              },
#    }

class HostGroupAdmin(object):
    list_display = ('name', 'description')
    list_display_links = ('name',)

    search_fields = ['name']
#    style_fields = {'hosts': 'checkbox-inline'}

class MaintainLogAdmin(object):
    list_display = (
        'host', 'maintain_type', 'time', 'operator', 'note')
    list_display_links = ('host',)

    list_filter = ['host', 'maintain_type', 'time', 'operator']
    search_fields = ['note']

    form_layout = (
        Col("col2",
            Fieldset('Record data',
                     'time', 'note',
                     css_class='unsort short_label no_title'
                     ),
            span=9, horizontal=True
            ),
        Col("col1",
            Fieldset('Comm data',
                     'host', 'maintain_type'
                     ),
            Fieldset('Maintain details',
                     'operator'
                     ),
            span=3
            )
    )
    reversion_enable = True

class AccessRecordAdmin(object):
    def avg_count(self, instance):
        return int(instance.view_count / instance.user_count)
    avg_count.short_description = "Avg Count"
    avg_count.allow_tags = True
    avg_count.is_column = True

    list_display = ('date', 'user_count', 'view_count', 'avg_count')
    list_display_links = ('date',)

    list_filter = ['date', 'user_count', 'view_count']
    actions = None
    aggregate_fields = {"user_count": "sum", 'view_count': "sum"}

    refresh_times = (3, 5, 10)
    data_charts = {
        "user_count": {'title': u"User Report", "x-field": "date", "y-field": ("user_count", "view_count"), "order": ('date',)},
        "avg_count": {'title': u"Avg Report", "x-field": "date", "y-field": ('avg_count',), "order": ('date',)},
        "per_month": {'title': u"Monthly Users", "x-field": "_chart_month", "y-field": ("user_count", ),
                              "option": {
                                         "series": {"bars": {"align": "center", "barWidth": 0.8,'show':True}},
                                         "xaxis": {"aggregate": "sum", "mode": "categories"},
                                         },
                            },
    }

    def _chart_month(self,obj):
        return obj.date.strftime("%B")

xadmin.sites.site.register(Host, HostAdmin)
xadmin.sites.site.register(HostGroup, HostGroupAdmin)
xadmin.sites.site.register(MaintainLog, MaintainLogAdmin)
xadmin.sites.site.register(IDC, IDCAdmin)
xadmin.sites.site.register(AccessRecord, AccessRecordAdmin)


text:
import json

import requests
from django.http import HttpResponse
from django.conf import settings

def stackoverflow(request, userid):
    user_r = requests.get('{0}users/{1}'.format(
        settings.STACKOVERFLOW_API_URL,
        userid))

    timeline_r = requests.get('{0}users/{1}/timeline'.format(
        settings.STACKOVERFLOW_API_URL,
        userid))

    context = {'user': user_r.json["users"][0]}
    context.update({'timeline': timeline_r.json["user_timelines"]})

    return HttpResponse(content=json.dumps(context),
                        status=timeline_r.status_code,
                        content_type=timeline_r.headers['content-type'])


text:
from .fetchers import NUGatewaySecuredDatasFetcher

from .fetchers import NUMetadatasFetcher

from .fetchers import NUGlobalMetadatasFetcher

from bambou import NURESTObject

class NUGatewaySecurity(NURESTObject):
    """ Represents a GatewaySecurity in the VSD

        Notes:
            This object represents the gateway security object
    """

    __rest_name__ = "gatewaysecurity"
    __resource_name__ = "gatewaysecurities"

    ## Constants

    CONST_ENTITY_SCOPE_GLOBAL = "GLOBAL"

    CONST_ENTITY_SCOPE_ENTERPRISE = "ENTERPRISE"

    def __init__(self, **kwargs):
        """ Initializes a GatewaySecurity instance

            Notes:
                You can specify all parameters while calling this methods.
                A special argument named `data` will enable you to load the
                object from a Python dictionary

            Examples:
                >>> gatewaysecurity = NUGatewaySecurity(id=u'xxxx-xxx-xxx-xxx', name=u'GatewaySecurity')
                >>> gatewaysecurity = NUGatewaySecurity(data=my_dict)
        """

        super(NUGatewaySecurity, self).__init__()

        # Read/Write Attributes

        self._last_updated_by = None
        self._gateway_id = None
        self._revision = None
        self._entity_scope = None
        self._associated_entity_type = None
        self._external_id = None

        self.expose_attribute(local_name="last_updated_by", remote_name="lastUpdatedBy", attribute_type=str, is_required=False, is_unique=False)
        self.expose_attribute(local_name="gateway_id", remote_name="gatewayID", attribute_type=str, is_required=False, is_unique=False)
        self.expose_attribute(local_name="revision", remote_name="revision", attribute_type=int, is_required=False, is_unique=False)
        self.expose_attribute(local_name="entity_scope", remote_name="entityScope", attribute_type=str, is_required=False, is_unique=False, choices=[u'ENTERPRISE', u'GLOBAL'])
        self.expose_attribute(local_name="associated_entity_type", remote_name="associatedEntityType", attribute_type=str, is_required=False, is_unique=False)
        self.expose_attribute(local_name="external_id", remote_name="externalID", attribute_type=str, is_required=False, is_unique=True)

        # Fetchers

        self.gateway_secured_datas = NUGatewaySecuredDatasFetcher.fetcher_with_object(parent_object=self, relationship="child")

        self.metadatas = NUMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child")

        self.global_metadatas = NUGlobalMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child")

        self._compute_args(**kwargs)

    # Properties

    @property
    def last_updated_by(self):
        """ Get last_updated_by value.

            Notes:
                ID of the user who last updated the object.

                This attribute is named `lastUpdatedBy` in VSD API.

        """
        return self._last_updated_by

    @last_updated_by.setter
    def last_updated_by(self, value):
        """ Set last_updated_by value.

            Notes:
                ID of the user who last updated the object.

                This attribute is named `lastUpdatedBy` in VSD API.

        """
        self._last_updated_by = value

    @property
    def gateway_id(self):
        """ Get gateway_id value.

            Notes:
                The gateway associated with this object. This is a read only attribute

                This attribute is named `gatewayID` in VSD API.

        """
        return self._gateway_id

    @gateway_id.setter
    def gateway_id(self, value):
        """ Set gateway_id value.

            Notes:
                The gateway associated with this object. This is a read only attribute

                This attribute is named `gatewayID` in VSD API.

        """
        self._gateway_id = value

    @property
    def revision(self):
        """ Get revision value.

            Notes:
                change revision number for the gateway security data

        """
        return self._revision

    @revision.setter
    def revision(self, value):
        """ Set revision value.

            Notes:
                change revision number for the gateway security data

        """
        self._revision = value

    @property
    def entity_scope(self):
        """ Get entity_scope value.

            Notes:
                Specify if scope of entity is Data center or Enterprise level

                This attribute is named `entityScope` in VSD API.

        """
        return self._entity_scope

    @entity_scope.setter
    def entity_scope(self, value):
        """ Set entity_scope value.

            Notes:
                Specify if scope of entity is Data center or Enterprise level

                This attribute is named `entityScope` in VSD API.

        """
        self._entity_scope = value

    @property
    def associated_entity_type(self):
        """ Get associated_entity_type value.

            Notes:
                Object type of the associated entity.

                This attribute is named `associatedEntityType` in VSD API.

        """
        return self._associated_entity_type

    @associated_entity_type.setter
    def associated_entity_type(self, value):
        """ Set associated_entity_type value.

            Notes:
                Object type of the associated entity.

                This attribute is named `associatedEntityType` in VSD API.

        """
        self._associated_entity_type = value

    @property
    def external_id(self):
        """ Get external_id value.

            Notes:
                External object ID. Used for integration with third party systems

                This attribute is named `externalID` in VSD API.

        """
        return self._external_id

    @external_id.setter
    def external_id(self, value):
        """ Set external_id value.

            Notes:
                External object ID. Used for integration with third party systems

                This attribute is named `externalID` in VSD API.

        """
        self._external_id = value


text:
namespace pts
{
	struct Type;
	struct NamedType;
	struct PointerType;
	struct TupleType;
	struct ArraySliceType;
	struct FixedArrayType;
	struct VariadicArrayType;
	struct FunctionType;

	struct Type
	{
		virtual ~Type() { }
		virtual std::string str();

		NamedType* toNamedType();
		TupleType* toTupleType();
		PointerType* toPointerType();
		FunctionType* toFunctionType();
		FixedArrayType* toFixedArrayType();
		ArraySliceType* toArraySliceType();
		VariadicArrayType* toVariadicArrayType();

		bool isNamedType();
		bool isTupleType();
		bool isPointerType();
		bool isFunctionType();
		bool isArraySliceType();
		bool isFixedArrayType();
		bool isVariadicArrayType();

		Location loc;

		protected:
			Type(const Location& l) : loc(l) { }
	};

	struct InferredType : Type
	{
		virtual ~InferredType() { }
		InferredType(const Location& l) : Type(l) { }

		virtual std::string str() override { return "?"; }

		static InferredType* get();
	};

	struct NamedType : Type
	{
		virtual ~NamedType() { }

		virtual std::string str() override;
		std::string name;

		PolyArgMapping_t genericMapping;

		static NamedType* create(const Location& l, const std::string& s);
		static NamedType* create(const Location& l, const std::string& s, const PolyArgMapping_t& genericMapping);

		// private:
		explicit NamedType(const Location& l, const std::string& n) : Type(l), name(n) { }
	};

	struct PointerType : Type
	{
		virtual ~PointerType() { }
		explicit PointerType(const Location& l, pts::Type* b, bool mut) : Type(l), base(b), isMutable(mut) { }
		virtual std::string str() override;

		pts::Type* base = 0;
		bool isMutable = false;
	};

	struct TupleType : Type
	{
		virtual ~TupleType() { }
		explicit TupleType(const Location& l, const std::vector<pts::Type*>& ts) : Type(l), types(ts) { }
		virtual std::string str() override;

		std::vector<pts::Type*> types;
	};

	// int[x], where x *is* a literal (eg. 4, 10, 0xF00D)
	struct FixedArrayType : Type
	{
		virtual ~FixedArrayType() { }
		explicit FixedArrayType(const Location& l, pts::Type* b, size_t s) : Type(l), base(b), size(s) { }
		virtual std::string str() override;

		pts::Type* base = 0;
		size_t size = 0;
	};

	struct VariadicArrayType : Type
	{
		virtual ~VariadicArrayType() { }
		explicit VariadicArrayType(const Location& l, pts::Type* b) : Type(l), base(b) { }
		virtual std::string str() override;

		pts::Type* base = 0;
	};

	struct ArraySliceType : Type
	{
		virtual ~ArraySliceType() { }
		explicit ArraySliceType(const Location& l, pts::Type* b, bool m) : Type(l), base(b), mut(m) { }
		virtual std::string str() override;

		pts::Type* base = 0;
		bool mut = false;
	};

	struct FunctionType : Type
	{
		virtual ~FunctionType() { }
		explicit FunctionType(const Location& l, const std::vector<pts::Type*>& args, pts::Type* ret) : Type(l), argTypes(args), returnType(ret) { }
		virtual std::string str() override;

		util::hash_map<std::string, TypeConstraints_t> genericTypes;
		std::vector<pts::Type*> argTypes;
		pts::Type* returnType = 0;
	};
}


text:
#include "System.h"
#include "Version.h"

#include <assert.h>
// Needs moving out of here!
#ifdef _WIN32
#include <windows.h>
#include <shellapi.h>
#endif

#include "DinodeckLua.h"
#include "Game.h"
#include "reflect/Reflect.h"
#include "Vector.h"
#include "LuaState.h"
#include "Settings.h"

Reflect System::Meta("System", System::Bind);

static int lua_IsWideScreen(lua_State* state)
{
    lua_pushboolean(state, true);
    return 1;
}

// These need to get the Game injection.
static int lua_GetScreenBottomRight(lua_State* state)
{
    Vector* vector = new (lua_newuserdata(state, sizeof(Vector))) Vector();;
    assert(vector != NULL);
    luaL_getmetatable(state, "Vector");
    lua_setmetatable(state, -2);
    Game* game = (Game*) LuaState::GetFromRegistry(state, "Game");
    assert(game);
    int width = game->GetSettings()->width;
    int height = game->GetSettings()->height;
    vector->SetXyzw(width/2, -height/2, 0, 0);
    return 1;
}

static int lua_GetScreenTopLeft(lua_State* state)
{
    Vector* vector = new (lua_newuserdata(state, sizeof(Vector))) Vector();
    assert(vector != NULL);
    luaL_getmetatable(state, "Vector");
    lua_setmetatable(state, -2);
    Game* game = (Game*) LuaState::GetFromRegistry(state, "Game");
    assert(game);
    int width = game->GetSettings()->width;
    int height = game->GetSettings()->height;
    vector->SetXyzw(-width/2, height/2, 0, 0);
    return 1;
}

static int lua_ScreenWidth(lua_State* state)
{
    Game* game = (Game*) LuaState::GetFromRegistry(state, "Game");
    assert(game);
    lua_pushnumber(state, game->GetSettings()->width);
    return 1;
}

static int lua_ScreenHeight(lua_State* state)
{
    Game* game = (Game*) LuaState::GetFromRegistry(state, "Game");
    assert(game);
    lua_pushnumber(state, game->GetSettings()->height);
    return 1;
}

static int lua_OpenURL(lua_State* state)
{
    if(!lua_isstring(state, -1))
    {
        luaL_typerror(state, -1, "string");
        return 0;
    }
    else
    {
#ifdef _WIN32
        const char* url = lua_tostring(state, -1);
        ShellExecute(GetActiveWindow(), "open", url, NULL, NULL, SW_SHOWNORMAL);
#endif
    }
    return 0;
}

static int lua_Version(lua_State* state)
{
    lua_pushstring(state, DINODECK_VERSION);
    return 1;
}

static int lua_Exit(lua_State* state)
{
    Game* game = (Game*) LuaState::GetFromRegistry(state, "Game");
    game->Stop();
    return 0;
}

static const struct luaL_reg luaBinding [] = {
  {"IsWideScreen", lua_IsWideScreen},
  {"ScreenWidth", lua_ScreenWidth},
  {"ScreenHeight", lua_ScreenHeight},
  {"ScreenTopLeft", lua_GetScreenTopLeft},
  {"ScreenBottomRight", lua_GetScreenBottomRight},
  {"OpenURL", lua_OpenURL},
  {"Version", lua_Version},
  {"Exit", lua_Exit},
  {NULL, NULL}  /* sentinel */
};

void System::Bind(LuaState* state)
{
    state->Bind
    (
        System::Meta.Name(),
        luaBinding
    );
}


text:
package io.splicer.adapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import io.realm.Realm;
import io.realm.RealmModel;
import io.realm.RealmObject;
import io.realm.RealmObjectSchema;
import io.splicer.fetcher.WebserviceRequestor;

/**
 * An ArrayAdapter that fetches typesafe objects from a Splicer server
 * to be displayed in a ListView Fragment. So think of it as the connector between a Splicer server and a droid ListView.
 * It holds the retrieved data in either a List or a Realm table and then provides the per-row data via the getRowView callback.
 * This class also is a convenience class that encapsulates functionality such that any derived class
 * simply needs to implement the abstract fetchData() and getRowView() methods.
 * Instantiate this class with the object type that will be held in the Array.
 *
 * @param <T>
 * @author gbinder
 * @see io.splicer.fetcher.JsonFetcher
 */
public abstract class BaseArrayAdapter<T> extends ArrayAdapter<T> implements WebserviceRequestor<T[]> {
    protected final boolean b_useRealmsData = true;
    protected final Context context;
    protected List<T> currentModel;
    //ok, so Realm does not yet have a built-in way to get the rowcount, so we'll use this to keep count if in RealmsData-mode
    protected int rowCount;
    protected int resourceId;

    public BaseArrayAdapter(Context context, int resourceId) {
        super(context, resourceId);
        this.context = context;
        this.currentModel = new ArrayList<T>();
        this.resourceId = resourceId;
    }

    @Override
    public int getCount() {
        if (b_useRealmsData) {
            return rowCount;
        } else {
            return currentModel.size();
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(resourceId, parent, false);

        T obj = null;
        // call subclass
        if (b_useRealmsData) {
            Log.w("BaseArrayAdapter", "Tying the view index to db's PK. This should work provided the PKs are specific to the client's experience, but its probably better to tie the view's index to the position in the database instead.");
            obj = findByKey(position + 1);//note that realm is one-based while getView is zero-based
        } else {
            obj = currentModel.get(position);
        }
        getRowView(rowView, obj);
        return rowView;
    }

    /**
     * implementation of WebServiceRequestor for rest/json:  this method updates this class's model with data just fetched from the server, and then
     * invalidates the view...
     * The droid OS then executes our "view" callback methods: it first calls our getView() method, which then in turn calls getRowView() of any subclasses.
     */
    public void onNetworkSuccess(T[] fetched) {
        Log.d("BaseArrayAdapter", "inside onNetworkSuccess: " + fetched.getClass());
        //set the model member
        if (b_useRealmsData) {
            RealmModel[] realmObjects = (RealmModel[]) fetched;
            //this worked with PKs
            /*
            if (realmObjects != null && realmObjects.length > 0) {
                Realm realm = Realm.getDefaultInstance();
                realm.beginTransaction();
                Log.d("BaseArrayAdapter", "Saving retrieved data to Realm db. count: " + realmObjects.length);
                for (int i = 0; i < realmObjects.length; i++) {
                    realm.copyToRealm(realmObjects[i]);
                }
                realm.commitTransaction();
                //FIXME when should we call realm.close?
                //realm.close();
            }
            */
            Realm realm = Realm.getDefaultInstance();
            List<RealmModel> list = Arrays.asList(realmObjects);
            realm.beginTransaction();
            realm.copyToRealm(list);
            realm.commitTransaction();
            rowCount = realmObjects.length;
        } else {
            currentModel = Arrays.asList(fetched);
        }
        if(rowCount == 0 && currentModel != null && currentModel.size() == 0 ){
            Log.w("UserArrayAdapter", "Empty Array returned from server.");
        }
        // invalidate the view
        this.notifyDataSetChanged();
    }

    /**
     * implementation of WebServiceRequestor
     */
    public void onNetworkFail(Exception e) {
        Log.e("UserArrayAdapter", "onNetworkFail. Exception: " + e.getMessage());
        showAlert(context, "Server Error", e.getMessage());
    }

    public static void showAlert(Context activity, String title, String message) {
        //Log.i("Displaying Alert", message);
        AlertDialog.Builder alert = new AlertDialog.Builder(activity);
        alert.setTitle(title);
        alert.setMessage(message);

        alert.setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alert.show();
    }

    public abstract void fetchData();

    /**
     * Needed because the Realm call needs to know T.class, which generics does not support
     *
     * @param position
     * @return
     */
    public abstract T findByKey(int position);

    /**
     * Convenience callback: in your subclass, this gets called instead of getView().
     * Implement this method to display one row in an appropriate ListView.
     * If you don't want to use this convenience method, you can certainly override the getView method instead.
     *
     * @param rowView
     * @param obj
     */
    protected abstract void getRowView(View rowView, T obj);

}


text:
package org.eclipse.rdf4j.query.algebra.evaluation.function.xsd;

import java.math.BigInteger;
import java.util.Optional;

import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil;
import org.eclipse.rdf4j.model.vocabulary.XSD;
import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException;

/**
 * Abstract superclass for {@link CastFunction}s that cast their arguments to an xsd:integer or one of its derived
 * types.
 *
 * @author Jeen Broekstra
 */
public abstract class IntegerCastFunction extends CastFunction {

	@Override
	protected Literal convert(ValueFactory valueFactory, Value value) throws ValueExprEvaluationException {
		if (value instanceof Literal) {
			Literal literal = (Literal) value;
			IRI datatype = literal.getDatatype();

			if (XMLDatatypeUtil.isNumericDatatype(datatype)) {
				if (XMLDatatypeUtil.isIntegerDatatype(datatype)) {
					String lexicalValue = XMLDatatypeUtil.collapseWhiteSpace(literal.getLabel());
					if (isValidForDatatype(lexicalValue)) {
						return valueFactory.createLiteral(lexicalValue, getXsdDatatype());
					}
				}

				// decimals, floats and doubles must be processed
				// separately, see
				// http://www.w3.org/TR/xpath-functions/#casting-from-primitive-to-primitive
				BigInteger integerValue;
				if (XSD.DECIMAL.equals(datatype) || XMLDatatypeUtil.isFloatingPointDatatype(datatype)) {
					integerValue = literal.decimalValue().toBigInteger();
				} else {
					integerValue = literal.integerValue();
				}
				try {
					return createTypedLiteral(valueFactory, integerValue).orElseThrow(() -> typeError(literal, null));
				} catch (ArithmeticException | NumberFormatException e) {
					throw typeError(literal, e);
				}
			} else if (datatype.equals(XSD.BOOLEAN)) {
				try {
					return createTypedLiteral(valueFactory, literal.booleanValue())
							.orElseThrow(() -> typeError(literal, null));
				} catch (IllegalArgumentException e) {
					throw typeError(literal, e);
				}
			}
		}
		throw typeError(value, null);
	}

	/**
	 * create a {@link Literal} with the specific datatype for the supplied {@link BigInteger} value.
	 *
	 * @param vf           the {@link ValueFactory} to use for creating the {@link Literal}
	 * @param integerValue the integer value to use for creating the {@link Literal}
	 * @return an {@link Optional} literal value, which may be empty if the supplied integerValue can not be
	 *         successfully converted to the specific datatype.
	 * @throws ArithmeticException if an error occurs when attempting to convert the supplied value to a value of the
	 *                             specific datatype.
	 */
	protected abstract Optional<Literal> createTypedLiteral(ValueFactory vf, BigInteger integerValue)
			throws ArithmeticException;

	/**
	 * create a {@link Literal} with the specific datatype for the supplied boolean value.
	 *
	 * @param vf           the {@link ValueFactory} to use for creating the {@link Literal}
	 * @param booleanValue the boolean value to use for creating the {@link Literal}
	 * @return an {@link Optional} literal value, which may be empty if the supplied boolean value can not be
	 *         successfully converted to the specific datatype.
	 */
	protected Optional<Literal> createTypedLiteral(ValueFactory vf, boolean booleanValue) {
		return Optional.of(vf.createLiteral(booleanValue ? "1" : "0", getXsdDatatype()));
	}
}


text:
/*
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StackExchange.Redis;
using Newtonsoft.Json;

namespace QMGAzure
{
    public class RedisCache
    {
        private IDatabase _cache;
        private static string _connectionString;
        public static ConnectionMultiplexer _connection
        {
            get
            {
                return lazyConnection.Value;
            }
        }

        public RedisCache(string connectionString)
        {
            _connectionString = connectionString;
            _cache = _connection.GetDatabase();
        }

        public RedisCache() { }

        public void SetString(string key, string value)
        {
            _cache.StringSetAsync(key, value);
        }

        public async Task<string> GetString(string key)
        {
            return await _cache.StringGetAsync(key);
        }

        public void SetObject(string key, object value)
        {
            _cache.StringSetAsync(key, JsonConvert.SerializeObject(value));
        }

        public async Task<T> GetObject<T>(string key)
        {
            var obj = await _cache.StringGetAsync(key);
            if(!obj.IsNull)
            {
                return JsonConvert.DeserializeObject<T>(obj);
            }else
            {
                return default(T);
            }
        }

        private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            return ConnectionMultiplexer.Connect(_connectionString);
        });
    }
}
*/


text:
package com.nanosai.gridops.tcp;

/**
 * This class can keep track of messages that have been sent asynchronously to remote nodes.
 * The message tracker keeps a list of the messages by message id and time sent, so you
 * can search this list to see which messages were sent and when.
 */
public class TcpMessageTracker {

    public TcpMessage[] messages = null;
    public long[] messageIds = null;
    public long[] messageSentTimes = null;
    public int nextMessageIndex = 0;

    public TcpMessageTracker(int messageCount) {
        this.messages = new TcpMessage[messageCount];
        this.messageIds = new long[messageCount];
        this.messageSentTimes = new long[messageCount];
    }

    public void insertMessage(TcpMessage message, long messageId, long messageSentTime) {
        this.messages[this.nextMessageIndex] = message;
        this.messageIds[this.nextMessageIndex] = messageId;
        this.messageSentTimes[this.nextMessageIndex++] = messageSentTime;
    }

    public int findMessage(long messageId){
        for(int i = 0; i < this.nextMessageIndex; i++) {
            if(this.messageIds[i] == messageId){
                return i;
            }
        }
        return -1;
    }

    public void removeMessage(long messageId){
        int messageIndex = findMessage(messageId);
        for(int i=messageIndex; i<this.nextMessageIndex-1; i++){
            this.messages[i] = this.messages[i+1];
            this.messageIds[i] = this.messageIds[i+1];
            this.messageSentTimes[i] = this.messageSentTimes[i+1];
            this.nextMessageIndex--;
        }
    }

}


text:
12U Ice Breaker Champions

                            Cobalt

13U Ice Breaker Champions

                            Barracks

11U Ice Breaker Champions Classic

                                Boone County Bandits

Tournaments

JWS tournaments is proud to partner with Nations Baseball
           for youth baseball. Nations Baseball & JWS tournaments offers incredible youth
            baseball tournament opportunities for all interested teams at all skill levels.

View details »

Property Management

Let us evaluate and provide feedback on how we can improve your field(s).  O
            ur ABI machines make infield maintenance and grooming a breeze.
            Call us at 513-258-0541 and schedule an appointment today.

Affiliates

               ?


text:
<?php

?>

<?php
// only show when there is a GV balance
  if ($customer_has_gv_balance ) {
?>

<?php require($template->get_template_dir('tpl_modules_send_or_spend.php',DIR_WS_TEMPLATE, $current_page_base,'templates'). '/tpl_modules_send_or_spend.php'); ?>

<?php
  }
?>

<?php if ($messageStack->size('checkout_cash') > 0) echo $messageStack->output('checkout_cash'); ?>

<?php echo HEADING_TITLE; ?>

<?php echo TEXT_YOUR_ORDER_NUMBER . $zv_orders_id; ?>

<?php if (DEFINE_CHECKOUT_SUCCESS_STATUS >= 1 and DEFINE_CHECKOUT_SUCCESS_STATUS <= 2) { ?>

<?php
/**
 * require the html_defined text for checkout success
 */
  require($define_page);
?>

<?php } ?>

<?php
if (isset($_SESSION['payment_method_messages']) && $_SESSION['payment_method_messages'] != '') {
?>

  <?php echo $_SESSION['payment_method_messages']; ?>

<?php
}
?>

<?php
  if (isset($_SESSION['customer_guest_id'])) {
    echo TEXT_CHECKOUT_LOGOFF_GUEST;
  } elseif (isset($_SESSION['customer_id'])) {
    echo TEXT_CHECKOUT_LOGOFF_CUSTOMER;
  }
?>

<a href="<?php echo zen_href_link(FILENAME_LOGOFF, '', 'SSL'); ?>"><?php echo zen_image_button(BUTTON_IMAGE_LOG_OFF , BUTTON_LOG_OFF_ALT); ?>

<?php
/**
 * The following creates a list of checkboxes for the customer to select if they wish to be included in product-notification
 * announcements related to products they've just purchased.
 **/
    if ($flag_show_products_notification == true) {
?>
<fieldset id="csNotifications">
<legend><?php echo TEXT_NOTIFY_PRODUCTS; ?></legend>
<?php echo zen_draw_form('order', zen_href_link(FILENAME_CHECKOUT_SUCCESS, 'action=update', 'SSL')); ?>

<?php foreach ($notificationsArray as $notifications) { ?>
<?php echo zen_draw_checkbox_field('notify[]', $notifications['products_id'], true, 'id="notify-' . $notifications['counter'] . '"') ;?>
<label class="checkboxLabel" for="<?php echo 'notify-' . $notifications['counter']; ?>"><?php echo $notifications['products_name']; ?>

<?php } ?>

<?php echo zen_image_submit(BUTTON_IMAGE_UPDATE, BUTTON_UPDATE_ALT); ?>

</form>
</fieldset>
<?php
    }
?>

<?php
  if (DOWNLOAD_ENABLED == 'true') require($template->get_template_dir('tpl_modules_downloads.php',DIR_WS_TEMPLATE, $current_page_base,'templates'). '/tpl_modules_downloads.php');
?>

<?php echo TEXT_SEE_ORDERS;?>

<?php echo TEXT_CONTACT_STORE_OWNER;?>

<?php echo TEXT_THANKS_FOR_SHOPPING; ?>


text: Node authentication code.  No app.


text:
module Spree
	module Admin
    class RolesController < ResourceController
      before_filter :load_permissions, :only => [:edit, :new, :create, :update]
      before_filter :restrict_unless_editable, :only => [:edit, :update]

      def index
        @roles = Spree::Role.page(params[:page])
      end

      def destroy
        @role = Spree::Role.find(params[:id])
        @role.destroy

        flash[:success] = Spree.t('notice_messages.role_deleted')

        respond_with(@role) do |format|
          format.html { redirect_to collection_url }
          format.js  { render_js_for_destroy }
        end
      end

      private
        def permitted_resource_params
          params.require(:role).permit(:name, :permission_ids => [])
        end

        def load_permissions
          @permissions = Spree::Permission.visible.all
        end

        def restrict_unless_editable
          redirect_to admin_roles_path unless @role.editable?
        end
    end
  end
end


text:
//
//  YSProgressView.m
//  12.25.YSSlider
//
//  Created by Color on 15/12/25.
//  Copyright © 2015年 com.moon-box. All rights reserved.
//

#import "YSProgressView.h"

@interface YSProgressView ()

/**
 *  进度条 progressView
 */
@property (nonatomic, strong) UIView *progressView;

/**
 *  progressView Rect
 */
@property (nonatomic) CGRect rect_progressView;

/**
 *  限制高度大小
 *
 *
 */
- (void)_setHeightRestrictionOfFrame:(CGFloat)height;

@end

@implementation YSProgressView

- (UIView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIView alloc] initWithFrame:CGRectZero];
        _progressView.backgroundColor = [UIColor redColor];
        [self addSubview:self.progressView];
    }
    return _progressView;
}

#pragma mark -  initWithFrame
-(void)awakeFromNib{
    [super awakeFromNib];

    self.backgroundColor = [UIColor colorWithRed:0.937 green:0.958 blue:1.000 alpha:1.000];

    [self _setHeightRestrictionOfFrame:self.frame.size.height];
}

#pragma mark - Privite Method
- (void)_setHeightRestrictionOfFrame:(CGFloat)height
{
    CGRect rect = self.frame;

    _progressHeight = MIN(height, 100.0);
    _progressHeight = MAX(_progressHeight, 5.0);

    self.frame = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, _progressHeight);
    //+++++++++++++++++++

    self.rect_progressView = CGRectZero;

    _rect_progressView.size.height = _progressHeight;
    self.progressView.frame = self.rect_progressView;

    self.layer.cornerRadius = self.progressView.layer.cornerRadius =  _progressHeight / 2.0;

}

#pragma mark - Setter

- (void)setProgressHeight:(CGFloat)progressHeight
{
    [self _setHeightRestrictionOfFrame:progressHeight];
}

- (void)setProgressTintColor:(UIColor *)progressTintColor
{
    _progressTintColor = progressTintColor;

    self.backgroundColor = _progressTintColor;
}

- (void)setTrackTintColor:(UIColor *)trackTintColor
{
    _trackTintColor = trackTintColor;

    self.progressView.backgroundColor = _trackTintColor;
}

- (void)setProgressValue:(CGFloat)progressValue
{
    _progressValue = progressValue;

    NSLog(@"%f  %f",progressValue,self.bounds.size.width);

//    _progressValue = MIN(progressValue, self.bounds.size.width);

    _rect_progressView.size.width = _progressValue;

    CGFloat maxValue = self.bounds.size.width;

    double durationValue = (_progressValue/2.0) / maxValue + .5;

    [UIView animateWithDuration:durationValue animations:^{

        self.progressView.frame = _rect_progressView;

    }];
}

@end