text:
export DEST_TYPE="maprdb"

# Dealing with bad data
# Set to 1 to remove fields, starting left to right in the variable REMOVE_FIELDS to see if the json parsing works
export REMOVE_FIELDS_ON_FAIL=1

# If REMOVE_FIELDS_ON_FAIL is set to 1, and there is an error, the parser will remove the data from fields left to right, once json conversion works, it will break and move on (so not all fields may be removed)
export REMOVE_FIELDS="key1,key2"

# Turn on verbose logging.  For Silence export DEBUG=0
export DEBUG=1

# Kafka or MapR Stream config
# You must provide Bootstrap servers (kafka nodes and their ports OR Zookeepers and the kafka ID of the chroot for your kafka instance
#
# If using mapr streams comment out ZOOKEEPERS, and instead provide BOOTSTRAP_BROKERS="mapr" and the specify the topic in the MapR Format: i.e. TOPIC="/path/to/maprstreams:topicname"
# You must provide Bootstrap servers (kafka nodes and their ports OR Zookeepers and the kafka ID of the chroot for your kafka instance
#export ZOOKEEPERS=""
#export KAFKA_ID=""
# OR
export BOOTSTRAP_BROKERS="mapr"

# This is the name of the consumer group your client will create/join. If you are running multiple instances this is great, name them the same and Kafka will partition the info
export GROUP_ID="some_groupid"

# When registering a consumer group, do you want to start at the first data in the queue (earliest) or the last (latest)
export OFFSET_RESET="earliest"

# The Topic to connect to
# the path to data is the HDFS path, not the mapr posix path. (i.e. not /mapr/cluster/path/to, just /path/to)
export TOPIC="/path/to/data/in/hdfs:topicname"

# This is the loop timeout, so that when this time is reached, it will cause the loop to occur (checking for older files etc)
export LOOP_TIMEOUT="5.0"

# The next three items has to do with the cacheing of records. As this come off the kafka queue, we store them in a list to keep from making smallish writes and dataframes
# These are very small/conservative, you should be able to increase, but we need to do testing at volume

export ROWMAX=2000 # Total max records cached. Regardless of size, once the number of records hits this number, the next record will cause a flush and write to parquet
export SIZEMAX=128000000  # Total size of records. This is a rough running size of records in bytes. Once the total hits this size, the next record will cause a flush and write to parquet
export TIMEMAX=10  # seconds since last write to force a write # The number of seconds since the last flush. Once this has been met, the next record from KAfka will cause a flush and write.

#### MapR DB items
# This is where you want to write the maprdb table. This the HDFS (maprfs) path, not the posix path
#export MAPRDB_TABLE_BASE="/path/to/mytable"

# Note another option is to use RANDOMROWKEYVAL to put a random number in the row key
# This is the field(s)  in your json you want to use as the hbase/maprdb row key If you want to concat fields, seperate by a comma and ensure your printed delim is correct
#export MAPRDB_ROW_KEY_FIELDS='key1,key2,RANDOMROWKEYVAL'

# This is the character, if you specified your fields as CSV above, that when we concat the fields, we put between them.  so if you have ip,ts as your row_key_fields, and use _ as your delim it may look like 123.123.123.123_2015-12-12 as your key
#export MAPRDB_ROW_KEY_DELIM="_"

# For the columns in your data, which fields will be in which column families.
# Format: cf1:field1,cf1:field2,cf2:field3,cf4:field4
#export MAPRDB_FAMILY_MAPPING='cf1:field1,cf1:field2,cf2:field3,cf4:field4"

# If the table does not exist, if this is set to 1, it will create it based on the column families. Otherwise it will exit (if not set to 1) - This could get ugly we don't set region size or permissions
#export MAPRDB_CREATE_TABLE=0
# If batch inserts are enabled, set to 1
#export MAPRDB_BATCH_ENABLED=1
# Print a drill view and exit
#export MAPRDB_PRINT_DRILL_VIEW=0

#### For type JSON and PARQ there are file options that are common.

# The base directory for the table (Posix only at this time, for MapR /mapr/cluster/path/to/data)
#export FILE_TABLE_BASE="/mapr/mycluster/data/mydata/mytable"
# Files of this size will cause the current file to be closed, and new one started
#export FILE_MAXSIZE="128000000"
# This is the value to use as a uniq identifier so when you have multiple writes writing to the same partition, they each get their own file. HOSTNAME in docker containers works well for this
#export FILE_UNIQ_ENV="HOSTNAME"
# The field in the src data that will be used for partitions
#export FILE_PARTITION_FIELD="day"
# If a partition has not been written to in this many seconds, close the file and move to the live data (so it can be queried)
#export FILE_PARTMAXAGE="30"
# If the partition field can not be found, use this instead
#export FILE_UNKNOWNPART="unknown"
# The diretory used for tmp files (in not write live setups, .something works because tools like drill don't query directory starting with .)
#export FILE_TMP_PART_DIR=".tmp"
# Should we write directly to the live directory? Usually not, this causes things querying the data to freak out.
#export FILE_WRITE_LIVE="0"

#### Json Specific Item
#export JSON_GZ_COMPRESS="1"

#### Parquet specific items
# Size to use for Parquet Offers
#export PARQ_OFFSETS="50000000"
# Commpression to use for Parquet Files
#export PARQ_COMPRESS="SNAPPY"
# Does the data have nulls in (Fast Parquet wants to know)
#export PARQ_HAS_NULLS="1"
# Do you want us to merge files, i.e. take a file that has lots of row groups read it all in and write it all out to reduce the row groups in the file?
#export PARQ_MERGE_FILE="1"

##################################
# The derived section allows us to create a field on the fly from a slice of a different field.
# for example, if you had a source field named ts of 2017-08-08T21:26:10.843768Z you could create a derived field of ts_day of 2017-08-08 by setting src to ts, dst to ts_day, start to 0 and end to 10
# If you want the script to fail if this conversion fails, then set req to 1
# Note, if you set DERIVED_SRC="" (or don't set it) nothing happens

#export DERIVED_SRC=""      # The field to src
#export DERIVED_DST=""      # The Field to place the derived value
#export DERIVED_START="0"   # The position to start things on
#export DERIVED_END="0"     # The End position, if you put 0 for this, it assumes the end of the string.. (essentially 0 is like doing a sliced of val[0:]
#export DERIVED_REQ="0"     # if this is 1 the script will exit if things go bonkers"

# Run Py ETL!
if [ "$DEST_TYPE" == "maprdb" ]; then
    # Mapr DB requires Python 2
    python -u /app/code/pyetl.py
else
    python3 -u /app/code/pyetl.py
fi


text:
package com.gilt.pickling.avroschema

import org.scalatest.{Assertions, FunSuite}
import com.gilt.pickling.TestObjs._
import scala.pickling._
import com.gilt.pickling.TestUtils._

class ArrayOfPrimitivesTest extends FunSuite with Assertions {

  test("Generate schema from a case class with an array of int field") {
    assert(fingerPrint("/avro/array/ArrayOfInts.avsc") === fingerPrint(Schema(ArrayOfInts(Array(123)))))
    assert(fingerPrint("/avro/array/ArrayOfInts.avsc") === fingerPrint(Schema(classOf[ArrayOfInts])))
    assert(fingerPrint("/avro/array/ArrayOfInts.avsc") === fingerPrint(Schema[ArrayOfInts]))
  }

  test("Generate schema from a case class with an array of long field") {
    assert(fingerPrint("/avro/array/ArrayOfLongs.avsc") === fingerPrint(Schema(ArrayOfLongs(Array(123L)))))
    assert(fingerPrint("/avro/array/ArrayOfLongs.avsc") === fingerPrint(Schema(classOf[ArrayOfLongs])))
    assert(fingerPrint("/avro/array/ArrayOfLongs.avsc") === fingerPrint(Schema[ArrayOfLongs]))
  }

  test("Generate schema from a case class with an array of double field") {
    assert(fingerPrint("/avro/array/ArrayOfDoubles.avsc") === fingerPrint(Schema(ArrayOfDoubles(Array(123D)))))
    assert(fingerPrint("/avro/array/ArrayOfDoubles.avsc") === fingerPrint(Schema(classOf[ArrayOfDoubles])))
    assert(fingerPrint("/avro/array/ArrayOfDoubles.avsc") === fingerPrint(Schema[ArrayOfDoubles]))
  }

  test("Generate schema from a case class with an array of float field") {
    assert(fingerPrint("/avro/array/ArrayOfFloats.avsc") === fingerPrint(Schema(ArrayOfFloats(Array(123F)))))
    assert(fingerPrint("/avro/array/ArrayOfFloats.avsc") === fingerPrint(Schema(classOf[ArrayOfFloats])))
    assert(fingerPrint("/avro/array/ArrayOfFloats.avsc") === fingerPrint(Schema[ArrayOfFloats]))
  }

  test("Generate schema from a case class with an array of boolean field") {
    assert(fingerPrint("/avro/array/ArrayOfBooleans.avsc") === fingerPrint(Schema(ArrayOfBooleans(Array(false, true)))))
    assert(fingerPrint("/avro/array/ArrayOfBooleans.avsc") === fingerPrint(Schema(classOf[ArrayOfBooleans])))
    assert(fingerPrint("/avro/array/ArrayOfBooleans.avsc") === fingerPrint(Schema[ArrayOfBooleans]))
  }

  test("Generate schema from a case class with an array of string field") {
    assert(fingerPrint("/avro/array/ArrayOfStrings.avsc") === fingerPrint(Schema(ArrayOfStrings(Array("abc")))))
    assert(fingerPrint("/avro/array/ArrayOfStrings.avsc") === fingerPrint(Schema(classOf[ArrayOfStrings])))
    assert(fingerPrint("/avro/array/ArrayOfStrings.avsc") === fingerPrint(Schema[ArrayOfStrings]))
  }

  test("Generate schema from a case class with an array of char field") {
    assert(fingerPrint("/avro/array/ArrayOfChars.avsc") === fingerPrint(Schema(ArrayOfChars(Array('a')))))
    assert(fingerPrint("/avro/array/ArrayOfChars.avsc") === fingerPrint(Schema(classOf[ArrayOfChars])))
    assert(fingerPrint("/avro/array/ArrayOfChars.avsc") === fingerPrint(Schema[ArrayOfChars]))
  }

  test("Generate schema from a case class with an array of byte field") {
    assert(fingerPrint("/avro/array/ArrayOfBytes.avsc") === fingerPrint(Schema(ArrayOfBytes(Array(1.toByte)))))
    assert(fingerPrint("/avro/array/ArrayOfBytes.avsc") === fingerPrint(Schema(classOf[ArrayOfBytes])))
    assert(fingerPrint("/avro/array/ArrayOfBytes.avsc") === fingerPrint(Schema[ArrayOfBytes]))
  }

  test("Generate schema from a case class with an array of short field") {
    assert(fingerPrint("/avro/array/ArrayOfShorts.avsc") === fingerPrint(Schema(ArrayOfShorts(Array(1.toShort)))))
    assert(fingerPrint("/avro/array/ArrayOfShorts.avsc") === fingerPrint(Schema(classOf[ArrayOfShorts])))
    assert(fingerPrint("/avro/array/ArrayOfShorts.avsc") === fingerPrint(Schema[ArrayOfShorts]))
  }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.red5.io.utils (Red5 :: IO 1.0.7-SNAPSHOT API)</title>
<meta name="date" content="2016-02-18">
<link rel="stylesheet" type="text/css" href="../../../../javadoc.css" title="Style">

org.red5.io.utils

Classes

ArrayUtils

BufferUtils

ConversionUtils

DOM2Writer

HexCharset

HexDump

IOUtils

ObjectMap

RandomGUID

Stax2DomBuilder

XMLUtils


text:
package zipkin2.elasticsearch;

import com.linecorp.armeria.client.WebClient;
import com.linecorp.armeria.common.AggregatedHttpRequest;
import com.linecorp.armeria.common.AggregatedHttpResponse;
import com.linecorp.armeria.common.HttpData;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.MediaType;
import com.linecorp.armeria.common.ResponseHeaders;
import com.linecorp.armeria.testing.junit5.server.mock.MockWebServerExtension;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import zipkin2.TestObjects;
import zipkin2.storage.QueryRequest;

import static org.assertj.core.api.Assertions.assertThat;
import static zipkin2.TestObjects.DAY;
import static zipkin2.TestObjects.TODAY;
import static zipkin2.elasticsearch.VersionSpecificTemplates.TYPE_SPAN;

class ElasticsearchSpanStoreTest {
  static final AggregatedHttpResponse EMPTY_RESPONSE =
    AggregatedHttpResponse.of(ResponseHeaders.of(HttpStatus.OK), HttpData.empty());

  @RegisterExtension static MockWebServerExtension server = new MockWebServerExtension();

  @BeforeEach void setUp() {
    storage = ElasticsearchStorage.newBuilder(() -> WebClient.of(server.httpUri())).build();
    spanStore = new ElasticsearchSpanStore(storage);
  }

  @AfterEach void tearDown() throws IOException {
    storage.close();
  }

  ElasticsearchStorage storage;
  ElasticsearchSpanStore spanStore;

  @Test void doesntTruncateTraceIdByDefault() throws Exception {
    server.enqueue(EMPTY_RESPONSE);
    spanStore.getTrace("48fec942f3e78b893041d36dc43227fd").execute();

    assertThat(server.takeRequest().request().contentUtf8())
      .contains("\"traceId\":\"48fec942f3e78b893041d36dc43227fd\"");
  }

  @Test void truncatesTraceIdTo16CharsWhenNotStrict() throws Exception {
    storage.close();
    storage = storage.toBuilder().strictTraceId(false).build();
    spanStore = new ElasticsearchSpanStore(storage);

    server.enqueue(EMPTY_RESPONSE);
    spanStore.getTrace("48fec942f3e78b893041d36dc43227fd").execute();

    assertThat(server.takeRequest().request().contentUtf8())
      .contains("\"traceId\":\"3041d36dc43227fd\"");
  }

  @Test void serviceNames_defaultsTo24HrsAgo_6x() throws Exception {
    server.enqueue(AggregatedHttpResponse.of(
      HttpStatus.OK, MediaType.JSON_UTF_8, TestResponses.SERVICE_NAMES));
    spanStore.getServiceNames().execute();

    requestLimitedTo2DaysOfIndices_singleTypeIndex();
  }

  @Test void spanNames_defaultsTo24HrsAgo_6x() throws Exception {
    server.enqueue(AggregatedHttpResponse.of(
      HttpStatus.OK, MediaType.JSON_UTF_8, TestResponses.SPAN_NAMES));
    spanStore.getSpanNames("foo").execute();

    requestLimitedTo2DaysOfIndices_singleTypeIndex();
  }

  @Test void searchDisabled_doesntMakeRemoteQueryRequests() throws Exception {
    storage.close();
    storage = ElasticsearchStorage.newBuilder(() -> WebClient.of(server.httpUri()))
      .searchEnabled(false)
      .build();

    // skip template check
    ElasticsearchSpanStore spanStore = new ElasticsearchSpanStore(storage);

    QueryRequest request = QueryRequest.newBuilder().endTs(TODAY).lookback(DAY).limit(10).build();
    assertThat(spanStore.getTraces(request).execute()).isEmpty();
    assertThat(spanStore.getServiceNames().execute()).isEmpty();
    assertThat(spanStore.getSpanNames("icecream").execute()).isEmpty();

    assertThat(server.takeRequest(100, TimeUnit.MILLISECONDS)).isNull();
  }

  void requestLimitedTo2DaysOfIndices_singleTypeIndex() {
    long today = TestObjects.midnightUTC(System.currentTimeMillis());
    long yesterday = today - TimeUnit.DAYS.toMillis(1);

    // 24 hrs ago always will fall into 2 days (ex. if it is 4:00pm, 24hrs ago is a different day)
    String indexesToSearch = ""
      + storage.indexNameFormatter().formatTypeAndTimestamp(TYPE_SPAN, yesterday)
      + ","
      + storage.indexNameFormatter().formatTypeAndTimestamp(TYPE_SPAN, today);

    AggregatedHttpRequest request = server.takeRequest().request();
    assertThat(request.path()).startsWith("/" + indexesToSearch + "/_search");
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Agaricus salmonicolor Berk. & Broome

### Remarks
null


text:
package com.squareup.otto;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Helper methods for finding methods annotated with {@link Produce} and {@link Subscribe}.
 *
 * @author Cliff Biffle
 * @author Louis Wasserman
 * @author Jake Wharton
 */
final class AnnotatedHandlerFinder {

    /**
     * Cache event bus producer methods for each class.
     */
    private static final ConcurrentMap<Class<?>, Map<String, Method>> PRODUCERS_CACHE =
            new ConcurrentHashMap<>();

    /**
     * Cache event bus subscriber methods for each class.
     */
    private static final ConcurrentMap<Class<?>, Map<String, Set<Method>>> SUBSCRIBERS_CACHE =
            new ConcurrentHashMap<>();

    private static void loadAnnotatedProducerMethods(Class<?> listenerClass,
                                                     Map<String, Method> producerMethods) {
        Map<String, Set<Method>> subscriberMethods = new HashMap<>();
        loadAnnotatedMethods(listenerClass, producerMethods, subscriberMethods);
    }

    private static void loadAnnotatedSubscriberMethods(Class<?> listenerClass,
                                                       Map<String, Set<Method>> subscriberMethods) {
        Map<String, Method> producerMethods = new HashMap<>();
        loadAnnotatedMethods(listenerClass, producerMethods, subscriberMethods);
    }

    /**
     * Load all methods annotated with {@link Produce} or {@link Subscribe} into their respective caches for the
     * specified class.
     */
    private static void loadAnnotatedMethods(Class<?> listenerClass, Map<String, Method> producerMethods, Map<String, Set<Method>> subscriberMethods) {
        Class<?> clazz = listenerClass;

        do {
            for (Method method : clazz.getDeclaredMethods())
            {
              // The compiler sometimes creates synthetic bridge methods as part of the
              // type erasure process. As of JDK8 these methods now include the same
              // annotations as the original declarations. They should be ignored for
              // subscribe/produce.
              if (method.isBridge())
              {
                continue;
              }
              if (method.isAnnotationPresent(Subscribe.class))
              {
                Class<?>[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length != 1)
                {
                  throw new IllegalArgumentException("Method " + method + " has @Subscribe annotation but requires "
                          + parameterTypes.length + " arguments.  Methods must require a single argument.");
                }

                Class<?> eventType = parameterTypes[0];
//                if (eventType.isInterface())
//                {
//                  throw new IllegalArgumentException("Method " + method + " has @Subscribe annotation on " + eventType
//                          + " which is an interface.  Subscription must be on a concrete class type.");
//                }

                if ((method.getModifiers() & Modifier.PUBLIC) == 0)
                {
                  throw new IllegalArgumentException("Method " + method + " has @Subscribe annotation on " + eventType
                          + " but is not 'public'.");
                }

                Subscribe annotation = method.getAnnotation(Subscribe.class);
                String keyName = annotation.event();
                if ("".equals(keyName))
                {
                  keyName = eventType.getName();
                }

                Set<Method> methods = subscriberMethods.get(keyName);
                if (methods == null)
                {
                  methods = new HashSet<Method>();
                  subscriberMethods.put(keyName, methods);
                }
                methods.add(method);
              }
              else if (method.isAnnotationPresent(Produce.class))
              {
                Class<?>[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length != 0)
                {
                  throw new IllegalArgumentException("Method " + method + "has @Produce annotation but requires "
                          + parameterTypes.length + " arguments.  Methods must require zero arguments.");
                }
                if (method.getReturnType() == Void.class)
                {
                  throw new IllegalArgumentException("Method " + method
                          + " has a return type of void.  Must declare a non-void type.");
                }

                Class<?> eventType = method.getReturnType();
                if (eventType.isInterface())
                {
                  throw new IllegalArgumentException("Method " + method + " has @Produce annotation on " + eventType
                          + " which is an interface.  Producers must return a concrete class type.");
                }
                if (eventType.equals(Void.TYPE))
                {
                  throw new IllegalArgumentException("Method " + method + " has @Produce annotation but has no return type.");
                }

                Produce annotation = method.getAnnotation(Produce.class);
                String keyName = annotation.event();
                if ("".equals(keyName))
                {
                  keyName = eventType.getName();
                }

                if (producerMethods.containsKey(keyName))
                {
                  throw new IllegalArgumentException("Producer for type " + eventType + " has already been registered.");
                }

                producerMethods.put(keyName, method);
              }
            }

            PRODUCERS_CACHE.put(listenerClass, producerMethods);
            SUBSCRIBERS_CACHE.put(listenerClass, subscriberMethods);
            if (clazz.isAnnotationPresent(InheritSubscribers.class)) {
                clazz = clazz.getSuperclass();
            } else {
                clazz = null;
            }
        } while (clazz != null);
    }

    /**
     * This implementation finds all methods marked with a {@link Produce} annotation.
     */
    static Map<String, EventProducer> findAllProducers(Object listener) {
        final Class<?> listenerClass = listener.getClass();
        Map<String, EventProducer> handlersInMethod = new HashMap<>();

        Map<String, Method> methods = PRODUCERS_CACHE.get(listenerClass);
        if (null == methods) {
            methods = new HashMap<>();
            loadAnnotatedProducerMethods(listenerClass, methods);
        }
        if (!methods.isEmpty()) {
            for (Map.Entry<String, Method> e : methods.entrySet()) {
                EventProducer producer = new EventProducer(listener, e.getValue());
                handlersInMethod.put(e.getKey(), producer);
            }
        }

        return handlersInMethod;
    }

    /**
     * This implementation finds all methods marked with a {@link Subscribe} annotation.
     */
    static Map<String, Set<EventHandler>> findAllSubscribers(Object listener) {
        Class<?> listenerClass = listener.getClass();
        Map<String, Set<EventHandler>> handlersInMethod = new HashMap<>();

        Map<String, Set<Method>> methods = SUBSCRIBERS_CACHE.get(listenerClass);
        if (null == methods) {
            methods = new HashMap<>();
            loadAnnotatedSubscriberMethods(listenerClass, methods);
        }
        if (!methods.isEmpty()) {
            for (Map.Entry<String, Set<Method>> e : methods.entrySet()) {
                Set<EventHandler> handlers = new HashSet<EventHandler>();
                for (Method m : e.getValue()) {
                    handlers.add(new EventHandler(listener, m));
                }
                handlersInMethod.put(e.getKey(), handlers);
            }
        }

        return handlersInMethod;
    }

    private AnnotatedHandlerFinder() {
        // No instances.
    }

}


text: import './app/user-greeting.component.spec';


text:
package operations

import (
	"github.com/qiniu/qshell/v2/iqshell"
	"github.com/qiniu/qshell/v2/iqshell/common/account"
	"github.com/qiniu/qshell/v2/iqshell/common/data"
	"github.com/qiniu/qshell/v2/iqshell/common/log"
	"os"
)

// ChangeInfo 切换账户
type ChangeInfo struct {
	Name string
}

func (info *ChangeInfo) Check() *data.CodeError {
	return nil
}

func Change(cfg *iqshell.Config, info ChangeInfo) {
	if shouldContinue := iqshell.CheckAndLoad(cfg, iqshell.CheckAndLoadInfo{
		Checker: &info,
	}); !shouldContinue {
		return
	}

	err := account.ChUser(info.Name)
	if err != nil {
		log.ErrorF("user change error:%v", err)
		os.Exit(data.StatusError)
		return
	}
}


text:
package org.cloudfoundry.client.v2.spaces;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;

/**
 * The response payload for the Remove Developer with the Space by Username operation
 */
@JsonDeserialize
@Value.Immutable
abstract class _RemoveSpaceDeveloperByUsernameResponse extends AbstractSpaceResource {

}


text:
using UnityEngine;
using System.Collections;

public class NonDestroyableBrick : Brick {

	public NonDestroyableBrick() {
		typeBrick = TypeBrick.NONE;
		objectBrick = ObjectBrick.NONE;
		currentHits = 0;
		neededHits = -1;
	}

	public override void addHits() {
	}
}


text:
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Users;
using osuTK;

namespace osu.Game.Tests.Visual
{
    [TestFixture]
    public class TestCaseUserPanel : OsuTestCase
    {
        public TestCaseUserPanel()
        {
            UserPanel flyte;
            UserPanel peppy;
            Add(new FillFlowContainer
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                AutoSizeAxes = Axes.Both,
                Spacing = new Vector2(10f),
                Children = new[]
                {
                    flyte = new UserPanel(new User
                    {
                        Username = @"flyte",
                        Id = 3103765,
                        Country = new Country { FlagName = @"JP" },
                        CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c6.jpg"
                    }) { Width = 300 },
                    peppy = new UserPanel(new User
                    {
                        Username = @"peppy",
                        Id = 2,
                        Country = new Country { FlagName = @"AU" },
                        CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
                        IsSupporter = true,
                    }) { Width = 300 },
                },
            });

            flyte.Status.Value = new UserStatusOnline();
            peppy.Status.Value = new UserStatusSoloGame();

            AddStep(@"spectating", () => { flyte.Status.Value = new UserStatusSpectating(); });
            AddStep(@"multiplaying", () => { flyte.Status.Value = new UserStatusMultiplayerGame(); });
            AddStep(@"modding", () => { flyte.Status.Value = new UserStatusModding(); });
            AddStep(@"offline", () => { flyte.Status.Value = new UserStatusOffline(); });
            AddStep(@"null status", () => { flyte.Status.Value = null; });
        }
    }
}


text:
namespace Problem_3.Company_Hierarchy.Company.Employees
{
    using System;
    using Interfaces;

    public abstract class Employee : Person, IEmployee
    {
        // FIELDS
        private decimal salary;
        private string department;

        // CONSTRUCTOR
        protected Employee(string firstName, string lastName, long id, decimal salary, string department)
            : base(firstName, lastName, id)
        {
            this.Salary = salary;
            this.Department = department;
        }

        // SALARY
        public decimal Salary
        {
            get { return this.salary; }
            set
            {
                if (value < 0)
                {
                    throw new ArgumentException("Salary", "cannot be negative value.");
                }
                this.salary = value;
            }
        }

        // DEPARTAMENT
        public string Department
        {
            get { return this.department; }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    throw new ArgumentNullException("Department", "cannot be NULL or Whitespace.");
                }

                if (value != "Production" && value != "Accounting"
                    && value != "Sales" && value != "Marketing")
                {
                    Console.Error.WriteLine("Allowed departments: Production, Accounting, Sales, Marketing.");
                    throw new ArgumentException("Unknown department.");
                }
                this.department = value;
            }
        }

        public override string ToString()
        {
            string employeeInfo = String.Format("Salary: {0}, Departament: {1}",
                this.salary, this.department);

            return base.ToString() + "\r\n" + employeeInfo;
        }
    }
}


text:
export enum VolumeChunkEncoding {
  RAW,
  GZIP,
}

export class VolumeChunkSourceParameters {
  url: string;
  encoding: VolumeChunkEncoding;

  static RPC_ID = 'n5/VolumeChunkSource';
}


text:
<?php

namespace n3b\Bundle\Util\HttpFoundation\StreamResponse;

use Symfony\Component\HttpFoundation\Response;

/**
 * Description of StreamResponse
 *
 * @author neb
 */
class StreamResponse extends Response
{
    public function sendContent()
    {
        $this->writer->write();
    }

    public function setWriter(StreamWriterInterface $obj)
    {
        $this->writer = $obj;
    }

    public function setContent($content)
    {
        $this->setWriter($content);
    }
}


text:
<?php

namespace Area4\Bundle\NewsBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class NewsType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title','text',array('label'=>'Titulo'))
            ->add('content','textarea',array('label'=>'Contenido'))
            //->add('created_at')
            //->add('updated_at')
            ->add('image','file',array('label'=>'Imagen principal'))
            //->add('tags',null,array('label'=>'Etiquetas'))
            ->add('category','entity',array('label'=>'Categoria','class'=>'Area4NewsBundle:Category'))
            ->add('published','checkbox',array('label'=>'Publicado'))
            //->add('published_by')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Area4\Bundle\NewsBundle\Entity\News'
        ));
    }

    public function getName()
    {
        return 'area4_bundle_newsbundle_newstype';
    }
}


text:
UPGRADE
=======

## Upgrade FROM v1.0.0-beta2 to v1.0.0-beta3

The Doctrine ORM configuring and related services are moved to a new package
at https://github.com/rollerworks/rollerworks-search-doctrine-orm-bundle.

If you are using Doctrine ORM then install the new package and update you're
application configuration as follow.

Before:

```yaml
# app/config/config.yml
rollerworks_search:
    doctrine:
        orm:
            cache_driver: rollerworks_cache.driver.session_driver
```

After:

```yaml
# app/config/config.yml
rollerworks_search_doctrine_orm:
    cache_driver: rollerworks_search.doctrine_orm.cache.array_driver
```

The original service names (except `rollerworks_cache.driver.session_driver`)
are left unchanged.


text:
@description Retrieve multiple resources from a server.
@function can.Model.findAll findAll
@parent can.Model.static

@signature `can.Model.findAll( params[, success[, error]] )`

Retrieve multiple resources from a server.

@param {Object} params Values to filter the request or results with.
@param {function(can.Model.List)} [success(list)] A callback to call on successful retrieval. The callback recieves
a can.Model.List of the retrieved resources.
@param {function(can.AjaxSettings)} [error(xhr)] A callback to call when an error occurs. The callback receives the
XmlHttpRequest object.
@return {can.Deferred} A deferred that resolves to a [can.Model.List] of retrieved models.

@signature `can.Model.findAll: findAllData( params ) -> deferred`

Implements `findAll` with a [can.Model.findAllData function]. This function
is passed to [can.Model.makeFindAll makeFindAll] to create the external
`findAll` method.

```
findAll: function(params){
 return $.get("/tasks",params)
}
```

@param {can.Model.findAllData} findAllData A function that accepts parameters
specifying a list of instance data to retrieve and returns a [can.Deferred]
that resolves to an array of those instances.

@signature `can.Model.findAll: "[METHOD] /path/to/resource"`

Implements `findAll` with a HTTP method and url to retrieve instance data.

   findAll: "GET /tasks"

If `findAll` is implemented with a string, this gets converted to
a [can.Model.findAllData findAllData function]
which is passed to [can.Model.makeFindAll makeFindAll] to create the external
`findAll` method.

@param {HttpMethod} METHOD An HTTP method. Defaults to `"GET"`.

@param {STRING} url The URL of the service to retrieve JSON data.

@return {JSON} The service should return a JSON object like:

```
{
 "data": [
   { "id" : 1, "name" : "do the dishes" },
   { "id" : 2, "name" : "mow the lawn" },
   { "id" : 3, "name" : "iron my shirts" }
 ]
}
```

This object is passed to [can.Model.models] to turn it into instances.

_Note: .findAll can also accept an array, but you
probably [should not be doing that](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)._

@signature `can.Model.findAll: {ajaxSettings}`

Implements `findAll` with a [can.AjaxSettings ajax settings object].

```
findAll: {url: "/tasks", dataType: "json"}
```

If `findAll` is implemented with an object, it gets converted to
a [can.Model.findAllData findAllData function]
which is passed to [can.Model.makeFindAll makeFindAll] to create the external
`findAll` method.

@param {can.AjaxSettings} ajaxSettings A settings object that
specifies the options available to pass to [can.ajax].

@body

## Use

`findAll( params, success(instances), error(xhr) ) -> Deferred` is used to retrieve model
instances from the server. After implementing `findAll`, use it to retrieve instances of the model
like:

```
Recipe.findAll({favorite: true}, function(recipes){
 recipes[0].attr('name') //-> "Ice Water"
}, function( xhr ){
 // called if an error
}) //-> Deferred
```

`findAll` uses [can.Model.parseModels parseModels] to parse the returned data. `can.Model.parseModels`
can be overwritten to handle non-standard data formats.

Before you can use `findAll`, you must implement it.

## Implement with a URL

Implement findAll with a url like:

```
Recipe = can.Model.extend({
 findAll : "/recipes.json"
},{});
```

The server should return data that looks like:

```
[
 {"id" : 57, "name": "Ice Water"},
 {"id" : 58, "name": "Toast"}
]
```

## Implement with an Object

Implement findAll with an object that specifies the parameters to
`can.ajax` (jQuery.ajax) like:

```
Recipe = can.Model.extend({
 findAll : {
   url: "/recipes.xml",
   dataType: "xml"
 }
},{});
```

## Implement with a Function

To implement with a function, `findAll` is passed __params__ to filter
the instances retrieved from the server and it should return a
deferred that resolves to an array of model data. For example:

```
Recipe = can.Model.extend({
 findAll : function(params){
   return $.ajax({
     url: '/recipes.json',
     type: 'get',
     dataType: 'json'})
 }
},{});
```


text:
/*!
 * \file tvm/relay/pattern_functor.h
 * \brief A more powerful visitor on ADT patterns that enables defining
 * arbitrary function signatures with type-based dispatch on first argument.
 */
#ifndef TVM_RELAY_PATTERN_FUNCTOR_H_
#define TVM_RELAY_PATTERN_FUNCTOR_H_

#include <tvm/node/ir_functor.h>
#include <string>
#include <utility>
#include <unordered_map>
#include "./expr.h"
#include "./op.h"
#include "./error.h"
#include "./adt.h"

namespace tvm {
namespace relay {

/*!
 * \brief A dynamical functor on ADT patterns that dispatches on its first argument.
 *  You can use this as a more powerful visitor, since it allows you to
 *  define the types of further arguments to VisitPattern.
 *
 * \sa tvm/ir_functor.h
 *
 * \tparam FType function signiture
 *  This type is only defined for FType with function signature R(const Pattern&,
 * Args...)
 */
template <typename FType>
class PatternFunctor;

// functions to be overriden.
#define PATTERN_FUNCTOR_DEFAULT                                      \
  { return VisitPatternDefault_(op, std::forward<Args>(args)...); }

#define RELAY_PATTERN_FUNCTOR_DISPATCH(OP)                                \
  vtable.template set_dispatch<OP>(                                       \
      [](const NodeRef& n, TSelf* self, Args... args) {                   \
        return self->VisitPattern_(static_cast<const OP*>(n.node_.get()), \
                                   std::forward<Args>(args)...);          \
      });

template <typename R, typename... Args>
class PatternFunctor<R(const Pattern& n, Args...)> {
 private:
  using TSelf = PatternFunctor<R(const Pattern& n, Args...)>;
  using FType = tvm::IRFunctor<R(const NodeRef& n, TSelf* self, Args...)>;

 public:
  /*! \brief the result type of this functor */
  using result_type = R;
  /*! \brief virtual destructor */
  virtual ~PatternFunctor() {}
  /*!
   * \brief Same as call.
   * \param n The expression node.
   * \param args Additional arguments.
   * \return The result of the call
   */
  R operator()(const Pattern& n, Args... args) {
    return VisitPattern(n, std::forward<Args>(args)...);
  }
  /*!
   * \brief The functor call.
   * \param n The expression node.
   * \param args Additional arguments.
   * \return The result of the call
   */
  virtual R VisitPattern(const Pattern& n, Args... args) {
    CHECK(n.defined());
    static FType vtable = InitVTable();
    return vtable(n, this, std::forward<Args>(args)...);
  }
  // Functions that can be overriden by subclass
  virtual R VisitPattern_(const PatternWildcardNode* op,
                          Args... args) PATTERN_FUNCTOR_DEFAULT;
  virtual R VisitPattern_(const PatternVarNode* op,
                          Args... args) PATTERN_FUNCTOR_DEFAULT;
  virtual R VisitPattern_(const PatternConstructorNode* op,
                          Args... args) PATTERN_FUNCTOR_DEFAULT;
  virtual R VisitPattern_(const PatternTupleNode* op,
                          Args... args) PATTERN_FUNCTOR_DEFAULT;
  virtual R VisitPatternDefault_(const Node* op, Args...) {
    throw Error(std::string("Do not have a default for ") + op->type_key());
  }

 private:
  // initialize the vtable.
  static FType InitVTable() {
    FType vtable;
    // Set dispatch
    RELAY_PATTERN_FUNCTOR_DISPATCH(PatternWildcardNode);
    RELAY_PATTERN_FUNCTOR_DISPATCH(PatternVarNode);
    RELAY_PATTERN_FUNCTOR_DISPATCH(PatternConstructorNode);
    RELAY_PATTERN_FUNCTOR_DISPATCH(PatternTupleNode);
    return vtable;
  }
};

/*! \brief A simple visitor wrapper around PatternFunctor.
 *
 * Exposes two visitors with default traversal strategies, one
 * which doesn't compute a result but can mutate internal state,
 * and another which functionally builds a new pattern.
 */
class PatternVisitor : public ::tvm::relay::PatternFunctor<void(const Pattern& n)> {
 public:
  void VisitPattern_(const PatternWildcardNode* op) override;
  void VisitPattern_(const PatternVarNode* op) override;
  void VisitPattern_(const PatternConstructorNode* op) override;
  void VisitPattern_(const PatternTupleNode* op) override;
  virtual void VisitType(const Type& t);
  virtual void VisitVar(const Var& v);
  virtual void VisitConstructor(const Constructor& c);
};

/*! \brief A wrapper around ExprFunctor which functionally updates the AST.
 *
 * ExprMutator uses memoization and self return in order to amortize
 * the cost of using functional updates.
 */
class PatternMutator
    : public ::tvm::relay::PatternFunctor<Pattern(const Pattern&)> {
 public:
  Pattern Mutate(const Pattern& pat);
  Pattern VisitPattern_(const PatternWildcardNode* op) override;
  Pattern VisitPattern_(const PatternVarNode* op) override;
  Pattern VisitPattern_(const PatternConstructorNode* op) override;
  Pattern VisitPattern_(const PatternTupleNode* op) override;
  /*! \brief Used to visit the types inside of patterns.
   *
   * Can be overloaded to transform the types in arbitrary
   * ways, one way would be to define a sub-class of type
   * visitor for types which transform them appropriately.
   */
  virtual Type VisitType(const Type& t);
  /*! \brief Used to visit the vars inside of patterns. */
  virtual Var VisitVar(const Var& v);
  /*! \brief Used to visit the vars inside of patterns. */
  virtual Constructor VisitConstructor(const Constructor& c);
 private:
  std::unordered_map<Var, Var, NodeHash, NodeEqual> var_map_;
};

}  // namespace relay
}  // namespace tvm
#endif  // TVM_RELAY_PATTERN_FUNCTOR_H_


text:
#import "UIView.h"

#import "CAMFlashButtonDelegate-Protocol.h"

@class CAMElapsedTimeView, CAMFlashButton, CAMFlipButton, CAMHDRButton;

@interface CAMTopBar : UIView <CAMFlashButtonDelegate>
{
    _Bool __flashButtonExpanded;
    long long _style;
    long long _backgroundStyle;
    CAMFlashButton *_flashButton;
    CAMElapsedTimeView *_elapsedTimeView;
    CAMHDRButton *_HDRButton;
    CAMFlipButton *_flipButton;
    long long _orientation;
    UIView *__backgroundView;
}

@property(nonatomic, getter=_isFlashButtonExpanded, setter=_setFlashButtonExpanded:) _Bool _flashButtonExpanded; // @synthesize _flashButtonExpanded=__flashButtonExpanded;
@property(readonly, nonatomic) UIView *_backgroundView; // @synthesize _backgroundView=__backgroundView;
@property(nonatomic) long long orientation; // @synthesize orientation=_orientation;
@property(retain, nonatomic) CAMFlipButton *flipButton; // @synthesize flipButton=_flipButton;
@property(retain, nonatomic) CAMHDRButton *HDRButton; // @synthesize HDRButton=_HDRButton;
@property(retain, nonatomic) CAMElapsedTimeView *elapsedTimeView; // @synthesize elapsedTimeView=_elapsedTimeView;
@property(retain, nonatomic) CAMFlashButton *flashButton; // @synthesize flashButton=_flashButton;
@property(nonatomic) long long backgroundStyle; // @synthesize backgroundStyle=_backgroundStyle;
@property(nonatomic) long long style; // @synthesize style=_style;
- (void)flashButtonDidCollapse:(id)arg1;
- (void)flashButtonWillExpand:(id)arg1;
- (void)flashButtonWasPressed:(id)arg1;
- (void)flashButtonModeDidChange:(id)arg1;
- (void)_layoutFloatingRecordingStyle;
- (void)_layoutFloatingStyle;
- (void)_layoutDefaultStyle;
- (struct UIEdgeInsets)_backgroundEdgeInsetsForStyle:(long long)arg1;
- (_Bool)_shouldHideHDRButton;
- (_Bool)_shouldHideElapsedTimeView;
- (void)_updateHiddenViewsForFlashExpansion;
- (void)_updateBackgroundStyleAnimated:(_Bool)arg1;
- (void)_updateStyleAnimated:(_Bool)arg1;
@property(readonly, nonatomic, getter=isFloating) _Bool floating;
- (void)setBackgroundStyle:(long long)arg1 animated:(_Bool)arg2;
- (void)setStyle:(long long)arg1 animated:(_Bool)arg2;
- (void)layoutSubviews;
- (struct CGSize)sizeThatFits:(struct CGSize)arg1;
- (void)dealloc;
- (id)initWithCoder:(id)arg1;
- (id)initWithFrame:(struct CGRect)arg1;
- (void)_commonCAMTopBarInitialization;

@end


text:
// Copyright 2019 Esri.
//
// 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.

using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using Esri.ArcGISRuntime.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.UI.Xaml;

namespace ArcGISRuntime.UWP.Samples.FindServiceAreasForMultipleFacilities
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Find service areas for multiple facilities",
        category: "Network analysis",
        description: "Find the service areas of several facilities from a feature service.",
        instructions: "Click 'find service area' to calculate and display the service area of each facility on the map. The polygons displayed around each facility represents the service area; in red is the area that is within 3 minutes away from the hospital by car. Light orange is the area that is within 5 minutes away from the hospital by car.",
        tags: new[] { "facilities", "feature service", "impedance", "network analysis", "service area", "travel time" })]
    [ArcGISRuntime.Samples.Shared.Attributes.OfflineData()]
    public partial class FindServiceAreasForMultipleFacilities
    {
        // URLs to resources used by the sample.
        private const string NetworkAnalysisUrl = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ServiceArea";
        private const string FacilitiesFeatureUrl = "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Facilities/FeatureServer/0";
        private const string IconUrl = "https://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png";

        // The table that contains the facilities.
        private ServiceFeatureTable _facilitiesTable;

        // The task for performing the service area analysis.
        private ServiceAreaTask _serviceAreaTask;

        // The graphics overlay for displaying the resulting polygons.
        private GraphicsOverlay _resultOverlay;

        // Symbology for the resulting service areas.
        private List<SimpleFillSymbol> _fillSymbols;

        public FindServiceAreasForMultipleFacilities()
        {
            InitializeComponent();
            Initialize();
        }

        private async void Initialize()
        {
            try
            {
                // Create the map and show it in the view.
                Map newMap = new Map(BasemapStyle.ArcGISLightGray);
                MyMapView.Map = newMap;

                // Create the table containing the facilities.
                _facilitiesTable = new ServiceFeatureTable(new Uri(FacilitiesFeatureUrl));

                // Create the layer for rendering the facilities table.
                FeatureLayer facilitiesLayer = new FeatureLayer(_facilitiesTable);

                // Create a simple renderer that will display an image for each facility.
                facilitiesLayer.Renderer = new SimpleRenderer(new PictureMarkerSymbol(new Uri(IconUrl)));

                // Add the layer to the map.
                newMap.OperationalLayers.Add(facilitiesLayer);

                // Create the graphics overlay for displaying the result polygons.
                _resultOverlay = new GraphicsOverlay();

                // Add the result overlay to the view.
                MyMapView.GraphicsOverlays.Add(_resultOverlay);

                // Create a list of fill symbols for rendering the results.
                _fillSymbols = new List<SimpleFillSymbol>();
                _fillSymbols.Add(new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.FromArgb(0x66, 0xFF, 0xA5, 0x00), null));
                _fillSymbols.Add(new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.FromArgb(0x66, 0xFF, 0x00, 0x00), null));

                // Wait for the table to load and zoom to its extent.
                await _facilitiesTable.LoadAsync();
                await MyMapView.SetViewpointGeometryAsync(_facilitiesTable.Extent, 50);

                // Enable the button now that the sample is ready.
                ServiceAreaButton.IsEnabled = true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                ShowMessage("Error", "Error starting the sample.");
            }
        }

        private async Task FindServiceAreas()
        {
            try
            {
                // Create the service area task.
                _serviceAreaTask = await ServiceAreaTask.CreateAsync(new Uri(NetworkAnalysisUrl));

                // Create the default parameters for the service.
                ServiceAreaParameters serviceAreaParameters = await _serviceAreaTask.CreateDefaultParametersAsync();

                // Configure the service area parameters.
                serviceAreaParameters.PolygonDetail = ServiceAreaPolygonDetail.High;
                serviceAreaParameters.ReturnPolygons = true;
                serviceAreaParameters.DefaultImpedanceCutoffs.Clear();
                serviceAreaParameters.DefaultImpedanceCutoffs.Add(0);
                serviceAreaParameters.DefaultImpedanceCutoffs.Add(3);
                serviceAreaParameters.DefaultImpedanceCutoffs.Add(5);

                // A query that finds all of the relevant facilities from the facilities feature service.
                QueryParameters facilityQueryParameters = new QueryParameters();
                facilityQueryParameters.WhereClause = "1=1";

                // Provide the feature service and the query as parameters to the service area task.
                serviceAreaParameters.SetFacilities(_facilitiesTable, facilityQueryParameters);

                // Perform the service area analysis.
                ServiceAreaResult result = await _serviceAreaTask.SolveServiceAreaAsync(serviceAreaParameters);

                // Count the features in the facilities layer.
                long facilityCount = await _facilitiesTable.QueryFeatureCountAsync(facilityQueryParameters);

                // Get the service area for each facility.
                for (int facilityIndex = 0; facilityIndex < facilityCount; facilityIndex++)
                {
                    // Get each area polygon from the result for that facility.
                    List<ServiceAreaPolygon> areaPolygons = result.GetResultPolygons(facilityIndex).ToList();

                    // Add each service area polygon to the graphics overlay.
                    for (int polygonIndex = 0; polygonIndex < areaPolygons.Count; polygonIndex++)
                    {
                        // Get the polygon from the result.
                        Polygon resultingPolygon = areaPolygons[polygonIndex].Geometry;

                        // Choose a symbol for the polygon.
                        SimpleFillSymbol selectedSymbol = _fillSymbols[polygonIndex % _fillSymbols.Count];

                        // Create and add the graphic.
                        _resultOverlay.Graphics.Add(new Graphic(resultingPolygon, selectedSymbol));
                    }
                }

                // Zoom to the extent of the results.
                await MyMapView.SetViewpointGeometryAsync(_resultOverlay.Extent, 50);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                ShowMessage("Error", "Couldn't complete service area analysis.");
            }
        }

        private async void FindServiceArea_Clicked(object sender, RoutedEventArgs e)
        {
            try
            {
                // Clear the old results.
                _resultOverlay?.Graphics.Clear();

                // Update the UI.
                ServiceAreaButton.IsEnabled = false;
                ProgressView.Visibility = Visibility.Visible;

                // Do the service area work.
                await FindServiceAreas();

                // Update the UI.
                ProgressView.Visibility = Visibility.Collapsed;
                ServiceAreaButton.IsEnabled = true;
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine(exception);
                ShowMessage("Error", "Couldn't complete the service area analysis.");
            }
        }

        private async void ShowMessage(string title, string detail)
        {
            await new MessageDialog(detail, title).ShowAsync();
        }
    }
}


text:
can.Model.LocalStorage("GGRC.Models.RecentlyViewedObject", {

  newInstance : function(attrs) {
    if(attrs instanceof can.Model) {
      var title = (attrs.title && attrs.title.trim()) || (attrs.name && attrs.name.trim()) || (attrs.email && attrs.email.trim());
      return new this({
        type : attrs.constructor.shortName
        , model : attrs.constructor
        , viewLink : attrs.viewLink
        , title : title
      });
    } else {
      return this._super(attrs);
    }
  }

}, {

  init : function() {
    this.attr("model", GGRC.Models[this.type] || CMS.Models[this.type]);
  }

  , stub : function() {
    return can.extend(this._super(), { title : this.title, viewLink : this.viewLink });
  }
});


text:
package scouter.client.counter.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;

import scouter.client.Images;
import scouter.client.group.view.XLogRealTimeGroupView;
import scouter.client.model.GroupObject;
import scouter.client.util.ConsoleProxy;
import scouter.client.util.ImageUtil;

public class OpenRealTimeTranXGroupViewAction extends Action {
	public final static String ID = OpenRealTimeTranXGroupViewAction.class.getName();

	private final IWorkbenchWindow window;
	private String grpName;
	private String objType;

	public OpenRealTimeTranXGroupViewAction(IWorkbenchWindow window, String label, GroupObject grpObj) {
		this.window = window;
		this.grpName = grpObj.getName();
		this.objType = grpObj.getObjType();
		setText(label);
		setId(ID);
		setImageDescriptor(ImageUtil.getImageDescriptor(Images.transrealtime));
	}

	public void run() {
		if (window != null) {
			try {
				window.getActivePage().showView(
						XLogRealTimeGroupView.ID, grpName + "&" + objType,
						IWorkbenchPage.VIEW_ACTIVATE);
			} catch (PartInitException e) {
				ConsoleProxy.error(e.toString());
			}
		}
	}
}


text:
<?php

namespace CybernetAPI;

use CybernetAPI\AbstractRoute as Route;
use Slim\Http\Request as Request;
use Slim\Http\Response as Response;

/**
 * Class Help
 * @package CybernetAPI\Roll
 */
class Help extends Route
{
    protected $help = [];
    /**
     * @param Request $request
     * @param Response $response
     * @return Response (JSON Encoded content)
     * @throws \Exception
     */
    public function __invoke(Request $request, Response $response)
    {
        $path = $request->getRequestTarget();
        $what = $request->getAttribute('what');

        $pathSegments = explode('/', $path);
        array_pop($pathSegments);
        $whatSegments = explode('/', $what);

        // To get help for a specific route, analyze the path and the "what" segments
        // TODO: Write help docs for routes and methods.
        // For now, just return generic help.

        $jsonResponse = $response->withJson($this->getHelp(), 200);
        return $jsonResponse;
    }

    public function getHelp()
    {
        $this->help['Description'] = <<<EOH
General help document. Not very helpful. Try: /help/roll or /roll/help
EOH;
        return parent::getHelp();
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:background="#131e37">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:weightSum="1.0"
        android:background="#0d3653">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView4"
            android:layout_gravity="center_horizontal"
            android:layout_weight=".05" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Reaction Test"
            android:id="@+id/reactionTestButton"
            android:layout_gravity="center_horizontal"
            android:layout_weight="0.25"
            android:textSize="32sp"
            android:onClick="launchReactionTest"
            android:background="#ffffff"
            android:layout_margin="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView5"
            android:layout_gravity="center_horizontal"
            android:layout_weight=".1" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Trivia Buzzer"
            android:id="@+id/triviaBuzzerButton"
            android:layout_gravity="center_horizontal"
            android:layout_weight="0.25"
            android:textSize="32sp"
            android:onClick="launchTriviaBuzzer"
            android:nestedScrollingEnabled="true"
            android:background="#ffffff"
            android:layout_margin="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView6"
            android:layout_gravity="center_horizontal"
            android:layout_weight=".1" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Statistics"
            android:id="@+id/statisticsButton"
            android:layout_gravity="center_horizontal"
            android:layout_weight="0.10"
            android:textSize="26sp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:onClick="launchStatsActivity"
            android:background="#ffffff"
            android:layout_margin="20dp" />
    </LinearLayout>
</RelativeLayout>


text:
"""Datasets input pipeline."""
import copy
import functools
import os
from absl import logging
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
import hparams
import preprocessing
ds_register = functools.partial(hparams.register, prefix='ds:')

# Input pipelines are slightly different (with regards to shuffling and
# preprocessing) between training and evaluation.
def build_dataset_input(is_training, image_size, image_dtype, data_dir, split,
                        data_config):
  """Generate input for training and eval."""
  ds_cls = get_dataset_class(data_config.ds_name)
  return ds_cls(
      is_training=is_training,
      data_dir=data_dir,
      split=split,
      cache=data_config.cache,
      image_size=image_size,
      image_dtype=image_dtype,
      augname=data_config.augname,
      mixup_alpha=data_config.mixup_alpha,
      cutmix_alpha=data_config.cutmix_alpha,
      ra_num_layers=data_config.ra_num_layers,
      ra_magnitude=data_config.ram)

def build_image_serving_input_fn(image_size, batch_size=None):
  """Builds a serving input fn for raw images."""

  def _image_serving_input_fn():
    """Serving input fn for raw images."""

    def _preprocess_image(image_bytes):
      """Preprocess a single raw image."""
      image = preprocessing.preprocess_image(
          image_bytes,
          is_training=False,
          image_size=image_size)
      return image

    image_bytes_list = tf.placeholder(
        shape=[batch_size],
        dtype=tf.string,
    )
    images = tf.map_fn(
        _preprocess_image, image_bytes_list, back_prop=False, dtype=tf.float32)
    return tf.estimator.export.ServingInputReceiver(
        images, {'image_bytes': image_bytes_list})
  return _image_serving_input_fn

class ImageNetInput():
  """Generates ImageNet input_fn from a series of TFRecord files.

  The format of the data required is created by the script at:
      https://github.com/tensorflow/tpu/blob/master/tools/datasets/imagenet_to_gcs.py
  """
  cfg = hparams.Config(
      data_dir=None,
      num_classes=1000,
      multiclass=False,
      tfds_split=None,
      splits=dict(
          train=dict(
              num_images=1_256_144, files='train*', slice=slice(20, None)),
          minival=dict(num_images=25_021, files='train*', slice=slice(0, 20)),
          eval=dict(num_images=50_000, files='val*', slice=slice(0, None)),
          trainval=dict(
              num_images=1_281_167, files='train*', slice=slice(0, None)),
      ),
  )

  def __init__(self,
               is_training,
               image_dtype=False,
               data_dir=None,
               split=None,
               image_size=224,
               cache=False,
               augname=None,
               mixup_alpha=None,
               cutmix_alpha=None,
               ra_num_layers=None,
               ra_magnitude=None,
               transpose_image=False,
               debug=False):
    """Create an input from TFRecord files.

    Args:
      is_training: `bool` for whether the input is for training
      image_dtype: iamge dtype. If None, use tf.float32.
      data_dir: `str` for the directory of the training and validation data;
      split: `str`, dataset split, common values {train, eval, test, traineval}.
      image_size: `int` for image size (both width and height).
      cache: if true, fill the dataset by repeating from its cache.
      augname: `string` that is the name of the augmentation method
          to apply to the image. `autoaugment` if AutoAugment is to be used or
          `randaugment` if RandAugment is to be used. If the value is `None` no
          no augmentation method will be applied applied. See autoaugment.py
          for more details.
      mixup_alpha: float to control the strength of Mixup regularization, set
          to 0.0 to disable.
      cutmix_alpha: float to control cutmix, set to 0.0 or None to disable.
      ra_num_layers: 'int', if RandAug is used, what should the number of
        layers be. See autoaugment.py for detailed description.
      ra_magnitude: 'int', if RandAug is used, what should the magnitude
        be. See autoaugment.py for detailed description.
      transpose_image: Whether to transpose the image. Useful for the "double
        transpose" trick for improved input throughput.
      debug: bool, If true, use deterministic behavior and add orig_image.
    """
    self.is_training = is_training
    self.image_dtype = image_dtype or tf.float32
    self.image_size = image_size
    self.augname = augname
    self.mixup_alpha = mixup_alpha
    self.cutmix_alpha = cutmix_alpha
    self.ra_num_layers = ra_num_layers
    self.ra_magnitude = ra_magnitude
    self.split = split or ('train' if is_training else 'eval')

    self.data_dir = data_dir or self.cfg.data_dir
    self.cache = cache
    self.transpose_image = transpose_image

    # for input pipeline performance.
    self.file_buffer_size_m = None
    self.shuffle_size_k = 128

    self.debug = debug
    self.orig_image = False
    # randomness
    self.shuffle_files = False if debug else True
    self.shuffle_seed = 1111 if debug else None

  def image_preprocessing(self, image):
    return preprocessing.preprocess_image(
        image,
        image_size=self.image_size,
        is_training=self.is_training,
        image_dtype=self.image_dtype,
        augname=self.augname,
        ra_num_layers=self.ra_num_layers,
        ra_magnitude=self.ra_magnitude)

  @property
  def split_info(self):
    return self.cfg.splits[self.split]

  def set_shapes(self, batch_size, features, labels):
    """Statically set the batch_size dimension."""
    features['image'].set_shape(features['image'].get_shape().merge_with(
        tf.TensorShape([batch_size, None, None, None])))
    labels['label'].set_shape(labels['label'].get_shape().merge_with(
        tf.TensorShape([batch_size, None])))
    return features, labels

  def _get_null_input(self, data):
    """Returns a null image (all black pixels).

    Args:
      data: element of a dataset, ignored in this method, since it produces
          the same null image regardless of the element.

    Returns:
      a tensor representing a null image.
    """
    del data  # Unused since output is constant regardless of input
    return tf.zeros([self.image_size, self.image_size, 3], self.image_dtype)

  def cutmix_mask(self, alpha, h, w):
    """Returns image mask for CutMix."""
    r_x = tf.random.uniform([], 0, w, tf.int32)
    r_y = tf.random.uniform([], 0, h, tf.int32)

    area = tf.distributions.Beta(alpha, alpha).sample()
    patch_ratio = tf.cast(tf.math.sqrt(1 - area), tf.float32)
    r_w = tf.cast(patch_ratio * tf.cast(w, tf.float32), tf.int32)
    r_h = tf.cast(patch_ratio * tf.cast(h, tf.float32), tf.int32)
    bbx1 = tf.clip_by_value(tf.cast(r_x - r_w // 2, tf.int32), 0, w)
    bby1 = tf.clip_by_value(tf.cast(r_y - r_h // 2, tf.int32), 0, h)
    bbx2 = tf.clip_by_value(tf.cast(r_x + r_w // 2, tf.int32), 0, w)
    bby2 = tf.clip_by_value(tf.cast(r_y + r_h // 2, tf.int32), 0, h)

    # Create the binary mask.
    pad_left = bbx1
    pad_top = bby1
    pad_right = tf.maximum(w - bbx2, 0)
    pad_bottom = tf.maximum(h - bby2, 0)
    r_h = bby2 - bby1
    r_w = bbx2 - bbx1

    mask = tf.pad(
        tf.ones((r_h, r_w)),
        paddings=[[pad_top, pad_bottom], [pad_left, pad_right]],
        mode='CONSTANT',
        constant_values=0)
    mask.set_shape((h, w))
    return mask[..., None]  # Add channel dim.

  def cutmix(self, image, label, mask):
    """Applies CutMix regularization to a batch of images and labels.

    Reference: https://arxiv.org/pdf/1905.04899.pdf

    Arguments:
      image: a Tensor of batched images.
      label: a Tensor of batched labels.
      mask: a Tensor of batched masks.

    Returns:
      A new dict of features with updated images and labels with the same
      dimensions as the input with CutMix regularization applied.
    """
    # actual area of cut & mix pixels
    mix_area = tf.reduce_sum(mask) / tf.cast(tf.size(mask), mask.dtype)
    mask = tf.cast(mask, image.dtype)
    mixed_image = (1. - mask) * image + mask * image[::-1]
    mix_area = tf.cast(mix_area, label.dtype)
    mixed_label = (1. - mix_area) * label + mix_area * label[::-1]

    return mixed_image, mixed_label

  def mixup(self, batch_size, alpha, image, label):
    """Applies Mixup regularization to a batch of images and labels.

    [1] Hongyi Zhang, Moustapha Cisse, Yann N. Dauphin, David Lopez-Paz
      Mixup: Beyond Empirical Risk Minimization.
      ICLR'18, https://arxiv.org/abs/1710.09412

    Arguments:
      batch_size: The input batch size for images and labels.
      alpha: Float that controls the strength of Mixup regularization.
      image: a Tensor of batched images.
      label: a Tensor of batch labels.

    Returns:
      A new dict of features with updated images and labels with the same
      dimensions as the input with Mixup regularization applied.
    """
    mix_weight = tf.distributions.Beta(alpha, alpha).sample([batch_size, 1])
    mix_weight = tf.maximum(mix_weight, 1. - mix_weight)
    img_weight = tf.cast(
        tf.reshape(mix_weight, [batch_size, 1, 1, 1]), image.dtype)
    # Mixup on a single batch is implemented by taking a weighted sum with the
    # same batch in reverse.
    image = image * img_weight + image[::-1] * (1. - img_weight)
    label_weight = tf.cast(mix_weight, label.dtype)
    label = label * label_weight + label[::-1] * (1 - label_weight)
    return image, label

  def mixing(self, batch_size, mixup_alpha, cutmix_alpha, features, labels):
    """Applies mixing regularization to a batch of images and labels.

    Arguments:
      batch_size: The input batch size for images and labels.
      mixup_alpha: Float that controls the strength of Mixup regularization.
      cutmix_alpha: FLoat that controls the strenght of Cutmix regularization.
      features: a dict of batched images.
      labels: a dict of batched labels.

    Returns:
      A new dict of features with updated images and labels with the same
      dimensions as the input.
    """
    image, label = features['image'], labels['label']
    if mixup_alpha and cutmix_alpha:
      # split the batch half-half, and aplly mixup and cutmix for each half.
      bs = batch_size // 2
      img1, lab1 = self.mixup(bs, mixup_alpha, image[:bs], label[:bs])
      img2, lab2 = self.cutmix(image[bs:], label[bs:],
                               features['cutmix_mask'][bs:])
      features['image'] = tf.concat([img1, img2], axis=0)
      labels['label'] = tf.concat([lab1, lab2], axis=0)
    elif mixup_alpha:
      features['image'], labels['label'] = self.mixup(batch_size, mixup_alpha,
                                                      image, label)
    elif cutmix_alpha:
      features['image'], labels['label'] = self.cutmix(
          image, label, features['cutmix_mask'])
    return features, labels

  def dataset_parser(self, value):
    """See base class."""
    if self.data_dir == 'null' or not self.data_dir:
      labels = tf.constant(0., tf.float32, (self.cfg.num_classes,))
      return {'image': value}, {'label': labels}

    keys_to_features = {
        'image/encoded': tf.FixedLenFeature((), tf.string, ''),
        'image/class/label': tf.FixedLenFeature([], tf.int64, -1),
    }

    parsed = tf.parse_single_example(value, keys_to_features)
    image_bytes = tf.reshape(parsed['image/encoded'], shape=[])
    image = self.image_preprocessing(image_bytes)
    # The labels will be in range [1,1000], 0 is reserved for background
    label = tf.cast(
        tf.reshape(parsed['image/class/label'], shape=[]), dtype=tf.int32)
    label -= 1  # get rid of the background.
    onehot_label = tf.one_hot(label, self.cfg.num_classes)
    features = {'image': image}
    labels = {'label': onehot_label}
    if self.cutmix_alpha:
      features['cutmix_mask'] = self.cutmix_mask(  #
          self.cutmix_alpha, self.image_size, self.image_size)
    if self.debug and self.orig_image:
      features['orig_image'] = tf.image.decode_image(image_bytes)
    return features, labels

  def fetch_dataset(self, filename):
    buffer_size = (self.file_buffer_size_m or 8) * 1024 * 1024  # 8 MiB
    dataset = tf.data.TFRecordDataset(filename, buffer_size=buffer_size)
    return dataset

  def make_source_dataset(self, index, num_hosts):
    """See base class."""
    if self.data_dir == 'null' or not self.data_dir:
      logging.info('Undefined data_dir implies null input')
      return tf.data.Dataset.range(1).repeat().map(self._get_null_input)

    filenames = tf.io.gfile.glob(
        os.path.join(self.data_dir, self.split_info['files']))
    filenames = sorted(filenames)[self.split_info['slice']]
    for f in filenames[:5]:
      logging.info('datafiles: %s', f)
    dataset = tf.data.Dataset.from_tensor_slices(filenames)

    # For multi-host training, we want each hosts to always process the same
    # subset of files.  Each host only sees a subset of the entire dataset,
    # allowing us to cache larger datasets in memory.
    dataset = dataset.shard(num_hosts, index)

    # file-level shuffle
    if self.is_training and self.shuffle_files:
      num_files_per_shard = (len(filenames) + num_hosts - 1) // num_hosts
      dataset = dataset.shuffle(num_files_per_shard, seed=self.shuffle_seed)

    if self.is_training and not self.cache:
      dataset = dataset.repeat()

    # Read the data from disk in parallel
    dataset = dataset.interleave(
        self.fetch_dataset,
        num_parallel_calls=tf.data.AUTOTUNE,
        deterministic=self.debug)

    if self.is_training and self.cache:
      dataset = dataset.cache().shuffle(
          self.shuffle_size_k * 1024, seed=self.shuffle_seed).repeat()
    else:
      dataset = dataset.shuffle(
          self.shuffle_size_k * 1024, seed=self.shuffle_seed)
    return dataset

  def input_fn(self, params):
    """Input function which provides a single batch for train or eval.

    Args:
      params: `dict` of parameters passed from the `TPUEstimator`.
          `params['batch_size']` is always provided and should be used as the
          effective batch size.

    Returns:
      A `tf.data.Dataset` object.
    """
    # Retrieves the batch size for the current shard. The # of shards is
    # computed according to the input pipeline deployment. See
    # tf.estimator.tpu.RunConfig for details.
    batch_size = params['batch_size']

    if 'context' in params:
      current_host = params['context'].current_input_fn_deployment()[1]
      num_hosts = params['context'].num_hosts
    else:
      current_host = 0
      num_hosts = 1

    return self._input_fn(batch_size, current_host, num_hosts)

  def _input_fn(self, batch_size, current_host, num_hosts):
    """Creates a dataset for the specified host."""
    dataset = self.make_source_dataset(current_host, num_hosts)
    dataset = dataset.map(
        self.dataset_parser,
        num_parallel_calls=tf.data.AUTOTUNE).batch(
            batch_size, drop_remainder=True)

    # Apply Mixup
    if self.is_training and (self.mixup_alpha or self.cutmix_alpha):
      dataset = dataset.map(
          functools.partial(self.mixing, batch_size, self.mixup_alpha,
                            self.cutmix_alpha),
          num_parallel_calls=tf.data.AUTOTUNE)

    # Assign static batch size dimension
    dataset = dataset.map(
        functools.partial(self.set_shapes, batch_size),
        num_parallel_calls=tf.data.AUTOTUNE)

    def transpose_image(features):
      # NHWC -> HWCN
      features['image'] = tf.transpose(features['image'], [1, 2, 3, 0])
      return features

    if self.transpose_image:
      dataset = dataset.map(
          lambda features, labels: (transpose_image(features), labels),
          num_parallel_calls=tf.data.AUTOTUNE)

    # Prefetch overlaps in-feed with training
    dataset = dataset.prefetch(tf.data.AUTOTUNE)
    options = tf.data.Options()
    options.deterministic = self.debug
    options.threading.max_intra_op_parallelism = 1
    options.threading.private_threadpool_size = 48
    dataset = dataset.with_options(options)
    return dataset

  def distribute_dataset_fn(self, global_batch_size):
    """Dataset for tf.distribute.Strategy.distribute_datasets_from_function."""

    def dataset_fn(input_context):
      return self._input_fn(
          input_context.get_per_replica_batch_size(global_batch_size),
          input_context.input_pipeline_id, input_context.num_input_pipelines)

    return dataset_fn

class ImageNet21kInput(ImageNetInput):
  """Generates input_fn from ImageNet21k TFRecord files."""
  cfg = copy.deepcopy(ImageNetInput.cfg)
  cfg.update(
      dict(
          data_dir=None,
          num_classes=21843,
          multiclass=True,
          splits=dict(
              train=dict(
                  num_images=12_720_275,
                  files='imagenet21k*',
                  slice=slice(20, None)),
              minival=dict(
                  num_images=25089, files='imagenet21k*', slice=slice(16, 20)),
              eval=dict(
                  num_images=100357, files='imagenet21k*', slice=slice(0, 16)),
          ),
      ))

  def dataset_parser(self, value):
    """See base class."""
    if self.data_dir == 'null' or not self.data_dir:
      values = tf.constant([2, 3], tf.int64)
      fake_labels = tf.sparse.to_dense(
          tf.sparse.SparseTensor(
              tf.expand_dims(values, -1), tf.ones_like(values),
              [self.cfg.num_classes]))
      return {'image': value}, {'label': fake_labels}

    keys_to_features = {
        'id':
            tf.io.FixedLenFeature([], tf.string),
        'image':
            tf.io.FixedLenFeature([], tf.string),
        'labels':
            # tf.io.VarLenFeature(tf.int64),
            tf.io.FixedLenSequenceFeature([], tf.int64, allow_missing=True),
    }

    parsed = tf.io.parse_single_example(value, keys_to_features)
    image_bytes = tf.reshape(parsed['image'], shape=[])
    image = self.image_preprocessing(image_bytes)
    labels = parsed['labels']
    labels = tf.sparse.SparseTensor(
        tf.expand_dims(labels, -1), tf.ones_like(labels),
        [self.cfg.num_classes])
    labels = tf.sparse.to_dense(labels)
    features = {'image': image}
    labels = {'label': labels}
    if self.debug:
      features['orig_image'] = tf.image.decode_image(image_bytes)
    return features, labels

class CIFAR10Input(ImageNetInput):
  """Cifar10 input from tfds."""
  cfg = copy.deepcopy(ImageNetInput.cfg)
  cfg.update(
      dict(
          try_gcs=True,
          data_dir=None,
          num_classes=10,
          multiclass=False,
          tfds_name='cifar10',
          splits=dict(
              train=dict(num_images=50000, tfds_split='train', slice=''),
              minival=dict(num_images=10000, tfds_split='test', slice=''),
              eval=dict(num_images=10000, tfds_split='test', slice=''),
          )))

  def preprocess(self, features):
    """The preprocessing function."""
    image = self.image_preprocessing(features['image'])
    new_features = {'image': image}
    if self.debug:
      new_features['orig_image'] = features['image']
    new_label = {'label': tf.one_hot(features['label'], self.cfg.num_classes)}
    return new_features, new_label

  def _input_fn(self, batch_size, current_host, num_hosts):
    logging.info('use tfds: %s[%s]', self.cfg.tfds_name,
                 self.cfg.splits[self.split]['tfds_split'])
    ds = tfds.load(
        self.cfg.tfds_name, split=self.cfg.splits[self.split]['tfds_split'], try_gcs=self.cfg.try_gcs)
    ds = ds.shard(num_hosts, current_host)
    if self.is_training:
      if self.cache:
        ds = ds.cache().shuffle(1024 * 16, seed=self.shuffle_seed).repeat()
      else:
        ds = ds.shuffle(self.shuffle_size_k * 1024, seed=self.shuffle_seed)
      ds = ds.repeat()

    ds = ds.map(
        self.preprocess, num_parallel_calls=tf.data.AUTOTUNE)
    ds = ds.prefetch(1)

    ds = ds.batch(batch_size, drop_remainder=True)
    ds = ds.prefetch(1)

    options = tf.data.Options()
    options.autotune.enabled = True
    return ds.with_options(options)

class CIFAR100Input(CIFAR10Input):
  """Cifar100 input from tfds."""
  cfg = copy.deepcopy(CIFAR10Input.cfg)
  cfg.update(
      dict(
          num_classes=100,
          tfds_name='cifar100',
          splits=dict(
              train=dict(num_images=50000, tfds_split='train', slice=''),
              minival=dict(num_images=10000, tfds_split='test', slice=''),
              eval=dict(num_images=10000, tfds_split='test', slice=''),
          )))

class FlowersInput(CIFAR10Input):
  """Flowers input from tfds."""
  cfg = copy.deepcopy(CIFAR10Input.cfg)
  cfg.update(
      dict(
          num_classes=102,
          tfds_name='oxford_flowers102',
          splits=dict(
              train=dict(
                  num_images=1020, tfds_split='train+validation', slice=''),
              minival=dict(num_images=1020, tfds_split='validation', slice=''),
              eval=dict(num_images=6149, tfds_split='test', slice=''),
          )))

class TFFlowersInput(CIFAR10Input):
  """TFFlowers input from tfds gcs."""
  cfg = copy.deepcopy(CIFAR10Input.cfg)
  cfg.update(
      dict(
          num_classes=5,
          tfds_name='tf_flowers',
          try_gcs=True,
          splits=dict(
              train=dict(num_images=2569, tfds_split='train[:70%]'),
              minival=dict(num_images=1101, tfds_split='train[30%:]'),
              eval=dict(num_images=1101, tfds_split='train[30%:]'),
          )))

class CarsInput(CIFAR10Input):
  """Car input from tfds."""
  cfg = copy.deepcopy(CIFAR10Input.cfg)
  cfg.update(
      dict(
          num_classes=196,
          tfds_name='cars196',
          splits=dict(
              train=dict(num_images=8_144, tfds_split='train', slice=''),
              minival=dict(num_images=8_041, tfds_split='test', slice=''),
              eval=dict(num_images=8_041, tfds_split='test', slice=''),
          )))

class ImageNetTfdsInput(CIFAR10Input):
  """ImageNet TFDS input from tfds."""
  cfg = copy.deepcopy(CIFAR10Input.cfg)
  cfg.update(
      dict(
          data_dir=None,
          num_classes=1000,
          multiclass=False,
          tfds_name='imagenet2012',
          splits=dict(
              train=dict(num_images=1_256_144, tfds_split='train[:98%]'),
              minival=dict(num_images=25_021, tfds_split='train[2%:]'),
              eval=dict(num_images=50_000, tfds_split='validation'),
              trainval=dict(num_images=1_281_167, tfds_split='train'),
          )))

def get_dataset_class(ds_name):
  return {
      'imagenet': ImageNetInput,
      'imagenet21k': ImageNet21kInput,
      'imagenettfds': ImageNetTfdsInput,
      'cifar10': CIFAR10Input,
      'cifar100': CIFAR100Input,
      'flowers': FlowersInput,
      'tfflowers': TFFlowersInput,
      'cars': CarsInput,
  }[ds_name]

################# Dataset training configs ####################
@ds_register
class ImageNet():
  """ImageNet train/eval configs."""
  cfg = hparams.Config(
      data=dict(
          ds_name='imagenet',
          multiclass=False,
      ),
      train=dict(
          epochs=350,
          lr_base=0.016,
          lr_warmup_epoch=5,
          lr_sched='exponential',
          label_smoothing=0.1,
      ),
      eval=dict(
          batch_size=8,
      ),
  )

@ds_register
class ImageNet21k():
  """ImageNet21k train/eval configs."""
  cfg = hparams.Config(
      model=dict(
          dropout_rate=0.000001,
          survival_prob=1.0,
      ),
      data=dict(
          ds_name='imagenet21k',
          multiclass=True,
          augname=None,  # Disable all augmentation and mixup.
          mixup_alpha=0,
          cutmix_alpha=0,
      ),
      train=dict(
          epochs=60,
          lr_base=0.008,
          lr_warmup_epoch=1,
          lr_sched='cosine',
          label_smoothing=0.0,
          isize=224,
          stages=0,  # do not apply staged training.
          sched=False,
      ),
      eval=dict(
          batch_size=128,
          isize=224,
      ),
  )

@ds_register
class ImagenetFt(ImageNet):
  """Finetune imagenet configs."""
  # Finetune should have less regularization due to the limited training steps.
  cfg = hparams.Config(
      model=dict(
          dropout_rate=0.000001,
          survival_prob=0.8,
      ),
      train=dict(
          batch_size=512,
          stages=0,
          epochs=15,
          optimizer='rmsprop',
          lr_sched='constant',
          lr_base=0.0005,
          lr_warmup_epoch=1,
          ema_decay=0.9996,
          weight_decay=1e-5,
          label_smoothing=0.1,
          min_steps=10000,
          isize=1.0,
      ),
      data=dict(
          ds_name='imagenettfds',
          augname='ft',
          mixup_alpha=0,
          cutmix_alpha=0,
      ),
  )

@ds_register
class Cifar10Ft(ImagenetFt):
  """Finetune cifar10 configs."""
  cfg = copy.deepcopy(ImagenetFt.cfg)
  cfg.data.ds_name = 'cifar10'

@ds_register
class Cifar100Ft(Cifar10Ft):
  """Finetune cifar100 configs."""
  cfg = copy.deepcopy(Cifar10Ft.cfg)
  cfg.data.override(dict(ds_name='cifar100'))

@ds_register
class FlowersFt(Cifar10Ft):
  """Finetune flower configs."""
  cfg = copy.deepcopy(Cifar10Ft.cfg)
  cfg.data.override(dict(ds_name='flowers'))

@ds_register
class TFFlowersFt(Cifar10Ft):
  """Finetune tfflower configs."""
  cfg = copy.deepcopy(Cifar10Ft.cfg)
  cfg.data.override(dict(ds_name='tfflowers'))

@ds_register
class CarsFt(Cifar10Ft):
  """Finetune car configs."""
  cfg = copy.deepcopy(Cifar10Ft.cfg)
  cfg.data.override(dict(ds_name='cars'))

################################################################################
def get_dataset_config(name, prefix='ds:'):
  """Main entry for dataset config, e.g., ImageNet or Cifar10Ft."""
  cfg = hparams.lookup(name, prefix).cfg
  cfg.data.update(get_dataset_class(cfg.data.ds_name).cfg)
  return cfg


text:
A little demo gem that changes numbers into words.

## Requirements

This gem is built for ruby 2.0.0 and above.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'numbertoword', :git => 'https://github.com/nikkij/numbertoword.git'
```

And then execute:

    $ bundle

Or install locally for development or to run tests:

    $ git clone https://github.com/nikkij/numbertoword.git

    $ cd numbertoword

    $ rake install

To run the rspec tests make sure you have the rspec gem installed or specified as a dependency in your Gemfile.

## Usage

Just type the command "numbertoword" at the console.

	$ numbertoword

At the prompt enter any number from 1 - 999,999,999 .

## Contributing

1. Fork it ( https://github.com/[my-github-username]/numbertoword/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
<?php
namespace Chamilo\Application\Survey\Export;

use Chamilo\Libraries\Architecture\Application\Application;

abstract class Manager extends Application
{
    const PARAM_ACTION = 'action';
    const PARAM_EXPORT_REGISTRATION_ID = 'export_registration_id';
    const PARAM_EXPORT_TEMPLATE_ID = 'export_template_id';
    const PARAM_EXPORT_ID = 'export_id';
    const ACTION_BROWSE = 'Browser';
    const ACTION_CREATE = 'Creator';
    const ACTION_EDIT = 'Editor';
    const ACTION_EDIT_EXPORT_RIGHTS = 'RightsEditor';
    const ACTION_DELETE = 'Deleter';
    const ACTION_EXPORT = 'Export';
    const ACTION_DELETE_EXPORT = 'ExportDeleter';
    const ACTION_CONVERT_ANSWERS = 'ConvertAnswers';
    const DEFAULT_ACTION = self::ACTION_BROWSE;

    // url
    function get_browse_export_templates_url()
    {
        return $this->get_url(array(self::PARAM_ACTION => self::ACTION_BROWSE));
    }

    function get_export_url($export_template)
    {
        return $this->get_url(
            array(
                self::PARAM_ACTION => self::ACTION_EXPORT,
                self::PARAM_EXPORT_TEMPLATE_ID => $export_template->get_id()));
    }

    function get_export_template_create_url($export_registration)
    {
        return $this->get_url(
            array(
                self::PARAM_ACTION => self::ACTION_CREATE,
                self::PARAM_EXPORT_REGISTRATION_ID => $export_registration->get_id()));
    }

    function get_export_template_delete_url($export_template)
    {
        return $this->get_url(
            array(
                self::PARAM_ACTION => self::ACTION_DELETE,
                self::PARAM_EXPORT_TEMPLATE_ID => $export_template->get_id()));
    }

    function get_export_template_edit_url($export_template)
    {
        return $this->get_url(
            array(
                self::PARAM_ACTION => self::ACTION_EDIT,
                self::PARAM_EXPORT_TEMPLATE_ID => $export_template->get_id()));
    }

    function get_export_template_rights_editor_url($export_template)
    {
        return $this->get_url(
            array(
                self::PARAM_ACTION => self::ACTION_EDIT_EXPORT_RIGHTS,
                self::PARAM_EXPORT_TEMPLATE_ID => $export_template->get_id()));
    }

    function get_export_tracker_delete_url($export_tracker)
    {
        return $this->get_url(
            array(
                self::PARAM_ACTION => self::ACTION_DELETE_EXPORT_TRACKER,
                self::PARAM_EXPORT_TRACKER_ID => $export_tracker->get_id()));
    }

    function get_convert_answers_url($publication_id)
    {
        return $this->get_url(
            array(
                self::PARAM_ACTION => self::ACTION_CONVERT_ANSWERS,
                \Chamilo\Application\Survey\Manager::PARAM_PUBLICATION_ID => $publication_id));
    }
}


text:
describe('Test admin.js', function() {

	var $scope, AdminCtrl;
	if(firebase.apps.length === 0) {
		initalizeFirebase();
	}

	beforeEach(module('teamform-admin-app'));
	beforeEach(inject(function($rootScope, $controller) {
		console.log("admin test");
		// compile = $compile;
		$scope = $rootScope.$new();
		AdminCtrl = $controller('AdminCtrl', {$scope: $scope});
	}));

	// function getCompiledElement() {
	// 	var element = angular.element('<div login></div>');
	// 	var compiledElement = compile(element)($scope);
	// 	$scope.$digest();
	// 	return compiledElement;
	// }

	// it('should contain span.close', function() {
	// 	var spanElement = getCompiledElement().find('span.close');
	// 	expect(spanElement).toBeDefined();
	// 	expect(spanElement.text()).toEqual("×");
	// });

	it('test paramLoadedCallback', function() {
		$scope.param = {};
		$scope.paramLoadedCallback();
		expect($scope.paramTest).toEqual("maxUndefined minUndefined noAdmin");
	});

	it("test getMemberName", function() {
		$scope.users = [
			{ $id: "234", "name": "apple" },
			{ $id: "5486asd", "name": "hello" }
		];
		expect($scope.getMemberName("234")).toEqual("apple");
		expect($scope.getMemberName("5486asd")).toEqual("hello");
		expect($scope.getMemberName("id_not_exist")).toEqual("null");
	});

	it("test getTeamMember", function() {
		var team1 = [ "123", "456" ];
		var team2 = [ "wsdw45" ];
		$scope.users = [
			{ $id: "456", "name": "hello" },
			{ $id: "123", "name": "world" },
			{ $id: "wsdw45", "name": "bye" }
		];

		var ret1 = $scope.getTeamMember(team1);
		var ret2 = $scope.getTeamMember(team2);
		expect(ret1[0]).toEqual('world');
		expect(ret1[1]).toEqual('hello');
		expect(ret2[0]).toEqual('bye');
	});

	it("test smartAssignment", function() {
		$scope.param.minTeamSize = 1;
		$scope.param.maxTeamSize = 3;
		$scope.team = [
			{$id: "team1",
				"size" : 1,
				"teamMembers" : [ "exist4" ]},
			{$id: "team2",
				"size" : 2,
		        "teamMembers" : [ "exist2" ]
			},
			{$id: "team3",
				"size" : 2,
		        "teamMembers" : [ "exist1" ]
			}
		];
		$scope.member = [
			{ $id: "111", "weight": 8 },
			{ $id: "123", "weight": 1 },
			{ $id: "234", "weight": 5 },
			{ $id: "exist4", inTeam: "team1", "weight": 4 },
			{ $id: "exist2", inTeam: "team2", "weight": 2 },
			{ $id: "exist1", inTeam: "team3", "weight": 1 }
		];
		$scope.users = [
			{ $id: "111", "name": "111" },
			{ $id: "123", "name": "123" },
			{ $id: "234", "name": "234" },
			{ $id: "exist4", "name": "exist4" },
			{ $id: "exist2", "name": "exist2" },
			{ $id: "exist1", "name": "exist1" }
		];

		function calculatSum(teamMembers) {
			var sum = 0;
			for(var idx = 0; idx < teamMembers.length; idx++) {
				for(var tmpIdx = 0; tmpIdx < $scope.member.length; tmpIdx++) {
					if($scope.member[tmpIdx].$id == teamMembers[idx]) {
						sum += $scope.member[tmpIdx].weight;
						break;
					}
				}
			}
			return sum;
		}

		$scope.smartAssignment();
		// no new member for full team
		expect($scope.team[0].teamMembers.length).toEqual(1);
		expect($scope.team.length).toEqual(4);
		expect(calculatSum($scope.team[1].teamMembers)).toEqual(7);
		expect(calculatSum($scope.team[2].teamMembers)).toEqual(2);
		expect(calculatSum($scope.team[3].teamMembers)).toEqual(8);

		// test all members have a team
		var nbMemInTeam = 0;
		for(var idx = 0; idx < $scope.member.length; idx++) {
			if($scope.member[idx].inTeam) nbMemInTeam++;
		}
		expect(nbMemInTeam).toEqual($scope.member.length);
	});

	it("test changeMinTeamSize", function() {
		$scope.param.minTeamSize = 5;
		$scope.param.maxTeamSize = 10;
		$scope.changeMinTeamSize(1);
		expect($scope.param.minTeamSize).toEqual(6);

		$scope.changeMinTeamSize(-10);
		expect($scope.param.minTeamSize).toEqual(6);
	});

	it("test changeMaxTeamSize", function() {
		$scope.param.maxTeamSize = 3;
		$scope.param.minTeamSize = 1;
		$scope.changeMaxTeamSize(1);
		expect($scope.param.maxTeamSize).toEqual(4);

		$scope.changeMaxTeamSize(-10);
		expect($scope.param.maxTeamSize).toEqual(4);
	});

	it("test setExpanded", function() {
		$scope.expanded = false;
		$scope.setExpanded();
		expect($scope.expanded).toEqual(true);
	});

	it("test hasTeam true", function() {
		var member = {inTeam: "dummy"};
		expect($scope.hasTeam(member)).toEqual(true);
	});

	it("test hasTeam false", function() {
		var member = {weight: 10};
		expect($scope.hasTeam(member)).toEqual(false);
	});

	it("test willEnableSmartAssignment false", function() {
		$scope.member = [
			{$id: "member1", inTeam: "Team1"},
			{$id: "member3", inTeam: "Team2"},
			{$id: "member2", inTeam: "Team3"}
		]
		expect($scope.willEnableSmartAssignment()).toEqual(false);

		$scope.member = [{$id: "member1", inTeam: "Team1"}];
		expect($scope.willEnableSmartAssignment()).toEqual(false);
	});

	it("test willEnableSmartAssignment true", function() {
		$scope.member = [
			{$id: "member1", inTeam: "Team1"},
			{$id: "member3"}];
		expect($scope.willEnableSmartAssignment()).toEqual(true);
	});

	it("test getTotalWeight", function() {
		$scope.member = [
			{$id: "member1", weight: 5},
			{$id: "member3", weight: 12}];
		var team = ["member1", "member3"];
		expect($scope.getTotalWeight(team)).toEqual(17);

		team = ["member_not_exist"];
		expect($scope.getTotalWeight(team)).toEqual(0);
	});

});


text:
Component to visualize Top / Bottom Members with background colored value

Link to blog: Design Studio SDK: Data Bound Leader Board (Top/Bottom Selection)