text:
package com.intellij.jsonpath.psi.impl;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.intellij.jsonpath.psi.JsonPathTypes.*;
import com.intellij.jsonpath.psi.JsonPathStringLiteralMixin;
import com.intellij.jsonpath.psi.*;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;

public class JsonPathStringLiteralImpl extends JsonPathStringLiteralMixin implements JsonPathStringLiteral {

  public JsonPathStringLiteralImpl(@NotNull ASTNode node) {
    super(node);
  }

  public void accept(@NotNull JsonPathVisitor visitor) {
    visitor.visitStringLiteral(this);
  }

  @Override
  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof JsonPathVisitor) accept((JsonPathVisitor)visitor);
    else super.accept(visitor);
  }

  @Override
  public @NotNull List<Pair<TextRange, String>> getTextFragments() {
    return JsonPathPsiUtils.getTextFragments(this);
  }

}


text:
'use strict';

//
// Expose the anchor Pagelet.
//
require('./pagelet').extend({
  view: '{{brand}}/anchor/view.hbs',
  js: '{{brand}}/anchor/base.js',

  //
  // Cortex.JS, the client-side framework is required to run client-side javascript
  //
  dependencies: [
    '../node_modules/cortex.js/dist/cortex.dev.js'
  ],

  //
  // Default data for the anchor hyperlink, can be changed by using `set`.
  //
  defaults: {
    href: '#',
    class: '',
    text: 'I scroll down, I hate jumping'
  },

  /**
   * Called after Pagelet construction, queue client side JS.
   *
   * @api private
   */
  initialize: function initialize() {
    this.queue.enlist('loader', { apps: [ 'anchor' ] });
    return this;
  }
}).on(module);

redpajama_set_name: RedPajamaGithub


text:
all:
	erl -noshell -run edoc_run application "'jabberlang'" '".."'\
		'[{def, {vsn, "trunk"}}, {dir, "."}, {stylesheet, "stylesheet.css"}, {preprocess, true}]'\
		-s erlang halt


text:
require 'mspec/runner/actions/tally'
require 'mspec/runner/actions/timer'
require 'mspec/runner/actions/filter'
require 'mspec/runner/actions/tag'
require 'mspec/runner/actions/taglist'
require 'mspec/runner/actions/tagpurge'
require 'mspec/runner/actions/debug'
require 'mspec/runner/actions/gdb'


text:
package com.amazonaws.services.managedblockchain.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;

import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.managedblockchain.model.*;
import com.amazonaws.transform.Marshaller;

import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * VoteOnProposalRequest Marshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class VoteOnProposalRequestProtocolMarshaller implements Marshaller<Request<VoteOnProposalRequest>, VoteOnProposalRequest> {

    private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
            .requestUri("/networks/{networkId}/proposals/{proposalId}/votes").httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false)
            .hasPayloadMembers(true).serviceName("AmazonManagedBlockchain").build();

    private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;

    public VoteOnProposalRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
        this.protocolFactory = protocolFactory;
    }

    public Request<VoteOnProposalRequest> marshall(VoteOnProposalRequest voteOnProposalRequest) {

        if (voteOnProposalRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            final ProtocolRequestMarshaller<VoteOnProposalRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
                    voteOnProposalRequest);

            protocolMarshaller.startMarshalling();
            VoteOnProposalRequestMarshaller.getInstance().marshall(voteOnProposalRequest, protocolMarshaller);
            return protocolMarshaller.finishMarshalling();
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package cloud.orbit.actors.extensions;

import cloud.orbit.actors.Actor;

import java.util.Collection;
import java.util.function.Predicate;

public interface ActorClassFinder extends ActorExtension
{
    <T extends Actor> Class<? extends T> findActorImplementation(Class<T> actorInterface);
    <T extends Actor> Collection<Class<? extends T>> findActorInterfaces(Predicate<Class<T>> predicate);
}


text:
using System;
using System.Reflection;

namespace MagicOnion
{
    internal static class Utils
    {
        public static bool IsNullable(this Type type)
        {
            return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
        }
    }
}


text:
using System.Threading.Tasks;
using TTMouseclickSimulator.Core.Actions;
using TTMouseclickSimulator.Core.Environment;

namespace TTMouseclickSimulator.Core.ToontownRewritten.Actions.DoodleInteraction
{
    /// <summary>
    /// An action that clicks on the doodle interaction panel (Feed, Scratch, Call)
    /// </summary>
    public class DoodlePanelAction : AbstractAction
    {

        private readonly DoodlePanelButton button;

        public DoodlePanelAction(DoodlePanelButton button)
        {
            this.button = button;
        }

        public override async Task RunAsync(IInteractionProvider provider)
        {
            var c = new Coordinates(1397, 206 + (int)this.button * 49);
            await MouseHelpers.DoSimpleMouseClickAsync(provider, c, VerticalScaleAlignment.Right);
        }

        public override string ToString() => $"Doodle Panel – Button: {this.button}";

        public enum DoodlePanelButton : int
        {
            Feed = 0,
            Scratch = 1,
            Call = 2
        }
    }
}


text:
import { Component, OnInit, Input } from '@angular/core';

import { User } from '../../_models/index';

@Component({
  selector: 'app-sidebar',
  templateUrl: '../../layout/default/sidebar.component.html',
})
export class SidebarComponent implements OnInit {
  @Input() user = new User;

  constructor() { }

  ngOnInit() {
  }
}


text:
package com.palmithor.musicapi.service.external.model;

import com.palmithor.musicapi.JsonTestUtils;
import com.palmithor.musicapi.TestConstants;
import org.junit.Test;

import java.io.FileNotFoundException;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * Test JSON conversion of Cover Art Archive response
 *
 * @author palmithor
 * @since 24.1.2017.
 */
public class CoverArtArchiveResponseJsonConversionTest {

    @Test
    public void testCoverArtArchiveResponse() throws FileNotFoundException {
        CoverArtArchiveResponse coverArtArchiveResponse = JsonTestUtils.readJsonFromFile(TestConstants.JsonFilePaths.COVER_ART_ARCHIVE_RESPONSE, CoverArtArchiveResponse.class);

        assertThat(coverArtArchiveResponse.getReleaseUrl(), is("http://musicbrainz.org/release/a146429a-cedc-3ab0-9e41-1aaf5f6cdc2d"));
        assertThat(coverArtArchiveResponse.getImages(), hasSize(1));
        CoverArtArchiveImage coverArtArchiveImage = coverArtArchiveResponse.getImages().get(0);
        assertThat(coverArtArchiveImage.getId(), is("3012495605"));
        assertThat(coverArtArchiveImage.getEdit(), is(20473306L));
        assertThat(coverArtArchiveImage.getUrl(), is("http://coverartarchive.org/release/a146429a-cedc-3ab0-9e41-1aaf5f6cdc2d/3012495605.jpg"));
        assertThat(coverArtArchiveImage.getTypes(), hasSize(1));
        assertThat(coverArtArchiveImage.getTypes(), contains("Front"));
        assertThat(coverArtArchiveImage.getThumbnails().getLargeImageUrl(), is("http://coverartarchive.org/release/a146429a-cedc-3ab0-9e41-1aaf5f6cdc2d/3012495605-500.jpg"));
        assertThat(coverArtArchiveImage.getThumbnails().getSmallImageUrl(), is("http://coverartarchive.org/release/a146429a-cedc-3ab0-9e41-1aaf5f6cdc2d/3012495605-250.jpg"));
        assertTrue(coverArtArchiveImage.getApproved());
        assertTrue(coverArtArchiveImage.getFront());
        assertFalse(coverArtArchiveImage.getBack());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using hw.DebugFormatter;
using hw.Helper;
using Reni.Basics;
using Reni.Code;
using Reni.Context;
using Reni.Feature;
using Reni.SyntaxTree;
using Reni.TokenClasses;
using Reni.Type;
using Reni.Validation;

namespace Reni.Struct;

sealed class CompoundView : DumpableObject, ValueCache.IContainer
{
    sealed class RecursionWhileObtainingCompoundSizeException : Exception
    {
        [EnableDump]
        readonly CompoundView CompoundView;

        public RecursionWhileObtainingCompoundSizeException
            (CompoundView compoundView) => CompoundView = compoundView;
    }

    sealed class ConverterAccess : DumpableObject, IConversion
    {
        [EnableDump]
        readonly FunctionType Parent;

        [EnableDump]
        readonly CompoundType Type;

        public ConverterAccess(FunctionType parent, CompoundType type)
        {
            Parent = parent;
            Type = type;
        }

        Result IConversion.Execute(Category category)
        {
            var innerResult = ((IConversion)Parent).Execute(category);
            var conversion = Type.Pointer.Mutation(Parent);
            var result = innerResult.ReplaceArg(conversion);
            return result;
        }

        TypeBase IConversion.Source => Type.Pointer;
    }

    static int NextObjectId;

    [EnableDump]
    [Node]
    internal readonly Compound Compound;

    [EnableDump]
    [Node]
    internal readonly int ViewPosition;

    [Node]
    readonly FunctionCache<int, AccessFeature> AccessFeaturesCache;

    [Node]
    readonly FunctionCache<int, FieldAccessType> FieldAccessTypeCache;

    [Node]
    readonly FunctionCache<FunctionSyntax, FunctionBodyType> FunctionBodyTypeCache;

    [Node]
    readonly ValueCache<CompoundType> TypeCache;

    [Node]
    readonly ValueCache<CompoundContext> CompoundContextCache;

    bool IsObtainCompoundSizeActive;

    bool IsDumpPrintResultViaObjectActive;

    bool IsEndPosition => ViewPosition == Compound.Syntax.EndPosition;

    [DisableDump]
    internal ContextBase Context
        => Compound.Parent.CompoundPositionContext(Compound.Syntax, ViewPosition);

    [DisableDump]
    internal CompoundType Type => TypeCache.Value;

    [DisableDump]
    TypeBase IndexType => Compound.IndexType;

    [DisableDump]
    internal CompoundContext CompoundContext => CompoundContextCache.Value;

    [DisableDump]
    internal Size CompoundViewSize
    {
        get
        {
            if(IsObtainCompoundSizeActive)
                throw new RecursionWhileObtainingCompoundSizeException(this);

            try
            {
                IsObtainCompoundSizeActive = true;
                var result = Compound.Size(ViewPosition);
                IsObtainCompoundSizeActive = false;
                return result;
            }
            catch(RecursionWhileObtainingCompoundSizeException)
            {
                IsObtainCompoundSizeActive = false;
                return null;
            }
        }
    }

    [DisableDump]
    internal bool IsHollow => Compound.IsHollow(ViewPosition);

    [DisableDump]
    internal Root Root => Compound.Root;

    [DisableDump]
    internal IEnumerable<IConversion> ConverterFeatures
        => Compound
            .Syntax
            .ConverterFunctions
            .Select(ConversionFunction);

    [DisableDump]
    internal string DumpPrintTextOfType
        => Compound
            .Syntax
            .EndPosition
            .Select(position => Compound.AccessType(ViewPosition, position)?.DumpPrintText ?? "?")
            .Stringify(", ")
            .Surround("(", ")");

    [DisableDump]
    internal IEnumerable<IConversion> MixinConversions
        => Compound
            .Syntax
            .MixInDeclarations
            .Select(AccessFeature);

    [DisableDump]
    ContextReferenceType ContextReferenceType
        => this.CachedValue(() => new ContextReferenceType(this));

    [DisableDump]
    internal IEnumerable<string> DeclarationOptions
    {
        get
        {
            yield return DumpPrintToken.TokenId;
            yield return AtToken.TokenId;

            foreach(var name in Compound.Syntax.AllNames)
                yield return name;
        }
    }

    internal Issue[] Issues => Compound.GetIssues(ViewPosition);
    internal bool HasIssues => Issues.Any();

    [DisableDump]
    internal int Count => Compound.Syntax.Statements.Length;

    internal CompoundView(Compound compound, int viewPosition)
        : base(NextObjectId++)
    {
        Compound = compound;
        ViewPosition = viewPosition;
        CompoundContextCache = new(() => new(this));

        TypeCache = new(() => new(this));

        AccessFeaturesCache
            = new(position => new(this, position));

        FieldAccessTypeCache
            = new(position => new(this, position));

        FunctionBodyTypeCache
            = new(syntax => new(this, syntax));

        StopByObjectIds();
    }

    ValueCache ValueCache.IContainer.Cache { get; } = new();

    protected override string GetNodeDump()
    {
        var result = base.GetNodeDump();
        result += "(" + (Context?.GetContextIdentificationDump() ?? "?") + ")";
        if(HasIssues)
            result += ".AllIssues[" + Issues.Length + "]";
        return result;
    }

    public string GetCompoundChildDump()
        => Compound.GetCompoundIdentificationDump() + PositionDump();

    string PositionDump()
    {
        if(IsEndPosition)
            return "{}";

        var names =
            Compound
                .Syntax
                .NameIndex
                .Where(item => item.Value == ViewPosition)
                .Select(item => item.Key)
                .Stringify("/");

        if(names == "")
            return "@" + ViewPosition;

        return ":" + names;
    }

    public string GetCompoundIdentificationDump()
        => Context.GetContextIdentificationDump();

    internal TypeBase FunctionalType(FunctionSyntax syntax) => FunctionBodyTypeCache[syntax];

    internal AccessFeature AccessFeature(int position) => AccessFeaturesCache[position];

    internal TypeBase AccessType(int position)
    {
        var result = Compound.AccessType(ViewPosition, position);
        if(result.IsHollow)
            return result;

        return FieldAccessTypeCache[position];
    }

    internal Result AccessViaPositionExpression(Category category, Result rightResult)
    {
        var position = rightResult
            .Conversion(IndexType)
            .SmartUn<PointerType>()
            .Evaluate(Compound.Root.ExecutionContext)
            .ToInt32();
        return AccessViaObjectPointer(category, position);
    }

    internal Size FieldOffset(int position)
        => Compound.FieldOffsetFromAccessPoint(ViewPosition, position);

    internal Result DumpPrintResultViaObject(Category category)
    {
        if(IsDumpPrintResultViaObjectActive)
            return Root.VoidType.Result(category, () => CodeBase.DumpPrintText("?"));

        IsDumpPrintResultViaObjectActive = true;
        var result = Root.ConcatPrintResult
        (
            category,
            ViewPosition,
            DumpPrintResultViaObject
        );
        IsDumpPrintResultViaObjectActive = false;
        return result;
    }

    Result AccessViaObjectPointer(Category category, int position)
    {
        var resultType = AccessType(position);
        if(resultType.IsHollow)
            return resultType.Result(category);

        return Type.SmartPointer.Mutation(resultType) & category;
    }

    internal Result AccessViaObject(Category category, int position)
    {
        var resultType = AccessType(position);
        if(resultType.IsHollow)
            return resultType.Result(category);

        return resultType.Result(category, Type.ObjectResult);
    }

    internal Result AccessValueViaObject(Category category, int position)
    {
        var resultType = ValueType(position);
        if(resultType.IsHollow)
            return resultType.Result(category);

        return resultType.Result
            (category, c => Type.ObjectResult(c).AddToReference(() => FieldOffset(position)));
    }

    internal Result ReplaceObjectPointerByContext(Result target)
    {
        var reference = Type.SmartPointer.CheckedReference;
        return target.ReplaceAbsolute(reference, ObjectPointerViaContext);
    }

    IConversion ConversionFunction(FunctionSyntax body)
    {
        IConversion result = new ConverterAccess(Function(body, Root.VoidType), Type);
        var source = result.Source;
        (source == Type.Pointer).Assert(source.Dump);
        (source == result.Result(Category.Code).Code.ArgType).Assert();
        return result;
    }

    internal FunctionType Function(FunctionSyntax body, TypeBase argsType)
        => Compound
            .Root
            .FunctionInstance(this, body, argsType.AssertNotNull());

    internal IEnumerable<FunctionType> Functions(FunctionSyntax body)
        => Compound
            .Root
            .FunctionInstances(this, body);

    internal Result ObjectPointerViaContext(Category category)
    {
        if(IsHollow)
            return Type.Result(category);

        return Type.SmartPointer
            .Result
            (
                category,
                ObjectPointerViaContext,
                () => Closures.Create(Compound)
            );
    }

    Result DumpPrintResultViaObject(Category category, int position)
    {
        var trace = ObjectId == -5 && position == 1;
        StartMethodDump(trace, category, position);
        try
        {
            BreakExecution();
            var accessType = ValueType(position).SmartPointer;
            var genericDumpPrintResult = accessType.GenericDumpPrintResult(category);
            Dump("genericDumpPrintResult", genericDumpPrintResult);
            BreakExecution();
            return ReturnMethodDump
            (
                genericDumpPrintResult.ReplaceAbsolute
                    (accessType.CheckedReference, c => AccessValueViaObject(c, position)));
        }
        finally
        {
            EndMethodDump();
        }
    }

    CodeBase ObjectPointerViaContext()
        => CodeBase.ReferenceCode(Compound).ReferencePlus(CompoundViewSize * -1);

    internal TypeBase ValueType(int position)
    {
        var accessType = Compound
            .AccessType(ViewPosition, position);

        return accessType
            .AssertNotNull()
            .TypeForStructureElement;
    }

    internal IImplementation Find(Definable definable, bool publicOnly)
    {
        var position = Compound.Syntax.Find(definable?.Id, publicOnly);
        return position == null? null : AccessFeature(position.Value);
    }

    internal Result AtTokenResult(Category category, Result rightResult)
        => AccessViaPositionExpression(category, rightResult)
            .ReplaceArg(ObjectPointerViaContext);

    internal Result ContextOperatorResult(Category category)
        => ContextReferenceType.Result(category, ContextOperatorCode);

    CodeBase ContextOperatorCode()
        => IsHollow
            ? CodeBase.Void
            : CodeBase
                .ReferenceCode(Type.ForcedReference)
                .ReferencePlus(CompoundViewSize);

    internal Result ArrayInstanceResult(Category category, TypeBase elementType)
    {
        var elementResults = Compound
            .Syntax
            .Statements
            .Length
            .Select(i => CreateElement(category, i, elementType))
            .ToArray();
        NotImplementedMethod(category, elementType, "elementResults", elementResults);
        return default;
    }

    Result CreateElement(Category category, int index, TypeBase elementType)
        => AccessViaObjectPointer(category, index).Conversion(elementType);
}


text:
class Complement
  DICTIONARY = { 'rna' => 'CGTA', 'dna' => 'GCAU' }

  def self.of_dna(sequence)
    sequence.tr(DICTIONARY['rna'], DICTIONARY['dna'])
  end

  def self.of_rna(sequence)
    sequence.tr(DICTIONARY['dna'], DICTIONARY['rna'])
  end
end


text:
import sys
import argparse
import numpy as np
from props import *

parser = argparse.ArgumentParser()
parser.add_argument('--num_decode', type=int, default=20)
parser.add_argument('--sim_delta', type=float, default=0.4)
parser.add_argument('--prop_delta', type=float, default=0.9)
args = parser.parse_args()

data = [line.split() for line in sys.stdin]
data = [(a,b,float(c),float(d)) for a,b,c,d in data]

def convert(x):
    return None if x == "None" else x

all_div = []
n_succ = 0
for i in range(0, len(data), args.num_decode):
    set_x = set([x[0] for x in data[i:i+args.num_decode]])
    assert len(set_x) == 1

    good = [convert(y) for x,y,sim,prop in data[i:i+args.num_decode] if sim >= args.sim_delta and prop >= args.prop_delta]
    if len(good) == 0:
        continue

    good = list(set(good))
    if len(good) == 1:
        all_div.append(0.0)
        continue
    n_succ += 1

    div = 0.0
    tot = 0
    for i in range(len(good)):
        for j in range(i + 1, len(good)):
            div += 1 - similarity(good[i], good[j])
            tot += 1
    div /= tot
    all_div.append(div)

all_div = np.array(all_div)
print(np.mean(all_div), np.std(all_div))
print(n_succ)


text:
/**
 * @author
 */

/**
 * @class Frame rate counter
 */
function FrameRateCounter() {
    this.lastFrameCount = 0;

    var dateTemp = new Date();
    this.frameLast = dateTemp.getTime();
    delete dateTemp;

    this.frameCtr = 0;
}

FrameRateCounter.prototype.countFrames = function() {
    var dateTemp = new Date();
    this.frameCtr++;

    if (dateTemp.getTime() >= this.frameLast + 1000) {
        this.lastFrameCount = this.frameCtr;
        this.frameLast = dateTemp.getTime();
        this.frameCtr = 0;
    }

    delete dateTemp;
}


text:
static pthread_mutex_t _pthreadLock = PTHREAD_MUTEX_INITIALIZER;

NSString * const GQModuleCenterEventUpdateValueKey = @"GQModuleCenterEventUpdateValueKey";

@interface GQModuleCenter ()

@property (nonatomic, strong) NSMutableArray<NSString *> *moduleClassNames;

@property (nonatomic, strong) NSMutableDictionary<NSString *, NSString *> *moduleActionIdentifierMap;

@property (nonatomic, strong) NSMutableArray<id <GQModuleMiddleware>> *middlewares;

@property (nonatomic, strong) NSMutableDictionary *middlewareMap;

@property (nonatomic, strong) NSNotificationCenter *notificationCenter;

@end

@implementation GQModuleCenter

+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    static GQModuleCenter *_sharedInstance = nil;

    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });

    return _sharedInstance;
}

- (instancetype)init
{
    self = [super init];

    if (self) {
        _middlewares = [NSMutableArray array];
        _middlewareMap = [NSMutableDictionary dictionary];
        _moduleClassNames = [NSMutableArray array];
        _moduleActionIdentifierMap = [NSMutableDictionary dictionary];

        _notificationCenter = [[NSNotificationCenter alloc] init];
    }

    return self;
}

+ (void)registerModuleWithClassName:(NSString *)name
{
    Class cls = NSClassFromString(name);

    // 不是GQModule的子类
    if (![cls isSubclassOfClass:[GQModule class]]) {
        return;
    }

    GQModuleCenter *sharedInstance = [self sharedInstance];

    pthread_mutex_lock(&_pthreadLock);

    if ([sharedInstance.moduleClassNames containsObject:name] == NO) {
        [sharedInstance.moduleClassNames addObject:name];

        for (NSString *identifier in [cls supportActionIdentifiers]) {
            sharedInstance.moduleActionIdentifierMap[identifier] = name;
        }
    }

    pthread_mutex_unlock(&_pthreadLock);
}

+ (void)unregisterModuleWithClassName:(NSString *)name
{
    GQModuleCenter *sharedInstance = [self sharedInstance];

    NSMutableArray *removeKeys = [NSMutableArray array];

    pthread_mutex_lock(&_pthreadLock);

    [sharedInstance.moduleClassNames removeObject:name];

    for (NSString *key in sharedInstance.moduleActionIdentifierMap) {

        if ([sharedInstance.moduleActionIdentifierMap[key] isEqualToString:name]) {
            [removeKeys addObject:key];
        }
    }

    [sharedInstance.moduleActionIdentifierMap removeObjectsForKeys:removeKeys];

    pthread_mutex_unlock(&_pthreadLock);
}

+ (GQModuleResponse *)invokeWithRequest:(GQModuleRequest *)request
{
    GQModuleCenter *sharedInstance = [self sharedInstance];

    // 中间件
    __block GQModuleRequest *processedRequest = request;

    [sharedInstance.middlewares enumerateObjectsUsingBlock:^(id<GQModuleMiddleware>  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

        if ([obj respondsToSelector:@selector(shouldProcessRequest:)]
            && [obj respondsToSelector:@selector(processRequest:)]) {
            if ([obj shouldProcessRequest:request]) {
                processedRequest = [obj processRequest:request];

                *stop = YES;
            }
        }
    }];

    NSString *identifier = processedRequest.identifier;
    NSDictionary *options = processedRequest.options;

    NSString *clsName = [sharedInstance.moduleActionIdentifierMap objectForKey:identifier];

    __block GQModuleResponse *response = nil;

    if (clsName) {
        GQModule *invokeModule = [NSClassFromString(clsName) currentModule];

        id rel = [invokeModule performActionWithIdentifier:identifier
                                      options:options];

        if (rel) {
            response = [[GQModuleResponse alloc] initWithObject:rel module:invokeModule];
        }
    }

    // 中间件
    [sharedInstance.middlewares enumerateObjectsWithOptions:NSEnumerationReverse
                                                 usingBlock:^(id<GQModuleMiddleware>  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

        if ([obj respondsToSelector:@selector(processResponse:withRequest:)]) {
            response = [obj processResponse:response
                                withRequest:processedRequest];
        }

    }];

    // Alway return a GQModuleResponse instance
    if (response == nil) {
        response = [[GQModuleResponse alloc] init];
    }

    return response;
}

@end

@implementation GQModuleCenter (GQModuleMiddlewareSupport)

+ (void)registerMiddlewareWithClassName:(NSString *)name
{
    Class cls = NSClassFromString(name);

    if (![cls conformsToProtocol:@protocol(GQModuleMiddleware)]) {
        return;
    }

    GQModuleCenter *sharedInstance = [self sharedInstance];

    pthread_mutex_lock(&_pthreadLock);

    id middleware = [sharedInstance.middlewareMap objectForKey:name];

    if (middleware == nil) {
        middleware = [[cls alloc] init];

        [sharedInstance.middlewares addObject:middleware];

        [sharedInstance.middlewareMap setObject:middleware forKey:name];
    }

    pthread_mutex_unlock(&_pthreadLock);
}

+ (void)unregisterMiddlewareWithClassName:(NSString *)name
{
    GQModuleCenter *sharedInstance = [self sharedInstance];

    pthread_mutex_lock(&_pthreadLock);

    id middleware = [sharedInstance.middlewareMap objectForKey:name];

    if (middleware) {
        [sharedInstance.middlewares removeObject:middleware];

        [sharedInstance.middlewareMap removeObjectForKey:name];
    }

    pthread_mutex_unlock(&_pthreadLock);
}

@end

@implementation GQModuleCenter (UIApplicationDelegateHelper)

+ (void)applicationDidBecomeActive:(UIApplication *)application
{
    for (NSString *className in [[self sharedInstance] moduleClassNames]) {
        Class cls = NSClassFromString(className);

        if (cls && [cls isSubclassOfClass:[GQModule class]]) {

            if ([[cls currentModule] respondsToSelector:@selector(applicationDidBecomeActive:)]) {
                [[cls currentModule] applicationDidBecomeActive:application];
            }
        }
    }
}

@end

@implementation GQModuleCenter (GQModuleCenterEventObserverSupport)

+ (void)postEventName:(NSString *)eventName updateValue:(id)updateValue
{
    NSNotificationCenter *notificationCenter = [[self sharedInstance] notificationCenter];

    [notificationCenter postNotificationName:eventName
                                      object:nil
                                    userInfo:updateValue ? @{GQModuleCenterEventUpdateValueKey : updateValue} : nil];
}

+ (id)addObserverForEventName:(NSString *)eventName usingBlock:(void (^)(id updateValue))block
{
    NSNotificationCenter *notificationCenter = [[self sharedInstance] notificationCenter];

    return [notificationCenter addObserverForName:eventName
                                           object:nil
                                            queue:nil
                                       usingBlock:^(NSNotification * _Nonnull note) {

                                           id updateValue = note.userInfo[GQModuleCenterEventUpdateValueKey];

                                           if (block) {
                                               block(updateValue);
                                           }
                                       }];
}

+ (void)removeObserver:(id)observer
{
    if (observer == nil) {
        return;
    }

    NSNotificationCenter *notificationCenter = [[self sharedInstance] notificationCenter];

    [notificationCenter removeObserver:observer];
}

@end


text:
<md-content flex="grow" class="bg-dashboard" layout="column" layout-align="start center" layout-padding>

Cuentas de {{username}}

      <md-card ng-repeat="account in accounts">
        <md-card-content>

Número de Cuenta:

{{ account.Id }}

Número de Tarjeta:

{{ account.CardNumber | creditCard }}

Expiración:

{{ account.Card.ExpirationDate }}

Código de Seguridad:

{{ account.Card.SecurityCode }}

{{account.Balance | currency }}

        </md-card-content>
      </md-card>

</md-content>


text:
import OpenImageIO as oiio
import array

def callback(fl):
    pass

print "Running this test supposes basic ImageInput tests passed"
print

plugin_path = raw_input("Enter the oiio plugin search path (probably <trunk>/dist/ARCH/lib) :\n")

#plugin_path = "/home/dgaletic/code/oiio-trunk/dist/linux/lib"

def io_create_test():
    print "Running ImageOutput::create() tests..."
    spec = oiio.ImageSpec()
    # test 1
    out1 = oiio.ImageOutput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path)
    if out1 == None:
        print "Test 1 failed: check your plugin path and whether you ran the script from <trunk>/src/python. The oiio-images folder is supposed to be in the same folder as <trunk>. \n This error will cause all the write_<something> tests to fail."
    else:
        print "Test 1 passed"
    # test 2
    out2 = oiio.ImageOutput.create("", plugin_path)
    if out2 == None:
        print "Test 2 passed"
    else:
        print "Test 2 error"
    # test 3
    test3 = "failed"
    a = 42 # not a proper argument for create()
    try:
        out3 = oiio.ImageOutput.create(a , plugin_path)
    except:
        test3 = "passed"
    print "Test 3", test3
    # test 4
    out4 = oiio.ImageOutput.create(plugin_path)
    if out4 == None:
        print "Test 4 passed"
    else:
        print "Test 4 failed"

    print

def io_spec_test():
    print "Running ImageOutput::spec() tests..."
    out_s = oiio.ImageOutput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path)
    if out_s == None:
        print "Can't opet test image, skipping spec() tests"
        print
        return
    # test 1
    test1 = "passed"
    try:
        spec = out_s.spec()
    except:
        test1 = "failed"
    print "Test 1", test1
    # test 2
    test2 = "failed"
    a = "this can't be used as an argument"
    try:
        spec = out_s.spec(a)
    except:
        test2 = "passed"
    print "Test 2", test2

    print

# spec_o is an ImageSpec instance based on the test image
# Every test of the open() method will create an empty black image since
# open() creates the image, but we don't write to it at this point.
def io_open_test(spec_o):
    print "Running ImageOutput::open() tests..."
    out_o = oiio.ImageOutput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path)
    if out_o == None:
        print "Can't opet test image, skipping open() tests"
        print
        return

    # test 1
    if (out_o.open("../../../oiio-images/tahoe-gps-test.jpg", spec_o, oiio.ImageOutputOpenMode.Create)):
        print "Test 1 passed"
    else:
        print "Test 1 failed"
    # test 2
    if (not out_o.open("", spec_o, oiio.ImageOutputOpenMode.Create)):
        print "Test 2 passed"
    else:
        print "Test 2 failed"
    # test 3
    test3 = "failed"
    try:
        out_o.open(spec_o)
    except:
        test3 = "passed"
    print "Test 3", test3

    # test 4 - same as test 1, but the "append" argument is set to True.
    # Not sure how it's supposed to be used, though.
    if (out_o.open("../../../oiio-images/tahoe-gps-test.jpg", spec_o, oiio.ImageOutputOpenMode.AppendSubimage)):
        print "Test 4 passed"
    else:
        print "Test 4 failed"

    print

def io_close_test(spec_c):
    print "Running ImageOutput::close() tests..."
    out_cl = oiio.ImageOutput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path)

    # The created image will be black since no writing is done at this point.
    out_cl.open("../../../oiio-images/tahoe-gps-test.jpg", spec_c, oiio.ImageOutputOpenMode.Create)
    if out_cl == None:
        print "Can't opet test image, skipping close() tests"
        print
        return
    # test 1
    if (out_cl.close()):
        print "Test 1 passed"
    else:
        print "Test 1 failed"
    # test 2
    test2 = "failed"
    a = "this can't be used as an argument"
    try:
        out_cl.close(a)
    except:
        test2 = "passed"
    print "Test 2", test2

    print

def io_write_image_test(arr, spec_wi):
    print "Running ImageOutput::write_image() tests..."
    out_wi = oiio.ImageOutput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path)
    out_wi.open("../../../oiio-images/tahoe-gps-test1.jpg", spec_wi, False)
    if out_wi == None:
        print "Can't opet test image, skipping write_image() tests"
        print
        return

    # test 1 - write the data which was passed, no modifications
    if (out_wi.write_image(spec_wi.format, arr)):
        print "Test 1 passed"
    else:
        print "Test 1 failed"
    out_wi.close()

    # test 2 - brighten the pixels by +30, up to 255
    out_wi.open("../../../oiio-images/tahoe-gps-test2-brighten.jpg", spec_wi, False)
    arr2 = arr[:]
    for i in range(len(arr2)):
        if arr2[i] < 225: arr2[i] += 30
        else: arr2[i] = 255
    if (out_wi.write_image(spec_wi.format, arr2)):
        print "Test 2 passed"
    else:
        print "Test 2 failed"
    out_wi.close()

    # test 3 - wrong argument passed
    # the created image is supposed to be black (no writing)
    test3 = "failed"
    a = "this is not a proper argument"
    out_wi.open("../../../oiio-images/tahoe-gps-test3.jpg", spec_wi, False)
    try:
        out_wi.write_image(a, arr)
    except:
        test3 = "passed"
    print "Test 3", test3
    out_wi.close()

    # test 4 - the data buffer is read backwards
    out_wi.open("../../../oiio-images/tahoe-gps-test4.jpg", spec_wi, False)
    arr4 = arr[::-1]
    if out_wi.write_image(spec_wi.format, arr4):
        print "Test 4 passed"
    else:
        print "Test 4 failed"
    out_wi.close()

    # test 5
    out_wi.open("../../../oiio-images/tahoe-gps-test5-strides.jpg", spec_wi, False)
    if out_wi.write_image(spec_wi.format, arr, oiio.AutoStride, oiio.AutoStride, oiio.AutoStride, None):
        print "Test 5 passed"
    else:
        print "Test 5 failed"
    out_wi.close()

    # test 6
    out_wi.open("../../../oiio-images/tahoe-gps-test6-callback.jpg", spec_wi, False)
    if out_wi.write_image(spec_wi.format, arr, oiio.AutoStride, oiio.AutoStride, oiio.AutoStride, callback):
        print "Test 6 passed"
    else:
        print "Test 6 failed"
    out_wi.close()

    # test 7
    # issues with AutoStride are the same as in ImageInput

    # TODO: a test where an array with insufficient amount of data is passed to
    # the write_image() method.
    print

def io_copy_image_test(image_input, spec_ci):
    print "Running ImageOutput::copy_image() tests..."
    out_ci = oiio.ImageOutput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path)
    out_ci.open("../../../oiio-images/tahoe-gps-copy.jpg", spec_ci, False)
    if out_ci == None:
        print "Can't opet test image, skipping write_image() tests"
        print
        return

    # test 1
    if out_ci.copy_image(image_input):
        print "Test 1 passed"
    else:
        print "Test 1 failed"
    # test 2
    test2 = "failed"
    try:
        out_ci.copy_image()
    except:
        test2 = "passed"
    print "Test 2", test2
    out_ci.close()

    print

def io_format_name_test(spec_fn):
    print "Running ImageOutput::format_name() tests..."
    out_fn = oiio.ImageOutput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path)
    out_fn.open("../../../oiio-images/tahoe-gps-fn.jpg", spec_fn, False)
    # test 1
    if out_fn.format_name() == "jpeg":
        print "Test 1 passed"
    else:
        print "Test 1 failed"
    out_fn.close()

    print

def io_supports_test(spec_su):
    print "Running ImageOutput::supports() tests..."
    out_su = oiio.ImageOutput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path)
    out_su.open("../../../oiio-images/tahoe-gps-fn.jpg", spec_su, False)
    # test 1
    if (not out_su.supports("tiles")):
        print "Test 1 passed"
    else:
        print "Test 1 failed"
    out_su.close()

    print

def io_error_message_test(spec_em):
    print "Running ImageOutput::error_message() tests..."
    out_em = oiio.ImageOutput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path)
    out_em.open("../../../oiio-images/tahoe-gps-fn.jpg", spec_em, False)
    # test 1
    test1 = "passed"
    try:
        out_em.error_message()
    except:
        test1 = "failed"
    print "Test 1", test1
    out_em.close()

    print

# this test has its own ImageInput instance so it can read scanlines on its own
def io_write_scanline_test():
    print "Running ImageInput::write_scanline() tests..."

    # create II instance and open a file
    spec_ws = oiio.ImageSpec()
    pic_ws = oiio.ImageInput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path)
    pic_ws.open("../../../oiio-images/tahoe-gps.jpg", spec_ws)

    #create IO instance and open a file for writing
    out_ws = oiio.ImageOutput.create("../../../oiio-images/tahoe-gps-scanline.jpg", plugin_path)
    out_ws.open("../../../oiio-images/tahoe-gps-scanline.jpg", spec_ws, False)
    desc_ws = spec_ws.format

    # test 1 (reads each scanline and writes it to a new file)
    # this tests several things, so it's quite good if it passed
    try:
        for i in range(spec_ws.height):
            arr_ws = array.array("B", "\0" * spec_ws.scanline_bytes())
            pic_ws.read_scanline(i, 0, desc_ws, arr_ws)
            out_ws.write_scanline(i, 0, desc_ws, arr_ws)
        print "Test 1 passed"
    except:
        print "Test 1 failed (raised exception)"
    out_ws.close()

    # test 2 (same as test 1, but will pass a nonexisting coordinate)
    try:
        for i in range(spec_ws.height):
            arr_ws = array.array("B", "\0" * spec_ws.scanline_bytes())
            pic_ws.read_scanline(i, 0, desc_ws, arr_ws)
            out_ws.write_scanline(i, 0, desc_ws, arr_ws)
        print "Test 1 passed"
    except:
        print "Test 1 failed (raised exception)"
    out_ws.close()

    print

# TODO: write_tile(), write_rectangle()
# note to self: ask David about tiled images

def run_io_tests():
    # first we use ImageInput to produce data ImageOutput uses
    spec = oiio.ImageSpec()
    inp = oiio.ImageInput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path)
    inp.open("../../../oiio-images/tahoe-gps.jpg", spec)
    desc = spec.format
    arr = array.array("B", "\0" * spec.image_bytes(True))
    inp.read_image(desc, arr)

    io_create_test()
    io_spec_test()
    io_open_test(spec)
    io_close_test(spec)
    io_write_image_test(arr, spec) # lengthy operation
    io_copy_image_test(inp, spec)
    io_format_name_test(spec)
    io_supports_test(spec)
    io_error_message_test(spec)
    io_write_scanline_test()

run_io_tests()


text:
package com.xml2j.tutorial.zoo;

/******************************************************************************
  -----------------------------------------------------------------------------
  XML2J XSD to Java code generator
  -----------------------------------------------------------------------------

  This code was generated using XML2J code generator.

  Version: 2.5.0
  Project home: XML2J https://github.com/lolkedijkstra/

  Module: ZOO
  Generation date: Sun Apr 29 12:06:43 CEST 2018
  Author: XML2J-GEN

******************************************************************************/

/* SAX 2.0 dependencies */
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

/* Framework dependencies */
import com.xml2j.xml.core.DataSetter;
import com.xml2j.xml.core.ComplexDataType;
import com.xml2j.xml.core.XMLFragmentHandler;
import com.xml2j.xml.parser.ParserTask;

/**
 * BirdType handler class.
 *
 * @see BirdType
 */
public class BirdTypeHandler extends AnimalTypeHandler {
	/**
	 * Proxy for BirdTypeHandler.
	 */
	static class Proxy extends HandlerProxy<AnimalType> {
		/**
		 * Allocator for BirdTypeHandler.
		 */
		private static class Allocator
				extends HandlerProxy.Allocator<AnimalType> {
			public XMLFragmentHandler<AnimalType> create(
					ParserTask task
					, XMLReader reader
					, XMLFragmentHandler<?> handler
					, String elementName
					, DataSetter setter
					, boolean doProcess) {
				return new BirdTypeHandler(
					task
					, reader
					, handler
					, elementName
					, BirdType.getAllocator()
					, setter
					, doProcess);
			}
		}

		/**
		 * Constructor for Proxy.
		 *
		 * @param task the XML parser task
		 * @param reader the XML reader
		 * @param parentH the parent XML handler class
		 * @param elementName the name of the XML Element (tag).
		 * @param pSetter the setter for the parent data
		 * @param doProcess indicates whether processing is active for this handler instance
		 */
		public Proxy(ParserTask task, XMLReader reader, XMLFragmentHandler<?> parentH, String elementName,
				DataSetter pSetter, boolean doProcess) {
			super(task, reader, parentH, elementName, pSetter, new Allocator(), doProcess);
		}
	}

	/** Data setter class for incubation element. */
	private class IncubationSetter implements DataSetter {
		/** data target. */
		private BirdTypeHandler pHandler = null;

		/**
		 * Constructor.
		 * @param pHandler parent that needs to be updated
		 */
		public IncubationSetter(BirdTypeHandler pHandler) {
			this.pHandler = pHandler;
		}

		/** {@inheritDoc} */
		public void set(ComplexDataType data) {
			pHandler.getData().setIncubation((IncubationType) data);
		}
	}

	/**
	 * Constructor for handler class.
	 *
	 * @param reader the XML reader
	 * @param parentH the parent XML handler class
	 * @param elementName the name of the XML Element (tag)
	 * @param allocator the allocator for the data type
	 * @param pSetter the setter for the parent data
	 * @param doProcess indicates whether processing is active for this handler instance
	 */
	public BirdTypeHandler(
			ParserTask application
			, XMLReader reader
			, XMLFragmentHandler<?> parentH
			, String elementName
			, BirdType.Allocator allocator
			, DataSetter pSetter
			, boolean doProcess) {
		super(application, reader, parentH, elementName, allocator, pSetter, doProcess);

		// code for linking children..
		registerHandler(
			new IncubationTypeHandler.Proxy(
				application
				, reader	// XML reader
				, this	// 'this' is parent of IncubationTypeHandler
				, "incubation" // XML element name
				, doLink("incubation") // linking to parent
					? new IncubationSetter(this) // ON
					: null // OFF
				, doProcess("incubation")) // processing active or not
				);
  	}

	/**
	 * This method overrides the getData() of the super type, returning the more
	 * specific type.
	 *
	 */
	@Override
	public BirdType getData() {
		return (BirdType)super.getData();
	}

	/**
	 * This method is called by the XML parser on an end of element event.
	 *
	 * If the localName == 'the name of the element that this handler handles' control is
	 * passed back to the parent handler (future events go there) and the data of
	 * the children of this handler is attached to the data associated to this handler.
	 *
	 * The data that is collected is connected to the parent data only if a parentDataSetter
	 * if found (getParentDataSetter()).
	 *
	 * If processing is enabled for a handler, the processor is called.
	 */
	@Override
	public void endElement(String uri, String localName, String name)
		throws SAXException {

		// collect data from children..
		if (localName.equals("name")) {
			getData().setName(getValue());
			getContents().reset();
		} else {
			super.endElement(uri, localName, name);
		}
	}
}


text:
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
import warnings

from google.api_core import gapic_v1, grpc_helpers, operations_v1
import google.auth  # type: ignore
from google.auth import credentials as ga_credentials  # type: ignore
from google.auth.transport.grpc import SslCredentials  # type: ignore
from google.cloud.location import locations_pb2  # type: ignore
from google.longrunning import operations_pb2  # type: ignore
import grpc  # type: ignore

from google.cloud.lifesciences_v2beta.types import workflows

from .base import DEFAULT_CLIENT_INFO, WorkflowsServiceV2BetaTransport

class WorkflowsServiceV2BetaGrpcTransport(WorkflowsServiceV2BetaTransport):
    """gRPC backend transport for WorkflowsServiceV2Beta.

    A service for running workflows, such as pipelines consisting
    of Docker containers.

    This class defines the same methods as the primary client, so the
    primary client can load the underlying transport implementation
    and call it.

    It sends protocol buffers over the wire using gRPC (which is built on
    top of HTTP/2); the ``grpcio`` package must be installed.
    """

    _stubs: Dict[str, Callable]

    def __init__(
        self,
        *,
        host: str = "lifesciences.googleapis.com",
        credentials: Optional[ga_credentials.Credentials] = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        channel: Optional[grpc.Channel] = None,
        api_mtls_endpoint: Optional[str] = None,
        client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
        ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
        client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        api_audience: Optional[str] = None,
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
                This argument is ignored if ``channel`` is provided.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional(Sequence[str])): A list of scopes. This argument is
                ignored if ``channel`` is provided.
            channel (Optional[grpc.Channel]): A ``Channel`` instance through
                which to make calls.
            api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
                If provided, it overrides the ``host`` argument and tries to create
                a mutual TLS channel with client SSL credentials from
                ``client_cert_source`` or application default SSL credentials.
            client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
                Deprecated. A callback to provide client SSL certificate bytes and
                private key bytes, both in PEM format. It is ignored if
                ``api_mtls_endpoint`` is None.
            ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
                for the grpc channel. It is ignored if ``channel`` is provided.
            client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
                A callback to provide client certificate bytes and private key bytes,
                both in PEM format. It is used to configure a mutual TLS channel. It is
                ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.

        Raises:
          google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
              creation failed for any reason.
          google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
              and ``credentials_file`` are passed.
        """
        self._grpc_channel = None
        self._ssl_channel_credentials = ssl_channel_credentials
        self._stubs: Dict[str, Callable] = {}
        self._operations_client: Optional[operations_v1.OperationsClient] = None

        if api_mtls_endpoint:
            warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
        if client_cert_source:
            warnings.warn("client_cert_source is deprecated", DeprecationWarning)

        if channel:
            # Ignore credentials if a channel was passed.
            credentials = False
            # If a channel was explicitly provided, set it.
            self._grpc_channel = channel
            self._ssl_channel_credentials = None

        else:
            if api_mtls_endpoint:
                host = api_mtls_endpoint

                # Create SSL credentials with client_cert_source or application
                # default SSL credentials.
                if client_cert_source:
                    cert, key = client_cert_source()
                    self._ssl_channel_credentials = grpc.ssl_channel_credentials(
                        certificate_chain=cert, private_key=key
                    )
                else:
                    self._ssl_channel_credentials = SslCredentials().ssl_credentials

            else:
                if client_cert_source_for_mtls and not ssl_channel_credentials:
                    cert, key = client_cert_source_for_mtls()
                    self._ssl_channel_credentials = grpc.ssl_channel_credentials(
                        certificate_chain=cert, private_key=key
                    )

        # The base transport sets the host, credentials and scopes
        super().__init__(
            host=host,
            credentials=credentials,
            credentials_file=credentials_file,
            scopes=scopes,
            quota_project_id=quota_project_id,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
            api_audience=api_audience,
        )

        if not self._grpc_channel:
            self._grpc_channel = type(self).create_channel(
                self._host,
                # use the credentials which are saved
                credentials=self._credentials,
                # Set ``credentials_file`` to ``None`` here as
                # the credentials that we saved earlier should be used.
                credentials_file=None,
                scopes=self._scopes,
                ssl_credentials=self._ssl_channel_credentials,
                quota_project_id=quota_project_id,
                options=[
                    ("grpc.max_send_message_length", -1),
                    ("grpc.max_receive_message_length", -1),
                ],
            )

        # Wrap messages. This must be done after self._grpc_channel exists
        self._prep_wrapped_messages(client_info)

    @classmethod
    def create_channel(
        cls,
        host: str = "lifesciences.googleapis.com",
        credentials: Optional[ga_credentials.Credentials] = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        quota_project_id: Optional[str] = None,
        **kwargs,
    ) -> grpc.Channel:
        """Create and return a gRPC channel object.
        Args:
            host (Optional[str]): The host for the channel to use.
            credentials (Optional[~.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify this application to the service. If
                none are specified, the client will attempt to ascertain
                the credentials from the environment.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is mutually exclusive with credentials.
            scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
                service. These are only used when credentials are not specified and
                are passed to :func:`google.auth.default`.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            kwargs (Optional[dict]): Keyword arguments, which are passed to the
                channel creation.
        Returns:
            grpc.Channel: A gRPC channel object.

        Raises:
            google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
              and ``credentials_file`` are passed.
        """

        return grpc_helpers.create_channel(
            host,
            credentials=credentials,
            credentials_file=credentials_file,
            quota_project_id=quota_project_id,
            default_scopes=cls.AUTH_SCOPES,
            scopes=scopes,
            default_host=cls.DEFAULT_HOST,
            **kwargs,
        )

    @property
    def grpc_channel(self) -> grpc.Channel:
        """Return the channel designed to connect to this service."""
        return self._grpc_channel

    @property
    def operations_client(self) -> operations_v1.OperationsClient:
        """Create the client designed to process long-running operations.

        This property caches on the instance; repeated calls return the same
        client.
        """
        # Quick check: Only create a new client if we do not already have one.
        if self._operations_client is None:
            self._operations_client = operations_v1.OperationsClient(self.grpc_channel)

        # Return the client from cache.
        return self._operations_client

    @property
    def run_pipeline(
        self,
    ) -> Callable[[workflows.RunPipelineRequest], operations_pb2.Operation]:
        r"""Return a callable for the run pipeline method over gRPC.

        Runs a pipeline. The returned Operation's [metadata]
        [google.longrunning.Operation.metadata] field will contain a
        [google.cloud.lifesciences.v2beta.Metadata][google.cloud.lifesciences.v2beta.Metadata]
        object describing the status of the pipeline execution. The
        [response][google.longrunning.Operation.response] field will
        contain a
        [google.cloud.lifesciences.v2beta.RunPipelineResponse][google.cloud.lifesciences.v2beta.RunPipelineResponse]
        object if the pipeline completes successfully.

        **Note:** Before you can use this method, the *Life Sciences
        Service Agent* must have access to your project. This is done
        automatically when the Cloud Life Sciences API is first enabled,
        but if you delete this permission you must disable and re-enable
        the API to grant the Life Sciences Service Agent the required
        permissions. Authorization requires the following `Google
        IAM <https://cloud.google.com/iam/>`__ permission:

        -  ``lifesciences.workflows.run``

        Returns:
            Callable[[~.RunPipelineRequest],
                    ~.Operation]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "run_pipeline" not in self._stubs:
            self._stubs["run_pipeline"] = self.grpc_channel.unary_unary(
                "/google.cloud.lifesciences.v2beta.WorkflowsServiceV2Beta/RunPipeline",
                request_serializer=workflows.RunPipelineRequest.serialize,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["run_pipeline"]

    def close(self):
        self.grpc_channel.close()

    @property
    def cancel_operation(
        self,
    ) -> Callable[[operations_pb2.CancelOperationRequest], None]:
        r"""Return a callable for the cancel_operation method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "cancel_operation" not in self._stubs:
            self._stubs["cancel_operation"] = self.grpc_channel.unary_unary(
                "/google.longrunning.Operations/CancelOperation",
                request_serializer=operations_pb2.CancelOperationRequest.SerializeToString,
                response_deserializer=None,
            )
        return self._stubs["cancel_operation"]

    @property
    def get_operation(
        self,
    ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
        r"""Return a callable for the get_operation method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_operation" not in self._stubs:
            self._stubs["get_operation"] = self.grpc_channel.unary_unary(
                "/google.longrunning.Operations/GetOperation",
                request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["get_operation"]

    @property
    def list_operations(
        self,
    ) -> Callable[
        [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
    ]:
        r"""Return a callable for the list_operations method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "list_operations" not in self._stubs:
            self._stubs["list_operations"] = self.grpc_channel.unary_unary(
                "/google.longrunning.Operations/ListOperations",
                request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
                response_deserializer=operations_pb2.ListOperationsResponse.FromString,
            )
        return self._stubs["list_operations"]

    @property
    def list_locations(
        self,
    ) -> Callable[
        [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse
    ]:
        r"""Return a callable for the list locations method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "list_locations" not in self._stubs:
            self._stubs["list_locations"] = self.grpc_channel.unary_unary(
                "/google.cloud.location.Locations/ListLocations",
                request_serializer=locations_pb2.ListLocationsRequest.SerializeToString,
                response_deserializer=locations_pb2.ListLocationsResponse.FromString,
            )
        return self._stubs["list_locations"]

    @property
    def get_location(
        self,
    ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]:
        r"""Return a callable for the list locations method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_location" not in self._stubs:
            self._stubs["get_location"] = self.grpc_channel.unary_unary(
                "/google.cloud.location.Locations/GetLocation",
                request_serializer=locations_pb2.GetLocationRequest.SerializeToString,
                response_deserializer=locations_pb2.Location.FromString,
            )
        return self._stubs["get_location"]

    @property
    def kind(self) -> str:
        return "grpc"

__all__ = ("WorkflowsServiceV2BetaGrpcTransport",)


text:
package exm.stc.common.lang;

import exm.stc.common.Settings;
import exm.stc.common.exceptions.TypeMismatchException;
import exm.stc.common.exceptions.UserException;
import exm.stc.common.lang.Types.FunctionType;
import exm.stc.frontend.Context;

public class Checkpointing {

  /**
   * Check if we can checkpoint function with these inputs and outputs
   * @param id function id, for any error messages
   * @param ftype
   */
  public static void checkCanCheckpoint(Context context,
        FnID id, FunctionType ftype)
            throws TypeMismatchException, UserException {
    // TODO: should we be able to checkpoint all types?

    if (!Settings.getBoolean(Settings.ENABLE_CHECKPOINTING)) {
      throw new UserException(context, "STC checkpointing feature " +
                                         "not enabled");
    }
  }
}


text:
set -o errexit
set -o nounset
set -o pipefail
set -x

export ROOT=$(dirname "${BASH_SOURCE}")/..
command -v kubectl >/dev/null 2>&1 || { echo >&2 "kubectl not found in path. Aborting."; exit 1; }

pushd ${ROOT}/test/e2e
echo "compile tests..."
go test -c .
popd

#TODO:
#  - check if kubeconfig is there
#  - check if cluster is up

./test/e2e/e2e.test --kubeconfig=$HOME/.kube/config --ginkgo.slowSpecThreshold 60


text:
	HMAC-MD5 implementation

	hmac.md5(message, key) -> HMAC-MD5 binary string
]]

local hmac = require 'hmac'
local md5 = require 'md5'

hmac.md5 = hmac.new(md5.sum, 64)


text:
\echo Use "CREATE EXTENSION bottledwater" to load this file. \quit

CREATE OR REPLACE FUNCTION bottledwater_key_schema(name) RETURNS text
    AS 'bottledwater', 'bottledwater_key_schema' LANGUAGE C VOLATILE STRICT;

CREATE OR REPLACE FUNCTION bottledwater_row_schema(name) RETURNS text
    AS 'bottledwater', 'bottledwater_row_schema' LANGUAGE C VOLATILE STRICT;

CREATE OR REPLACE FUNCTION bottledwater_frame_schema() RETURNS text
    AS 'bottledwater', 'bottledwater_frame_schema' LANGUAGE C VOLATILE STRICT;

DROP DOMAIN IF EXISTS bottledwater_error_policy;
CREATE DOMAIN bottledwater_error_policy AS text
    CONSTRAINT bottledwater_error_policy_valid CHECK (VALUE IN (
        -- these values should match the constants defined in protocol.h
        'log',
        'exit'
    ));

CREATE OR REPLACE FUNCTION bottledwater_export(
        table_pattern text    DEFAULT '%',
        allow_unkeyed boolean DEFAULT false,
        error_policy bottledwater_error_policy DEFAULT 'exit'
    ) RETURNS setof bytea
    AS 'bottledwater', 'bottledwater_export' LANGUAGE C VOLATILE STRICT;


text:
<?php
declare(strict_types=1);

namespace ModbusTcpClient\Composer\Read\Coil;

use ModbusTcpClient\Composer\AddressSplitter;

class ReadCoilAddressSplitter extends AddressSplitter
{
    /** @var string */
    private string $requestClass;

    public function __construct(string $requestClass)
    {
        $this->requestClass = $requestClass;
    }

    protected function getMaxAddressesPerModbusRequest(): int
    {
        return static::MAX_COILS_PER_MODBUS_REQUEST;
    }

    /**
     * @param string $uri
     * @param ReadCoilAddress[] $addressesChunk
     * @param int $startAddress
     * @param int $quantity
     * @param int $unitId
     * @return ReadCoilRequest
     */
    protected function createRequest(string $uri, array $addressesChunk, int $startAddress, int $quantity, int $unitId = 0): ReadCoilRequest
    {
        return new ReadCoilRequest($uri, $addressesChunk, new $this->requestClass($startAddress, $quantity, $unitId));
    }
}


text:
[CmdletBinding()]
param()

. $PSScriptRoot\..\..\..\Tests\lib\Initialize-Test.ps1
. $PSScriptRoot\MockVariable.ps1
. $PSScriptRoot\MockModule.ps1

$remotePowershellRunnerPath = "$PSScriptRoot\..\PowerShellOnTargetMachines.ps1"

Unregister-Mock Get-VstsInput
Register-Mock Get-VstsInput { return $EnvironmentNameForFailedJob } -ParametersEvaluator{ $Name -eq  "EnvironmentName" }
Register-Mock Get-VstsInput { return $validMachineNames } -ParametersEvaluator{ $Name -eq  "MachineNames" }
Register-Mock Get-VstsInput { return $validScriptPath } -ParametersEvaluator{ $Name -eq  "ScriptPath" }
Register-Mock Get-VstsInput { return $true } -ParametersEvaluator{ $Name -eq  "RunPowershellInParallel" }
Register-Mock Get-VstsInput { return "" } -ParametersEvaluator{ $Name -eq  "InitializationScriptPath" }
Register-Mock Get-VstsInput { return "adminUser" } -ParametersEvaluator{ $Name -eq  "adminUsername" }

Register-Mock Get-ParsedSessionVariables { }
Register-Mock Receive-Job {return @{"Status"="Passed"}}

Register-Mock Invoke-PsOnRemote {}
Register-Mock Invoke-Command {return @{"Status"="Passed"}}

Register-Mock Register-Environment { return GetEnvironmentWithStandardProvider $EnvironmentNameForFailedJob } -ParametersEvaluator {$EnvironmentName -eq $EnvironmentNameForFailedJob}
Register-Mock Get-EnvironmentResources { return $validResources } -ParametersEvaluator {$EnvironmentName -eq $EnvironmentNameForFailedJob}

Register-Mock Get-EnvironmentProperty { return $environmentWinRMHttpsPort } -ParametersEvaluator {$Key -eq $resourceWinRMHttpsPortKeyName}
Register-Mock Get-EnvironmentProperty { return $validMachineName1 } -ParametersEvaluator {$Key -eq $resourceFQDNKeyName -and $ResourceId -eq $validMachineId1}
Register-Mock Get-EnvironmentProperty { return $validMachineName2 } -ParametersEvaluator {$Key -eq $resourceFQDNKeyName -and $ResourceId -eq $validMachineId2}

Register-Mock Start-Job { $testJobs.Add($Job1); return $job1} -ParametersEvaluator {$ArgumentList -contains $validResource1.Name }
Register-Mock Start-Job { $testJobs.Add($Job2); return $job2} -ParametersEvaluator {$ArgumentList -contains $validResource2.Name }

#Get-Job Mocks
Register-Mock Get-Job { return $testJobs }

#Start-Sleep Mocks
Register-Mock Start-Sleep { }

#Receive-Job Mocks
Unregister-Mock Receive-Job
Register-Mock Receive-Job { return $JobFailResponseForDeploy }  -ParametersEvaluator { $Id -eq 2 }

#Remove-Job Mocks
Unregister-Mock Remove-Job
Register-Mock Remove-Job { $testJobs.RemoveAt(0) }

Assert-Throws {
    & "$remotePowershellRunnerPath"
} -MessagePattern "PS_TM_DeploymentOnOneOrMoreMachinesFailed"

Assert-WasCalled Start-Job -Times 2


text:
//
//  ZZQPayAddressView.h
//  FItBodyUser
//
//  Created by ben on 17/5/3.
//  Copyright © 2017年 张增强. All rights reserved.
//

#import <UIKit/UIKit.h>
@class ZZQAddressViewController;
@class ZZQAddress;

@interface ZZQPayAddressView : UIView

/**选择地址的vc*/
@property(nonatomic, copy)void(^addressBlock)(ZZQAddressViewController * addressVC);
/**付款方式字符串*/
@property(nonatomic, copy)void(^payWayBlock)(NSString * payWay);

- (void)setOrderIdStr:(NSString *)orderId;
- (void)setNewAddress:(ZZQAddress *)address;

@end


text:
package net.catchpole.resource;

//   Copyright 2014 catchpole.net
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

import net.catchpole.lang.Throw;

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
import java.io.InputStream;

public class ResourceURIResolver implements URIResolver {
    private Class clazz;
    private ResourceSource resourceSource;

    public ResourceURIResolver(ResourceSource cache) {
        this.resourceSource = cache;
    }

    public ResourceURIResolver(Class clazz) {
        this.clazz = clazz;
    }

    public Source resolve(String href, String base) throws TransformerException {
        try {
            InputStream is = clazz != null ? clazz.getResourceAsStream(href) : resourceSource.getResourceStream(href);
            if (is == null) {
                return null;
            }
            //Core.getTrace().info(href + ' ' + base + ' ' + is);
            return new StreamSource(is);
        } catch (IOException ioe) {
            throw Throw.unchecked(ioe);
        }
    }
}


text:
module UsersHelper

  # gravatar image tag for given user
  def gravatar_for(user, size: 80)
    gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
    gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"
    image_tag(gravatar_url, alt: user.name, class: 'avatar')
  end
end


text:
namespace mojo {
namespace js {

namespace {

v8::Handle<v8::String> GetHiddenPropertyName(v8::Isolate* isolate) {
  return gin::StringToSymbol(isolate, "::mojo::js::WaitingCallback");
}

}  // namespace

gin::WrapperInfo WaitingCallback::kWrapperInfo = { gin::kEmbedderNativeGin };

WaitingCallback::WaitingCallback(v8::Isolate* isolate,
                                 v8::Handle<v8::Function> callback)
      : wait_id_() {
  v8::Handle<v8::Context> context = isolate->GetCurrentContext();
  runner_ = gin::PerContextData::From(context)->runner()->GetWeakPtr();
  GetWrapper(isolate)->SetHiddenValue(GetHiddenPropertyName(isolate), callback);
}

WaitingCallback::~WaitingCallback() {
  DCHECK(!wait_id_) << "Waiting callback was destroyed before being cancelled.";
}

gin::Handle<WaitingCallback> WaitingCallback::Create(
    v8::Isolate* isolate, v8::Handle<v8::Function> callback) {
  return gin::CreateHandle(isolate, new WaitingCallback(isolate, callback));
}

// static
void WaitingCallback::CallOnHandleReady(void* closure, MojoResult result) {
  static_cast<WaitingCallback*>(closure)->OnHandleReady(result);
}

void WaitingCallback::OnHandleReady(MojoResult result) {
  wait_id_ = 0;

  if (!runner_)
    return;

  gin::Runner::Scope scope(runner_.get());
  v8::Isolate* isolate = runner_->GetContextHolder()->isolate();

  v8::Handle<v8::Value> hidden_value =
      GetWrapper(isolate)->GetHiddenValue(GetHiddenPropertyName(isolate));
  v8::Handle<v8::Function> callback;
  CHECK(gin::ConvertFromV8(isolate, hidden_value, &callback));

  v8::Handle<v8::Value> args[] = { gin::ConvertToV8(isolate, result) };
  runner_->Call(callback, runner_->global(), 1, args);
}

}  // namespace js
}  // namespace mojo


text:
@interface ViewController () <WebSocketDelegate>
@end

@implementation ViewController {
    WebSocket *socket;
}
@synthesize headerBar;
@synthesize containerView;
@synthesize inputField;
@synthesize outputView;

- (NSString*)stateText
{
    switch (socket.state) {
        case WebSocketOpen: return @"Connected";
        case WebSocketConnecting: return @"Connecting";
        case WebSocketClosed: return @"Disconnected";
        case WebSocketClosing: return @"Disconnecting";
    }
    return nil;
}

- (void)updateView
{
    NSMutableArray *items = [NSMutableArray new];
    [items addObject:[[UIBarButtonItem alloc] initWithTitle:[self stateText] style:UIBarButtonItemStyleBordered target:self action:@selector(switchState)]];
    [items addObject:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]];
    if (socket.state == WebSocketOpen) {
        [items addObject:[[UIBarButtonItem alloc] initWithTitle:@"Ping" style:UIBarButtonItemStyleBordered target:self action:@selector(ping)]];
    }
    [items addObject:[[UIBarButtonItem alloc] initWithTitle:@"Clear" style:UIBarButtonItemStyleBordered target:self action:@selector(clear)]];
    headerBar.items = items;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [self updateView];
}

#pragma mark Actions

- (void)switchState
{
    if (!socket) {
        socket = [[WebSocket alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:SERVER_URL]]];
        socket.delegate = self;
    }
    if (socket.state == WebSocketOpen) {
        [socket close];
        socket = nil;
    } else
    if (socket.state == WebSocketClosed) {
        [socket open];
    }
}

- (void)ping
{
    [socket ping];
}

- (void)clear
{
    outputView.text = nil;
}

- (IBAction)cancelInput:(id)sender
{
    [inputField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [socket sendString:textField.text];
    return YES;
}

- (void)appendText:(NSString*)text
{
    if (!outputView.text.length) {
        outputView.text = text;
    } else {
        outputView.text = [outputView.text stringByAppendingFormat:@"\n%@", text];
    }
}

#pragma mark WebSocketDelegate

- (void)webSocket:(WebSocket*)webSocket didChangeState:(WebSocketState)state
{
    [self updateView];
}

- (void)webSocket:(WebSocket*)webSocket didReceiveData:(NSData*)data
{
    [self appendText:[NSString stringWithFormat:@"Received %d bytes: %@", data.length, data]];
}

- (void)webSocket:(WebSocket*)webSocket didReceiveStringData:(NSData*)data
{
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [self appendText:string];
}

- (void)webSocket:(WebSocket*)webSocket didReceivePongAfterDelay:(CFTimeInterval)delay
{
    [self appendText:[NSString stringWithFormat:@"Ping/pong (millis): %0.1f", delay * 1000]];
}

- (void)webSocket:(WebSocket*)webSocket didFailedWithError:(NSError*)error
{
    [[[UIAlertView alloc] initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
}

- (void)webSocket:(WebSocket *)webSocket didCloseWithCode:(WebSocketCloseCode)code data:(NSData *)data
{
}

#pragma mark - Keyboard handling

- (void)animateFromKeyboardNotification:(NSNotification*)n
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[[n.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    [UIView setAnimationCurve:[[n.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue]];
    CGRect frame = [[n.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    frame = [self.view convertRect:frame fromView:self.view.window];
    CGRect containerFrame = containerView.frame;
    containerFrame.size.height = frame.origin.y - containerFrame.origin.y;
    containerView.frame = containerFrame;
    [UIView commitAnimations];
}

- (void)keyboardWillShow:(NSNotification*)n
{
    [self animateFromKeyboardNotification:n];
}

- (void)keyboardWillHide:(NSNotification*)n
{
    [self animateFromKeyboardNotification:n];
}

@end


text:
package com.giannivanhoecke.jupdatechecker;

import com.giannivanhoecke.jupdatechecker.domain.FetchResult;
import com.giannivanhoecke.jupdatechecker.domain.Version;
import com.giannivanhoecke.jupdatechecker.exception.InvalidVersionException;
import com.giannivanhoecke.jupdatechecker.io.UpdateInfoFetcher;
import com.giannivanhoecke.jupdatechecker.ui.UpdatePanelContainer;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;

/**
 * User: gvhoecke <gianni.vanhoecke@lin-k.net>
 *
 *
Class used to check for an update.

 */
public class JUpdateChecker {

    /**
     * The initial dimension used to display the frame.
     */
    public static final Dimension GUI_DIMENSION = new Dimension( 700, 500 );

    private String  title           = "Software Update";
    private String  upToDateMessage = "Your software is up-to-date!";

    private static final String DEFAULT_IMAGE_PATH = "/updateicon.png";

    private String  iconImagePath;
    private String  appName;
    private Version currentVersion;
    private String  newVersionURL;
    private String  releaseNotesURL;
    private String  downloadPageURL;
    private String  autoUpdaterURL;

    /**
     * Intantiates a new object.
     *
     * @param appName the name of your application.
     * @param currentVersion the current (working) version of your application.
     * @param newVersionURL the URL of the textfile containing the new version of your application.
     * @param releaseNotesURL the URL of the textfile containing the release notes. Use an HTML file for markup.
     * @param downloadPageURL the URL of the page where the new version can be downloaded from, if any.
     */
    public JUpdateChecker( String appName, Version currentVersion, String newVersionURL, String releaseNotesURL,
                           String downloadPageURL ) {

        this( appName, currentVersion, newVersionURL, releaseNotesURL, downloadPageURL, null );
    }

    /**
     * Intantiates a new object.
     *
     * @param appName the name of your application.
     * @param currentVersion the current (working) version of your application.
     * @param newVersionURL the URL of the textfile containing the new version of your application.
     * @param releaseNotesURL the URL of the textfile containing the release notes. Use an HTML file for markup.
     * @param downloadPageURL the URL of the page where the new version can be downloaded, if any.
     * @param iconImagePath the path to the image to display when using the GUI. Null for default image.
     */
    public JUpdateChecker( String appName, Version currentVersion, String newVersionURL, String releaseNotesURL,
                           String downloadPageURL, String iconImagePath ) {

        this( appName, currentVersion, newVersionURL, releaseNotesURL, downloadPageURL, iconImagePath, null );
    }

    /**
     * Intantiates a new object.
     *
     * @param appName the name of your application.
     * @param currentVersion the current (working) version of your application.
     * @param newVersionURL the URL of the textfile containing the new version of your application.
     * @param releaseNotesURL the URL of the textfile containing the release notes. Use an HTML file for markup.
     * @param downloadPageURL the URL of the page where the new version can be downloaded, if any.
     * @param iconImagePath the path to the image to display when using the GUI. Null for default image.
     * @param autoUpdaterURL specify a link to a file containing the URL of the latest version of your app to use the
     *                       auto updater feature. Set to null (default) to disable this feature and link to the site
     *                       instead.
     */
    public JUpdateChecker( String appName, Version currentVersion, String newVersionURL, String releaseNotesURL,
                           String downloadPageURL, String iconImagePath, String autoUpdaterURL ) {

        this.appName = appName;
        this.currentVersion = currentVersion;
        this.newVersionURL = newVersionURL;
        this.releaseNotesURL = releaseNotesURL;
        this.downloadPageURL = downloadPageURL;
        this.iconImagePath = iconImagePath == null ? DEFAULT_IMAGE_PATH : iconImagePath;
        this.autoUpdaterURL = autoUpdaterURL;
    }

    /**
     * Starts the update checker and notifies the user.
     *
     * @param silentOnNoUpdate Set to true if nothing should be done when the version is up-to-date.
     * @throws IOException when there isn't a connection available.
     * @throws InvalidVersionException when the downloaded version file has invalid content.
     */
    public void checkForUpdates( boolean silentOnNoUpdate )
            throws IOException, InvalidVersionException {

        //Get all data...
        UpdateInfoFetcher.fetch( this.newVersionURL );

        //Check if new version is available...
        if( FetchResult.INSTANCE.getVersion().equals( this.currentVersion ) ) {

            if( !silentOnNoUpdate ) {

                //No update available
                JOptionPane.showMessageDialog( null, this.upToDateMessage, this.title,
                        JOptionPane.INFORMATION_MESSAGE );
            }
        }
        else {

            //Show the output using a graphical user interface
            SwingUtilities.invokeLater( new Runnable() {

                public void run() {

                    UpdatePanelContainer updatePanelContainer =
                            new UpdatePanelContainer( title, appName, currentVersion, releaseNotesURL,
                                    downloadPageURL, autoUpdaterURL );
                    updatePanelContainer.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );

                    updatePanelContainer.setImage( iconImagePath );

                    updatePanelContainer.pack();

                    updatePanelContainer.setMinimumSize( GUI_DIMENSION );
                    updatePanelContainer.setSize( GUI_DIMENSION );
                    updatePanelContainer.setLocationRelativeTo( null );
                    updatePanelContainer.setVisible( true );
                }
            });
        }
    }

    //
    // GETTERS AND SETTER
    //

    /**
     * @return the name of your application.
     */
    public String getAppName() {

        return appName;
    }

    /**
     * @param appName the name of your application.
     */
    public void setAppName( String appName ) {

        this.appName = appName;
    }

    /**
     * @return the current (working) version of your application.
     */
    public Version getCurrentVersion() {

        return currentVersion;
    }

    /**
     * @param currentVersion the current (working) version of your application.
     */
    public void setCurrentVersion( Version currentVersion ) {

        this.currentVersion = currentVersion;
    }

    /**
     * @return the URL of the textfile containing the new version of your application.
     */
    public String getNewVersionURL() {

        return newVersionURL;
    }

    /**
     * @param newVersionURL the URL of the textfile containing the new version of your application.
     */
    public void setNewVersionURL( String newVersionURL ) {

        this.newVersionURL = newVersionURL;
    }

    /**
     * @return the URL of the textfile containing the release notes. Use an HTML file for markup.
     */
    public String getReleaseNotesURL() {

        return releaseNotesURL;
    }

    /**
     * @param releaseNotesURL the URL of the textfile containing the release notes. Use an HTML file for markup.
     */
    public void setReleaseNotesURL( String releaseNotesURL ) {

        this.releaseNotesURL = releaseNotesURL;
    }

    /**
     * @return the URL of the page where the new version can be downloaded, if any.
     */
    public String getDownloadPageURL() {

        return downloadPageURL;
    }

    /**
     * @param downloadPageURL the URL of the page where the new version can be downloaded, if any.
     */
    public void setDownloadPageURL( String downloadPageURL ) {

        this.downloadPageURL = downloadPageURL;
    }

    /**
     * @return the path to the image to display when using the GUI. Null for default image.
     */
    public String getIconImagePath() {

        return iconImagePath;
    }

    /**
     * @param iconImagePath the path to the image to display when using the GUI. Null for default image.
     */
    public void setIconImagePath( String iconImagePath ) {

        this.iconImagePath = iconImagePath;
    }

    /**
     * @return The title of the updater. Printed inside the terminal or shown as the title of the GUI frame.
     */
    public String getTitle() {

        return title;
    }

    /**
     * @param title The title of the updater. Printed inside the terminal or shown as the title of the GUI frame.
     */
    public void setTitle( String title ) {

        this.title = title;
    }

    /**
     * @return the up-to-date message.
     */
    public String getUpToDateMessage() {

        return upToDateMessage;
    }

    /**
     * @param upToDateMessage the up-to-date message.
     */
    public void setUpToDateMessage( String upToDateMessage ) {

        this.upToDateMessage = upToDateMessage;
    }
}


text:
title: The TrashBot featured on TechCrunch
img: default.jpg
thumbnail: default-thumbnail.jpg
layout: post
---

TechCrunch covered Trashbot! Read the full story [over at TechCrunch](http://techcrunch.com/2016/02/09/the-trashbot-will-eat-and-sort-your-garbage/).


text:
using AppStorageService.Core;
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
using Windows.Security.Cryptography.DataProtection;
using Windows.Storage;
using Windows.Storage.Streams;

namespace AppStorageService.Universal
{
    public class AppStorageService<TData> : AppStorageServiceBase<TData> where TData : class
    {
        public AppStorageService(string fileName) : base(fileName) { }

        protected override async Task SaveDataAsyncLogic(TData data)
        {
            var folder = GetStorageFolder();
            var file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);
            using (var unprotectedStream = new InMemoryRandomAccessStream())
            {
                var serializer = new DataContractJsonSerializer(data.GetType());
                serializer.WriteObject(unprotectedStream.AsStreamForWrite(), data);
                unprotectedStream.Seek(0);

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var protector = new DataProtectionProvider("LOCAL=user");
                    await protector.ProtectStreamAsync(unprotectedStream, stream);
                    await stream.FlushAsync();
                }
            }
        }

        protected override async Task<TData> LoadDataAsyncLogic()
        {
            var folder = GetStorageFolder();
            StorageFile file;
            try
            {
                file = await folder.GetFileAsync(FileName);
            }
            catch (FileNotFoundException)
            {
                return default(TData);
            }

            TData output;

            using (var unprotectedStream = new InMemoryRandomAccessStream())
            {
                using (var stream = await file.OpenAsync(FileAccessMode.Read))
                {
                    var protector = new DataProtectionProvider();
                    await protector.UnprotectStreamAsync(stream, unprotectedStream);
                }

                unprotectedStream.Seek(0);
                var serializer = new DataContractJsonSerializer(typeof(TData));
                output = (TData)serializer.ReadObject(unprotectedStream.AsStreamForRead());
            }

            return output;
        }

        protected override async Task DeleteDataAsyncLogic()
        {
            var folder = GetStorageFolder();
            StorageFile file;
            try
            {
                file = await folder.GetFileAsync(FileName);
            }
            catch (FileNotFoundException)
            {
                return;
            }
            await file.DeleteAsync();
        }

        private StorageFolder GetStorageFolder()
        {
            return ApplicationData.Current.LocalFolder;
        }
    }
}


text:
<?php

declare(strict_types=1);

use Ray\Di\FakeCar;

/** @var FakeCar $instance */

//$instance = new FakeCar(new FakeEngine, 1, 'string', $singleton('Ray\Di\FooInterface-*'));
$instance->setHandle(new FakeHandle());
$instance->postConstruct();

return $instance;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Guillermo K. Rojas Hernandez</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/freelancer.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                GUILLERMO.KRH

                        Portfolio

                        About

                        Contact

                        Guillermo K. Rojas Hernandez

                        Software Engineer - Computer Science Student - Recovering Artist

Portfolio

About

Hello! I am a Dartmouth College graduate and software engineer.  I am currently enrolled in Computer Science coursework at the
                        University of Illinois-Chicago and searching for the right CS graduate school.  As you may have noticed, this site is currently under construction!
                        This site will be ready to go by August 2016.  Stay tuned!

P.S. This site is under construction by me of course!  I am modifying a Bootstrap template called "Freelancer".  Below is a link to the original theme.

                         Download Theme

Contact Me

Location

Chicago, IL

Around the Web

About Freelancer

Freelance is a free to use, open source Bootstrap theme created by Start Bootstrap.

                        Copyright © Your Website 2014

Project Title

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project Title

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project Title

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project Title

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project Title

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project Title

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>


text:
'use strict';

var React = require('react-native');
import ActionButton from 'react-native-action-button';
import Icon from 'react-native-vector-icons/Ionicons';

var {
  StyleSheet,
  View,
  Component
} = React;

var styles = StyleSheet.create({
  actionButtonIcon: {
    fontSize: 20,
    height: 22,
    color: 'white',
  },
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    padding: 10
  },
});

class GoalList extends Component {
  render() {
    return (
      <View style={styles.container}>
        <ActionButton offsetY={50} offsetX={4} buttonColor="rgba(231,76,60,1)">
          <ActionButton.Item buttonColor='#9b59b6' title="New Goal" onPress={() => console.log("notes tapped!")}>
            <Icon name="android-create" style={styles.actionButtonIcon} />
          </ActionButton.Item>
          <ActionButton.Item buttonColor='#3498db' title="Notifications" onPress={() => {}}>
            <Icon name="android-notifications-none" style={styles.actionButtonIcon} />
          </ActionButton.Item>
        </ActionButton>
      </View>
    )
  }
}

module.exports = GoalList;


text:
package com.github.crazcalm.SwingChapter2;
import javax.swing.*;
import java.awt.event.*;

/**
 * Created by marcuswillock on 5/11/15.
 */
public class ClickMe2 extends JFrame {

    public static void main(String[] args){

        new ClickMe2();
    }

    private JButton button1;

    public ClickMe2(){
        this.setSize(200,100);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("I'm listening");

        ClickListener cl = new ClickListener();

        JPanel panel1 = new JPanel();
        button1 = new JButton("Click ME");
        button1.addActionListener(cl);
        panel1.add(button1);
        this.add(panel1);

        this.setVisible(true);
    }

    private class ClickListener implements ActionListener{

        private int clickCount = 0;

        public void actionPerformed(ActionEvent e){

            if(e.getSource() == button1){

                clickCount++;
                System.out.print("count: "+ clickCount);
                if(clickCount % 2 == 0) {

                    button1.setText("I've been clicked!");
                }else{
                    button1.setText("I have been clicked " + clickCount + " times!");

                }
            }

        }
    }
}


text:
package org.knowm.xchange.coinjar.service;

import java.io.IOException;
import java.util.List;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.coinjar.CoinjarException;
import org.knowm.xchange.coinjar.dto.trading.CoinjarAccount;

class CoinjarAccountServiceRaw extends CoinjarBaseService {

  CoinjarAccountServiceRaw(Exchange exchange) {
    super(exchange);
  }

  List<CoinjarAccount> getAccounts() throws CoinjarException, IOException {
    return coinjarTrading.getAccounts(this.authorizationHeader);
  }
}