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

namespace Sharper.C.Testing.Arbitraries
{

public static partial class SystemArbitrariesModule
{
    public const int DefaultFunc1CacheSize = 1000;

    public static Arbitrary<Func<A, B>> AnyFunc1<A, B>
      ( Arbitrary<B> arbB
      , IEqualityComparer<A> comp
      , int cacheSize = DefaultFunc1CacheSize
      )
    =>
        Arb.From(GenAnyFunc1(arbB.Generator, comp, cacheSize));

    public static Arbitrary<Func<A, B>> AnyFunc1<A, B>
      ( Arbitrary<B> arbB
      , int cacheSize = DefaultFunc1CacheSize
      )
      where A : IEquatable<A>
    =>
        AnyFunc1(arbB, EqualityComparer<A>.Default, cacheSize);

    public static Arbitrary<Func<A, B>> AnyFunc1Unchecked<A, B>
      ( Arbitrary<B> arbB
      , int cacheSize = DefaultFunc1CacheSize
      )
    =>
        AnyFunc1(arbB, EqualityComparer<A>.Default, cacheSize);

    public static Gen<Func<A, B>> GenAnyFunc1<A, B>
      ( Gen<B> genB
      , IEqualityComparer<A> comp
      , int cacheSize
      )
    =>
        from bs in Gen.ListOf(cacheSize, genB)
            .Select(e => e.AsEnumerable().GetEnumerator())
        from cache in
            Gen
            .Constant
              ( new Func<IDictionary<A, B>>
                  ( () => new Dictionary<A, B>(cacheSize, comp)
                  )
              )
            .Select(f => f())
        select
            new Func<A, B>
              ( a =>
                {
                    if (!cache.ContainsKey(a))
                    {
                        bs.MoveNext();
                        cache.Add(a, bs.Current);
                    }
                    return cache[a];
                });
}

}


text:
package com.ibatis.common.beans;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import org.junit.jupiter.api.Test;

class ComplexBeanProbeTest {

  @Test
  void testSetObject() {
    SimpleClass mySimpleClass = new SimpleClass();
    Probe probe = ProbeFactory.getProbe(mySimpleClass);
    probe.setObject(mySimpleClass, "myInt", Integer.valueOf(1));
    assertEquals(1, mySimpleClass.getMyInt());
    probe.setObject(mySimpleClass, "myInt", Integer.valueOf(2));
    assertEquals(2, mySimpleClass.getMyInt());
    try {
      probe.setObject(mySimpleClass, "myInt", null);
      fail();
    } catch (RuntimeException e) {
      assertTrue(e.getMessage().contains("'myInt' to value 'null'"));
    }
    try {
      probe.setObject(mySimpleClass, "myInt", Float.valueOf(1.2f));
      fail();
    } catch (RuntimeException e) {
      assertTrue(e.getMessage().contains("'myInt' to value '1.2'"));
    }
  }

  public class SimpleClass {

    int myInt;

    public int getMyInt() {
      return myInt;
    }

    public void setMyInt(int myInt) {
      this.myInt = myInt;
    }
  }

}

redpajama_set_name: RedPajamaGithub


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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.hive.ql.io.sarg.PredicateLeaf;
import org.apache.hadoop.hive.ql.io.sarg.PredicateLeaf.Operator;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.parquet.filter2.predicate.FilterApi;
import org.apache.parquet.filter2.predicate.FilterPredicate;
import org.apache.parquet.io.api.Binary;
import org.apache.parquet.schema.PrimitiveType;
import org.apache.parquet.schema.Type;

import static org.apache.parquet.filter2.predicate.FilterApi.eq;
import static org.apache.parquet.filter2.predicate.FilterApi.lt;
import static org.apache.parquet.filter2.predicate.FilterApi.ltEq;
import static org.apache.parquet.filter2.predicate.FilterApi.binaryColumn;
import static org.apache.parquet.filter2.predicate.FilterApi.booleanColumn;
import static org.apache.parquet.filter2.predicate.FilterApi.doubleColumn;
import static org.apache.parquet.filter2.predicate.FilterApi.floatColumn;
import static org.apache.parquet.filter2.predicate.FilterApi.intColumn;

public class LeafFilterFactory {
  private static final Logger LOG = LoggerFactory.getLogger(LeafFilterFactory.class);

  class IntFilterPredicateLeafBuilder extends FilterPredicateLeafBuilder {
    /**
     * @param op         consists of EQUALS, NULL_SAFE_EQUALS, LESS_THAN, LESS_THAN_EQUALS, IS_NULL
     * @param literal
     * @param columnName
     * @return
     */
    @Override
    public FilterPredicate buildPredict(Operator op, Object literal,
                                        String columnName) {
      switch (op) {
        case LESS_THAN:
          return lt(intColumn(columnName), ((Number) literal).intValue());
        case IS_NULL:
        case EQUALS:
        case NULL_SAFE_EQUALS:
          return eq(intColumn(columnName),
            (literal == null) ? null : ((Number) literal).intValue());
        case LESS_THAN_EQUALS:
          return ltEq(intColumn(columnName), ((Number) literal).intValue());
        default:
          throw new RuntimeException("Unknown PredicateLeaf Operator type: " + op);
      }
    }
  }

  class LongFilterPredicateLeafBuilder extends FilterPredicateLeafBuilder {
    @Override
    public FilterPredicate buildPredict(Operator op, Object constant,
                                        String columnName) {
      switch (op) {
        case LESS_THAN:
          return lt(FilterApi.longColumn(columnName), ((Number) constant).longValue());
        case IS_NULL:
        case EQUALS:
        case NULL_SAFE_EQUALS:
          return eq(FilterApi.longColumn(columnName),
            (constant == null) ? null : ((Number) constant).longValue());
        case LESS_THAN_EQUALS:
          return ltEq(FilterApi.longColumn(columnName),
            ((Number) constant).longValue());
        default:
          throw new RuntimeException("Unknown PredicateLeaf Operator type: " + op);
      }
    }
  }

  class FloatFilterPredicateLeafBuilder extends FilterPredicateLeafBuilder {
    @Override
    public FilterPredicate buildPredict(Operator op, Object constant, String columnName) {
      switch (op) {
      case LESS_THAN:
        return lt(floatColumn(columnName), ((Number) constant).floatValue());
      case IS_NULL:
      case EQUALS:
      case NULL_SAFE_EQUALS:
        return eq(floatColumn(columnName),
            (constant == null) ? null : ((Number) constant).floatValue());
      case LESS_THAN_EQUALS:
        return ltEq(FilterApi.floatColumn(columnName), ((Number) constant).floatValue());
      default:
        throw new RuntimeException("Unknown PredicateLeaf Operator type: " + op);
      }
    }
  }

  class DoubleFilterPredicateLeafBuilder extends FilterPredicateLeafBuilder {

    @Override
    public FilterPredicate buildPredict(Operator op, Object constant,
                                        String columnName) {
      switch (op) {
        case LESS_THAN:
          return lt(doubleColumn(columnName), ((Number) constant).doubleValue());
        case IS_NULL:
        case EQUALS:
        case NULL_SAFE_EQUALS:
          return eq(doubleColumn(columnName),
            (constant == null) ? null : ((Number) constant).doubleValue());
        case LESS_THAN_EQUALS:
          return ltEq(FilterApi.doubleColumn(columnName),
            ((Number) constant).doubleValue());
        default:
          throw new RuntimeException("Unknown PredicateLeaf Operator type: " + op);
      }
    }
  }

  class BooleanFilterPredicateLeafBuilder extends FilterPredicateLeafBuilder {
    @Override
    public FilterPredicate buildPredict(Operator op, Object constant,
                                        String columnName) throws Exception{
      switch (op) {
        case IS_NULL:
        case EQUALS:
        case NULL_SAFE_EQUALS:
          return eq(booleanColumn(columnName),
            (constant == null) ? null : ((Boolean) constant).booleanValue());
        default:
          throw new RuntimeException("Unknown PredicateLeaf Operator type: " + op);
      }
    }
  }

  class BinaryFilterPredicateLeafBuilder extends FilterPredicateLeafBuilder {
    @Override
    public FilterPredicate buildPredict(Operator op, Object constant,
                                        String columnName) throws Exception{
      switch (op) {
        case LESS_THAN:
          return lt(binaryColumn(columnName), Binary.fromString((String) constant));
        case IS_NULL:
        case EQUALS:
        case NULL_SAFE_EQUALS:
          return eq(binaryColumn(columnName),
            (constant == null) ? null : Binary.fromString((String) constant));
        case LESS_THAN_EQUALS:
          return ltEq(binaryColumn(columnName), Binary.fromString((String) constant));
        default:
          // should never be executed
          throw new RuntimeException("Unknown PredicateLeaf Operator type: " + op);
      }
    }
  }

  /**
   * get leaf filter builder by FilterPredicateType, currently date, decimal and timestamp is not
   * supported yet.
   * @param type FilterPredicateType
   * @return
   * @throws HiveException Exception is thrown for unsupported data types so we can skip filtering
   */
  public FilterPredicateLeafBuilder getLeafFilterBuilderByType(
      PredicateLeaf.Type type,
      Type parquetType) throws HiveException {
    switch (type){
      case LONG:
        if (parquetType.asPrimitiveType().getPrimitiveTypeName() ==
            PrimitiveType.PrimitiveTypeName.INT32) {
          return new IntFilterPredicateLeafBuilder();
        } else {
          return new LongFilterPredicateLeafBuilder();
        }
      case FLOAT:
        if (parquetType.asPrimitiveType().getPrimitiveTypeName() ==
            PrimitiveType.PrimitiveTypeName.FLOAT) {
          return new FloatFilterPredicateLeafBuilder();
        } else {
          return new DoubleFilterPredicateLeafBuilder();
        }
      case STRING:  // string, char, varchar
        return new BinaryFilterPredicateLeafBuilder();
      case BOOLEAN:
        return new BooleanFilterPredicateLeafBuilder();
      case DATE:
      case DECIMAL:
      case TIMESTAMP:
      default:
        String msg = "Conversion to Parquet FilterPredicate not supported for " + type;
        LOG.debug(msg);
        throw new HiveException(msg);
    }
  }
}


text:
#include <string>
#include <vector>
#include <utility>
#include <cassert>
#include <map>
#include <unordered_set>
#include "VHDLObj.hpp"
#include "process.hpp"
#include "events.hpp"

std::vector<std::shared_ptr<warped::Event> > Process::initializeLP() {
   std::cout << name_ << " initialization" << std::endl;
   std::vector<std::shared_ptr<warped::Event> > response_events;
   return response_events;
}

std::vector<std::shared_ptr<warped::Event> > Process::receiveEvent( const warped::Event& event ) {
   const VHDLEvent my_event = static_cast<const VHDLEvent&>(event);
   std::cout << name_ << ": received a message from " << event.sender_name_ <<
   " at time " << std::to_string(event.timestamp()) << ". " << std::endl;
   std::vector<std::shared_ptr<warped::Event> > events;
   switch(my_event.gettype())
   {
      case EVENT_WAIT:
         /* Resume */
         std::cout << name_ << ": it is a resume message. " << std::endl;
         events = executeVHDL( event );
         break;
      case EVENT_SIGNAL:
         {
            std::cout << name_ << ": it is a signal changed message. " << std::endl;
            const SigEvent sign_event = static_cast<const SigEvent&>(event);
            // Is the signal in my sensitivity list?
            if(sens_list_.find(sign_event.SignalName()) != sens_list_.end())
            {
               std::cout << name_ << ": the signal " << sign_event.SignalName() <<
               " has new the new value of " << std::to_string(sign_event.Value()) <<
               ". " << std::endl;
               events = executeVHDL( event );
            } else {
               std::cout << name_ << ": the signal " << sign_event.SignalName() <<
               " is not in my sensitivity list. " << std::endl;
               assignSignal( sign_event.SignalName(), sign_event.Value(), 0, sign_event.timestamp() );
            }
            break;
         }
      default:
         /* This should not happen */
         assert(false);
   }
   return events;
}

std::vector<std::shared_ptr<warped::Event> > Process::executeVHDL( const warped::Event& event ) {
   std::vector<std::shared_ptr<warped::Event> > events;
   std::vector<std::shared_ptr<warped::Event> > temp;
   switch(state_.waitLabel)
   {
      case 0: state_.waitLabel++;
              std::cout << name_ << ": executing 10 something wait. " << std::endl;
              // try to assign a signal immediately.
              temp = assignSignal("signame", 1, 0, event.timestamp());
              events.insert(events.end(), temp.begin(), temp.end());
              // go to sleep
              temp = executeWait( state_.waitLabel, event.timestamp() + 10 );
              events.insert(events.end(), temp.begin(), temp.end());
              break;
      case 1: state_.waitLabel++;
              // try to assign a signal with a delay of 5.
              temp = assignSignal("signame", 1, 5, event.timestamp());
              events.insert(events.end(), temp.begin(), temp.end());
              // go to sleep
              std::cout << name_ << ": executing 20 something wait. " << std::endl;
              temp = executeWait( state_.waitLabel, event.timestamp() + 20 );
              events.insert(events.end(), temp.begin(), temp.end());
              break;
      case 2: std::cout << name_ << ": finished computation of the process. Resetting state. "
      << std::endl;
              state_.resetState();
              break;
      default: /* This should not happen */
              assert(false);
              break;
   }
   return events;
}

std::vector<std::shared_ptr<warped::Event> > Process::assignSignal( const std::string name,
                                                                    const int value,
                                                                    const unsigned int delay,
                                                                    const unsigned int timestamp ) {
   std::vector<std::shared_ptr<warped::Event> > events;
   if (delay == 0) {
      std::cout << name_ << ": assigning the signal without sending a message. " << std::endl;
   } else {
      std::cout << name_ << ": sending a message to assign a signal with a delay of " << std::to_string(delay) << ". " << std::endl;
      events.emplace_back(new SigEvent { name_, value, name, timestamp + delay });
   }
   return events;
}

std::vector<std::shared_ptr<warped::Event> > Process::executeWait( unsigned int waitID, unsigned int howmuch ) {
   std::vector<std::shared_ptr<warped::Event> > events;
   std::cout << name_ << ": sending event to myself at time " << std::to_string(howmuch) << " to resume! " << std::endl;
   events.emplace_back(new Wait { name_, howmuch, waitID });
   return events;
}


text:
import { Component} from '@angular/core';
import {  CORE_DIRECTIVES,
  FORM_DIRECTIVES
} from '@angular/common';
import { Router } from '@angular/router-deprecated';

@Component({
  selector: 'file-upload-menu',
  templateUrl: 'app/menu/file-upload-menu.component.html',
  directives: [FORM_DIRECTIVES, CORE_DIRECTIVES],
  providers: []
})

export class FileUploadMenuComponent  {

  constructor(private router: Router) {
    }
   viewUploadedFilesPage() {
		 this.router.navigate(['ViewUploadedFiles']);
	 }
	 manualFileUploadPage() {
		 this.router.navigate(['ManualFileUpload']);
	 }
}


text:
using System;
using System.Text;

namespace GoogleMapsApi
{
    public class DirectionsService
    {
        public static readonly Uri ApiUrl = new Uri("https://maps.googleapis.com/maps/api/directions/");

        public static DirectionsResponse GetResponse(string origin, string destination, DirectionsRequest additional)
        {
            var url = new Uri(String.Format("{0}json?origin={1}&destination={2}{3}{4}{5}{6}{7}{8}{9}",
                ApiUrl,
                Http.UrlEncoding(origin),
                Http.UrlEncoding(destination),
                GetSensorString(additional),
                GetWaypointString(additional),
                GetUnitString(additional),
                GetAvoidString(additional),
                GetRegionString(additional),
                GetAlternativesString(additional),
                GetModeString(additional)
                ));
            return Http.Get(url).As<DirectionsResponse>();
        }

        private static string GetWaypointString(DirectionsRequest additional)
        {
            if (additional.WayPoints.Count > 0)
            {
                StringBuilder sb = new StringBuilder("&waypoints=");
                foreach (var s in additional.WayPoints)
                {
                    sb.Append(s);
                    sb.Append("|");
                }
                return sb.ToString();
            }
            return String.Empty;
        }

        private static string GetUnitString(DirectionsRequest additional)
        {
            return String.Format("&units={0}", additional.Unit.ToString());
        }

        private static string GetAvoidString(DirectionsRequest additional)
        {
            StringBuilder sb = new StringBuilder();
            if (additional.AvoidHighways)
            {
                sb.Append("&avoid=highways");
            }
            if (additional.AvoidTolls)
            {
                sb.Append("&avoid=tolls");
            }
            return sb.ToString();
        }

        private static string GetRegionString(DirectionsRequest additional)
        {
            if (String.IsNullOrEmpty(additional.Region))
                return String.Empty;
            return String.Format("&region=", additional.Region);
        }

        private static string GetSensorString(DirectionsRequest additional)
        {
            return String.Format("&sensor={0}", additional.Sensor ? "true" : "false");
        }

        private static string GetAlternativesString(DirectionsRequest additional)
        {
            if (additional.Alternatives)
            {
                return "&alternatives=true";
            }
            return String.Empty;
        }

        private static string GetModeString(DirectionsRequest additional)
        {
            return String.Format("&mode={0}", additional.TravelMode.ToString());
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swiperefresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/bgCommon">

        <android.support.v4.widget.NestedScrollView
            android:id="@+id/nested_scroll_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true"
            android:scrollbarStyle="outsideOverlay"
            android:scrollbars="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/movie_list_horizontal_margin"
                android:layout_marginRight="@dimen/movie_list_horizontal_margin"
                android:orientation="vertical">

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/recyclerview"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

                <include
                    android:id="@+id/footer"
                    layout="@layout/view_load_more_footer" />

            </LinearLayout>

        </android.support.v4.widget.NestedScrollView>

    </android.support.v4.widget.SwipeRefreshLayout>

</layout>


text:
/**
 *
 */
package javax.jmdns.impl;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;

import javax.jmdns.impl.tasks.RecordReaper;
import javax.jmdns.impl.tasks.Responder;
import javax.jmdns.impl.tasks.resolver.ServiceInfoResolver;
import javax.jmdns.impl.tasks.resolver.ServiceResolver;
import javax.jmdns.impl.tasks.resolver.TypeResolver;
import javax.jmdns.impl.tasks.state.Announcer;
import javax.jmdns.impl.tasks.state.Canceler;
import javax.jmdns.impl.tasks.state.Prober;
import javax.jmdns.impl.tasks.state.Renewer;

/**
 * This class is used by JmDNS to start the various task required to run the DNS discovery. This interface is only there in order to support MANET modifications.
 *

 * Note:  This is not considered as part of the general public API of JmDNS.
 *

 *
 * @author Pierre Frisch
 */
public interface DNSTaskStarter {

    /**
     * DNSTaskStarter.Factory enable the creation of new instance of DNSTaskStarter.
     */
    public static final class Factory {

        private static volatile Factory                        _instance;
        private final ConcurrentMap<JmDNSImpl, DNSTaskStarter> _instances;

        /**
         * This interface defines a delegate to the DNSTaskStarter class to enable subclassing.
         */
        public static interface ClassDelegate {

            /**
             * Allows the delegate the opportunity to construct and return a different DNSTaskStarter.
             *
             * @param jmDNSImpl
             *            jmDNS instance
             * @return Should return a new DNSTaskStarter Object.
             * @see #classDelegate()
             * @see #setClassDelegate(ClassDelegate anObject)
             */
            public DNSTaskStarter newDNSTaskStarter(JmDNSImpl jmDNSImpl);
        }

        private static final AtomicReference<Factory.ClassDelegate> _databaseClassDelegate = new AtomicReference<Factory.ClassDelegate>();

        private Factory() {
            super();
            _instances = new ConcurrentHashMap<JmDNSImpl, DNSTaskStarter>(20);
        }

        /**
         * Assigns delegate as DNSTaskStarter's class delegate. The class delegate is optional.
         *
         * @param delegate
         *            The object to set as DNSTaskStarter's class delegate.
         * @see #classDelegate()
         * @see DNSTaskStarter.Factory.ClassDelegate
         */
        public static void setClassDelegate(Factory.ClassDelegate delegate) {
            _databaseClassDelegate.set(delegate);
        }

        /**
         * Returns DNSTaskStarter's class delegate.
         *
         * @return DNSTaskStarter's class delegate.
         * @see #setClassDelegate(ClassDelegate anObject)
         * @see DNSTaskStarter.Factory.ClassDelegate
         */
        public static Factory.ClassDelegate classDelegate() {
            return _databaseClassDelegate.get();
        }

        /**
         * Returns a new instance of DNSTaskStarter using the class delegate if it exists.
         *
         * @param jmDNSImpl
         *            jmDNS instance
         * @return new instance of DNSTaskStarter
         */
        protected static DNSTaskStarter newDNSTaskStarter(JmDNSImpl jmDNSImpl) {
            DNSTaskStarter instance = null;
            Factory.ClassDelegate delegate = _databaseClassDelegate.get();
            if (delegate != null) {
                instance = delegate.newDNSTaskStarter(jmDNSImpl);
            }
            return (instance != null ? instance : new DNSTaskStarterImpl(jmDNSImpl));
        }

        /**
         * Return the instance of the DNSTaskStarter Factory.
         *
         * @return DNSTaskStarter Factory
         */
        public static Factory getInstance() {
            if (_instance == null) {
                synchronized (DNSTaskStarter.Factory.class) {
                    if (_instance == null) {
                        _instance = new Factory();
                    }
                }
            }
            return _instance;
        }

        /**
         * Return the instance of the DNSTaskStarter for the JmDNS.
         *
         * @param jmDNSImpl
         *            jmDNS instance
         * @return the DNSTaskStarter
         */
        public DNSTaskStarter getStarter(JmDNSImpl jmDNSImpl) {
            DNSTaskStarter starter = _instances.get(jmDNSImpl);
            if (starter == null) {
                _instances.putIfAbsent(jmDNSImpl, newDNSTaskStarter(jmDNSImpl));
                starter = _instances.get(jmDNSImpl);
            }
            return starter;
        }

    }

    public static final class DNSTaskStarterImpl implements DNSTaskStarter {

        private final JmDNSImpl _jmDNSImpl;

        /**
         * The timer is used to dispatch all outgoing messages of JmDNS. It is also used to dispatch maintenance tasks for the DNS cache.
         */
        private final Timer     _timer;

        /**
         * The timer is used to dispatch maintenance tasks for the DNS cache.
         */
        private final Timer     _stateTimer;

        public static class StarterTimer extends Timer {

            // This is needed because in some case we cancel the timers before all the task have finished running and in some case they will try to reschedule
            private volatile boolean _cancelled;

            /**
             *
             */
            public StarterTimer() {
                super();
                _cancelled = false;
            }

            /**
             * @param isDaemon
             */
            public StarterTimer(boolean isDaemon) {
                super(isDaemon);
                _cancelled = false;
            }

            /**
             * @param name
             * @param isDaemon
             */
            public StarterTimer(String name, boolean isDaemon) {
                super(name, isDaemon);
                _cancelled = false;
            }

            /**
             * @param name
             */
            public StarterTimer(String name) {
                super(name);
                _cancelled = false;
            }

            /*
             * (non-Javadoc)
             * @see java.util.Timer#cancel()
             */

            public synchronized void cancel() {
                if (_cancelled) return;
                _cancelled = true;
                super.cancel();
            }

            /*
             * (non-Javadoc)
             * @see java.util.Timer#schedule(java.util.TimerTask, long)
             */

            public synchronized void schedule(TimerTask task, long delay) {
                if (_cancelled) return;
                super.schedule(task, delay);
            }

            /*
             * (non-Javadoc)
             * @see java.util.Timer#schedule(java.util.TimerTask, java.util.Date)
             */

            public synchronized void schedule(TimerTask task, Date time) {
                if (_cancelled) return;
                super.schedule(task, time);
            }

            /*
             * (non-Javadoc)
             * @see java.util.Timer#schedule(java.util.TimerTask, long, long)
             */

            public synchronized void schedule(TimerTask task, long delay, long period) {
                if (_cancelled) return;
                super.schedule(task, delay, period);
            }

            /*
             * (non-Javadoc)
             * @see java.util.Timer#schedule(java.util.TimerTask, java.util.Date, long)
             */

            public synchronized void schedule(TimerTask task, Date firstTime, long period) {
                if (_cancelled) return;
                super.schedule(task, firstTime, period);
            }

            /*
             * (non-Javadoc)
             * @see java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, long, long)
             */

            public synchronized void scheduleAtFixedRate(TimerTask task, long delay, long period) {
                if (_cancelled) return;
                super.scheduleAtFixedRate(task, delay, period);
            }

            /*
             * (non-Javadoc)
             * @see java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, java.util.Date, long)
             */

            public synchronized void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) {
                if (_cancelled) return;
                super.scheduleAtFixedRate(task, firstTime, period);
            }

        }

        public DNSTaskStarterImpl(JmDNSImpl jmDNSImpl) {
            super();
            _jmDNSImpl = jmDNSImpl;
            _timer = new StarterTimer("JmDNS(" + _jmDNSImpl.getName() + ").Timer", true);
            _stateTimer = new StarterTimer("JmDNS(" + _jmDNSImpl.getName() + ").State.Timer", false);
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#purgeTimer()
         */

        public void purgeTimer() {
            _timer.purge();
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#purgeStateTimer()
         */

        public void purgeStateTimer() {
            _stateTimer.purge();
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#cancelTimer()
         */

        public void cancelTimer() {
            _timer.cancel();
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#cancelStateTimer()
         */

        public void cancelStateTimer() {
            _stateTimer.cancel();
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#startProber()
         */

        public void startProber() {
            new Prober(_jmDNSImpl).start(_stateTimer);
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#startAnnouncer()
         */

        public void startAnnouncer() {
            new Announcer(_jmDNSImpl).start(_stateTimer);
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#startRenewer()
         */

        public void startRenewer() {
            new Renewer(_jmDNSImpl).start(_stateTimer);
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#startCanceler()
         */

        public void startCanceler() {
            new Canceler(_jmDNSImpl).start(_stateTimer);
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#startReaper()
         */

        public void startReaper() {
            new RecordReaper(_jmDNSImpl).start(_timer);
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#startServiceInfoResolver(javax.jmdns.impl.ServiceInfoImpl)
         */

        public void startServiceInfoResolver(ServiceInfoImpl info) {
            new ServiceInfoResolver(_jmDNSImpl, info).start(_timer);
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#startTypeResolver()
         */

        public void startTypeResolver() {
            new TypeResolver(_jmDNSImpl).start(_timer);
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#startServiceResolver(java.lang.String)
         */

        public void startServiceResolver(String type) {
            new ServiceResolver(_jmDNSImpl, type).start(_timer);
        }

        /*
         * (non-Javadoc)
         * @see javax.jmdns.impl.DNSTaskStarter#startResponder(javax.jmdns.impl.DNSIncoming, int)
         */

        public void startResponder(DNSIncoming in, int port) {
            new Responder(_jmDNSImpl, in, port).start(_timer);
        }
    }

    /**
     * Purge the general task timer
     */
    public void purgeTimer();

    /**
     * Purge the state task timer
     */
    public void purgeStateTimer();

    /**
     * Cancel the generals task timer
     */
    public void cancelTimer();

    /**
     * Cancel the state task timer
     */
    public void cancelStateTimer();

    /**
     * Start a new prober task
     */
    public void startProber();

    /**
     * Start a new announcer task
     */
    public void startAnnouncer();

    /**
     * Start a new renewer task
     */
    public void startRenewer();

    /**
     * Start a new canceler task
     */
    public void startCanceler();

    /**
     * Start a new reaper task. There is only supposed to be one reaper running at a time.
     */
    public void startReaper();

    /**
     * Start a new service info resolver task
     *
     * @param info
     *            service info to resolve
     */
    public void startServiceInfoResolver(ServiceInfoImpl info);

    /**
     * Start a new service type resolver task
     */
    public void startTypeResolver();

    /**
     * Start a new service resolver task
     *
     * @param type
     *            service type to resolve
     */
    public void startServiceResolver(String type);

    /**
     * Start a new responder task
     *
     * @param in
     *            incoming message
     * @param port
     *            incoming port
     */
    public void startResponder(DNSIncoming in, int port);

}


text:
/**
 * Contains request routing logic.
 */

import {Router} from 'worktop';
import {KV, read} from 'worktop/kv';
import {ServerRequest} from 'worktop/request';

import {FetchError} from './errors';
import {
  CHARSET_UTF_8,
  CacheControl,
  ContentType,
  HeaderKeys,
  withHeaders,
} from './headers';
import {AmpExp, injectAmpExp, injectAmpGeo} from './injectors';
import {enqueueCacheAndClone, getCacheFor, hashObject} from './injectors-cache';
import {rtvMetadata} from './metadata';
import {chooseRtv} from './rtv';
import {fetchImmutableAmpFileOrDie, fetchImmutableUrlOrDie} from './storage';
import {getAmpFileUrl} from './storage-util';

// KV Binding via `wrangler.toml` config.
declare const CONFIG: KV.Namespace;

const RTV_METADATA_EXTRA_HEADERS: ReadonlyMap<HeaderKeys, string> = new Map([
  [
    HeaderKeys.CONTENT_TYPE,
    `${ContentType.APPLICATION_JSON}; ${CHARSET_UTF_8}`,
  ],
]);
const EXPERIMENTS_EXTRA_HEADERS: ReadonlyMap<HeaderKeys, string> = new Map([
  [HeaderKeys.X_FRAME_OPTIONS, 'deny'],
  [
    HeaderKeys.CONTENT_SECURITY_POLICY,
    "default-src * blob: data:; script-src blob: https://cdn.ampproject.org/lts/ https://cdn.ampproject.org/rtv/ https://cdn.ampproject.org/sw/ https://cdn.ampproject.org/v0.js https://cdn.ampproject.org/v0.mjs https://cdn.ampproject.org/v0/ https://cdn.ampproject.org/viewer/; object-src 'none'; style-src 'unsafe-inline' https://cdn.ampproject.org/rtv/ https://cdn.materialdesignicons.com https://cloud.typography.com https://fast.fonts.net https://fonts.googleapis.com https://maxcdn.bootstrapcdn.com https://p.typekit.net https://pro.fontawesome.com https://use.fontawesome.com https://use.typekit.net; report-uri https://csp.withgoogle.com/csp/amp",
  ],
]);

const router = new Router();

router.onerror = (req, res, status, error) => {
  if (!(error instanceof FetchError)) {
    error = new FetchError(status ?? 500, 'Internal Server Error');
  }
  console.error(error?.stack ?? error);
  return new Response(error.message, {status: (error as FetchError).status});
};

router.add('GET', '/', () => Response.redirect('https://amp.dev/'));

router.add('GET', '/favicon.ico', () => {
  return fetchImmutableUrlOrDie('https://amp.dev/static/img/favicon.png');
});

router.add('GET', '/rtv/metadata', async (request) => {
  return withHeaders(
    await rtvMetadata(request.origin),
    CacheControl.RTV_METADATA_FILE,
    RTV_METADATA_EXTRA_HEADERS
  );
});

/**
 * Handles amp-geo requests.
 * @param req - the request object.
 * @param rtv - RTV number to use.
 * @param path - path to the requested amp-geo file, must start with `/`.
 * @returns a dynamically injected amp-geo response, possibly from cache.
 */
async function ampGeoRequest(
  {cf, extend}: ServerRequest,
  rtv: string,
  path: string
): Promise<Response> {
  const url = getAmpFileUrl(rtv, path);
  const cacheKey = `${cf.country ?? ''};${cf.regionCode ?? ''}`;

  const cachedResponse = await getCacheFor(url, cacheKey, cf);
  if (cachedResponse) {
    console.log('Serving', url, 'with dynamic key', cacheKey, 'from cache');
    return withHeaders(cachedResponse, CacheControl.AMP_GEO);
  }
  console.log('Cache miss for', url, 'with dynamic key', cacheKey);

  const response = await injectAmpGeo(
    await fetchImmutableUrlOrDie(url),
    cf.country,
    cf.regionCode
  );

  return withHeaders(
    enqueueCacheAndClone(extend, response, url, cacheKey),
    CacheControl.AMP_GEO
  );
}

router.add(
  'GET',
  /^\/rtv\/(?<rtv>\d+)(?<wild>\/v0\/amp-geo-.+\.m?js)$/,
  (req) => {
    return ampGeoRequest(req, req.params.rtv, req.params.wild);
  }
);

router.add('GET', '/rtv/:rtv/*', async ({cf, params}) => {
  const response = await fetchImmutableAmpFileOrDie(
    params.rtv,
    `/${params.wild}`,
    cf
  );

  return withHeaders(response, CacheControl.STATIC_RTV_FILE);
});

router.add('GET', /^\/(?:\w+-)?v0\.m?js$/, async (req) => {
  console.log('Serving unversioned entry-file request to', req.path);

  const rtv = await chooseRtv(req);
  const ampExpConfig = (await read<AmpExp>(CONFIG, 'AMP_EXP', {
    type: 'json',
  })) ?? {experiments: []};

  const url = getAmpFileUrl(rtv, req.path);
  const cacheKey = await hashObject(ampExpConfig);

  const cachedResponse = await getCacheFor(url, cacheKey, req.cf);
  if (cachedResponse) {
    console.log('Serving', url, 'with dynamic key', cacheKey, 'from cache');
    return withHeaders(cachedResponse, CacheControl.ENTRY_FILE);
  }
  console.log('Cache miss for', url, 'with dynamic key', cacheKey);

  const response = await injectAmpExp(
    await fetchImmutableUrlOrDie(url),
    rtv,
    ampExpConfig
  );

  return withHeaders(
    enqueueCacheAndClone(req.extend, response, url, cacheKey),
    CacheControl.ENTRY_FILE
  );
});

router.add('GET', /^(?:\/lts)?\/v0\/amp-geo-.+\.m?js$/, async (req) => {
  console.log('Serving unversioned amp-geo request to', req.path);

  const rtv = await chooseRtv(req);
  return ampGeoRequest(req, rtv, req.path);
});

/**
 * Handles unversioned requests to /experiments.html.
 *
 * @param req - the request object.
 * @returns Response object with experiments.html content.
 */
async function unversionedExperimentsRequest(
  req: ServerRequest
): Promise<Response> {
  console.log('Serving unversioned experiments.html request to', req.path);

  const rtv = await chooseRtv(req);
  const response = await fetchImmutableAmpFileOrDie(rtv, req.path, req.cf);

  return withHeaders(
    response,
    CacheControl.ENTRY_FILE,
    EXPERIMENTS_EXTRA_HEADERS
  );
}

router.add('GET', '/lts/experiments.html', unversionedExperimentsRequest);
router.add('GET', '/experiments.html', unversionedExperimentsRequest);

/**
 * Handles unversioned requests to service worker files.
 *
 * @param req - the request object.
 * @returns Response object with service worker content.
 */
async function unversionedServiceWorkerRequest(
  req: ServerRequest
): Promise<Response> {
  console.log('Serving unversioned service worker request to', req.path);

  const rtv = await chooseRtv(req);
  const response = await fetchImmutableAmpFileOrDie(rtv, req.path, req.cf);

  return withHeaders(response, CacheControl.SERVICE_WORKER_FILE);
}

router.add('GET', '/lts/sw/*', unversionedServiceWorkerRequest);
router.add('GET', '/sw/*', unversionedServiceWorkerRequest);

router.add('GET', '/lts/*', async (req) => {
  console.log('Serving unversioned LTS request to', req.path);
  const rtv = await chooseRtv(req);
  const response = await fetchImmutableAmpFileOrDie(rtv, req.path, req.cf);

  return withHeaders(response, CacheControl.LTS);
});

router.add('GET', '/*', async (req) => {
  console.log('Serving unversioned request to', req.path);

  const rtv = await chooseRtv(req);
  const response = await fetchImmutableAmpFileOrDie(rtv, req.path, req.cf);

  return withHeaders(response, CacheControl.DEFAULT);
});

export default router;


text:
package models.poloniex

import java.time.OffsetDateTime
import utils.Misc

case class PoloniexMarketUpdate(marketName: String, info: PoloniexMarketMessage)

//"BTC_1CR":{"id":1,"last":"0.00185835","lowestAsk":"0.00195342","highestBid":"0.00185835","percentChange":"-0.02771891",
// "baseVolume":"6.80216315","quoteVolume":"3424.46300964","isFrozen":"0","high24hr":"0.00220238","low24hr":"0.00178000"}
case class PoloniexMarketMessage(id: Int,
                                 last: BigDecimal,
                                 lowestAsk: BigDecimal,
                                 highestBid: BigDecimal,
                                 percentChange: BigDecimal,
                                 baseVolume: BigDecimal,
                                 quoteVolume: BigDecimal,
                                 isFrozen: String,
                                 high24hr: BigDecimal,
                                 low24hr: BigDecimal)

//[{"date":1405699200,"high":0.0045388,"low":0.00403001,"open":0.00404545,"close":0.00427592,"volume":44.11655644,
//"quoteVolume":10259.29079097,"weightedAverage":0.00430015}, ...]
case class PoloMarketCandle(date: OffsetDateTime,
                         high: BigDecimal,
                         low: BigDecimal,
                         open: BigDecimal,
                         close: BigDecimal,
                         volume: BigDecimal,
                         quoteVolume: BigDecimal,
                         weightedAverage: BigDecimal)


text:
package org.neo4j.cypher.internal.compiler.v2_3.spi

import java.net.URL

import org.apache.commons.lang3.SystemUtils
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.neo4j.cypher.internal.compiler.v2_3.TaskCloser
import org.neo4j.cypher.internal.compiler.v2_3.test_helpers.CreateTempFileTestSupport
import org.neo4j.cypher.internal.frontend.v2_3.test_helpers.CypherFunSuite
import org.neo4j.io.fs.FileUtils
import org.scalatest.fixture

class CSVResourcesTest extends CypherFunSuite with CreateTempFileTestSupport {

  var resources: CSVResources = _
  var cleaner: TaskCloser = _

  override def beforeEach() {
    cleaner = mock[TaskCloser]
    resources = new CSVResources(cleaner)
  }

  test("should handle strings") {
    // given
    val url = createCSVTempFileURL {
      writer =>
        writer.println("1")
        writer.println("2")
        writer.println("3")
        writer.println("4")
    }

    //when
    val result: List[Array[String]] = resources.getCsvIterator(new URL(url)).toList

    (result zip List(
      Array[String]("1"),
      Array[String]("2"),
      Array[String]("3"),
      Array[String]("4")
    )).foreach {
      case (r, expected) =>
        r should equal(expected)
    }
  }

  test("should handle with headers") {
    // given
    val url = createCSVTempFileURL {
      writer =>
        writer.println("a,b")
        writer.println("1,2")
        writer.println("3,4")
    }

    //when
    val result = resources.getCsvIterator(new URL(url)).toList

    //then
    (result zip List(
      Array[String]("a", "b"),
      Array[String]("1", "2"),
      Array[String]("3", "4")
    )).foreach {
      case (r, expected) =>
        r should equal(expected)
    }
  }

  test("should handle with headers even for uneven files") {
    // given
    val url = createCSVTempFileURL {
      writer =>
        writer.println("a,b")
        writer.println("1,2")
        writer.println("3")
    }

    //when
    val result = resources.getCsvIterator(new URL(url)).toList

    //then
    (result zip List(
      Array[String]("a", "b"),
      Array[String]("1", "2"),
      Array[String]("3")
    )).foreach {
      case (r, expected) =>
        r should equal(expected)
    }
  }

  test("should give a helpful message when asking for headers with empty file") {
    // given
    val url = createCSVTempFileURL(_ => {})

    //when
    val result = resources.getCsvIterator(new URL(url)).toList

    result should equal(List.empty)
  }

  test("should register a task in the cleanupper") {
    // given
    val url = createCSVTempFileURL {
      writer =>
        writer.println("a,b")
        writer.println("1,2")
        writer.println("3,4")
    }

    // when
    resources.getCsvIterator(new URL(url))

    // then
    verify(cleaner, times(1)).addTask(any(classOf[Boolean => Unit]))
  }

  test("should accept and use a custom field terminator") {
    // given
    val url = createCSVTempFileURL {
      writer =>
        writer.println("122\tfoo")
        writer.println("23\tbar")
        writer.println("3455\tbaz")
        writer.println("4\tx")
    }

    //when
    val result: List[Array[String]] = resources.getCsvIterator(new URL(url), Some("\t")).toList

    (result zip List(
      Array[String]("122", "foo"),
      Array[String]("23", "bar"),
      Array[String]("3455", "baz"),
      Array[String]("4", "x")
    )).foreach {
      case (r, expected) =>
        r should equal(expected)
    }
  }

  test("should treat the file as UTF-8 encoded") {
    // given
    val url = createCSVTempFileURL {
      writer =>
        writer.println("Malm\u0246")
        writer.println("K\u0248benhavn")
    }

    //when
    val result: List[Array[String]] = resources.getCsvIterator(new URL(url)).toList

    (result zip List(
      Array[String]("Malm\u0246"),
      Array[String]("K\u0248benhavn")
    )).foreach {
      case (r, expected) =>
        r should equal(expected)
    }
  }

  test("should propagate source description") {
    // given
    val url = createCSVTempFileURL {
      writer =>
        // an illegal value. There's currently no other way to verify source description
        // from a CSV resource (since it returns an iterator) than via an exception
        // that provides it.
        writer.println("\"quoted\" and then some")
    }

    // when
    val e = intercept[IllegalStateException](resources.getCsvIterator(new URL(url)))

    var path = url.replace("file:", "")
    if (SystemUtils.IS_OS_WINDOWS) {
      // remove first '/' before something like C:
      path = path.substring(1, path.length)
      // fix '/' into '\'
      path = FileUtils.fixSeparatorsInPath(path)
    }
    e.getMessage should include(path)
  }

  test("should parse multiline fields") {
    // given
    val url = createCSVTempFileURL {
      writer =>
        writer.println("a\tb")
        writer.println("1\t\"Bar\"")
        writer.println("2\t\"Bar\n\nQuux\n\"")
        writer.println("3\t\"Bar\n\nQuux\"")
    }

    //when
    val result: List[Array[String]] = resources.getCsvIterator(new URL(url), Some("\t")).toList

    (result zip List(
      Array[String]("a", "b"),
      Array[String]("1", "Bar"),
      Array[String]("2", "Bar\n\nQuux\n"),
      Array[String]("3", "Bar\n\nQuux")
    )).foreach {
      case (r, expected) =>
        r should equal(expected)
    }
  }
}


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Andreas Joelsson (andreas.joelsson@gmail.com)
 */
package io.github.scrier.opus.nuke.task.procedures;

import java.util.ArrayList;

import io.github.scrier.opus.common.message.BaseMsgC;
import io.github.scrier.opus.common.message.MessageService;

public class MessageServiceMock extends MessageService {

	private ArrayList<BaseMsgC> messages;
	private final int DefaultTimeout = 10;

	public MessageServiceMock() {
		super(new MessageIFImpl());
		setMessages(new ArrayList<BaseMsgC>());
	}

	@Override
  public void publishMessage(BaseMsgC message) {
	  messages.add(message);
  }

	public void clear() {
		messages.clear();
	}

	public int size() {
		return messages.size();
	}

	public boolean isEmpty() {
		return messages.isEmpty();
	}

	public BaseMsgC getMessage(int index) {
		if( index >= size() ) {
			return null;
		}
		return messages.get(index);
	}

	/**
	 * @return the messages
	 */
  public ArrayList<BaseMsgC> getMessages() {
	  return messages;
  }

	/**
	 * @param messages the messages to set
	 */
  private void setMessages(ArrayList<BaseMsgC> messages) {
	  this.messages = messages;
  }

  public void waitForMessages(int expectedNoOfMessages) {
  	waitForMessages(expectedNoOfMessages, DefaultTimeout);
  }

  public void waitForMessages(int expectedNoOfMessages, int timeout) {
  	timeout *= 10;
  	while( expectedNoOfMessages > messages.size() && timeout-- > 0 ) {
  		try {
	      Thread.sleep(100);
      } catch (InterruptedException e) {
	      return;
      }
  	}
  }

}


text:
'use strict';

const _ = require('lodash');
const { connectionArgs } = require('graphql-relay');

const { getType, getConnection } = require('../../types/type');
const { SCALARS } = require('../../types/generateTypeDefs');

const exchangeTypes = {
  any: 'JSON',
  Any: 'JSON',
  Number: 'Int',
  number: 'Int',
  boolean: 'Boolean',
  Object: 'JSON',
  object: 'JSON',
  PersistedModel: 'JSON'
};

/**
 * Checks if a given remote method allowed based on the allowed verbs
 * @param {*} method
 * @param {*} allowedVerbs
 */
function isRemoteMethodAllowed(method, allowedVerbs) {

  let httpArray = method.http;

  if (!_.isArray(method.http)) {
    httpArray = [method.http];
  }

  const results = httpArray.map((item) => {

    const verb = item.verb;

    if (allowedVerbs && !_.includes(allowedVerbs, verb)) {
      return false;
    }

    return true;
  });

  const result = _.includes(results, true);

  return result;
}

/**
 * Extracts query params from a remote method
 * @param {*} method
 */
function getRemoteMethodInput(method, isConnection = false) {
  const acceptingParams = {};

  method.accepts.forEach((param) => {
    let paramType = '';
    if (typeof param.type === 'object') {
      paramType = 'JSON';
    } else if (!SCALARS[param.type.toLowerCase()]) {
      paramType = `${param.type}Input`;
    } else {
      paramType = _.upperFirst(param.type);
    }
    if (param.arg) {
      acceptingParams[param.arg] = {
        type: getType(exchangeTypes[paramType] || paramType)
      };
    }
  });

  return (isConnection) ? Object.assign({}, acceptingParams, connectionArgs) : acceptingParams;
}

/**
 * Extracts query output fields from a remote method
 * @param {*} method
 */
function getRemoteMethodOutput(method) {

  // let returnType = 'JSON';

  // if (method.returns && method.returns[0]) {
  //   if (!SCALARS[method.returns[0].type] && typeof method.returns[0].type !== 'object') {
  //     returnType = `${method.returns[0].type}`;
  //   } else {
  //     returnType = `${_.upperFirst(method.returns[0].type)}`;
  //     if (typeof method.returns[0].type === 'object') {
  //       returnType = 'JSON';
  //     }
  //   }
  // }

  // const type = exchangeTypes[returnType] || returnType;

  // return getType(type) || getType('JSON');

  let returnType = 'JSON';
  let list = false;

  if (method.returns && method.returns[0]) {
    if (!SCALARS[method.returns[0].type] && typeof method.returns[0].type !== 'object') {
      returnType = `${method.returns[0].type}`;
    } else {
      returnType = `${method.returns[0].type}`;
      if (_.isArray(method.returns[0].type) && _.isString(method.returns[0].type[0])) {
        returnType = method.returns[0].type[0];
        list = true;
      } else if (typeof method.returns[0].type === 'object') {
        returnType = 'JSON';
      }
    }
  }

  let type = exchangeTypes[returnType] || returnType;
  type = (list) ? getConnection(type) : getType(type);
  type = type || getType('JSON');

  return {
    type,
    list
  };
}

/**
 * Returns query name for a remote method
 * @param {*} model
 * @param {*} method
 */
function getRemoteMethodQueryName(model, method) {
  return `${model.modelName}${_.upperFirst(method.name)}`;
}

/**
 * Check if the given access token can invoke the method
 * @param {*} args
 * @param {*} method
 * @param {*} model
 * @param {*} context
 * @return {Promise}
 */
function checkAccess(args, method, model, context) {
  const ctx = Object.assign(context, {
    model,
    modelName : method.sharedClass.name,
    property : method.name,
    accessType : method.accessType
  });
  return Promise.resolve().then(() => new Promise((resolve, reject) => {
    model.checkAccess(context.req.accessToken, args.id, method, ctx, (err, allowed) => {
      if (err) {
        reject(err);
      }
      resolve(allowed);
    });
  }));
}

module.exports = {
  exchangeTypes,
  isRemoteMethodAllowed,
  getRemoteMethodInput,
  getRemoteMethodOutput,
  getRemoteMethodQueryName,
  checkAccess
};


text:
exports.seed = async function(knex, Promise) {
  // It should usually always be 1 but just to be safe.
  const applicationId = await knex('applications').where('name', 'test_app').select('id');
  await knex('domains').insert([
        {
          name: 'localhost:4000',
          active: true,
          applicationId: applicationId[0].id
        },
        {
          name: 'localhost:8000',
          active: true,
          applicationId: applicationId[0].id
        }
  ]);
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to Apereo under one or more contributor license
    agreements. See the NOTICE file distributed with this work
    for additional information regarding copyright ownership.
    Apereo licenses this file to you under the Apache License,
    Version 2.0 (the "License"); you may not use this file
    except in compliance with the License.  You may obtain a
    copy of the License at the following location:

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

-->
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

    <display-name>Email Preview Portlet</display-name>
    <description>A portlet for previewing unread email in a user's mail inbox.</description>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/context/applicationContext.xml
            /WEB-INF/context/casContext.xml
        </param-value>
    </context-param>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>email-preview.webapp.root</param-value>
    </context-param>

    <!-- Must be the first listener so the webAppRootKey gets set for logback -->
    <listener>
        <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
    </listener>
    <!-- Needed to remove JMX registration and allow for classloader GC -->
    <listener>
        <listener-class>ch.qos.logback.classic.selector.servlet.ContextDetachingSCL</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Filter used for CAS proxy granting ticket functionality. Will do nothing if not using CAS proxy tickets -->
    <filter>
        <filter-name>CAS Validation Filter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetBeanName</param-name>
            <param-value>ticketValidationFilter</param-value>
        </init-param>
    </filter>

  <!-- Filter used for CAS proxy granting ticket functionality. Will do nothing if not using CAS proxy tickets -->
	<filter-mapping>
        <filter-name>CAS Validation Filter</filter-name>
        <url-pattern>/proxy/receptor</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>ViewRendererServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>ViewRendererServlet</servlet-name>
        <url-pattern>/WEB-INF/servlet/view</url-pattern>
    </servlet-mapping>

</web-app>


text:
RefCountedMemory::RefCountedMemory() {
}

RefCountedMemory::~RefCountedMemory() {
}

const unsigned char* RefCountedStaticMemory::front() const {
  return data_;
}

size_t RefCountedStaticMemory::size() const {
  return length_;
}

RefCountedBytes::RefCountedBytes() {
}

RefCountedBytes::RefCountedBytes(const std::vector<unsigned char>& initializer)
    : data_(initializer) {
}

RefCountedBytes* RefCountedBytes::TakeVector(
    std::vector<unsigned char>* to_destroy) {
  RefCountedBytes* bytes = new RefCountedBytes;
  bytes->data_.swap(*to_destroy);
  return bytes;
}

const unsigned char* RefCountedBytes::front() const {
  // STL will assert if we do front() on an empty vector, but calling code
  // expects a NULL.
  return size() ? &data_.front() : NULL;
}

size_t RefCountedBytes::size() const {
  return data_.size();
}

RefCountedBytes::~RefCountedBytes() {
}

namespace base {

RefCountedString::RefCountedString() {}

RefCountedString::~RefCountedString() {}

// static
RefCountedString* RefCountedString::TakeString(std::string* to_destroy) {
  RefCountedString* self = new RefCountedString;
  to_destroy->swap(self->data_);
  return self;
}

const unsigned char* RefCountedString::front() const {
  return data_.empty() ? NULL :
         reinterpret_cast<const unsigned char*>(data_.data());
}

size_t RefCountedString::size() const {
  return data_.size();
}

}  //  namespace base


text:
<!DOCTYPE html>

    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <meta charset="utf-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta name="keywords">
    <meta name="description">

    <title>Citizens Advice style guide- Subscribe by email
    </title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=2.0" name="viewport">
    <meta content="48a2415d-980f-4763-a5b9-e10e000636b3" name="cab-guid">
    <meta content="EWS" name="cab-extent">
    <meta content="../../static/images/apple-touch-icon.png">
    <meta content="B53C5C20449FC2233D3862B4DBEDFA3E" name="msvalidate.01">

    <link href="../../css/guide.css" rel="stylesheet">
    <link href="../../images/favicon/32.png" rel="shortcut icon">
    <link href="../../images/favicon/228.png" rel="apple-touch-icon">

Skip to contentSkip to footer

Blog

Policy blog

Subscribe by email

              <form></form>

                Your email
                <input id="standardField" placeholder="email@email.com" type="email">

                <legend for="checkbox">Select the blogs you'd like to subscribe to</legend>

                  <input name="checkbox" type="checkbox">

Charity blog
A blog for the whole charity

                  <input name="checkbox" type="checkbox">

Policy blog
Our blog about policy updates and changes

                  <input checked name="checkbox" type="checkbox">

Digital blog
The digital teams blog

                <button type="submit" class="btn tick-button-icon">Update email preferences</button>

Copyright © 2016 Citizens Advice, an operating name of the National Association of Citizens Advice Bureaux.
Registered charity number 279057; Registered in England 1436945; VAT number GB726020276. 3rd Floor North, 200 Aldersgate, London, EC1A 4HD


text:
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/bearsunday/BEAR.QueryRepository/badges/quality-score.png?b=1.x)](https://scrutinizer-ci.com/g/bearsunday/BEAR.QueryRepository/?branch=1.x)
[![codecov](https://codecov.io/gh/bearsunday/BEAR.QueryRepository/branch/1.x/graph/badge.svg?token=eh3c9AF4Mr)](https://codecov.io/gh/koriym/BEAR.QueryRepository)
[![Type Coverage](https://shepherd.dev/github/bearsunday/BEAR.QueryRepository/coverage.svg)](https://shepherd.dev/github/bearsunday/BEAR.QueryRepository)
![Continuous Integration](https://github.com/bearsunday/BEAR.QueryRepository/workflows/Continuous%20Integration/badge.svg)

BEAR.QueryRepository is a distributed cache famework for BEAR.Resource application.
[CQRS](http://martinfowler.com/bliki/CQRS.html) inspired **BEAR.QueryRepository** segregates reads and writes into two separate repository.

Documentation is available at [BEAR.Sunday cache manual](http://bearsunday.github.io/manuals/1.0/ja/cache.html).

## Demo

```
php demo/run.php
```


text:
.class Lcom/htc/painting/penmenu/PenMenu$RestoreSettingListener;
.super Ljava/lang/Object;
.source "PenMenu.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/htc/painting/penmenu/PenMenu;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "RestoreSettingListener"
.end annotation

# instance fields
.field mPenMenu:Lcom/htc/painting/penmenu/PenMenu;

# direct methods
.method public constructor <init>(Lcom/htc/painting/penmenu/PenMenu;)V
    .locals 0
    .parameter "menu"

    .prologue
    .line 4069
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 4070
    iput-object p1, p0, Lcom/htc/painting/penmenu/PenMenu$RestoreSettingListener;->mPenMenu:Lcom/htc/painting/penmenu/PenMenu;

    .line 4071
    return-void
.end method

# virtual methods
.method public onRestoreFinish(I)V
    .locals 2
    .parameter "token"

    .prologue
    .line 4077
    iget-object v0, p0, Lcom/htc/painting/penmenu/PenMenu$RestoreSettingListener;->mPenMenu:Lcom/htc/painting/penmenu/PenMenu;

    new-instance v1, Lcom/htc/painting/penmenu/PenMenu$RestoreSettingListener$1;

    invoke-direct {v1, p0, p1}, Lcom/htc/painting/penmenu/PenMenu$RestoreSettingListener$1;-><init>(Lcom/htc/painting/penmenu/PenMenu$RestoreSettingListener;I)V

    invoke-virtual {v0, v1}, Lcom/htc/painting/penmenu/PenMenu;->post(Ljava/lang/Runnable;)Z

    .line 4103
    return-void
.end method


text:
package com.headwire.aemdc.companion;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.headwire.aemdc.runner.BasisRunner;
import com.headwire.aemdc.runner.DynamicRunner;
import com.headwire.aemdc.util.FilesDirsUtil;

/**
 * Reflection API to get template type Runner object
 *
 * @author Marat Saitov, 15.11.2016
 */
public class Reflection {

  private static final Logger LOG = LoggerFactory.getLogger(Reflection.class);

  private final Properties props;
  private final Config config;

  /**
   * Constructor
   *
   * @param config
   *          - properties config
   */
  public Reflection(final Config config) {
    this.config = config;

    // Get properties from reflection file
    props = FilesDirsUtil.getPropertiesFromContextClassLoader(Constants.REFLECTION_PROPS_FILE_PATH);
  }

  /**
   * Get Runner according to the template type of resource.
   *
   * @param resource
   *          - resource object
   * @return runner object
   */
  public BasisRunner getRunner(final Resource resource) {
    BasisRunner runner = null;
    final String type = resource.getType();

    if (StringUtils.isNotBlank(type)) {
      final String fullyQualifiedClassName = props.getProperty(type);

      if (StringUtils.isNotBlank(fullyQualifiedClassName)) {
        try {
          final Class<?> c = Class.forName(fullyQualifiedClassName);
          final Constructor<?> ctor = c.getDeclaredConstructor(Resource.class, Config.class);
          ctor.setAccessible(true);
          runner = (BasisRunner) ctor.newInstance(resource, config);

        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException
            | SecurityException | IllegalArgumentException | InvocationTargetException e) {
          LOG.error("Can't get class instance for template type [{}]. ", type, e);
        }
      } else if (config.getDynamicTypes().contains(type)) {
        runner = new DynamicRunner(resource, config);
      } else {
        LOG.error("Unknown <type> argument [{}].", type);
      }
    }

    return runner;
  }
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import collections
import processors.hra.extractors as extractors

class TestHRAPublicationExtractor(object):
    def test_extracts_publication_identifiers(self):
        record = collections.defaultdict(lambda: '')
        record.update({
            'nct_id': '00020500',
            'euctr_id': '2013-030180-02',
            'isrctn_id': '02018090',
        })
        expected_identifiers = [{
            'nct': 'NCT00020500',
            'euctr': 'EUCTR2013-030180-02',
            'isrctn': 'ISRCTN02018090',
        }]
        publication = extractors.extract_publication(record)

        assert publication['identifiers'] == expected_identifiers

    def test_ignores_invalid_identifiers(self):
        record = collections.defaultdict(lambda: '')
        record.update({
            'nct_id': '00020500',
            'euctr_id': 'EUCTR0000-000000-00',
            'isrctn_id': 'ISRCTN00000000',
        })
        expected_identifiers = [{'nct': 'NCT00020500'}]
        publication = extractors.extract_publication(record)

        assert publication['identifiers'] == expected_identifiers

    def test_extracts_identifiers_from_abstract(self):
        record = collections.defaultdict(lambda: '')
        record['research_summary'] = 'This publication mentions NCT00020500'
        expected_identifiers = [{'nct': 'NCT00020500'}]
        publication = extractors.extract_publication(record)

        assert publication['identifiers'] == expected_identifiers

    def test_creates_url_from_title(self):
        record = collections.defaultdict(lambda: '')
        record['application_title'] = 'Longterm F/U study of BOTOX® in Idiopathic Overactive Bladder patients'
        expected_url = 'http://www.hra.nhs.uk/news/research-summaries/longterm-fu-study-of-botox-in-idiopathic-overactive-bladder-patients'
        publication = extractors.extract_publication(record)

        assert publication['source_url'] == expected_url


text:
import logging

from taskflow.patterns import linear_flow

from pumphouse import events
from pumphouse import exceptions
from pumphouse import task

LOG = logging.getLogger(__name__)

class RetrieveTenant(task.BaseCloudTask):
    def execute(self, tenant_id):
        tenant = self.cloud.keystone.tenants.get(tenant_id)
        return tenant.to_dict()

class EnsureTenant(task.BaseCloudTask):
    def execute(self, tenant_info):
        try:
            tenant = self.cloud.keystone.tenants.find(name=tenant_info["name"])
        except exceptions.keystone_excs.NotFound:
            tenant = self.cloud.keystone.tenants.create(
                tenant_info["name"],
                description=tenant_info["description"],
                enabled=tenant_info["enabled"],
            )
            LOG.info("Created tenant: %s", tenant)
            self.created_event(tenant)
        return tenant.to_dict()

    def created_event(self, tenant):
        LOG.info("Tenant created: %s", tenant.id)
        events.emit("create", {
            "id": tenant.id,
            "type": "tenant",
            "cloud": self.cloud.name,
            "data": tenant.to_dict(),
        }, namespace="/events")

class AddTenantAdmin(task.BaseCloudTask):
    def execute(self, tenant_info):
        tenant = self.cloud.keystone.tenants.get(tenant_info["id"])
        user = self.cloud.keystone.auth_ref.user_id
        admin_roles = [r for r in self.cloud.keystone.roles.list()
                       if r.name == "admin"]
        if not admin_roles:
            raise exceptions.NotFound
        admin_role = admin_roles[0]
        try:
            self.cloud.keystone.tenants.add_user(tenant,
                                                 user,
                                                 admin_role)
        except exceptions.keystone_excs.Conflict:
            LOG.warning("User %s is admin in tenant %r", user, tenant)
        return tenant_info

def migrate_tenant(context, tenant_id):
    tenant_binding = "tenant-{}".format(tenant_id)
    tenant_retrieve = "{}-retrieve".format(tenant_binding)
    tenant_ensure = "{}-create".format(tenant_binding)
    tenant_addadmin = "{}-ensure".format(tenant_binding)
    flow = linear_flow.Flow("migrate-tenant-{}".format(tenant_id)).add(
        RetrieveTenant(context.src_cloud,
                       name=tenant_binding,
                       provides=tenant_binding,
                       rebind=[tenant_retrieve]),
        EnsureTenant(context.dst_cloud,
                     name=tenant_ensure,
                     provides=tenant_ensure,
                     rebind=[tenant_binding]),
        AddTenantAdmin(context.dst_cloud,
                       name=tenant_addadmin,
                       provides=tenant_addadmin,
                       rebind=[tenant_ensure]),
    )
    context.store[tenant_retrieve] = tenant_id
    return flow


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="repo"
            type="com.simple.creact.simple.app.data.entity.github.Repo" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="20dp"
        android:paddingTop="20dp">

        <TextView
            android:id="@+id/repo_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:gravity="center"
            android:singleLine="true"
            android:text="@{@string/repo_name_format(repo.name,repo.stars)}" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text='@{""+repo.stars}'
            android:textColor="@android:color/holo_red_dark"
            android:visibility="gone" />
    </RelativeLayout>
</layout>


text:
using l10n_util::GetStringUTF16;
using l10n_util::GetStringUTF8;

namespace views {
namespace examples {

// ScrollView's content, which draws gradient color on background.
// TODO(oshima): add child views as well.
class ScrollViewExample::ScrollableView : public View {
 public:
  ScrollableView() {
    SetColor(SK_ColorRED, SK_ColorCYAN);

    auto* layout_manager = SetLayoutManager(std::make_unique<views::BoxLayout>(
        views::BoxLayout::Orientation::kVertical, gfx::Insets(), 0));

    const auto add_child = [this](std::unique_ptr<View> view) {
      auto* container = AddChildView(std::make_unique<View>());
      container->SetLayoutManager(std::make_unique<views::BoxLayout>(
          views::BoxLayout::Orientation::kVertical));
      container->AddChildView(std::move(view));
    };
    add_child(std::make_unique<LabelButton>(
        Button::PressedCallback(),
        GetStringUTF16(IDS_SCROLL_VIEW_BUTTON_LABEL)));
    add_child(std::make_unique<RadioButton>(
        GetStringUTF16(IDS_SCROLL_VIEW_RADIO_BUTTON_LABEL), 0));
    layout_manager->SetDefaultFlex(1);
  }

  ScrollableView(const ScrollableView&) = delete;
  ScrollableView& operator=(const ScrollableView&) = delete;

  void SetColor(SkColor from, SkColor to) {
    from_color_ = from;
    to_color_ = to;
  }

  void OnPaintBackground(gfx::Canvas* canvas) override {
    cc::PaintFlags flags;
    flags.setShader(gfx::CreateGradientShader(
        gfx::Point(), gfx::Point(0, height()), from_color_, to_color_));
    flags.setStyle(cc::PaintFlags::kFill_Style);
    canvas->DrawRect(GetLocalBounds(), flags);
  }

 private:
  SkColor from_color_;
  SkColor to_color_;
};

ScrollViewExample::ScrollViewExample()
    : ExampleBase(GetStringUTF8(IDS_SCROLL_VIEW_SELECT_LABEL).c_str()) {}

ScrollViewExample::~ScrollViewExample() = default;

void ScrollViewExample::CreateExampleView(View* container) {
  auto scroll_view = std::make_unique<ScrollView>();
  scrollable_ = scroll_view->SetContents(std::make_unique<ScrollableView>());
  scrollable_->SetBounds(0, 0, 1000, 100);
  scrollable_->SetColor(SK_ColorYELLOW, SK_ColorCYAN);

  container->SetLayoutManager(std::make_unique<FlexLayout>())
      ->SetOrientation(LayoutOrientation::kVertical);

  auto full_flex = FlexSpecification(MinimumFlexSizeRule::kScaleToZero,
                                     MaximumFlexSizeRule::kUnbounded)
                       .WithWeight(1);

  // Add scroll view.
  scroll_view_ = container->AddChildView(std::move(scroll_view));
  scroll_view_->SetProperty(views::kFlexBehaviorKey, full_flex);

  // Add control buttons.
  auto* button_panel = container->AddChildView(std::make_unique<View>());
  button_panel->SetLayoutManager(std::make_unique<FlexLayout>())
      ->SetOrientation(LayoutOrientation::kHorizontal);

  button_panel->AddChildView(std::make_unique<LabelButton>(
      base::BindRepeating(&ScrollViewExample::ButtonPressed,
                          base::Unretained(this), gfx::Rect(0, 0, 1000, 100),
                          SK_ColorYELLOW, SK_ColorCYAN),
      GetStringUTF16(IDS_SCROLL_VIEW_WIDE_LABEL)));
  button_panel->AddChildView(std::make_unique<LabelButton>(
      base::BindRepeating(&ScrollViewExample::ButtonPressed,
                          base::Unretained(this), gfx::Rect(0, 0, 100, 1000),
                          SK_ColorRED, SK_ColorCYAN),
      GetStringUTF16(IDS_SCROLL_VIEW_TALL_LABEL)));
  button_panel->AddChildView(std::make_unique<LabelButton>(
      base::BindRepeating(&ScrollViewExample::ButtonPressed,
                          base::Unretained(this), gfx::Rect(0, 0, 1000, 1000),
                          SK_ColorRED, SK_ColorGREEN),
      GetStringUTF16(IDS_SCROLL_VIEW_BIG_SQUARE_LABEL)));
  button_panel->AddChildView(std::make_unique<LabelButton>(
      base::BindRepeating(&ScrollViewExample::ButtonPressed,
                          base::Unretained(this), gfx::Rect(0, 0, 100, 100),
                          SK_ColorYELLOW, SK_ColorGREEN),
      GetStringUTF16(IDS_SCROLL_VIEW_SMALL_SQUARE_LABEL)));
  button_panel->AddChildView(std::make_unique<LabelButton>(
      base::BindRepeating(&View::ScrollRectToVisible,
                          base::Unretained(scroll_view_->contents()),
                          gfx::Rect(20, 500, 1000, 500)),
      GetStringUTF16(IDS_SCROLL_VIEW_SCROLL_TO_LABEL)));

  for (View* child : button_panel->children())
    child->SetProperty(views::kFlexBehaviorKey, full_flex);
}

void ScrollViewExample::ButtonPressed(gfx::Rect bounds,
                                      SkColor from,
                                      SkColor to) {
  scrollable_->SetBoundsRect(std::move(bounds));
  scrollable_->SetColor(from, to);
}

}  // namespace examples
}  // namespace views


text:
@implementation UIViewController (ShowAlert)

- (void) showAlertWithTitle:(NSString *)title andDescription:(NSString *)description
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:description
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil, nil];
    [alert show];
}

@end


text:
/*
 * Programmer:	Quincey Koziol <koziol@hdfgroup.org>
 *		Wednesday, April 11, 2007
 *
 * Purpose:	This file contains declarations which are visible only within
 *		the H5E package.  Source files outside the H5E package should
 *		include H5Eprivate.h instead.
 */
#ifndef H5E_PACKAGE
#error "Do not include this file outside the H5E package!"
#endif

#ifndef _H5Epkg_H
#define _H5Epkg_H

/* Get package's private header */
#include "H5Eprivate.h"

/* Other private headers needed by this file */

/**************************/
/* Package Private Macros */
/**************************/

/* Amount to indent each error */
#define H5E_INDENT              2

/* Number of slots in an error stack */
#define H5E_NSLOTS	        32

#ifdef H5_HAVE_THREADSAFE
/*
 * The per-thread error stack. pthread_once() initializes a special
 * key that will be used by all threads to create a stack specific to
 * each thread individually. The association of stacks to threads will
 * be handled by the pthread library.
 *
 * In order for this macro to work, H5E_get_my_stack() must be preceeded
 * by "H5E_t *estack =".
 */
#define H5E_get_my_stack()  H5E_get_stack()
#else /* H5_HAVE_THREADSAFE */
/*
 * The current error stack.
 */
#define H5E_get_my_stack() (H5E_stack_g + 0)
#endif /* H5_HAVE_THREADSAFE */

/****************************/
/* Package Private Typedefs */
/****************************/

/* Some syntactic sugar to make the compiler happy with two different kinds of callbacks */
#ifndef H5_NO_DEPRECATED_SYMBOLS
typedef struct {
    unsigned    vers;       /* Which version callback to use */
    hbool_t     is_default; /* If the printing function is the library's own. */
    H5E_auto1_t func1;      /* Old-style callback, NO error stack param. */
    H5E_auto2_t func2;      /* New-style callback, with error stack param. */
    H5E_auto1_t func1_default;      /* The saved library's default function - old style. */
    H5E_auto2_t func2_default;      /* The saved library's default function - new style. */
} H5E_auto_op_t;
#else /* H5_NO_DEPRECATED_SYMBOLS */
typedef struct {
    H5E_auto_t  func2;      /* Only the new style callback function is available. */
} H5E_auto_op_t;
#endif /* H5_NO_DEPRECATED_SYMBOLS */

/* Some syntactic sugar to make the compiler happy with two different kinds of callbacks */
typedef struct {
    unsigned vers;              /* Which version callback to use */
    union {
#ifndef H5_NO_DEPRECATED_SYMBOLS
        H5E_walk1_t func1;      /* Old-style callback, NO error stack param. */
#endif /* H5_NO_DEPRECATED_SYMBOLS */
        H5E_walk2_t func2;      /* New-style callback, with error stack param. */
    }u;
} H5E_walk_op_t;

/* Error class */
typedef struct H5E_cls_t {
    char *cls_name;             /* Name of error class */
    char *lib_name;             /* Name of library within class */
    char *lib_vers;             /* Version of library */
} H5E_cls_t;

/* Major or minor message */
typedef struct H5E_msg_t {
    char        *msg;           /* Message for error */
    H5E_type_t   type;          /* Type of error (major or minor) */
    H5E_cls_t   *cls;           /* Which error class this message belongs to */
} H5E_msg_t;

/* Error stack */
struct H5E_t {
    size_t nused;		        /* Num slots currently used in stack  */
    H5E_error2_t slot[H5E_NSLOTS];	/* Array of error records	     */
    H5E_auto_op_t auto_op;              /* Operator for 'automatic' error reporting */
    void *auto_data;                    /* Callback data for 'automatic error reporting */
};

/*****************************/
/* Package Private Variables */
/*****************************/

#ifndef H5_HAVE_THREADSAFE
/*
 * The current error stack.
 */
H5_DLLVAR H5E_t	H5E_stack_g[1];
#endif /* H5_HAVE_THREADSAFE */

/******************************/
/* Package Private Prototypes */
/******************************/
H5_DLL herr_t H5E__term_deprec_interface(void);
#ifdef H5_HAVE_THREADSAFE
H5_DLL H5E_t *H5E_get_stack(void);
#endif /* H5_HAVE_THREADSAFE */
H5_DLL ssize_t H5E_get_msg(const H5E_msg_t *msg_ptr, H5E_type_t *type,
    char *msg, size_t size);
H5_DLL herr_t H5E_print(const H5E_t *estack, FILE *stream, hbool_t bk_compat);
H5_DLL herr_t H5E_walk(const H5E_t *estack, H5E_direction_t direction,
    const H5E_walk_op_t *op, void *client_data);
H5_DLL herr_t H5E_get_auto(const H5E_t *estack, H5E_auto_op_t *op,
    void **client_data);
H5_DLL herr_t H5E_set_auto(H5E_t *estack, const H5E_auto_op_t *op,
    void *client_data);
H5_DLL herr_t H5E_pop(H5E_t *err_stack, size_t count);

#endif /* _H5Epkg_H */


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

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="common-fhir-beans.xml"/>

    <bean id="routeBuilder"
          class="org.openehealth.ipf.platform.camel.ihe.fhir.iti65.Iti65TestRouteBuilder">
        <constructor-arg value="false"/>
        <constructor-arg value="true"/>
    </bean>

    <bean id="batch" class="org.openehealth.ipf.platform.camel.ihe.fhir.core.custom.CustomFhirComponent">
        <property name="name" value="batch"/>
        <property name="fhirTransactionConfiguration">
            <bean class="org.openehealth.ipf.commons.ihe.fhir.FhirTransactionConfiguration">
                <constructor-arg index="0" value="batch"/>
                <constructor-arg index="1" value="description"/>
                <constructor-arg index="2" value="false"/>
                <constructor-arg index="3"><null/></constructor-arg>
                <constructor-arg index="4"><null/></constructor-arg>
                <constructor-arg index="5" ref="fhirContext"/>
                <constructor-arg index="6">
                    <bean class="org.openehealth.ipf.commons.ihe.fhir.BatchTransactionResourceProvider"
                          factory-method="getInstance"/>
                </constructor-arg>
                <constructor-arg index="7">
                    <bean class="org.openehealth.ipf.commons.ihe.fhir.BatchTransactionClientRequestFactory"
                          factory-method="getInstance"/>
                </constructor-arg>
                <constructor-arg index="8"><null/></constructor-arg>

                <property name="staticConsumerSelector">
                    <bean class="org.openehealth.ipf.commons.ihe.fhir.BundleProfileSelector">
                        <constructor-arg name="profileUris" value="http://thissucks.com"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

</beans>


text:
import os, sys
import collections
import itertools
import queue
import statistics
import threading

from ..core import config, exc, logging, utils
log = logging.logger(__package__)
from . import remote
from ..sensors import ultrasonic

class Controller(remote.Controller):

    N_SAMPLES = 10

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.started = False
        self.sensor_queues = {}
        self.sensor_threads = []
        self.distances = {}

    def dispatch(self, action, params):
        if not self.started and action not in ("start", "stop"):
            log.warn("Cannot dispatch %s : %s when not yet started", action, ", ".join(params))
        else:
           super().dispatch(action, params)

    def distance_sensor(self, sensor, queue):
        sensor.steady_trigger()
        while not self.finished():
            queue.put(sensor.find_distance_mm())

    def handle_start(self):
        for position in "left", "right":
            sensor_name = "%s_ultrasonic" % position
            sensor_config = config[sensor_name]
            sensor = ultrasonic.Sensor(sensor_config.trigger_pin, sensor_config.echo_pin)
            queue = self.sensor_queues[position] = queue.Queue()
            self.distances[position] = deque.deque([], self.N_SAMPLES)
            sensor_thread = threading.Thread(target=self.distance_sensor, args=(sensor, queue))
            self.sensor_threads.append(sensor_thread)

        for sensor_thread in self.sensor_threads:
            thread.start()
        self.started = True

        self.robot.forward()

    def handle_stop(self):
        self.robot.stop()
        self.started = False

    def read_distances(self):
        for position in self.sensor_queues:
            try:
                distance = self.sensor_queues[position].get_nowait()
            except queue.Empty:
                continue
            else:
                self.distances[position].append(distance)

    def movement(self, distances):
        robust_distances = utils.without_outliers(distances)
        #
        # Determine the overall movement over the last N_SAMPLES. If this is negative, we're
        # moving closer to that side; if positive, we're moving away.
        #
        return sum(b - a for (a, b) in zip(robust_distances[:-1], robust_distances[1:]))

    def effective_movement(self):
        left_movement = self.movement(self.distances["left"])
        right_movement = self.movement(self.distances["right"])
        if left_movement > right_movement:
            return "left":
        else:
            return "right"

    def generate_commands(self):
        #
        # Handle remote commands first
        #
        super().generate_commands()
        #
        # Pick up the latest movements recorded from the lateral sensors
        #
        self.read_distances()
        #
        # Determine whether we need to move
        #
        effective_movement = self.effective_movement()
        if effective_movement == "left":
            self.robot.turn("right")
        elif effective_movement == "right":
            self.robot.turn("left")


text:
@interface APITestViewController (Device)

@end


text:
<?php defined('SYSPATH') or die('No direct access allowed.');

class Dittobase extends Model_Dittobase {
}


text:
class LinkCourseAssessmentAnswerAutoGradingToJobs < ActiveRecord::Migration
  def change
    remove_column :course_assessment_answer_auto_gradings, :status, :integer,
                  null: false, default: 0
    change_table :course_assessment_answer_auto_gradings do |t|
      t.uuid :job_id, foreign_key: { references: :jobs, on_delete: :set_null }, index: :unique
    end
  end
end


text:
<?php

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) )
	exit();

if ( ! class_exists( 'GADWP_Frontend_Setup' ) ) {

	final class GADWP_Frontend_Setup {

		private $gadwp;

		public function __construct() {
			$this->gadwp = GADWP();

			// Styles & Scripts
			add_action( 'wp_enqueue_scripts', array( $this, 'load_styles_scripts' ) );
		}

		/**
		 * Styles & Scripts conditional loading
		 *
		 * @param
		 *            $hook
		 */
		public function load_styles_scripts() {
			$lang = get_bloginfo( 'language' );
			$lang = explode( '-', $lang );
			$lang = $lang[0];

			/*
			 * Item reports Styles & Scripts
			 */
			if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_front'] ) && $this->gadwp->config->options['frontend_item_reports'] ) {

				wp_enqueue_style( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.css', null, GADWP_CURRENT_VERSION );

				wp_enqueue_style( 'gadwp-frontend-item-reports', GADWP_URL . 'front/css/item-reports.css', null, GADWP_CURRENT_VERSION );

				$country_codes = GADWP_Tools::get_countrycodes();
				if ( $this->gadwp->config->options['ga_target_geomap'] && isset( $country_codes[$this->gadwp->config->options['ga_target_geomap']] ) ) {
					$region = $this->gadwp->config->options['ga_target_geomap'];
				} else {
					$region = false;
				}

				wp_enqueue_style( "wp-jquery-ui-dialog" );

				wp_register_script( 'googlejsapi', 'https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22visualization%22%2C%22version%22%3A%221%22%2C%22language%22%3A%22' . $lang . '%22%2C%22packages%22%3A%5B%22corechart%22%2C%20%22table%22%2C%20%22orgchart%22%2C%20%22geochart%22%5D%7D%5D%7D%27', array(), null );

				wp_enqueue_script( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.js', array( 'jquery' ), GADWP_CURRENT_VERSION );

				wp_enqueue_script( 'gadwp-frontend-item-reports', GADWP_URL . 'common/js/reports.js', array( 'gadwp-nprogress', 'googlejsapi', 'jquery', 'jquery-ui-dialog' ), GADWP_CURRENT_VERSION, true );

				/* @formatter:off */
				wp_localize_script( 'gadwp-frontend-item-reports', 'gadwpItemData', array(
					'ajaxurl' => admin_url( 'admin-ajax.php' ),
					'security' => wp_create_nonce( 'gadwp_frontend_item_reports' ),
					'dateList' => array(
						'today' => __( "Today", 'google-analytics-dashboard-for-wp' ),
						'yesterday' => __( "Yesterday", 'google-analytics-dashboard-for-wp' ),
						'7daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 7 ),
						'14daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 14 ),
						'30daysAgo' =>  sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 30 ),
						'90daysAgo' =>  sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 90 ),
						'365daysAgo' =>  sprintf( _n( "%s Year", "%s Years", 1, 'google-analytics-dashboard-for-wp' ), __('One', 'google-analytics-dashboard-for-wp') ),
						'1095daysAgo' =>  sprintf( _n( "%s Year", "%s Years", 3, 'google-analytics-dashboard-for-wp' ), __('Three', 'google-analytics-dashboard-for-wp') ),
					),
					'reportList' => array(
						'uniquePageviews' => __( "Unique Views", 'google-analytics-dashboard-for-wp' ),
						'users' => __( "Users", 'google-analytics-dashboard-for-wp' ),
						'organicSearches' => __( "Organic", 'google-analytics-dashboard-for-wp' ),
						'pageviews' => __( "Page Views", 'google-analytics-dashboard-for-wp' ),
						'visitBounceRate' => __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
						'locations' => __( "Location", 'google-analytics-dashboard-for-wp' ),
						'referrers' => __( "Referrers", 'google-analytics-dashboard-for-wp' ),
						'searches' => __( "Searches", 'google-analytics-dashboard-for-wp' ),
						'trafficdetails' => __( "Traffic", 'google-analytics-dashboard-for-wp' ),
						'technologydetails' => __( "Technology", 'google-analytics-dashboard-for-wp' ),
					),
					'i18n' => array(
							__( "A JavaScript Error is blocking plugin resources!", 'google-analytics-dashboard-for-wp' ), //0
							__( "Traffic Mediums", 'google-analytics-dashboard-for-wp' ),
							__( "Visitor Type", 'google-analytics-dashboard-for-wp' ),
							__( "Search Engines", 'google-analytics-dashboard-for-wp' ),
							__( "Social Networks", 'google-analytics-dashboard-for-wp' ),
							__( "Unique Views", 'google-analytics-dashboard-for-wp' ),
							__( "Users", 'google-analytics-dashboard-for-wp' ),
							__( "Page Views", 'google-analytics-dashboard-for-wp' ),
							__( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
							__( "Organic Search", 'google-analytics-dashboard-for-wp' ),
							__( "Pages/Session", 'google-analytics-dashboard-for-wp' ),
							__( "Invalid response", 'google-analytics-dashboard-for-wp' ),
							__( "Not enough data collected", 'google-analytics-dashboard-for-wp' ),
							__( "This report is unavailable", 'google-analytics-dashboard-for-wp' ),
							__( "report generated by", 'google-analytics-dashboard-for-wp' ), //14
							__( "This plugin needs an authorization:", 'google-analytics-dashboard-for-wp' ) . ' <strong>' . __( "authorize the plugin", 'google-analytics-dashboard-for-wp' ) . '</strong>!',
							__( "Browser", 'google-analytics-dashboard-for-wp' ), //16
							__( "Operating System", 'google-analytics-dashboard-for-wp' ),
							__( "Screen Resolution", 'google-analytics-dashboard-for-wp' ),
							__( "Mobile Brand", 'google-analytics-dashboard-for-wp' ),
					),
					'colorVariations' => GADWP_Tools::variations( $this->gadwp->config->options['ga_dash_style'] ),
					'region' => $region,
					'language' => get_bloginfo( 'language' ),
					'filter' => $_SERVER["REQUEST_URI"],
					'viewList' => false,
					'scope' => 'front-item',
				 )
				);
				/* @formatter:on */
			}
		}
	}
}


text:
class GpdbSchema < Schema
  include SandboxSchema

  has_many :views, :source => :datasets, :class_name => 'GpdbView', :foreign_key => :schema_id
  has_many :tables, :source => :datasets, :class_name => 'GpdbTable', :foreign_key => :schema_id

  validates :name, :format => /^[^\/?&]*$/

  before_save :mark_schemas_as_stale

  def class_for_type(type)
    type == 'r' ? GpdbTable : GpdbView
  end

  private

  def mark_schemas_as_stale
    if stale? && stale_at_changed?
      datasets.each do |dataset|
        dataset.mark_stale! unless dataset.type == "ChorusView"
      end
    end
  end
end


text:
using System.ComponentModel.DataAnnotations;

namespace AspNetDeploy.Model
{
    public enum UserRole
    {
        [Display(Name = "Undefined")]
        Undefined = 0,

        [Display(Name = "Observer")]
        Observer = 1,

        [Display(Name = "Developer")]
        Developer = 10,

        [Display(Name = "Power Developer")]
        PowerDeveloper = 20,

        [Display(Name = "Tester")]
        Tester = 100,

        [Display(Name = "Publisher")]
        Publisher = 1000,

        [Display(Name = "Admin")]
        Admin = 10000
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Report of the Department of Agriculture, Government Research Institute of Formosa 19: 298 (1919)

#### Original name
Leptosphaerulina moricola Sawada

### Remarks
null


text:
CREATE DATABASE IF NOT EXISTS news CHARACTER SET UTF8;
USE news;
DROP TABLE IF EXISTS subscribe;
CREATE TABLE subscribe (
user VARCHAR(64) NOT NULL PRIMARY KEY COMMENT '主键',
inquirys tinyint(1) DEFAULT 1,
orders tinyint(1) DEFAULT 1,
returns tinyint(1) DEFAULT 1
);

INSERT INTO subscribe(user) values('kenas');

select * from subscribe;
delete from subscribe where user != "";

update subscribe set inquirys = 1, orders = 1, returns = 1 where user = "user_1421649662306";
drop table subscribe;
select * from subscribe;


text:
package it.unibz.krdb.obda.sesame;

import it.unibz.krdb.obda.ontology.Assertion;

import java.util.Iterator;

import org.openrdf.model.Statement;

/***
 * An iterator that will dynamically construct ABox assertions for the given
 * predicate based on the results of executing the mappings for the predicate in
 * each data source.
 *
 */
public class SesameStatementIterator implements Iterator<Statement> {
	private final Iterator<Assertion> iterator;

	public SesameStatementIterator(Iterator<Assertion> it) {
		this.iterator = it;
	}

	public boolean hasNext() {
		return iterator.hasNext();
	}

    /* //another version which skips errors
    public Statement next() {
        try {
            Assertion assertion = iterator.next();
            Statement statement = new SesameStatement(assertion);
            return statement;
        } catch (IllegalArgumentException ex){
            System.err.println("Skip the assertion cannot be converted into triple: ");
            ex.printStackTrace();
            return next();
        }

    }*/

	public Statement next() {
		Assertion assertion = iterator.next();
		Statement individual = new SesameStatement(assertion);
		return individual;
	}

	public void remove() {
		throw new UnsupportedOperationException("This iterator is read-only");
	}

}


text:
"""CourseAuditLog API Tests for Version 1.0.

This is a testing template for the generated CourseAuditLogAPI Class.
"""
import unittest
import requests
import secrets
from py3canvas.apis.course_audit_log import CourseAuditLogAPI
from py3canvas.apis.course_audit_log import Courseeventlink
from py3canvas.apis.course_audit_log import Courseevent
from py3canvas.apis.course_audit_log import Createdeventdata
from py3canvas.apis.course_audit_log import Updatedeventdata

class TestCourseAuditLogAPI(unittest.TestCase):
    """Tests for the CourseAuditLogAPI."""

    def setUp(self):
        self.client = CourseAuditLogAPI(secrets.instance_address, secrets.access_token)

    def test_query_by_course(self):
        """Integration test for the CourseAuditLogAPI.query_by_course method."""
        course_id = None  # Change me!!

        r = self.client.query_by_course(course_id, end_time=None, start_time=None)

    def test_query_by_account(self):
        """Integration test for the CourseAuditLogAPI.query_by_account method."""
        account_id = None  # Change me!!

        r = self.client.query_by_account(account_id, end_time=None, start_time=None)