text:
.class public abstract Lcom/google/android/gms/dynamic/zzg;
.super Ljava/lang/Object;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/google/android/gms/dynamic/zzg$zza;
    }
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "<T:",
        "Ljava/lang/Object;",
        ">",
        "Ljava/lang/Object;"
    }
.end annotation

# instance fields
.field private final zzapA:Ljava/lang/String;

.field private zzapB:Ljava/lang/Object;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "TT;"
        }
    .end annotation
.end field

# direct methods
.method protected constructor <init>(Ljava/lang/String;)V
    .registers 2

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput-object p1, p0, Lcom/google/android/gms/dynamic/zzg;->zzapA:Ljava/lang/String;

    return-void
.end method

# virtual methods
.method protected final zzas(Landroid/content/Context;)Ljava/lang/Object;
    .registers 5
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Landroid/content/Context;",
            ")TT;"
        }
    .end annotation

    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lcom/google/android/gms/dynamic/zzg$zza;
        }
    .end annotation

    iget-object v0, p0, Lcom/google/android/gms/dynamic/zzg;->zzapB:Ljava/lang/Object;

    if-nez v0, :cond_2b

    invoke-static {p1}, Lcom/google/android/gms/common/internal/zzx;->zzw(Ljava/lang/Object;)Ljava/lang/Object;

    invoke-static {p1}, Lcom/google/android/gms/common/GooglePlayServicesUtil;->getRemoteContext(Landroid/content/Context;)Landroid/content/Context;

    move-result-object v0

    if-nez v0, :cond_15

    new-instance v0, Lcom/google/android/gms/dynamic/zzg$zza;

    const-string v1, "Could not get remote context."

    invoke-direct {v0, v1}, Lcom/google/android/gms/dynamic/zzg$zza;-><init>(Ljava/lang/String;)V

    throw v0

    :cond_15
    invoke-virtual {v0}, Landroid/content/Context;->getClassLoader()Ljava/lang/ClassLoader;

    move-result-object v0

    :try_start_19
    iget-object v1, p0, Lcom/google/android/gms/dynamic/zzg;->zzapA:Ljava/lang/String;

    invoke-virtual {v0, v1}, Ljava/lang/ClassLoader;->loadClass(Ljava/lang/String;)Ljava/lang/Class;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/Class;->newInstance()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/os/IBinder;

    invoke-virtual {p0, v0}, Lcom/google/android/gms/dynamic/zzg;->zzd(Landroid/os/IBinder;)Ljava/lang/Object;

    move-result-object v0

    iput-object v0, p0, Lcom/google/android/gms/dynamic/zzg;->zzapB:Ljava/lang/Object;
    :try_end_2b
    .catch Ljava/lang/ClassNotFoundException; {:try_start_19 .. :try_end_2b} :catch_2e
    .catch Ljava/lang/InstantiationException; {:try_start_19 .. :try_end_2b} :catch_37
    .catch Ljava/lang/IllegalAccessException; {:try_start_19 .. :try_end_2b} :catch_40

    :cond_2b
    iget-object v0, p0, Lcom/google/android/gms/dynamic/zzg;->zzapB:Ljava/lang/Object;

    return-object v0

    :catch_2e
    move-exception v0

    new-instance v1, Lcom/google/android/gms/dynamic/zzg$zza;

    const-string v2, "Could not load creator class."

    invoke-direct {v1, v2, v0}, Lcom/google/android/gms/dynamic/zzg$zza;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    throw v1

    :catch_37
    move-exception v0

    new-instance v1, Lcom/google/android/gms/dynamic/zzg$zza;

    const-string v2, "Could not instantiate creator."

    invoke-direct {v1, v2, v0}, Lcom/google/android/gms/dynamic/zzg$zza;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    throw v1

    :catch_40
    move-exception v0

    new-instance v1, Lcom/google/android/gms/dynamic/zzg$zza;

    const-string v2, "Could not access creator."

    invoke-direct {v1, v2, v0}, Lcom/google/android/gms/dynamic/zzg$zza;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    throw v1
.end method

.method protected abstract zzd(Landroid/os/IBinder;)Ljava/lang/Object;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Landroid/os/IBinder;",
            ")TT;"
        }
    .end annotation
.end method


text:
"""A LazyLoader class."""

import importlib
import types

class LazyLoader(types.ModuleType):
  """Lazily import a module to avoid pulling in large deps, defer checks."""

  # The lint error here is incorrect.
  def __init__(self, local_name, parent_module_globals, name,
               on_first_access=None):
    self._local_name = local_name
    self._parent_module_globals = parent_module_globals
    self._on_first_access = on_first_access

    super(LazyLoader, self).__init__(name)

  def _load(self):
    """Load the module and insert it into the parent's globals."""
    if callable(self._on_first_access):
      self._on_first_access()
      self._on_first_access = None
    # Import the target module and insert it into the parent's namespace
    module = importlib.import_module(self.__name__)
    if self._parent_module_globals is not None:
      self._parent_module_globals[self._local_name] = module
      self._parent_module_globals = None

      # Update this object's dict so that if someone keeps a reference to the
      # LazyLoader, lookups are efficient (__getattr__ is only called on lookups
      # that fail).
      self.__dict__.update(module.__dict__)

    return module

  def __getattr__(self, item):
    module = self._load()
    return getattr(module, item)

  def __dir__(self):
    module = self._load()
    return dir(module)

  def __reduce__(self):
    return importlib.import_module, (self.__name__,)

redpajama_set_name: RedPajamaGithub


text:
title: "Leanne reviews How to Catch a Star"
location-display-name: Gainsborough Community Library
format: recording
link: 2ZhccyMm5qk
category: group
service: youtube
---


text:
${title}

@inject

                TestService.ts:

                    export default class TestService{

                        static instancesCounter = 0;

                        constructor(){
                            TestService. <var>instancesCounter</var> = TestService. <var>instancesCounter</var> +1;
                        }

                        displayInstancesCounter():void{
                            alert(`There are ${TestService. <var>instancesCounter</var>} instances of TestService !`);
                        }
                    }

                MyPage.ts:

                    import {TestService} from './TestService';
                    import {inject} from 'Injector'

                    @inject(TestService)
                    export default class MyPage{

                        testServiceInstance:TestService;

                        constructor(testService:any){
                            this.testServiceInstance = testService;

                            this.testServiceInstance.displayInstancesCounter(); // 1 instance

                            let dummyInstance =  new TestService();
                            dummyInstance.displayInstancesCounter(); // 2 instances
                        }

                    }

                MyOtherPage.ts:

                    import {TestService} from './TestService';
                    import {inject} from 'Injector'
                    export default class MyOtherPage{
                        testServiceInstance:TestService;

                        constructor(testService:any){
                            this.testServiceInstance = testService;

                            this.testServiceInstance.displayInstancesCounter(); // 2 instance
                        }
                    }


text:
Language for scripted server-side processing of existing endpoints and services.

[![Build Status](https://travis-ci.org/JSONScript/jsonscript.svg?branch=master)](https://travis-ci.org/JSONScript/jsonscript)
[![npm version](https://badge.fury.io/js/jsonscript.svg)](https://www.npmjs.com/package/jsonscript)

## Script example

```json
{
  "$$array.map": {
    "data": [
      { "path": "/resource/1", "body": { "test": 1 } },
      { "path": "/resource/2", "body": { "test": 2 } },
      { "path": "/resource/3", "body": { "test": 3 } },
    ],
    "iterator": {
      "$func": [
        { "$$router.get": { "path": { "$data": "/path" } } },
        { "$$router.put": { "$data": "/" } },
      ],
      "$args": ["path", "body"]
    }
  }
}
```

Using YAML for the same script makes it more readable:

```yaml
$$array.map:
  data:
    - { path: /resource/1, body: { test: 1 } }
    - { path: /resource/2, body: { test: 2 } }
    - { path: /resource/3, body: { test: 3 } }
  iterator:
    $func:
      - $$router.get: { path: { $data: /path } }
      - $$router.put: { $data: / }
    $args: [ path, body ]
```

When executed on the server, the script above iterates array of requests, retrieves resource for each path and then updates it with a new value.

See [Language](https://github.com/JSONScript/jsonscript/blob/master/LANGUAGE.md).

## Problem

Management of remote systems is usually done via APIs.

It is often required to make multiple sequential or parallel calls, sometimes with some conditions between calls, to get the required result. It can be achieved in two ways:

1. Sending multiple requests to the remote system and implementing all the logic in the client system. The advantage of this approach is that the remote system remains unchanged and the client can easily change the logic and flow of requests. The disadvantage is the latency and the traffic - each request should travel via the network.

2. Implementing additional methods/endpoints/parameters in the remote system. The advantage of this approach is that the client has to make only one request. The disadvantage is that it requires changing the remote system (= coding + testing + documenting + deploying + monitoring + supporting...). In some cases it is simply impossible. When it is possible, it inevitably leads to the growing complexity of the remote system as more and more specialized methods/APIs are added to it.

In some cases, developers implement "batch endpoints" that allow to process multiple requests sequentially or in parallel in a single HTTP request. It covers only use cases when results are independent and there are no conditions or some other logic between requests.

## Solution

JSONScript allows you to send a script to the remote system that will be interpreted by the remote system. It will execute the script and return all results to the client. All this in a single HTTP (or any other transport) request.

JSONScript allows to keep the API of remote system conscise and simple, only implementing basic methods. At the same time JSONScript allows the client to implement an advanced logic with conditions and looping, sequential and concurrent execution, defining and calling functions and handling exceptions. In this way quite advanced execution can be requested from the remote system in a single transport request.

At the same time JSONScript allows keeping the remote system completely secure as only the functions and objects registered with the interpreter can be used from the JSONScript script and the interpreter can limit resources (time, memory, etc.) that the script can use.

## Script execution

As the script executes, each instruction returns some data. By default this data replaces the script itself and all results will be available to the interpreter to pass back to the host system that requested execution. Host system usually sends results back to the client, but can do anything else with them, e.g. logging, storing to the database, etc.).

## Schema

See [Schema](https://github.com/JSONScript/jsonscript/blob/master/SCHEMA.md) for JSON-schemas for the script and for instruction definitions.

## Implementations

JSONScript interpreter for node-js: [jsonscript-js](https://github.com/epoberezkin/jsonscript-js)

Express 4 middleware/route-handler: [jsonscript-express](https://github.com/JSONScript/jsonscript-express) (it supports scripted processing of existing express app routes)

Proxy server: [jsonscript-proxy](https://github.com/JSONScript/jsonscript-proxy) (it supports scripted processing of other existing services).

## License

[MIT](https://github.com/JSONScript/jsonscript/blob/master/LICENSE)


text:
extern "C++" {
#endif

#include <qglobal.h>

#define QSCINTILLA_VERSION      0x020702
#define QSCINTILLA_VERSION_STR  "2.7.2"

// Under Windows, define QSCINTILLA_MAKE_DLL to create a Scintilla DLL, or
// define QSCINTILLA_DLL to link against a Scintilla DLL, or define neither
// to either build or link against a static Scintilla library.
#if defined(Q_OS_WIN)

#if defined(QSCINTILLA_DLL)
#define QSCINTILLA_EXPORT       __declspec(dllimport)
#elif defined(QSCINTILLA_MAKE_DLL)
#define QSCINTILLA_EXPORT       __declspec(dllexport)
#endif

#endif

#if !defined(QSCINTILLA_EXPORT)
#define QSCINTILLA_EXPORT
#endif

#if !defined(QT_BEGIN_NAMESPACE)
#define QT_BEGIN_NAMESPACE
#define QT_END_NAMESPACE
#endif

#ifdef __APPLE__
}
#endif

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Web;

namespace BrightcoveOS.NET_MAPI_Wrapper.Tests.IntegrationTests.AudioTrackRead
{
	[TestFixture]
	public class FindAudioTracksByReferenceIdsTests : AudioTrackReadTestBase
	{
		[Test]
		public void FindAudioTracksByReferenceIds_Test_Basic()
		{
			// Rather than hardcoding a list of ids, dynamically fetch the first 5 ids
			// of the videos on the first page of the FindAllAudioTracks result.
			string[] ids = _api.FindAllAudioTracks(5, 0).Select(x => x.ReferenceId).ToArray();

			// Now, actually check the call you really want to test.
			_audioTracks = _api.FindAudioTracksByReferenceIds(ids);

			Assert.AreEqual(ids.Length, _audioTracks.Count);
			Assert.AreEqual(0, _audioTracks.Count(o => o == null));
		}
	}
}


text:
package quasar.connector.datasource

import cats.{Hash, Order, Show}

import scala.{Product, Serializable}

sealed trait Reconfiguration extends Product with Serializable

object Reconfiguration {

  implicit val orderHash: Order[Reconfiguration] with Hash[Reconfiguration] =
    new Order[Reconfiguration] with Hash[Reconfiguration] {

      def hash(r: Reconfiguration) = r match {
        case Reset => 0
        case Preserve => 1
      }

      def compare(r1: Reconfiguration, r2: Reconfiguration) =
        hash(r1) - hash(r2)
    }

  implicit val show: Show[Reconfiguration] =
    Show.fromToString[Reconfiguration]

  case object Reset extends Reconfiguration
  case object Preserve extends Reconfiguration
}


text:
package org.brackit.server.io.file;

/**
 *
 * File interface supporting block-oriented accesses.
 *
 * @author Ou Yi
 *
 */
public interface BlockFile {

	void open() throws FileException;

	void close() throws FileException;

	void read(int blockNo, byte[] buffer, int numBlocks) throws FileException;

	void write(int blockNo, byte[] buffer, int numBlocks) throws FileException;

	void sync() throws FileException;

	int getBlockCnt() throws FileException;
}


text:
template <class T, class U>
void test_remove_const_imp()
{
    static_assert((std::is_same<typename std::remove_const<T>::type, U>::value), "");
#if _LIBCPP_STD_VER > 11
    static_assert((std::is_same<std::remove_const_t<T>, U>::value), "");
#endif
}

template <class T>
void test_remove_const()
{
    test_remove_const_imp<T, T>();
    test_remove_const_imp<const T, T>();
    test_remove_const_imp<volatile T, volatile T>();
    test_remove_const_imp<const volatile T, volatile T>();
}

int main()
{
    test_remove_const<void>();
    test_remove_const<int>();
    test_remove_const<int[3]>();
    test_remove_const<int&>();
    test_remove_const<const int&>();
    test_remove_const<int*>();
    test_remove_const<const int*>();
}


text:
package com.navercorp.pinpoint.plugin.rabbitmq.client;

import com.navercorp.pinpoint.bootstrap.async.AsyncContextAccessor;
import com.navercorp.pinpoint.bootstrap.config.Filter;
import com.navercorp.pinpoint.bootstrap.instrument.ClassFilters;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentClass;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentException;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentMethod;
import com.navercorp.pinpoint.bootstrap.instrument.Instrumentor;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformCallback;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformTemplate;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformTemplateAware;
import com.navercorp.pinpoint.bootstrap.interceptor.BasicMethodInterceptor;
import com.navercorp.pinpoint.bootstrap.interceptor.scope.ExecutionPolicy;
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPlugin;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPluginSetupContext;
import com.navercorp.pinpoint.plugin.rabbitmq.client.field.accessor.LocalAddressAccessor;
import com.navercorp.pinpoint.plugin.rabbitmq.client.field.accessor.RemoteAddressAccessor;
import com.navercorp.pinpoint.plugin.rabbitmq.client.field.getter.ChannelGetter;
import com.navercorp.pinpoint.plugin.rabbitmq.client.field.setter.HeadersFieldSetter;
import com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.AMQCommandConstructInterceptor;
import com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.ChannelBasicGetInterceptor;
import com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.ChannelBasicPublishInterceptor;
import com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.DeliveryConstructInterceptor;
import com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.QueueingConsumerHandleInterceptor;
import com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.QueueingConsumerOnNextInterceptor;
import com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.RabbitMQConsumerDispatchInterceptor;
import com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.RabbitMQConsumerHandleCompleteInboundCommandInterceptor;
import com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.SocketChannelFrameHandlerConstructInterceptor;
import com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.SocketFrameHandlerConstructInterceptor;

import java.security.ProtectionDomain;
import java.util.List;

import static com.navercorp.pinpoint.common.util.VarArgs.va;

/**
 * @author Jinkai.Ma
 * @author Jiaqi Feng
 * @author HyunGil Jeong
 */
public class RabbitMQClientPlugin implements ProfilerPlugin, TransformTemplateAware {
    private final PLogger logger = PLoggerFactory.getLogger(this.getClass());

    private TransformTemplate transformTemplate;

    @Override
    public void setup(ProfilerPluginSetupContext context) {
        RabbitMQClientPluginConfig config = new RabbitMQClientPluginConfig(context.getConfig());

        if (!config.isTraceRabbitMQClient()) {
            logger.info("{} disabled", this.getClass().getSimpleName());
            return;
        }
        logger.info("{} config:{}", this.getClass().getSimpleName(), config);

        addCommonEditors(config.isTraceRabbitMQClientProducer(), config.isTraceRabbitMQClientConsumer());
        if (config.isTraceRabbitMQClientProducer()) {
            addAmqpBasicPropertiesEditor();
        }
        if (config.isTraceRabbitMQClientConsumer()) {
            addAMQChannelEditor();
            addConsumerDispatchEditor();
            addConsumerEditors();
            addCustomConsumerEditors(config.getConsumerClasses());
        }

        addSpringAmqpSupport(config.isTraceRabbitMQClientProducer(), config.isTraceRabbitMQClientConsumer());
    }

    private void addAmqpBasicPropertiesEditor() {
        transformTemplate.transform("com.rabbitmq.client.AMQP$BasicProperties", BasicPropertiesTransform.class);
    }

    public static class BasicPropertiesTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            target.addSetter(HeadersFieldSetter.class, "headers");
            return target.toBytecode();
        }
    }

    public static class ChannelTransform implements TransformCallback {

        public ChannelTransform() {
        }

        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            final RabbitMQClientPluginConfig config = new RabbitMQClientPluginConfig(instrumentor.getProfilerConfig());
            final boolean traceProducer = config.isTraceRabbitMQClientProducer();
            final boolean traceConsumer = config.isTraceRabbitMQClientConsumer();

            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            if (traceProducer) {
                // copy AMQP.BasicProperties
                target.weave("com.navercorp.pinpoint.plugin.rabbitmq.client.aspect.ChannelAspect");

                final InstrumentMethod basicPublish = target.getDeclaredMethod("basicPublish", "java.lang.String", "java.lang.String", "boolean", "boolean", "com.rabbitmq.client.AMQP$BasicProperties", "byte[]");
                if (basicPublish != null) {
                    basicPublish.addScopedInterceptor(ChannelBasicPublishInterceptor.class, RabbitMQClientConstants.RABBITMQ_PRODUCER_SCOPE, ExecutionPolicy.BOUNDARY);
                }
            }
            if (traceConsumer) {
                final InstrumentMethod basicGet = target.getDeclaredMethod("basicGet", "java.lang.String", "boolean");
                if (basicGet != null) {
                    basicGet.addScopedInterceptor(ChannelBasicGetInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE);
                }
            }
            return target.toBytecode();
        }
    }

    private void addCommonEditors(final boolean traceProducer, final boolean traceConsumer) {
        if (!traceProducer && !traceConsumer) {
            return;
        }
        // Channels
        transformTemplate.transform("com.rabbitmq.client.impl.ChannelN", ChannelTransform.class);
        transformTemplate.transform("com.rabbitmq.client.impl.recovery.AutorecoveringChannel", ChannelTransform.class);
        // FrameHandler implementations for end point and remote address
        transformTemplate.transform("com.rabbitmq.client.impl.SocketFrameHandler", SocketFrameHandlerTransform.class);
        transformTemplate.transform("com.rabbitmq.client.impl.nio.SocketChannelFrameHandler", SocketChannelFrameHandlerTransform.class);
        // Envelope - for asynchrnous trace propagation for consumers
        transformTemplate.transform("com.rabbitmq.client.Envelope", EnvelopeTransform.class);
        // AMQCommand - for pinpoint header propagation
        transformTemplate.transform("com.rabbitmq.client.impl.AMQCommand", AMQCommandTransform.class);
    }

    public static class SocketFrameHandlerTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            target.addField(LocalAddressAccessor.class);
            target.addField(RemoteAddressAccessor.class);
            final InstrumentMethod constructor1 = target.getConstructor("java.net.Socket");
            if (constructor1 != null) {
                constructor1.addScopedInterceptor(SocketFrameHandlerConstructInterceptor.class, RabbitMQClientConstants.RABBITMQ_FRAME_HANDLER_CREATION_SCOPE);
            }
            final InstrumentMethod constructor2 = target.getConstructor("java.net.Socket", "java.util.concurrent.ExecutorService");
            if (constructor2 != null) {
                constructor2.addScopedInterceptor(SocketFrameHandlerConstructInterceptor.class, RabbitMQClientConstants.RABBITMQ_FRAME_HANDLER_CREATION_SCOPE);
            }
            return target.toBytecode();
        }
    }

    public static class SocketChannelFrameHandlerTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            target.addField(LocalAddressAccessor.class);
            target.addField(RemoteAddressAccessor.class);
            final InstrumentMethod constructor = target.getConstructor("com.rabbitmq.client.impl.nio.SocketChannelFrameHandlerState");
            if (constructor != null) {
                constructor.addScopedInterceptor(SocketChannelFrameHandlerConstructInterceptor.class, RabbitMQClientConstants.RABBITMQ_FRAME_HANDLER_CREATION_SCOPE);
            }
            return target.toBytecode();
        }
    }

    public static class EnvelopeTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            target.addField(AsyncContextAccessor.class);
            return target.toBytecode();
        }
    }

    public static class AMQCommandTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            InstrumentMethod constructor = target.getConstructor("com.rabbitmq.client.Method", "com.rabbitmq.client.impl.AMQContentHeader", "byte[]");
            if (constructor != null) {
                constructor.addScopedInterceptor(AMQCommandConstructInterceptor.class, RabbitMQClientConstants.RABBITMQ_PRODUCER_SCOPE, ExecutionPolicy.INTERNAL);
            }
            return target.toBytecode();
        }
    }

    private void addAMQChannelEditor() {
        transformTemplate.transform("com.rabbitmq.client.impl.AMQChannel", AMQChannelTransform.class);
    }

    public static class AMQChannelTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            final InstrumentMethod handleCompleteInboundCommand = target.getDeclaredMethod("handleCompleteInboundCommand", "com.rabbitmq.client.impl.AMQCommand");
            if (handleCompleteInboundCommand != null) {
                RabbitMQClientPluginConfig config = new RabbitMQClientPluginConfig(instrumentor.getProfilerConfig());
                Filter<String> excludeExchangeFilter = config.getExcludeExchangeFilter();
                handleCompleteInboundCommand.addInterceptor(RabbitMQConsumerHandleCompleteInboundCommandInterceptor.class, va(excludeExchangeFilter));
            }
            return target.toBytecode();
        }
    }

    private void addConsumerDispatchEditor() {
        transformTemplate.transform("com.rabbitmq.client.impl.ConsumerDispatcher", ConsumerDispatcherTransform.class);
    }

    public static class ConsumerDispatcherTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            final InstrumentMethod handleDelivery = target.getDeclaredMethod("handleDelivery", "com.rabbitmq.client.Consumer", "java.lang.String", "com.rabbitmq.client.Envelope", "com.rabbitmq.client.AMQP$BasicProperties", "byte[]");
            if (handleDelivery == null) {
                return null;
            }
            RabbitMQClientPluginConfig config = new RabbitMQClientPluginConfig(instrumentor.getProfilerConfig());
            Filter<String> excludeExchangeFilter = config.getExcludeExchangeFilter();
            handleDelivery.addInterceptor(RabbitMQConsumerDispatchInterceptor.class, va(excludeExchangeFilter));
            target.addGetter(ChannelGetter.class, "channel");
            return target.toBytecode();
        }
    }

    private void addConsumerEditors() {
        // DefaultConsumer
        transformTemplate.transform("com.rabbitmq.client.DefaultConsumer", DefaultConsumerTransform.class);
        // QueueingConsumer
        transformTemplate.transform("com.rabbitmq.client.QueueingConsumer$Delivery", QueueingConsumerDeliveryTransform.class);
        transformTemplate.transform("com.rabbitmq.client.QueueingConsumer", QueueingConsumerTransform.class);
    }

    public static class DefaultConsumerTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            if (RabbitMQUtils.addConsumerHandleDeliveryInterceptor(target)) {
                return target.toBytecode();
            }
            return null;
        }
    }

    public static class QueueingConsumerDeliveryTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            InstrumentMethod constructor = target.getConstructor("com.rabbitmq.client.Envelope", "com.rabbitmq.client.AMQP$BasicProperties", "byte[]");
            if (constructor == null) {
                return null;
            }
            constructor.addScopedInterceptor(DeliveryConstructInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE, ExecutionPolicy.INTERNAL);
            target.addField(AsyncContextAccessor.class);
            return target.toBytecode();
        }
    }

    public static class QueueingConsumerTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            if (RabbitMQUtils.addConsumerHandleDeliveryInterceptor(target)) {
                InstrumentMethod nextDelivery = target.getDeclaredMethod("nextDelivery");
                if (nextDelivery != null) {
                    nextDelivery.addScopedInterceptor(QueueingConsumerOnNextInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE);
                }
                InstrumentMethod nextDeliveryTimeout = target.getDeclaredMethod("nextDelivery", "long");
                if (nextDeliveryTimeout != null) {
                    nextDeliveryTimeout.addScopedInterceptor(QueueingConsumerOnNextInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE);
                }
                InstrumentMethod handle = target.getDeclaredMethod("handle", "com.rabbitmq.client.QueueingConsumer$Delivery");
                if (handle != null) {
                    handle.addInterceptor(QueueingConsumerHandleInterceptor.class);
                }
                return target.toBytecode();
            }
            return null;
        }
    }

    private void addCustomConsumerEditors(List<String> customConsumers) {
        for (String customConsumer : customConsumers) {
            transformTemplate.transform(customConsumer, CustomConsumerTransform.class);
        }
    }

    public static class CustomConsumerTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            if (RabbitMQUtils.addConsumerHandleDeliveryInterceptor(target)) {
                return target.toBytecode();
            }
            // Check inner classes for consumer implementations
            for (InstrumentClass potentialConsumer : target.getNestedClasses(ClassFilters.ACCEPT_ALL)) {
                if (potentialConsumer.hasMethod("handleDelivery", "java.lang.String", "com.rabbitmq.client.Envelope", "com.rabbitmq.client.AMQP$BasicProperties", "byte[]")) {
                    instrumentor.transform(loader, potentialConsumer.getName(), PotentialConsumerTransform.class);
                }
            }
            return null;
        }
    }

    public static class PotentialConsumerTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            if (RabbitMQUtils.addConsumerHandleDeliveryInterceptor(target)) {
                return target.toBytecode();
            }
            return null;
        }
    }

    private void addSpringAmqpSupport(final boolean traceProducer, final boolean traceConsumer) {
        if (!traceProducer && !traceConsumer) {
            return;
        }

        transformTemplate.transform("org.springframework.amqp.rabbit.core.RabbitTemplate", RabbitTemplateTransform.class);

        // Spring-amqp rabbit client transformation
        if (traceConsumer) {
            // Message
            transformTemplate.transform("org.springframework.amqp.core.Message", MessageTransform.class);

            // Delivery
            // spring-rabbit pre-1.7.0
            transformTemplate.transform("org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$Delivery", BlockingQueueConsumerDeliveryTransform.class);
            // spring-rabbit 1.7.0+
            transformTemplate.transform("org.springframework.amqp.rabbit.support.Delivery", DeliveryTransform.class);

            // BlockingQueueConsumer
            transformTemplate.transform("org.springframework.amqp.rabbit.listener.BlockingQueueConsumer", BlockingQueueConsumerTransform.class);
            transformTemplate.transform("org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$InternalConsumer", BlockingQueueConsumerInternalConsumerTransform.class);
            // Spring-rabbit 1.7.7+, 2.0.3+
            transformTemplate.transform("org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$ConsumerDecorator", BlockingQueueConsumerConsumerDecoratorTransform.class);
        }
    }

    public static class RabbitTemplateTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);

            for (InstrumentMethod publicApi : target.getDeclaredMethods(RabbitMQUtils.getPublicApiFilter())) {
                publicApi.addScopedInterceptor(BasicMethodInterceptor.class, va(RabbitMQClientConstants.RABBITMQ_CLIENT_INTERNAL), RabbitMQClientConstants.RABBITMQ_TEMPLATE_API_SCOPE);
            }
            InstrumentMethod invoke = target.getDeclaredMethod("invoke", "org.springframework.amqp.rabbit.core.RabbitOperations$OperationsCallback");
            if (invoke != null) {
                invoke.addInterceptor(BasicMethodInterceptor.class, va(RabbitMQClientConstants.RABBITMQ_CLIENT_INTERNAL));
            }

            final RabbitMQClientPluginConfig config = new RabbitMQClientPluginConfig(instrumentor.getProfilerConfig());
            final boolean traceConsumer = config.isTraceRabbitMQClientConsumer();
            if (traceConsumer) {
                // Internal consumer implementations
                if (!RabbitMQUtils.addConsumerHandleDeliveryInterceptor(target)) {
                    // Check inner classes for consumer implementations
                    for (InstrumentClass potentialConsumer : target.getNestedClasses(ClassFilters.ACCEPT_ALL)) {
                        if (potentialConsumer.hasMethod("handleDelivery", "java.lang.String", "com.rabbitmq.client.Envelope", "com.rabbitmq.client.AMQP$BasicProperties", "byte[]")) {
                            instrumentor.transform(loader, potentialConsumer.getName(), PotentialConsumerTransform.class);
                        }
                    }
                }
            }

            return target.toBytecode();
        }
    }

    public static class MessageTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            target.addField(AsyncContextAccessor.class);
            return target.toBytecode();
        }
    }

    public static class BlockingQueueConsumerDeliveryTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            // spring-rabbit pre-1.4.2
            InstrumentMethod constructor1 = target.getConstructor("com.rabbitmq.client.Envelope", "com.rabbitmq.client.AMQP$BasicProperties", "byte[]");
            if (constructor1 != null) {
                constructor1.addScopedInterceptor(DeliveryConstructInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE, ExecutionPolicy.INTERNAL);
            }
            // spring-rabbit 1.4.2 to 1.6.x
            InstrumentMethod constructor2 = target.getConstructor("java.lang.String", "com.rabbitmq.client.Envelope", "com.rabbitmq.client.AMQP$BasicProperties", "byte[]");
            if (constructor2 != null) {
                constructor2.addScopedInterceptor(DeliveryConstructInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE, ExecutionPolicy.INTERNAL);
            }
            target.addField(AsyncContextAccessor.class);
            return target.toBytecode();
        }
    }

    public static class DeliveryTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            InstrumentMethod constructor = target.getConstructor("java.lang.String", "com.rabbitmq.client.Envelope", "com.rabbitmq.client.AMQP$BasicProperties", "byte[]");
            if (constructor != null) {
                constructor.addScopedInterceptor(DeliveryConstructInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE, ExecutionPolicy.INTERNAL);
            }
            // spring-rabbit 2.1.0+
            InstrumentMethod constructor_2_1_0 = target.getConstructor("java.lang.String", "com.rabbitmq.client.Envelope", "com.rabbitmq.client.AMQP$BasicProperties", "byte[]", "java.lang.String");
            if (constructor_2_1_0 != null) {
                constructor_2_1_0.addScopedInterceptor(DeliveryConstructInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE, ExecutionPolicy.INTERNAL);
            }
            target.addField(AsyncContextAccessor.class);
            return target.toBytecode();
        }
    }

    public static class BlockingQueueConsumerTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            InstrumentMethod nextMessage = target.getDeclaredMethod("nextMessage");
            if (nextMessage != null) {
                nextMessage.addScopedInterceptor(QueueingConsumerOnNextInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE);
            }
            InstrumentMethod nextMessageTimeout = target.getDeclaredMethod("nextMessage", "long");
            if (nextMessageTimeout != null) {
                nextMessageTimeout.addScopedInterceptor(QueueingConsumerOnNextInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE);
            }
            // spring-rabbit pre-1.7.0
            InstrumentMethod handle1 = target.getDeclaredMethod("handle", "org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$Delivery");
            if (handle1 != null) {
                handle1.addInterceptor(QueueingConsumerHandleInterceptor.class);
            }
            // spring-rabbit 1.7.0+
            InstrumentMethod handle2 = target.getDeclaredMethod("handle", "org.springframework.amqp.rabbit.support.Delivery");
            if (handle2 != null) {
                handle2.addInterceptor(QueueingConsumerHandleInterceptor.class);
            }
            return target.toBytecode();
        }
    }

    public static class BlockingQueueConsumerInternalConsumerTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            if (RabbitMQUtils.addConsumerHandleDeliveryInterceptor(target)) {
                return target.toBytecode();
            }
            return null;
        }
    }

    public static class BlockingQueueConsumerConsumerDecoratorTransform implements TransformCallback {
        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            if (RabbitMQUtils.addConsumerHandleDeliveryInterceptor(target)) {
                return target.toBytecode();
            }
            return null;
        }
    }

    @Override
    public void setTransformTemplate(TransformTemplate transformTemplate) {
        this.transformTemplate = transformTemplate;
    }
}


text:
namespace google {
namespace cloud {
namespace spanner_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {

//
// MakeProtoValue() is an overloaded helper function for creating
// google::protobuf::Value protos from convenient user-supplied arguments.
//

google::protobuf::Value MakeProtoValue(spanner::Value v) {
  google::protobuf::Value value;
  std::tie(std::ignore, value) = ToProto(std::move(v));
  return value;
}

google::protobuf::Value MakeProtoValue(std::string s) {
  google::protobuf::Value value;
  value.set_string_value(std::move(s));
  return value;
}

google::protobuf::Value MakeProtoValue(double d) {
  google::protobuf::Value value;
  value.set_number_value(d);
  return value;
}

template <typename T>
google::protobuf::Value MakeProtoValue(std::vector<T> v) {
  google::protobuf::Value value;
  for (auto& e : v) {
    *value.mutable_list_value()->add_values() = MakeProtoValue(std::move(e));
  }
  return value;
}

// Run on (6 X 2300 MHz CPU s)
// CPU Caches:
//   L1 Data 32K (x3)
//   L1 Instruction 32K (x3)
//   L2 Unified 256K (x3)
//   L3 Unified 46080K (x1)
// Load Average: 0.14, 1.27, 1.77
// --------------------------------------------------------------------------
// Benchmark                                Time             CPU   Iterations
// --------------------------------------------------------------------------
// BM_MergeChunkStrings                  95.0 ns         94.4 ns      7408343
// BM_MergeChunkListOfInts                317 ns          315 ns      2208054
// BM_MergeChunkListOfStrings             481 ns          480 ns      1000000
// BM_MergeChunkListsOfListOfString       817 ns          809 ns       837894

void BM_MergeChunkStrings(benchmark::State& state) {
  auto const a = MakeProtoValue("foo");
  auto const b = MakeProtoValue("bar");
  for (auto _ : state) {
    auto value = a;
    auto chunk = b;
    auto unused = MergeChunk(value, std::move(chunk));
    benchmark::DoNotOptimize(unused);
  }
}
BENCHMARK(BM_MergeChunkStrings);

void BM_MergeChunkListOfInts(benchmark::State& state) {
  auto const a = MakeProtoValue(std::vector<double>{2, 3});
  auto const b = MakeProtoValue(std::vector<double>{4});
  for (auto _ : state) {
    auto value = a;
    auto chunk = b;
    auto unused = MergeChunk(value, std::move(chunk));
    benchmark::DoNotOptimize(unused);
  }
}
BENCHMARK(BM_MergeChunkListOfInts);

void BM_MergeChunkListOfStrings(benchmark::State& state) {
  auto const a = MakeProtoValue(std::vector<std::string>{"a", "b"});
  auto const b = MakeProtoValue(std::vector<std::string>{"c", "d"});
  for (auto _ : state) {
    auto value = a;
    auto chunk = b;
    auto unused = MergeChunk(value, std::move(chunk));
    benchmark::DoNotOptimize(unused);
  }
}
BENCHMARK(BM_MergeChunkListOfStrings);

void BM_MergeChunkListsOfListOfString(benchmark::State& state) {
  auto const a = MakeProtoValue(std::vector<spanner::Value>{
      spanner::Value("a"), spanner::Value(std::vector<std::string>{"b", "c"})});
  auto const b = MakeProtoValue(std::vector<spanner::Value>{
      spanner::Value(std::vector<std::string>{"d"}), spanner::Value("e")});
  for (auto _ : state) {
    auto value = a;
    auto chunk = b;
    auto unused = MergeChunk(value, std::move(chunk));
    benchmark::DoNotOptimize(unused);
  }
}
BENCHMARK(BM_MergeChunkListsOfListOfString);

}  // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace spanner_internal
}  // namespace cloud
}  // namespace google


text:
<!DOCTYPE html>

Options

	Encoding

			<input type="radio" name="encoding" id="encode-default" value="" />(default)

			<input type="radio" name="encoding" id="encode-xml" value="xml" />XML

			<input type="radio" name="encoding" id="encode-json" value="json" />JSON

 Pretty

		 <input
			type="radio" name="pretty" id="pretty-default" value="" />(default)
		  <input
			type="radio" name="pretty" id="pretty-true" value="true" />On
		  <input
			type="radio" name="pretty" id="pretty-false" value="false" />Off

 Summary

			<input type="radio" name="_summary" id="summary-default" value="" />(none)

			<input type="radio" name="_summary" id="summary-true" value="true" />true

			<input type="radio" name="_summary" id="summary-text" value="text" />text

			<input type="radio" name="_summary" id="summary-data" value="data" />data

			<input type="radio" name="_summary" id="summary-count" value="count" />count

Server

			Server Home/Actions

Resources

					Patient

	<input th:if="${resourceName.empty} == false" type="hidden" id="resource" name="resource" th:value="${resourceName}"/>


text:
/******************************************************************************
 * @section DESCRIPTION
 *
 * This function populates the model state.
 *
 * If a state file is provided to the model then its contents are checked
 * to see if it agrees with the current simulation set-up, if so it is used
 * to initialize the model state.  If no state file is provided then the
 * model initializes all variables with defaults and the user should expect
 * to throw out the beginning of the simulation period as model spin-up.
 *****************************************************************************/

#include <vic_driver_image.h>

/******************************************************************************
 * @brief    This function handles tasks related to populating model state.
 *****************************************************************************/
void
vic_populate_model_state(dmy_struct *dmy_current)
{
    extern all_vars_struct *all_vars;
    extern lake_con_struct *lake_con;
    extern domain_struct    local_domain;
    extern option_struct    options;
    extern soil_con_struct *soil_con;
    extern veg_con_struct **veg_con;

    size_t                  i;

    // read the model state from the netcdf file if there is one
    if (options.INIT_STATE) {
        vic_restore();
    }
    else {
        // else generate a default state
        for (i = 0; i < local_domain.ncells_active; i++) {
            generate_default_state(&(all_vars[i]), &(soil_con[i]), veg_con[i],
                                   dmy_current);
            if (options.LAKES) {
                generate_default_lake_state(&(all_vars[i].lake_var),
                                            &(soil_con[i]), lake_con[i]);
            }
        }
    }

    // compute those state variables that are derived from the others
    for (i = 0; i < local_domain.ncells_active; i++) {
        compute_derived_state_vars(&(all_vars[i]), &(soil_con[i]), veg_con[i]);
        if (options.LAKES) {
            compute_derived_lake_dimensions(&(all_vars[i].lake_var),
                                            lake_con[i]);
        }
    }
}


text:
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Game.Rulesets.Judgements;

namespace osu.Game.Rulesets.Catch.Judgements
{
    public class CatchJudgement : Judgement
    {
        // todo: wangs
    }
}


text:
package httputils

import (
	"mime"
	"net/http"
)

// MimeTypes stores the MIME content type.
var MimeTypes = struct {
	TextPlain   string
	Tar         string
	OctetStream string
}{"text/plain", "application/tar", "application/octet-stream"}

// DetectContentType returns a best guess representation of the MIME
// content type for the bytes at c.  The value detected by
// http.DetectContentType is guaranteed not be nil, defaulting to
// application/octet-stream when a better guess cannot be made. The
// result of this detection is then run through mime.ParseMediaType()
// which separates the actual MIME string from any parameters.
func DetectContentType(c []byte) (string, map[string]string, error) {

	ct := http.DetectContentType(c)
	contentType, args, err := mime.ParseMediaType(ct)
	if err != nil {
		return "", nil, err
	}

	return contentType, args, nil
}


text:
koa-http-api
============

## Install

    npm install -g grunt-cli
    npm install


text:
primitive-man
=============

A port of Lemmings to HTML5


text:
import serial, sys, thread, time, struct
from Tkinter import *

WINDOW_HEIGHT 	= 320
WINDOW_WIDTH 	= 1280
PIXEL_HEIGHT 	= WINDOW_HEIGHT / 8
PIXEL_WIDTH 	= WINDOW_WIDTH / 32

FRAME_BUFFER_SIZE = 768
TOUCH_BUFFER_SIZE = 16

# Make the COM_PORT 1 less than the port you wanna use
COM_PORT 		= 3
BAUDRATE 		= 460800
TEST_MODE 		= False
HUMAN_READABLE  = False

EVENT_CLICK 	= 4
EVENT_RELEASE 	= 5
EVENT_DRAG 		= 6

touch_active = False
update_display = False
current_touch_pos = 0,0
ser = serial.Serial()
rectangles = [[]]
canvas = None
root = None
frame_buffer_read = None
frame_buffer_write = None
count = 0

def recieve_touch_buffer():
	global ser, canvas, frame_buffer_read, frame_buffer_write, update_display, count

	while 1:
		touch_buffer = ser.read(TOUCH_BUFFER_SIZE)
		touch_buffer = struct.unpack(TOUCH_BUFFER_SIZE * 'B', touch_buffer)

		print str(count)

		count = count + 1

		frame_buffer_read = [0] * 768

		for i in range(TOUCH_BUFFER_SIZE):
			for bit in range(8):
				if (touch_buffer[i] & (0x01 << (7 - bit))) == (0x01 << (7 -bit)):
					frame_buffer_read[(((3 - (i%4)) + ((i / 4) * 4)) * 8 + bit) * 3] = 255

		update_display = True

def open_serial():
	global ser

	ser.baudrate = BAUDRATE
	ser.port = COM_PORT
	try:
		ser.open()
	except ValueError:
		print "Failed to connect to device over COM Port: " + str(COM_PORT)
		sys.exit()

# Creates a canvas given inside a Tk object and fills the
# canvas with rectangle array.
def create_canvas(master):
	global canvas

	canvas = Canvas(master, width=WINDOW_WIDTH, height=WINDOW_HEIGHT)
	canvas.pack()

	rectangle_array = [[canvas.create_rectangle(i * PIXEL_WIDTH, j * PIXEL_HEIGHT, (i+1) * PIXEL_WIDTH, (j+1) * PIXEL_HEIGHT, fill="blue") for j in range(8)] for i in range(32)]

	return rectangle_array

def update():
	global frame_buffer_read, root, update_display

	if update_display == True:
		for i in range(0, FRAME_BUFFER_SIZE, 3):
			mycolor = '#%02x%02x%02x' % (int(frame_buffer_read[i]), int(frame_buffer_read[i + 1]), int(frame_buffer_read[i + 2]))
			canvas.itemconfig(rectangles[(i / 3) % 32][(i / 3) / 32], fill=mycolor)

		update_display = False

	root.after(1, update)

def main():
	global ser, rectangles, canvas, root

	if not TEST_MODE:
		open_serial()
		if not ser.isOpen():
			print "Failed to connect to device over COM Port: " + str(COM_PORT)
			sys.exit()

	root = Tk()

	rectangles = create_canvas(root)

	try:
		thread.start_new_thread(recieve_touch_buffer, ())
	except:
		print "Failed to start simulator threads...exiting"
		sys.exit(2)

	root.after(1, update)
	root.mainloop()

if __name__ == "__main__":
	main()


text:
<?php

namespace Eloquent\Phony\Pho;

use Eloquent\Phony\Facade\AbstractFacade;
use Eloquent\Phony\Facade\FacadeDriver;

/**
 * A facade for Phony usage under Pho.
 */
class Phony extends AbstractFacade
{
    /**
     * Get the facade driver.
     *
     * @return FacadeDriver The facade driver.
     */
    protected static function driver()
    {
        return PhoFacadeDriver::instance();
    }
}


text:
require 'sass/tree/node'

module Sass::Tree
  class AttrNode < ValueNode
    attr_accessor :name

    def initialize(name, value, style)
      @name = name
      super(value, style)
    end

    def ==(other)
      self.class == other.class && name == other.name && super
    end

    def to_s(tabs, parent_name = nil)
      if value[-1] == ?;
        raise Sass::SyntaxError.new("Invalid attribute: #{declaration.dump} (This isn't CSS!).", @line)
      end
      real_name = name
      real_name = "#{parent_name}-#{real_name}" if parent_name

      if value.empty? && children.empty?
        raise Sass::SyntaxError.new("Invalid attribute: #{declaration.dump}.", @line)
      end

      join_string = case @style
                    when :compact; ' '
                    when :compressed; ''
                    else "\n"
                    end
      spaces = '  ' * (tabs - 1)
      to_return = ''
      if !value.empty?
        to_return << "#{spaces}#{real_name}:#{@style == :compressed ? '' : ' '}#{value};#{join_string}"
      end

      children.each do |kid|
        to_return << "#{kid.to_s(tabs, real_name)}" << join_string
      end

      (@style == :compressed && parent_name) ? to_return : to_return[0...-1]
    end

    private

    def declaration
      ":#{name} #{value}"
    end

    def invalid_child?(child)
      if !child.is_a?(AttrNode) && !child.is_a?(CommentNode)
        "Illegal nesting: Only attributes may be nested beneath attributes."
      end
    end
  end
end


text:
/* This file is part of OWL JavaScript Utilities.

OWL JavaScript Utilities is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.

OWL JavaScript Utilities is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with OWL JavaScript Utilities.  If not, see
<http://www.gnu.org/licenses/>.
*/

/*
  Hey, so, this deep copy is still the only attempt at a truly
  comprehensive approach, even years later. Kudos to the original
  author, one 'Oran Looney' (or, at least, that's what his blog
  sez'.

  All I did was lift it out of the closure wrapper to make it
  CommonJS requireable.
*/

function Clone() {}

// clone objects, skip other types.
function clone(target) {
  if ( typeof target == 'object' ) {
    Clone.prototype = target;
    return new Clone();
  } else {
    return target;
  }
}

// Shallow Copy
function copy(target) {
  if (typeof target !== 'object' ) {
    return target;  // non-object have value sematics, so target is already a copy.
  } else {
    var value = target.valueOf();
    if (target != value) {
      // the object is a standard object wrapper for a native type, say String.
      // we can make a copy by instantiating a new object around the value.
      return new target.constructor(value);
    } else {
      // ok, we have a normal object. If possible, we'll clone the original's prototype
      // (not the original) to get an empty object with the same prototype chain as
      // the original.  If just copy the instance properties.  Otherwise, we have to
      // copy the whole thing, property-by-property.
      if ( target instanceof target.constructor && target.constructor !== Object ) {
	var c = clone(target.constructor.prototype);

	// give the copy all the instance properties of target.  It has the same
	// prototype as target, so inherited properties are already there.
	for ( var property in target) {
	  if (target.hasOwnProperty(property)) {
	    c[property] = target[property];
	  }
	}
      } else {
	var c = {};
	for ( var property in target ) c[property] = target[property];
      }

      return c;
    }
  }
}

// Deep Copy
var deepCopiers = [];

function DeepCopier(config) {
  for ( var key in config ) this[key] = config[key];
}
DeepCopier.prototype = {
  constructor: DeepCopier,

  // determines if this DeepCopier can handle the given object.
  canCopy: function(source) { return false; },

  // starts the deep copying process by creating the copy object.  You
  // can initialize any properties you want, but you can't call recursively
  // into the DeeopCopyAlgorithm.
  create: function(source) { },

  // Completes the deep copy of the source object by populating any properties
  // that need to be recursively deep copied.  You can do this by using the
  // provided deepCopyAlgorithm instance's deepCopy() method.  This will handle
  // cyclic references for objects already deepCopied, including the source object
  // itself.  The "result" passed in is the object returned from create().
  populate: function(deepCopyAlgorithm, source, result) {}
};

function DeepCopyAlgorithm() {
  // copiedObjects keeps track of objects already copied by this
  // deepCopy operation, so we can correctly handle cyclic references.
  this.copiedObjects = [];
  var thisPass = this;
  this.recursiveDeepCopy = function(source) {
    return thisPass.deepCopy(source);
  }
  this.depth = 0;
}
DeepCopyAlgorithm.prototype = {
  constructor: DeepCopyAlgorithm,

  maxDepth: 256,

  // add an object to the cache.  No attempt is made to filter duplicates;
  // we always check getCachedResult() before calling it.
  cacheResult: function(source, result) {
    this.copiedObjects.push([source, result]);
  },

  // Returns the cached copy of a given object, or undefined if it's an
  // object we haven't seen before.
  getCachedResult: function(source) {
    var copiedObjects = this.copiedObjects;
    var length = copiedObjects.length;
    for ( var i=0; i<length; i++ ) {
      if ( copiedObjects[i][0] === source ) {
	return copiedObjects[i][1];
      }
    }
    return undefined;
  },

  // deepCopy handles the simple cases itself: non-objects and object's we've seen before.
  // For complex cases, it first identifies an appropriate DeepCopier, then calls
  // applyDeepCopier() to delegate the details of copying the object to that DeepCopier.
  deepCopy: function(source) {
    // null is a special case: it's the only value of type 'object' without properties.
    if ( source === null ) return null;

    // All non-objects use value semantics and don't need explict copying.
    if ( typeof source !== 'object' ) return source;

    var cachedResult = this.getCachedResult(source);

    // we've already seen this object during this deep copy operation
    // so can immediately return the result.  This preserves the cyclic
    // reference structure and protects us from infinite recursion.
    if ( cachedResult ) return cachedResult;

    // objects may need special handling depending on their class.  There is
    // a class of handlers call "DeepCopiers"  that know how to copy certain
    // objects.  There is also a final, generic deep copier that can handle any object.
    for ( var i=0; i<deepCopiers.length; i++ ) {
      var deepCopier = deepCopiers[i];
      if ( deepCopier.canCopy(source) ) {
	return this.applyDeepCopier(deepCopier, source);
      }
    }
    // the generic copier can handle anything, so we should never reach this line.
    throw new Error("no DeepCopier is able to copy " + source);
  },

  // once we've identified which DeepCopier to use, we need to call it in a very
  // particular order: create, cache, populate.  This is the key to detecting cycles.
  // We also keep track of recursion depth when calling the potentially recursive
  // populate(): this is a fail-fast to prevent an infinite loop from consuming all
  // available memory and crashing or slowing down the browser.
  applyDeepCopier: function(deepCopier, source) {
    // Start by creating a stub object that represents the copy.
    var result = deepCopier.create(source);

    // we now know the deep copy of source should always be result, so if we encounter
    // source again during this deep copy we can immediately use result instead of
    // descending into it recursively.
    this.cacheResult(source, result);

    // only DeepCopier::populate() can recursively deep copy.  So, to keep track
    // of recursion depth, we increment this shared counter before calling it,
    // and decrement it afterwards.
    this.depth++;
    if ( this.depth > this.maxDepth ) {
      throw new Error("Exceeded max recursion depth in deep copy.");
    }

    // It's now safe to let the deepCopier recursively deep copy its properties.
    deepCopier.populate(this.recursiveDeepCopy, source, result);

    this.depth--;

    return result;
  }
};

// entry point for deep copy.
//   source is the object to be deep copied.
//   maxDepth is an optional recursion limit. Defaults to 256.
function deepCopy(source, maxDepth) {
  var deepCopyAlgorithm = new DeepCopyAlgorithm();
  if ( maxDepth ) deepCopyAlgorithm.maxDepth = maxDepth;
  return deepCopyAlgorithm.deepCopy(source);
}

// publicly expose the DeepCopier class.
deepCopy.DeepCopier = DeepCopier;

// publicly expose the list of deepCopiers.
deepCopy.deepCopiers = deepCopiers;

// make deepCopy() extensible by allowing others to
// register their own custom DeepCopiers.
deepCopy.register = function(deepCopier) {
  if ( !(deepCopier instanceof DeepCopier) ) {
    deepCopier = new DeepCopier(deepCopier);
  }
  deepCopiers.unshift(deepCopier);
}

// Generic Object copier
// the ultimate fallback DeepCopier, which tries to handle the generic case.  This
// should work for base Objects and many user-defined classes.
deepCopy.register({
  canCopy: function(source) { return true; },

  create: function(source) {
    if ( source instanceof source.constructor ) {
      return clone(source.constructor.prototype);
    } else {
      return {};
    }
  },

  populate: function(deepCopy, source, result) {
    for ( var key in source ) {
      if ( source.hasOwnProperty(key) ) {
	result[key] = deepCopy(source[key]);
      }
    }
    return result;
  }
});

// Array copier
deepCopy.register({
  canCopy: function(source) {
    return ( source instanceof Array );
  },

  create: function(source) {
    return new source.constructor();
  },

  populate: function(deepCopy, source, result) {
    for ( var i=0; i<source.length; i++) {
      result.push( deepCopy(source[i]) );
    }
    return result;
  }
});

// Date copier
deepCopy.register({
  canCopy: function(source) {
    return ( source instanceof Date );
  },

  create: function(source) {
    return new Date(source);
  }
});

// HTML DOM Node

// utility function to detect Nodes.  In particular, we're looking
// for the cloneNode method.  The global document is also defined to
// be a Node, but is a special case in many ways.
function isNode(source) {
  return false; // LJF change here -- I don't care that I am breaking
  // this for the browser. at all.
  if ( window.Node ) {
    return source instanceof Node;
  } else {
    // the document is a special Node and doesn't have many of
    // the common properties so we use an identity check instead.
    if ( source === document ) return true;
    return (
      typeof source.nodeType === 'number' &&
	source.attributes &&
	source.childNodes &&
	source.cloneNode
    );
  }
}

// Node copier
deepCopy.register({
  canCopy: function(source) { return isNode(source); },

  create: function(source) {
    // there can only be one (document).
    if ( source === document ) return document;

    // start with a shallow copy.  We'll handle the deep copy of
    // its children ourselves.
    return source.cloneNode(false);
  },

  populate: function(deepCopy, source, result) {
    // we're not copying the global document, so don't have to populate it either.
    if ( source === document ) return document;

    // if this Node has children, deep copy them one-by-one.
    if ( source.childNodes && source.childNodes.length ) {
      for ( var i=0; i<source.childNodes.length; i++ ) {
	var childCopy = deepCopy(source.childNodes[i]);
	result.appendChild(childCopy);
      }
    }
  }
});

exports.DeepCopyAlgorithm = DeepCopyAlgorithm;
exports.copy = copy;
exports.clone = clone;
exports.deepCopy = deepCopy;


text:
/* eslint-disable react/prop-types */
import React from 'react';

const registerMachineForm = props => (

Register new Machine

After creating MachineOwner contract you should be able to register new Machine

    <form>
      <fieldset className="uk-fieldset">

          <input className="uk-input" type="text" placeholder="Model" name="model"
            onChange={props.onChange} value={props.state.model} />

          <input className="uk-input" type="text" placeholder="Make" name="make"
            onChange={props.onChange} value={props.state.make} />

          <input className="uk-input" type="text" placeholder="VIN" name="vin"
            onChange={props.onChange} value={props.state.vin} />

          <button className="uk-button uk-button-default"
            disabled={props.state._disabled} onClick={props.onSubmit}>Register</button>

      </fieldset>
    </form>

);

export default registerMachineForm;


text:
	# See $(GFXLIB)/tools/gmake_scripts/readme.txt for the list of variables
	OPT_OS					= osx
	OPT_LINK_OPTIMIZE		= no

# uGFX settings
	# See $(GFXLIB)/tools/gmake_scripts/library_ugfx.mk for the list of variables
	GFXLIB					= ../../path/to/ugfx
	GFXBOARD				= OSX
	GFXDEMO					= modules/gdisp/basics

# OSX settings
	# See $(GFXLIB)/tools/gmake_scripts/os_osx.mk for the list of variables
	OSX_SDK = /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk
	OSX_ARCH = -mmacosx-version-min=10.11

##############################################################################################
# Set these for your project
#

ARCH     =
SRCFLAGS = -ggdb -O0
CFLAGS   =
CXXFLAGS =
ASFLAGS  =
LDFLAGS  =

SRC      =
OBJS     =
DEFS     =
LIBS     =
INCPATH  = /opt/X11/include
LIBPATH  = /opt/X11/lib

##############################################################################################
# These should be at the end
#

include $(GFXLIB)/tools/gmake_scripts/library_ugfx.mk
include $(GFXLIB)/tools/gmake_scripts/os_$(OPT_OS).mk
include $(GFXLIB)/tools/gmake_scripts/compiler_gcc.mk
# *** EOF ***


text:
layout: post
title: "Making a Game Again?"
category: News
tags: [News, Ludum Dare]
time: 09:16:36
---

I've gotta do a lab today at school, tomorrow I need to do the exam I missed when I had my glasses-missing headaches and I'm going to Ikea and some other shops for, you guessed it, shopping! Sure it's fun and sure I need to do these things but the only thing on my mind now is making a new game. This weekend [Ludum Dare](http://www.ludumdare.com/compo/) is on again and I would really, really like to enter it! It's been [over a year](http://www.ludumdare.com/compo/) since my last Ludum Dare and almost 11 months since my [last game](/games/wheres_teddy).

I want to make games again..

I can't promise a new game this weekend but I think I might have the time for some game creation on friday, saturday and sunday evening/night so I just might. The last time I even had a massage course the whole day on sunday/saturday so I should be fine.

This time I also think I can come up with some more sound and music compared to the last time (where I only had two thuds!). I got [LMMS](http://lmms.sourceforge.net/), a free music creation program. I really suck at making music though lol.

I haven't made a game since I switched to Slackware either, luckily [SFML](http://www.sfml-dev.org/) is cross platform. I've also got my old [7days library](https://github.com/treeman/7days), my collection of old game creating codebase which I was pretty proud of for a while.

For graphics I think I'm aiming for some pixelated cool stuff with [mtPaint](http://mtpaint.sourceforge.net/). Pixelated stuff looks awesome, if you're good at it, and I'd like to make something similar.. At least a little similar.

  Unreleased fun pixel graphics

So for a quick recap, if I'm going to make a game again this is what I'm going to use:

1.  [LMMS](http://lmms.sourceforge.net/) for music
2.  [SFML](http://www.sfml-dev.org/) as the core game library (graphics, sound and input)
3.  [7days library](https://github.com/treeman/7days) for useful stuff
4.  [mtPaint](http://mtpaint.sourceforge.net/) for pixel graphics

As usual it'll be made in C++ (I might do something else another time) and I'll probably listen to *Raubtier, Sarah Brightman, Hans Zimmer* and some classical composers *(Mozart, Bach, Vivaldi etc)*.


text:
require(['dojo/dom-construct',
        'dojo/_base/window',
        'dojo/dom',
        'dojo/dom-style',
        'dojo/_base/fx',
        'dojo/_base/kernel'], function(domConstruct,win,dom,style,fx,kernel) {

	kernel.global.DojoGrailsSpinner = {
		/**
		 * Creates the spinner object <div> and attaches it to the body as the first
		 * element.
		 */
		create:function() {
			var attrObj = {
				  id:"grailsdojospinner",
				  className:"grailsdojospinner"
			}
			var spinner = domConstruct.create("div", attrObj, win.body(), 'first');
			return spinner;
		},

		/**
		 * Will display the spinner. If it doesn't exist, will create it first.
		 */
		show:function() {
			if (!dojoGrailsPluginConfig.showSpinner){
				return;
			}

		    var spinner = dom.byId("grailsdojospinner");
		    if (!spinner){
		    	spinner = this.create();
			}
			fx.fadeIn({
				node:spinner,
			    duration:100,
			    beforeBegin: function(obj) {
			    	style.set(obj, "opacity", "0");
			    	style.set(obj, "display", "block");
			    }
			}).play();
		},

		/**
		 * Will hide the spinner.
		 */
		hide:function() {
			if(!dojoGrailsPluginConfig.showSpinner){
				return;
			}

			fx.fadeOut({
				node:"grailsdojospinner",
			    duration:300,
			    onEnd: function(obj) {
			    	style.set(obj, "display", "none");
			    }
			}).play();
		}
	}
});


text:
#pragma once

#include "output.h"
#include <string>

namespace cbor
{
class encoder
{
private:
	output* _out;

public:
	encoder(output& out);

	~encoder();

	void write_bool(bool value);

	void write_int(int value);

	void write_int(long long value);

	void write_int(unsigned int value);

	void write_int(unsigned long long value);

	void write_bytes(const unsigned char* data, unsigned int size);

	void write_string(const char* data, unsigned int size);

	void write_string(const std::string str);

	void write_array(int size);

	void write_map(int size);

	void write_tag(const unsigned int tag);

	void write_special(int special);

	void write_float(float value);

	void write_double(double value);

	void write_null();

	void write_undefined();

private:
	void write_type_value(int major_type, unsigned int value);

	void write_type_value(int major_type, unsigned long long value);
};
}


text:
<?php

final class HarbormasterCircleCIBuildStepImplementation
  extends HarbormasterBuildStepImplementation {

  public function getName() {
    return pht('Build with CircleCI');
  }

  public function getGenericDescription() {
    return pht('Trigger a build in CircleCI.');
  }

  public function getBuildStepGroupKey() {
    return HarbormasterExternalBuildStepGroup::GROUPKEY;
  }

  public function getDescription() {
    return pht('Run a build in CircleCI.');
  }

  public function getEditInstructions() {
    $hook_uri = '/harbormaster/hook/circleci/';
    $hook_uri = PhabricatorEnv::getProductionURI($hook_uri);

    return pht(<<<EOTEXT
WARNING: This build step is new and experimental!

To build **revisions** with CircleCI, they must:

  - belong to a tracked repository;
  - the repository must have a Staging Area configured;
  - the Staging Area must be hosted on GitHub; and
  - you must configure the webhook described below.

To build **commits** with CircleCI, they must:

  - belong to a repository that is being imported from GitHub; and
  - you must configure the webhook described below.

Webhook Configuration
=====================

Add this webhook to your `circle.yml` file to make CircleCI report results
to Harbormaster. Until you install this hook, builds will hang waiting for
a response from CircleCI.

```lang=yml
notify:
  webhooks:
    - url: %s
```

Environment
===========

These variables will be available in the build environment:

| Variable | Description |
|----------|-------------|
| `HARBORMASTER_BUILD_TARGET_PHID` | PHID of the Build Target.

EOTEXT
    ,
    $hook_uri);
  }

  public static function getGitHubPath($uri) {
    $uri_object = new PhutilURI($uri);
    $domain = $uri_object->getDomain();

    $domain = phutil_utf8_strtolower($domain);
    switch ($domain) {
      case 'github.com':
      case 'www.github.com':
        return $uri_object->getPath();
      default:
        return null;
    }
  }

  public function execute(
    HarbormasterBuild $build,
    HarbormasterBuildTarget $build_target) {
    $viewer = PhabricatorUser::getOmnipotentUser();

    $buildable = $build->getBuildable();

    $object = $buildable->getBuildableObject();
    $object_phid = $object->getPHID();
    if (!($object instanceof HarbormasterCircleCIBuildableInterface)) {
      throw new Exception(
        pht(
          'Object ("%s") does not implement interface "%s". Only objects '.
          'which implement this interface can be built with CircleCI.',
          $object_phid,
          'HarbormasterCircleCIBuildableInterface'));
    }

    $github_uri = $object->getCircleCIGitHubRepositoryURI();
    $build_type = $object->getCircleCIBuildIdentifierType();
    $build_identifier = $object->getCircleCIBuildIdentifier();

    $path = self::getGitHubPath($github_uri);
    if ($path === null) {
      throw new Exception(
        pht(
          'Object ("%s") claims "%s" is a GitHub repository URI, but the '.
          'domain does not appear to be GitHub.',
          $object_phid,
          $github_uri));
    }

    $path_parts = trim($path, '/');
    $path_parts = explode('/', $path_parts);
    if (count($path_parts) < 2) {
      throw new Exception(
        pht(
          'Object ("%s") claims "%s" is a GitHub repository URI, but the '.
          'path ("%s") does not have enough components (expected at least '.
          'two).',
          $object_phid,
          $github_uri,
          $path));
    }

    list($github_namespace, $github_name) = $path_parts;
    $github_name = preg_replace('(\\.git$)', '', $github_name);

    $credential_phid = $this->getSetting('token');
    $api_token = id(new PassphraseCredentialQuery())
      ->setViewer($viewer)
      ->withPHIDs(array($credential_phid))
      ->needSecrets(true)
      ->executeOne();
    if (!$api_token) {
      throw new Exception(
        pht(
          'Unable to load API token ("%s")!',
          $credential_phid));
    }

    // When we pass "revision", the branch is ignored (and does not even need
    // to exist), and only shows up in the UI. Use a cute string which will
    // certainly never break anything or cause any kind of problem.
    $ship = "\xF0\x9F\x9A\xA2";
    $branch = "{$ship}Harbormaster";

    $token = $api_token->getSecret()->openEnvelope();
    $parts = array(
      'https://circleci.com/api/v1/project',
      phutil_escape_uri($github_namespace),
      phutil_escape_uri($github_name)."?circle-token={$token}",
    );

    $uri = implode('/', $parts);

    $data_structure = array();
    switch ($build_type) {
      case 'tag':
        $data_structure['tag'] = $build_identifier;
        break;
      case 'revision':
        $data_structure['revision'] = $build_identifier;
        break;
      default:
        throw new Exception(
          pht(
            'Unknown CircleCI build type "%s". Expected "%s" or "%s".',
            $build_type,
            'tag',
            'revision'));
    }

    $data_structure['build_parameters'] = array(
      'HARBORMASTER_BUILD_TARGET_PHID' => $build_target->getPHID(),
    );

    $json_data = phutil_json_encode($data_structure);

    $future = id(new HTTPSFuture($uri, $json_data))
      ->setMethod('POST')
      ->addHeader('Content-Type', 'application/json')
      ->addHeader('Accept', 'application/json')
      ->setTimeout(60);

    $this->resolveFutures(
      $build,
      $build_target,
      array($future));

    $this->logHTTPResponse($build, $build_target, $future, pht('CircleCI'));

    list($status, $body) = $future->resolve();
    if ($status->isError()) {
      throw new HarbormasterBuildFailureException();
    }

    $response = phutil_json_decode($body);
    $build_uri = idx($response, 'build_url');
    if (!$build_uri) {
      throw new Exception(
        pht(
          'CircleCI did not return a "%s"!',
          'build_url'));
    }

    $target_phid = $build_target->getPHID();

    // Write an artifact to create a link to the external build in CircleCI.

    $api_method = 'harbormaster.createartifact';
    $api_params = array(
      'buildTargetPHID' => $target_phid,
      'artifactType' => HarbormasterURIArtifact::ARTIFACTCONST,
      'artifactKey' => 'circleci.uri',
      'artifactData' => array(
        'uri' => $build_uri,
        'name' => pht('View in CircleCI'),
        'ui.external' => true,
      ),
    );

    id(new ConduitCall($api_method, $api_params))
      ->setUser($viewer)
      ->execute();
  }

  public function getFieldSpecifications() {
    return array(
      'token' => array(
        'name' => pht('API Token'),
        'type' => 'credential',
        'credential.type'
          => PassphraseTokenCredentialType::CREDENTIAL_TYPE,
        'credential.provides'
          => PassphraseTokenCredentialType::PROVIDES_TYPE,
        'required' => true,
      ),
    );
  }

  public function supportsWaitForMessage() {
    // NOTE: We always wait for a message, but don't need to show the UI
    // control since "Wait" is the only valid choice.
    return false;
  }

  public function shouldWaitForMessage(HarbormasterBuildTarget $target) {
    return true;
  }

}


text:
* [FEATURE] allow setting of environment variables. Useful for resetting (local copies of) global variables that each child process gets. e.g.
**extraSteps**, **build**, and **deploy** all run in child processes with a copy of the parent shell's environment variables. This feature allows you to modify
the child_process' copy of those variables without modifying the parent process environment variables.

### 0.0.10
* [MAINT] removed `async` module and use a simpler approach for uploading files consecutively.
* [MAINT] added a hardcoded timeout of 30 seconds that prints out the file attempting to be uploaded.<br>
        How to handle this is still up in the works. Possible behavior:
          - Skip file and add it to end of queue (unless it resolved in meantime)
          - Cancel entire build ?
          - Retry upload right away (Can you cancel an initiated upload to S3?)

### 0.0.9
* [BUGFIX] concurrency was lowered to 1 at a time for uploading files to s3

### 0.0.8
* [FEATURE] specify multiple default cli-args inside `includeOptions` Array
* [BREAKING ENHANCHEMENT] cli-args for custom commands are escaped using a proper tool [shell-escape](https://github.com/xxorax/node-shell-escape). cli-args are no longer always wrapped in double quotes
* [TESTS] add tests for formatting a custom command

### 0.0.6
* [FEATURE] new cli-arg 'prepend-path' allows you to specify a subdirectory in an s3 bucket to put assets

### 0.0.5

* [FEATURE] allow default cli-args when running custom scripts during deploy process

### 0.0.4

This release introduces better formatted for running extra-step commands and more test coverage.

* [BREAKING ENHANCEMENT] command line arguments are formatted in a more commonly supported way (no more = signs)
* [TESTS] command formatting and running extra-steps
* [MAINT] fix typos and added some documentation/commenting


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "tbproduct".
 *
 * @property integer $product_id
 * @property string $product_partno
 * @property string $product_name
 * @property string $product_sellingPice
 * @property integer $product_stock
 * @property integer $product_categoryid
 * @property string $product_description
 * @property integer $product_reorderLevel
 * @property string $product_unitName
 * @property string $product_active
 * @property string $product_averageCost
 * @property integer $product_markupPercent
 * @property string $product_type
 *
 * @property Tbcategory $productCategory
 */
class Product extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbproduct';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_partno', 'product_name', 'product_sellingPice', 'product_stock', 'product_categoryid', 'product_description', 'product_reorderLevel', 'product_unitName', 'product_averageCost', 'product_markupPercent', 'product_type'], 'required'],
            [['product_sellingPice', 'product_averageCost'], 'number'],
            [['product_stock', 'product_categoryid', 'product_reorderLevel', 'product_markupPercent'], 'integer'],
            [['product_description'], 'string'],
			[['product_supply_tax', 'product_purchase_tax'], 'string', 'max' => 10],
            [['product_partno'], 'string', 'max' => 15],
            [['product_name'], 'string', 'max' => 55],
            [['product_unitName'], 'string', 'max' => 6],
            [['product_active', 'product_type'], 'string', 'max' => 1]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'product_id' => 'Product ID',
            'product_partno' => 'Product Partno',
            'product_name' => 'Product Name',
            'product_sellingPice' => 'Product Selling Pice',
            'product_stock' => 'Product Stock',
            'product_categoryid' => 'Product Categoryid',
            'product_description' => 'Product Description',
            'product_reorderLevel' => 'Product Reorder Level',
            'product_unitName' => 'Product Unit Name',
            'product_active' => 'Product Active',
            'product_averageCost' => 'Product Average Cost',
            'product_markupPercent' => 'Product Markup Percent',
            'product_type' => 'Product Type',
			'product_supply_tax' => 'Product Supply Tax',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductCategory()
    {
        return $this->hasOne(Tbcategory::className(), ['category_id' => 'product_categoryid']);
    }
}


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyDescription("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c6a197d6-0c14-4b95-9301-1bb3399ef2d9")]

#if NET35
#else
[assembly: System.Reflection.AssemblyMetadata("Verify.ProjectDirectory", "C:\\Projects\\Repos\\dparvin\\PropertyGridHelpers\\Code\\SampleControls\\")]
[assembly: System.Reflection.AssemblyMetadata("Verify.SolutionDirectory", "C:\\Projects\\Repos\\dparvin\\PropertyGridHelpers\\Code\\PropertyGridHelpers\\")]
#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

using Orleans;
using Orleans.Hosting;
using Orleans.ApplicationParts;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Storage;
using Orleans.Streams;

namespace Orleankka.Legacy.Cluster
{
    using Behaviors;
    using Streams;
    using Utility;

    public class LegacyOrleankkaClusterOptions
    {
        readonly Dictionary<string, Action<OptionsBuilder<SimpleMessageStreamProviderOptions>>> smsStreamProviders =
             new Dictionary<string, Action<OptionsBuilder<SimpleMessageStreamProviderOptions>>>();

        string[] persistentStreamProviders = new string[0];

        public LegacyOrleankkaClusterOptions AddSimpleMessageStreamProvider(string name, Action<OptionsBuilder<SimpleMessageStreamProviderOptions>> configureOptions = null)
        {
            Requires.NotNullOrWhitespace(name, nameof(name));
            smsStreamProviders.Add(name, configureOptions);
            return this;
        }

        public LegacyOrleankkaClusterOptions RegisterPersistentStreamProviders(params string[] names)
        {
            Requires.NotNull(names, nameof(names));
            persistentStreamProviders = names;
            return this;
        }

        internal void Configure(IApplicationPartManager apm, IServiceCollection services)
        {
            var assemblies = apm.ApplicationParts
                .OfType<AssemblyPart>().Select(x => x.Assembly)
                .Distinct()
                .ToArray();

            var actors = assemblies.SelectMany(x => x.GetTypes())
                .Where(x => typeof(Actor).IsAssignableFrom(x) && x.IsClass && !x.IsAbstract)
                .ToArray();

            RegisterStreamSubscriptions(services, actors);
            RegisterSimpleMessageStreamProviders(services);
            RegisterBehaviors(actors);

            BootStreamSubscriptions(services);
        }

        void RegisterSimpleMessageStreamProviders(IServiceCollection services)
        {
            foreach (var each in smsStreamProviders)
            {
                var name = each.Key;
                var configureOptions = each.Value;

                configureOptions?.Invoke(services.AddOptions<SimpleMessageStreamProviderOptions>(name));
                services.ConfigureNamedOptionForLogging<SimpleMessageStreamProviderOptions>(name);
                services.AddSingletonNamedService<IStreamProvider>(name, (s, n) => new SimpleMessageStreamProviderMatcher(s, n));
            }
        }

        static void RegisterStreamSubscriptions(IServiceCollection services, Type[] actors)
        {
            var subscriptions = new StreamSubscriptionSpecificationRegistry();

            foreach (var actor in actors)
            {
                var dispatcher = new Dispatcher(actor);
                subscriptions.Register(StreamSubscriptionSpecification.From(actor, dispatcher));
            }

            services.AddSingleton(subscriptions);
        }

        static void RegisterBehaviors(Type[] actors)
        {
            foreach (var each in actors)
                ActorBehavior.Register(each);
        }

        void BootStreamSubscriptions(IServiceCollection services)
        {
            const string name = "orlssb";
            services.AddOptions<PersistentStreamProviderMatcherOptions>(name).Configure(c => c.Providers = persistentStreamProviders);
            services.AddSingletonNamedService(name, PersistentStreamProviderMatcher.Create);
            services.AddSingletonNamedService(name, (s, n) => (ILifecycleParticipant<ISiloLifecycle>) s.GetRequiredServiceByName<IGrainStorage>(n));
        }
    }

    public static class LegacySiloHostBuilderExtensions
    {
        public static ISiloHostBuilder UseOrleankkaLegacyFeatures(this ISiloHostBuilder builder) =>
            UseOrleankkaLegacyFeatures(builder, new LegacyOrleankkaClusterOptions());

        public static ISiloHostBuilder UseOrleankkaLegacyFeatures(this ISiloHostBuilder builder, Func<LegacyOrleankkaClusterOptions, LegacyOrleankkaClusterOptions> configure) =>
            UseOrleankkaLegacyFeatures(builder, configure(new LegacyOrleankkaClusterOptions()));

        public static ISiloHostBuilder UseOrleankkaLegacyFeatures(this ISiloHostBuilder builder, LegacyOrleankkaClusterOptions cfg) =>
            builder.ConfigureServices(services => UseOrleankkaLegacyFeatures(builder.GetApplicationPartManager(), services, cfg));

        public static ISiloBuilder UseOrleankkaLegacyFeatures(this ISiloBuilder builder) =>
            UseOrleankkaLegacyFeatures(builder, new LegacyOrleankkaClusterOptions());

        public static ISiloBuilder UseOrleankkaLegacyFeatures(this ISiloBuilder builder, Func<LegacyOrleankkaClusterOptions, LegacyOrleankkaClusterOptions> configure) =>
            UseOrleankkaLegacyFeatures(builder, configure(new LegacyOrleankkaClusterOptions()));

        public static ISiloBuilder UseOrleankkaLegacyFeatures(this ISiloBuilder builder, LegacyOrleankkaClusterOptions cfg) =>
            builder.ConfigureServices(services => UseOrleankkaLegacyFeatures(builder.GetApplicationPartManager(), services, cfg));

        static void UseOrleankkaLegacyFeatures(IApplicationPartManager apm, IServiceCollection services, LegacyOrleankkaClusterOptions cfg) =>
            cfg.Configure(apm, services);
    }
}


text:
typeform client for node and the browser

##Installation

clone this repo

##Usage

import (*ES6*) or require the package and set your API-key for authentication.
Every method of the library returns a promise tha will be fulfilled with
typeform.io's response.

**src** folder contain the ES6 version.
**dist** folder contains the ES5 version.

```javascript
import Typeform from 'typeform-js';

let typeform = Typeform('MY_API_SECRET');
```

##Available endpoints

###base

The base endpoint response contains information about the API.

example

```javascript
typeform.base().then( res => console.log(res));
```

###forms

####Create a form

arguments:

| Command | Type | Optional | Description |
| --- | --- | --- | --- |
| Title  | string | no | form title |
| Fields | array  | no | form fields |
| Extra  | object | yes | extra options |

example

```javascript
typeform.form( "My first typeform",
    [
        {
            "type": "short_text",
            "question": "What is your name?"
        }
    ],
	{ "branding": false }
);
```

####Get a form

arguments:

| Command | Type | Optional | Description |
| --- | --- | --- | --- |
| Id  | string | no | form id |

example:

```javascript
typeform.form.get( 'id' );
```

###images

####send an image

arguments:

| Command | Type | Optional | Description |
| --- | --- | --- | --- |
| Url  | string | no | url to sent |

example

```javascript
typeform.image( "http://MY_IMAGE.URL");
```

####Get an image

arguments:

| Command | Type | Optional | Description |
| --- | --- | --- | --- |
| Id  | string | no | image id |

example:

```javascript
typeform.image.get( 'id' );
```

###designs

####Create a design

arguments:

| Command | Type | Optional | Description |
| --- | --- | --- | --- |
| Colors  | object | no | design colors |
| Font | string  | no | google web font for this design |

example

```javascript
typeform.design({
        "question": "#3D3D3D",
        "button": "#4FB0AE",
        "answer": "#4FB0AE",
        "background": "#FFFFFF"
    },
    'Playfair'
);
```

####Get a design

arguments:

| Command | Type | Optional | Description |
| --- | --- | --- | --- |
| Id  | string | no | design id |

example:

```javascript
typeform.design.get( 'id' );
```

###urls

####Create a new url

arguments:

| Command | Type | Optional | Description |
| --- | --- | --- | --- |
| form_id  | object | no | actual id |

example

```javascript
typeform.url('anId');
```

####Get a url

arguments:

| Command | Type | Optional | Description |
| --- | --- | --- | --- |
| Id  | string | no | url id |

example:

```javascript
typeform.url.get( 'id' );
```

###Get a url

arguments:

| Command | Type | Optional | Description |
| --- | --- | --- | --- |
| Old_id  | string | no | current url id |
| New_id  | string | no | new url id |

example:

```javascript
typeform.url.set( 'id', 'newSuperCoolId' );
```

#TODO

- fields Objects?


text:
layout: post
date: 2018-03-11
title: "Sarah Houston Roxanne 2012"
category: Sarah Houston
tags: [Sarah Houston,2012]
---
### Sarah Houston Roxanne
Just **$459.99**
### 2012

BRANDS	Sarah Houston

Years	2012

Buy it: [https://www.readybrides.com/en/sarah-houston/47348-sarah-houston-roxanne.html](https://www.readybrides.com/en/sarah-houston/47348-sarah-houston-roxanne.html)


text:
package org.zaproxy.clientapi.gen.deprecated;

import java.util.HashMap;
import java.util.Map;
import org.zaproxy.clientapi.core.ApiResponse;
import org.zaproxy.clientapi.core.ClientApi;
import org.zaproxy.clientapi.core.ClientApiException;

/** API implementation with deprecated methods, (re)moved from generated class. */
@SuppressWarnings("javadoc")
public class AuthorizationDeprecated {

    private final ClientApi api;

    public AuthorizationDeprecated(ClientApi api) {
        this.api = api;
    }

    /**
     * @deprecated (1.1.0) Use the method without the API key and use one of the {@code ClientApi}
     *     constructors that allow to set the API key (e.g. {@link ClientApi#ClientApi(String, int,
     *     String)}).
     */
    @Deprecated
    public ApiResponse setBasicAuthorizationDetectionMethod(
            String apikey,
            String contextid,
            String headerregex,
            String bodyregex,
            String statuscode,
            String logicaloperator)
            throws ClientApiException {
        Map<String, String> map = new HashMap<>();
        if (apikey != null) {
            map.put("apikey", apikey);
        }
        map.put("contextId", contextid);
        if (headerregex != null) {
            map.put("headerRegex", headerregex);
        }
        if (bodyregex != null) {
            map.put("bodyRegex", bodyregex);
        }
        if (statuscode != null) {
            map.put("statusCode", statuscode);
        }
        if (logicaloperator != null) {
            map.put("logicalOperator", logicaloperator);
        }
        return api.callApi("authorization", "action", "setBasicAuthorizationDetectionMethod", map);
    }
}