text:
package org.apache.kafka.streams.kstream.internals;

import static java.time.Duration.ofMillis;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;

import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.TestInputTopic;
import org.apache.kafka.streams.TestOutputTopic;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.CogroupedKStream;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Grouped;
import org.apache.kafka.streams.kstream.KGroupedStream;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Named;
import org.apache.kafka.streams.kstream.SlidingWindows;
import org.apache.kafka.streams.kstream.TimeWindowedCogroupedKStream;
import org.apache.kafka.streams.kstream.TimeWindowedDeserializer;
import org.apache.kafka.streams.kstream.Windowed;
import org.apache.kafka.streams.state.WindowStore;
import org.apache.kafka.streams.test.TestRecord;
import org.apache.kafka.test.MockAggregator;
import org.apache.kafka.test.MockInitializer;
import org.apache.kafka.test.StreamsTestUtils;
import org.junit.Before;
import org.junit.Test;

@SuppressWarnings("deprecation")
public class SlidingWindowedCogroupedKStreamImplTest {

    private static final String TOPIC = "topic";
    private static final String TOPIC2 = "topic2";
    private static final String OUTPUT = "output";
    private static final long WINDOW_SIZE_MS = 500L;
    private final StreamsBuilder builder = new StreamsBuilder();

    private KGroupedStream<String, String> groupedStream;

    private TimeWindowedCogroupedKStream<String, String> windowedCogroupedStream;

    private final Properties props = StreamsTestUtils.getStreamsConfig(Serdes.String(), Serdes.String());

    @Before
    public void setup() {
        final KStream<String, String> stream = builder.stream(TOPIC, Consumed
                .with(Serdes.String(), Serdes.String()));
        final KStream<String, String> stream2 = builder.stream(TOPIC2, Consumed
                .with(Serdes.String(), Serdes.String()));

        groupedStream = stream.groupByKey(Grouped.with(Serdes.String(), Serdes.String()));
        final KGroupedStream<String, String> groupedStream2 = stream2.groupByKey(Grouped.with(Serdes.String(), Serdes.String()));
        final CogroupedKStream<String, String> cogroupedStream = groupedStream.cogroup(MockAggregator.TOSTRING_ADDER)
                .cogroup(groupedStream2, MockAggregator.TOSTRING_REMOVER);
        windowedCogroupedStream = cogroupedStream.windowedBy(SlidingWindows.withTimeDifferenceAndGrace(ofMillis(
            WINDOW_SIZE_MS), ofMillis(2000L)));
    }

    @Test
    public void shouldNotHaveNullInitializerOnAggregate() {
        assertThrows(NullPointerException.class, () ->  windowedCogroupedStream.aggregate(null));
    }

    @Test
    public void shouldNotHaveNullMaterializedOnTwoOptionAggregate() {
        assertThrows(NullPointerException.class, () ->  windowedCogroupedStream.aggregate(MockInitializer.STRING_INIT, (Materialized<String, String, WindowStore<Bytes, byte[]>>) null));
    }

    @Test
    public void shouldNotHaveNullNamedTwoOptionOnAggregate() {
        assertThrows(NullPointerException.class, () ->  windowedCogroupedStream.aggregate(MockInitializer.STRING_INIT, (Named) null));
    }

    @Test
    public void shouldNotHaveNullInitializerTwoOptionNamedOnAggregate() {
        assertThrows(NullPointerException.class, () ->  windowedCogroupedStream.aggregate(null, Named.as("test")));
    }

    @Test
    public void shouldNotHaveNullInitializerTwoOptionMaterializedOnAggregate() {
        assertThrows(NullPointerException.class, () ->  windowedCogroupedStream.aggregate(null, Materialized.as("test")));
    }

    @Test
    public void shouldNotHaveNullInitializerThreeOptionOnAggregate() {
        assertThrows(NullPointerException.class, () ->  windowedCogroupedStream.aggregate(null, Named.as("test"), Materialized.as("test")));
    }

    @Test
    public void shouldNotHaveNullMaterializedOnAggregate() {
        assertThrows(NullPointerException.class, () ->  windowedCogroupedStream.aggregate(MockInitializer.STRING_INIT, Named.as("Test"), null));
    }

    @Test
    public void shouldNotHaveNullNamedOnAggregate() {
        assertThrows(NullPointerException.class, () ->  windowedCogroupedStream.aggregate(MockInitializer.STRING_INIT, null, Materialized.as("test")));
    }

    @Test
    public void namedParamShouldSetName() {
        final StreamsBuilder builder = new StreamsBuilder();
        final KStream<String, String> stream = builder.stream(TOPIC, Consumed
                .with(Serdes.String(), Serdes.String()));
        groupedStream = stream.groupByKey(Grouped.with(Serdes.String(), Serdes.String()));
        groupedStream.cogroup(MockAggregator.TOSTRING_ADDER)
                .windowedBy(SlidingWindows.withTimeDifferenceAndGrace(ofMillis(WINDOW_SIZE_MS), ofMillis(2000L)))
                .aggregate(MockInitializer.STRING_INIT, Named.as("foo"));

        assertThat(builder.build().describe().toString(), equalTo(
                "Topologies:\n" +
                        "   Sub-topology: 0\n" +
                        "    Source: KSTREAM-SOURCE-0000000000 (topics: [topic])\n" +
                        "      --> foo-cogroup-agg-0\n" +
                        "    Processor: foo-cogroup-agg-0 (stores: [COGROUPKSTREAM-AGGREGATE-STATE-STORE-0000000001])\n" +
                        "      --> foo-cogroup-merge\n" +
                        "      <-- KSTREAM-SOURCE-0000000000\n" +
                        "    Processor: foo-cogroup-merge (stores: [])\n" +
                        "      --> none\n" +
                        "      <-- foo-cogroup-agg-0\n\n"));
    }

    @Test
    public void slidingWindowAggregateStreamsTest() {
        final KTable<Windowed<String>, String> customers = windowedCogroupedStream.aggregate(
                MockInitializer.STRING_INIT, Materialized.with(Serdes.String(), Serdes.String()));
        customers.toStream().to(OUTPUT);

        try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) {
            final TestInputTopic<String, String> testInputTopic = driver.createInputTopic(
                    TOPIC, new StringSerializer(), new StringSerializer());
            final TestOutputTopic<Windowed<String>, String> testOutputTopic = driver.createOutputTopic(
                    OUTPUT, new TimeWindowedDeserializer<>(new StringDeserializer(), WINDOW_SIZE_MS), new StringDeserializer());

            testInputTopic.pipeInput("k1", "A", 500);
            testInputTopic.pipeInput("k2", "A", 500);
            testInputTopic.pipeInput("k2", "A", 501);
            testInputTopic.pipeInput("k1", "A", 502);
            testInputTopic.pipeInput("k1", "B", 503);
            testInputTopic.pipeInput("k2", "B", 503);
            testInputTopic.pipeInput("k2", "B", 504);
            testInputTopic.pipeInput("k1", "B", 504);

            final List<TestRecord<Windowed<String>, String>> results = testOutputTopic.readRecordsToList();

            final List<TestRecord<Windowed<String>, String>> expected = new LinkedList<>();
            // k1-A-500
            expected.add(new TestRecord<>(new Windowed<>("k1", new TimeWindow(0L, 500L)), "0+A", null, 500L));
            // k2-A-500
            expected.add(new TestRecord<>(new Windowed<>("k2", new TimeWindow(0L, 500L)), "0+A", null, 500L));
            // k2-A-501
            expected.add(new TestRecord<>(new Windowed<>("k2", new TimeWindow(501L, 1001L)), "0+A", null, 501L));
            expected.add(new TestRecord<>(new Windowed<>("k2", new TimeWindow(1L, 501L)), "0+A+A", null, 501L));
            // k1-A-502
            expected.add(new TestRecord<>(new Windowed<>("k1", new TimeWindow(501L, 1001L)), "0+A", null, 502L));
            expected.add(new TestRecord<>(new Windowed<>("k1", new TimeWindow(2L, 502L)), "0+A+A", null, 502L));
            // k1-B-503
            expected.add(new TestRecord<>(new Windowed<>("k1", new TimeWindow(501L, 1001L)), "0+A+B", null, 503L));
            expected.add(new TestRecord<>(new Windowed<>("k1", new TimeWindow(503L, 1003L)), "0+B", null, 503L));
            expected.add(new TestRecord<>(new Windowed<>("k1", new TimeWindow(3L, 503L)), "0+A+A+B", null, 503L));
            // k2-B-503
            expected.add(new TestRecord<>(new Windowed<>("k2", new TimeWindow(501L, 1001L)), "0+A+B", null, 503L));
            expected.add(new TestRecord<>(new Windowed<>("k2", new TimeWindow(502L, 1002)), "0+B", null, 503L));
            expected.add(new TestRecord<>(new Windowed<>("k2", new TimeWindow(3L, 503L)), "0+A+A+B", null, 503L));
            // k2-B-504
            expected.add(new TestRecord<>(new Windowed<>("k2", new TimeWindow(502L, 1002L)), "0+B+B", null, 504L));
            expected.add(new TestRecord<>(new Windowed<>("k2", new TimeWindow(501L, 1001L)), "0+A+B+B", null, 504L));
            expected.add(new TestRecord<>(new Windowed<>("k2", new TimeWindow(504L, 1004L)), "0+B", null, 504L));
            expected.add(new TestRecord<>(new Windowed<>("k2", new TimeWindow(4L, 504L)), "0+A+A+B+B", null, 504L));
            // k1-B-504
            expected.add(new TestRecord<>(new Windowed<>("k1", new TimeWindow(503L, 1003L)), "0+B+B", null, 504L));
            expected.add(new TestRecord<>(new Windowed<>("k1", new TimeWindow(501L, 1001L)), "0+A+B+B", null, 504L));
            expected.add(new TestRecord<>(new Windowed<>("k1", new TimeWindow(504L, 1004L)), "0+B", null, 504L));
            expected.add(new TestRecord<>(new Windowed<>("k1", new TimeWindow(4L, 504L)), "0+A+A+B+B", null, 504L));

            assertEquals(expected, results);
        }
    }

    @Test
    public void slidingWindowAggregateOverlappingWindowsTest() {

        final KTable<Windowed<String>, String> customers = groupedStream.cogroup(MockAggregator.TOSTRING_ADDER)
                .windowedBy(SlidingWindows.withTimeDifferenceAndGrace(ofMillis(WINDOW_SIZE_MS), ofMillis(2000L))).aggregate(
                        MockInitializer.STRING_INIT, Materialized.with(Serdes.String(), Serdes.String()));
        customers.toStream().to(OUTPUT);

        try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) {
            final TestInputTopic<String, String> testInputTopic = driver.createInputTopic(
                    TOPIC, new StringSerializer(), new StringSerializer());
            final TestOutputTopic<Windowed<String>, String> testOutputTopic = driver.createOutputTopic(
                    OUTPUT, new TimeWindowedDeserializer<>(new StringDeserializer(), WINDOW_SIZE_MS), new StringDeserializer());

            testInputTopic.pipeInput("k1", "A", 500);
            testInputTopic.pipeInput("k2", "A", 500);
            testInputTopic.pipeInput("k1", "B", 750);
            testInputTopic.pipeInput("k2", "B", 750);
            testInputTopic.pipeInput("k2", "A", 1000L);
            testInputTopic.pipeInput("k1", "A", 1000L);

            // left window k1@500
            assertOutputKeyValueTimestamp(testOutputTopic, "k1", "0+A", 500);
            // left window k2@500
            assertOutputKeyValueTimestamp(testOutputTopic, "k2", "0+A", 500);
            // right window k1@500
            assertOutputKeyValueTimestamp(testOutputTopic, "k1", "0+B", 750);
            // left window k1@750
            assertOutputKeyValueTimestamp(testOutputTopic, "k1", "0+A+B", 750);
            // right window k2@500
            assertOutputKeyValueTimestamp(testOutputTopic, "k2", "0+B", 750);
            // left window k2@750
            assertOutputKeyValueTimestamp(testOutputTopic, "k2", "0+A+B", 750);
            // right window k2@500 update
            assertOutputKeyValueTimestamp(testOutputTopic, "k2", "0+B+A", 1000);
            // right window k2@750
            assertOutputKeyValueTimestamp(testOutputTopic, "k2", "0+A", 1000);
            // left window k2@1000
            assertOutputKeyValueTimestamp(testOutputTopic, "k2", "0+A+B+A", 1000);
            // right window k1@500 update
            assertOutputKeyValueTimestamp(testOutputTopic, "k1", "0+B+A", 1000);
            // right window k1@750
            assertOutputKeyValueTimestamp(testOutputTopic, "k1", "0+A", 1000);
            // left window k1@1000
            assertOutputKeyValueTimestamp(testOutputTopic, "k1", "0+A+B+A", 1000);
        }
    }

    private void assertOutputKeyValueTimestamp(final TestOutputTopic<Windowed<String>, String> outputTopic,
                                               final String expectedKey,
                                               final String expectedValue,
                                               final long expectedTimestamp) {
        final TestRecord<Windowed<String>, String> realRecord = outputTopic.readRecord();
        final TestRecord<String, String> nonWindowedRecord = new TestRecord<>(
                realRecord.getKey().key(), realRecord.getValue(), null, realRecord.timestamp());
        final TestRecord<String, String> testRecord = new TestRecord<>(expectedKey, expectedValue, null, expectedTimestamp);
        assertThat(nonWindowedRecord, equalTo(testRecord));
    }
}


text:
package com.xiaoshangxing.utils.runtimePermission;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;

/**
 * Created by Yan Zhenjie on 2016/12/28.
 */
class SettingExecutor implements SettingService {

    private Object object;
    private int requestCode;

    SettingExecutor(@NonNull Object mObject, int mRequestCode) {
        object = mObject;
        requestCode = mRequestCode;
    }

    private static void startForResult(Object object, Intent intent, int requestCode) {
        if (object instanceof Activity) {
            ((Activity) object).startActivityForResult(intent, requestCode);
        } else if (object instanceof android.support.v4.app.Fragment) {
            ((android.support.v4.app.Fragment) object).startActivityForResult(intent, requestCode);
        } else if (object instanceof android.app.Fragment) {
            ((android.app.Fragment) object).startActivityForResult(intent, requestCode);
        }
    }

    @Override
    public void execute() {
        Context context = PermissionUtils.getContext(object);
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
        intent.setData(uri);
        startForResult(object, intent, requestCode);
    }

    @Override
    public void cancel() {
    }

}

redpajama_set_name: RedPajamaGithub


text:
package gov.hhs.onc.sdcct.xml.jaxb.metadata.impl;

import com.sun.msv.grammar.xmlschema.SimpleTypeExp;
import gov.hhs.onc.sdcct.xml.jaxb.metadata.JaxbContextMetadata;
import gov.hhs.onc.sdcct.xml.jaxb.metadata.JaxbSchemaMetadata;
import gov.hhs.onc.sdcct.xml.jaxb.metadata.JaxbSimpleTypeMetadata;
import javax.annotation.Nullable;
import javax.xml.namespace.QName;

public class JaxbSimpleTypeMetadataImpl<T> extends AbstractJaxbTypeMetadata<SimpleTypeExp, T> implements JaxbSimpleTypeMetadata<T> {
    public JaxbSimpleTypeMetadataImpl(JaxbContextMetadata context, JaxbSchemaMetadata schema, SimpleTypeExp expr, String name, QName qname,
        @Nullable Class<T> beanClass, @Nullable Class<? extends T> beanImplClass) {
        super(context, schema, expr, name, qname, false, beanClass, beanImplClass);
    }
}


text:
ants
====
simple ants swarm simulation with opengl

build the project
--------------------------------------

clone the project by running
```bash
git clone git://github.com/etixsoftware/ants.git
```

install glut (OpenGL Utility Toolkit) if you use apt-get run following command
```bash
sudo apt-get install freeglut3 freeglut3-dev
```

build the project
```bash
cd ants && make all
```

run simulation with
```bash
./ants
```
control the simulation
--------------------------------------

```
(c) config
    (a) ants
        (n) count
            (number number of ants)
            (ENTER) -> return to config
    (f) food
        (n) count
            (number number of food)
            (ENTER) -> return to config
    (s) size of field
        (x) width
            (width)
            (ENTER) -> return to config
        (y) height
            (height)
            (ENTER) -> return to config
    (p) period
        (period)
        (ENTER)
(w) faster -10ms
(s) slower +10ms
(e) very fast
(q) quit
(h) halt on/off
(p) play
(r) reset
(d) debug on/off
```


text:
require 'chicago/schema/query_column'

module Chicago
  module Schema
    # Parses AST column representations, returning an Array of
    # QueryColumns.
    #
    # Columns can be simple dotted references, like
    #
    #     "sales.product.name"
    #
    # calculations like:
    #
    #     {:column => "sales.total", :op => "sum"}
    #
    # or pivoted calculations like:
    #
    #     {:column => "sales.total",
    #      :op => "sum"
    #      :pivot => "sales.date.year"}
    #
    class ColumnParser
      # Creates a new ColumnParser for a schema.
      def initialize(schema)
        @schema = schema
      end

      # Parses a column element. An element may be a string reference
      # like "foo.bar", or more complicated like {:column =>
      # "foo.bar", :op => "sum"}
      #
      # @return [Array<Column>] an array of columns. In most cases
      #   this will be a 1-element array, unless the column is
      #   pivoted.
      def parse(elem)
        [_parse(elem)].flatten
      end

      protected

      # Returns an Array of values, given a column to pivot with.
      #
      # May be overridden by subclasses.
      #
      # @raise UnimplementedError if a column with unknown or too many
      #   elements is used as a pivot column. In future this
      #   restriction may be lifted.
      def pivotable_elements(pivot_col)
        if pivot_col.column_type == :boolean
          [true, false]
        elsif pivot_col.elements
          pivot_col.elements
        elsif has_pivotable_integer_range?(pivot_col)
          (pivot_col.min..pivot_col.max).to_a
        else
          raise UnimplementedError.new("General pivoting not yet support")
        end
      end

      # Returns true if an Integer column can be used as pivot column.
      #
      # Default is to allow columns with a range 500 wide or less to
      # be used as pivot columns.
      #
      # May be overridden by subclasses
      #
      # @return Boolean true if this column can be pivoted.
      def has_pivotable_integer_range?(pivot_col)
        pivot_col.column_type == :integer &&
          pivot_col.max &&
          pivot_col.min &&
          (pivot_col.max - pivot_col.min <= 500)
      end

      private

      def _parse(elem)
        elem.kind_of?(Hash) ? complex_column(elem) : simple_column(elem)
      end

      def complex_column(elem)
        elem.symbolize_keys!
        elem[:pivot] ? pivoted_column(elem) : calculated_column(elem)
      end

      def pivoted_column(elem)
        pivoted_column = _parse(elem[:column])
        pivoted_by = _parse(elem[:pivot])
        unit = [:avg, :count].include?(elem[:op].to_sym) ? nil : 0
        pivoted_column.pivot(pivoted_by, pivotable_elements(pivoted_by), unit).map do |c|
          c.calculate(elem[:op].to_sym)
        end
      end

      def simple_column(elem)
        table, col, table_qualifier = parse_parts(elem)
        QueryColumn.column(table, col, elem.to_sym, table_qualifier)
      end

      def calculated_column(elem)
        col = _parse(elem[:column])
        elem[:op] ? col.calculate(elem[:op].to_sym) : col
      end

      def parse_parts(str)
        table, parts = parse_table(str)
        col = table[parts.shift]
        # To cope with bare dimension references.
        col = table.original_key if col.nil?

        if col.kind_of?(Chicago::Schema::Dimension)
          table = col
          col = parts.empty? ? table : table[parts.first]
          table_qualifier = table.label if table.roleplayed?
        end

        [table, col, table_qualifier]
      end

      def parse_table(str)
        parts = str.split('.').map(&:to_sym)
        root = parts.shift
        table = @schema.fact(root) || @schema.dimension(root)
        [table, parts]
      end
    end
  end
end


text:
.class Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;
.super Landroid/content/BroadcastReceiver;
.source "WifiApDialogSec.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/samsung/android/settings/wifi/WifiApDialogSec;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

# direct methods
.method constructor <init>(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)V
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V

    return-void
.end method

# virtual methods
.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
    .locals 8

    const v7, 0x1090009

    const v6, 0x1090008

    const/4 v5, 0x1

    const/4 v4, 0x0

    const-string/jumbo v3, "plugged"

    invoke-virtual {p2, v3, v4}, Landroid/content/Intent;->getIntExtra(Ljava/lang/String;I)I

    move-result v2

    if-ne v2, v5, :cond_3

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-wrap0(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)Z

    move-result v3

    if-eqz v3, :cond_3

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3, v5}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-set0(Lcom/samsung/android/settings/wifi/WifiApDialogSec;I)I

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    iget-object v4, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get10(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v4

    iget-object v5, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v5}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get11(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v5

    add-int/2addr v4, v5

    new-array v4, v4, [Ljava/lang/String;

    invoke-static {v3, v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-set5(Lcom/samsung/android/settings/wifi/WifiApDialogSec;[Ljava/lang/String;)[Ljava/lang/String;

    const/4 v1, 0x0

    :goto_0
    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get10(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v3

    if-ge v1, v3, :cond_0

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get20(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)[Ljava/lang/String;

    move-result-object v3

    iget-object v4, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get21(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)[Ljava/lang/String;

    move-result-object v4

    aget-object v4, v4, v1

    aput-object v4, v3, v1

    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    :cond_0
    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get11(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v3

    if-lez v3, :cond_1

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get10(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v1

    :goto_1
    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get10(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v3

    iget-object v4, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get11(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v4

    add-int/2addr v3, v4

    if-ge v1, v3, :cond_1

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get20(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)[Ljava/lang/String;

    move-result-object v3

    iget-object v4, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get22(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)[Ljava/lang/String;

    move-result-object v4

    iget-object v5, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v5}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get10(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v5

    sub-int v5, v1, v5

    aget-object v4, v4, v5

    aput-object v4, v3, v1

    add-int/lit8 v1, v1, 0x1

    goto :goto_1

    :cond_1
    new-instance v0, Landroid/widget/ArrayAdapter;

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get6(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)Landroid/content/Context;

    move-result-object v3

    iget-object v4, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get20(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)[Ljava/lang/String;

    move-result-object v4

    invoke-direct {v0, v3, v6, v4}, Landroid/widget/ArrayAdapter;-><init>(Landroid/content/Context;I[Ljava/lang/Object;)V

    invoke-virtual {v0, v7}, Landroid/widget/ArrayAdapter;->setDropDownViewResource(I)V

    :cond_2
    :goto_2
    return-void

    :cond_3
    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3, v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-set0(Lcom/samsung/android/settings/wifi/WifiApDialogSec;I)I

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get11(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v3

    if-lez v3, :cond_5

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    iget-object v4, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get11(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v4

    new-array v4, v4, [Ljava/lang/String;

    invoke-static {v3, v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-set5(Lcom/samsung/android/settings/wifi/WifiApDialogSec;[Ljava/lang/String;)[Ljava/lang/String;

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get10(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v1

    :goto_3
    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get10(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v3

    iget-object v4, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get11(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v4

    add-int/2addr v3, v4

    if-ge v1, v3, :cond_4

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get20(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)[Ljava/lang/String;

    move-result-object v3

    iget-object v4, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get22(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)[Ljava/lang/String;

    move-result-object v4

    aget-object v4, v4, v1

    aput-object v4, v3, v1

    add-int/lit8 v1, v1, 0x1

    goto :goto_3

    :cond_4
    new-instance v0, Landroid/widget/ArrayAdapter;

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get6(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)Landroid/content/Context;

    move-result-object v3

    iget-object v4, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get20(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)[Ljava/lang/String;

    move-result-object v4

    invoke-direct {v0, v3, v6, v4}, Landroid/widget/ArrayAdapter;-><init>(Landroid/content/Context;I[Ljava/lang/Object;)V

    invoke-virtual {v0, v7}, Landroid/widget/ArrayAdapter;->setDropDownViewResource(I)V

    goto :goto_2

    :cond_5
    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get1(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)Landroid/widget/RadioButton;

    move-result-object v3

    invoke-virtual {v3}, Landroid/widget/RadioButton;->isChecked()Z

    move-result v3

    if-eqz v3, :cond_2

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get0(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)Landroid/widget/RadioButton;

    move-result-object v3

    invoke-virtual {v3, v5}, Landroid/widget/RadioButton;->setChecked(Z)V

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get1(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)Landroid/widget/RadioButton;

    move-result-object v3

    invoke-virtual {v3, v4}, Landroid/widget/RadioButton;->setChecked(Z)V

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get3(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)Landroid/widget/Spinner;

    move-result-object v3

    invoke-virtual {v3, v4}, Landroid/widget/Spinner;->setVisibility(I)V

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get5(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)Landroid/widget/TextView;

    move-result-object v3

    invoke-virtual {v3, v4}, Landroid/widget/TextView;->setVisibility(I)V

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get4(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)Landroid/widget/TextView;

    move-result-object v3

    const/16 v4, 0x8

    invoke-virtual {v3, v4}, Landroid/widget/TextView;->setVisibility(I)V

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get9(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v3

    sput v3, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->mSelectedChannel:I

    sget-boolean v3, Lcom/android/settings/Utils;->SUPPORT_MOBILEAP_5G_BASED_ON_COUNTRY:Z

    if-eqz v3, :cond_6

    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get3(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)Landroid/widget/Spinner;

    move-result-object v3

    iget-object v4, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v4}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get9(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)I

    move-result v4

    invoke-virtual {v3, v4}, Landroid/widget/Spinner;->setSelection(I)V

    goto/16 :goto_2

    :cond_6
    iget-object v3, p0, Lcom/samsung/android/settings/wifi/WifiApDialogSec$1;->this$0:Lcom/samsung/android/settings/wifi/WifiApDialogSec;

    invoke-static {v3}, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->-get3(Lcom/samsung/android/settings/wifi/WifiApDialogSec;)Landroid/widget/Spinner;

    move-result-object v3

    sget v4, Lcom/samsung/android/settings/wifi/WifiApDialogSec;->mSelectedChannel:I

    invoke-virtual {v3, v4}, Landroid/widget/Spinner;->setSelection(I)V

    goto/16 :goto_2
.end method


text:
    background-image: url(../images/icon-64.png);
    background-size: 32px 32px;
}


text:
using Microsoft.EntityFrameworkCore;
using Scacchi.Modello;

namespace Scacchi.Servizi{
    public class DataBase : DbContext{
        public DataBase() : base()
        {
            this.Database.EnsureCreated();
        }
        public DbSet<Mossa> Mosse {get;set;}
         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
             optionsBuilder.UseSqlite(@"Data Source=..\..\..\Database.db");
         }
         protected override void OnModelCreating(ModelBuilder modelBuilder) {
             modelBuilder.Entity<Mossa>().ToTable("Mosse").HasKey(p => p.IdMossa);
         }
    }
}


text:
'use strict'

const packageJson = require('../../package.json')
const paths = require('../../config/paths.json')
const packageName = require('../../gulpfile.js').packageName

const gulp = require('gulp')
const rename = require('gulp-rename')
const runSequence = require('run-sequence')
const run = require('gulp-run')
const del = require('del')

gulp.task('package:gem', cb => {
  runSequence('package:gem:prepare', 'package:gem:build', 'package:gem:tgz', 'package:gem:copy', 'package:gem:clean', cb)
})

gulp.task('package:gem:prepare', () => {
  gulp.src(paths.bundleCss + '**/*').pipe(gulp.dest(paths.gemCss))
  gulp.src(paths.bundleImg + '**/*').pipe(gulp.dest(paths.gemImg))
  gulp.src(paths.bundleScss + '**/*').pipe(gulp.dest(paths.gemScss))
  gulp.src(paths.bundleJs + '**/*').pipe(gulp.dest(paths.gemJs))
  gulp.src(paths.bundleTemplates + '**/*').pipe(gulp.dest(paths.gemTemplates))

  gulp.src(paths.bundleComponents + '**/*')
    .pipe(rename(path => {
    // Partials files require a _ prefix, and use underscores, not dashes
      path.basename = '_' + path.basename.replace(/-/g, '_')
    }))
    .pipe(gulp.dest(paths.gemComponents))

  gulp.src(`lib/packaging/gem/${packageJson.name}.gemspec`).pipe(gulp.dest(paths.gem))
  gulp.src('lib/packaging/gem/lib/govuk_frontend_alpha.rb').pipe(gulp.dest(paths.gemLib))
  return gulp.src('package.json').pipe(gulp.dest(paths.gemConfig))
})

gulp.task('package:gem:tgz', () => {
  run(`tar -czf ${paths.pkg}${packageName}-gem.tgz -C ${paths.gem} .`).exec()
})

gulp.task('package:gem:build', () => run(`cd ${paths.gem} && gem build ${packageJson.name}.gemspec`).exec())
gulp.task('package:gem:copy', () => gulp.src(`${paths.gem}${packageName}.gem`).pipe(gulp.dest(paths.pkg)))
gulp.task('package:gem:clean', () => del(`${paths.gem}${packageName}.gem`))


text:
This inspection reports any instances of Groovy if
statements with identical "then" and else branches. Such statements are almost certainly
programmer error.

Powered by InspectorGroovy


text:
- Add support for Ruby 3.1
- Add `rubygems_mfa_required`

## 1.4.3 (2021-12-03)
- Source code metadata url added to the gemspec
- Fixed MIT-LICENSE content

## 1.4.2 (2021-11-29)
- Update homepage and source code reference
- Fix the license content

## 1.4.1 (2021-04-21)
- Re-license with MIT
- Remove Ruby 2.5 support and update minimum Ruby requirement to 2.6

## 1.4.0 (2020-09-05)
- 1.4 release without any changes to match Karafka releases versioning

## 1.3.1 (2020-04-28)
- Ruby 2.6.5 support
- Ruby 2.7.1 support
- Drop support for Ruby < 2.5
- Change license to LGPL-3.0

## 1.3.0 (2019-09-09)
- Final `1.3.0` release

## 1.3.0.rc1 (2019-07-31)
- Ruby 2.6.3 support
- Support for Karafka 1.3

## 1.2.0
- Ruby 2.4.2 support
- Ruby 2.5.0 support

## 1.1.0
- Support of Karafka 0.6+
- Support of multiple Karafka processes execution
- Support of multiple Karafka servers deployment
- Support for specifying customer groups, including multi-role customer groups execution

## 1.0.0

- Gem init
- Capistrano integration via #install_plugin
- Code quality remarks


text:
Given /^I have an application token$/ do
  application = FactoryGirl.create :application

  header  'Authorization',
          ActionController::HttpAuthentication::Token.encode_credentials(application.token)
end

When /^I try to access secure data$/ do
  get domains_url
end

Then /^I must be able to view the data$/ do
  expect(last_response.status).to eql 200
end

Then /^I must not be able to view the data$/ do
  expect(last_response.status).to eql 404
end


text:
package org.terasology.logic.characters.events;

import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.network.NetworkEvent;
import org.terasology.network.ServerEvent;

/**
 * @author Immortius
 */
@ServerEvent(lagCompensate = true)
public class AttackRequest extends NetworkEvent {

    private EntityRef item = EntityRef.NULL;

    protected AttackRequest() {
    }

    public AttackRequest(EntityRef withItem) {
        this.item = withItem;
    }

    public EntityRef getItem() {
        return item;
    }
}


text:
/* shifter should be able to split this up into separate modules */

YUI.add('bar', function (Y, NAME) {
    Y[NAME] = 1;
}, 'something', { requires: ['foo'] });

YUI.add('baz', function (Y, NAME) {
    Y[NAME] = 2;
}, 'something', { requires: ['bar'] });


text:
import   re, os, zipfile, shutil
from anki.lang import _
from anki.utils import  ids2str, splitFields, json
from anki.hooks import runHook
from anki import Collection

class Exporter(object):
    def __init__(self, col, did=None):
        self.col = col
        self.did = did

    def exportInto(self, path):
        self._escapeCount = 0
        file = open(path, "wb")
        self.doExport(file)
        file.close()

    def escapeText(self, text):
        "Escape newlines, tabs, CSS and quotechar."
        # fixme: we should probably quote fields with newlines
        # instead of converting them to spaces
        text = text.replace("\n", " ")
        text = text.replace("\t", " " * 8)
        text = re.sub("(?i)<style>.*?</style>", "", text)
        if "\"" in text:
            text = "\"" + text.replace("\"", "\"\"") + "\""
        return text

    def cardIds(self):
        if not self.did:
            cids = self.col.db.list("select id from cards")
        else:
            cids = self.col.decks.cids(self.did, children=True)
        self.count = len(cids)
        return cids

# Cards as TSV
######################################################################

class TextCardExporter(Exporter):

    key = _("Cards in Plain Text")
    ext = ".txt"
    hideTags = True

    def __init__(self, col):
        Exporter.__init__(self, col)

    def doExport(self, file):
        ids = sorted(self.cardIds())
        strids = ids2str(ids)
        def esc(s):
            # strip off the repeated question in answer if exists
            s = re.sub("(?si)^.*<hr id=answer>\n*", "", s)
            return self.escapeText(s)
        out = ""
        for cid in ids:
            c = self.col.getCard(cid)
            out += esc(c.q())
            out += "\t" + esc(c.a()) + "\n"
        file.write(out.encode("utf-8"))

# Notes as TSV
######################################################################

class TextNoteExporter(Exporter):

    key = _("Notes in Plain Text")
    ext = ".txt"

    def __init__(self, col):
        Exporter.__init__(self, col)
        self.includeID = False
        self.includeTags = True

    def doExport(self, file):
        cardIds = self.cardIds()
        data = []
        for id, flds, tags in self.col.db.execute("""
select guid, flds, tags from notes
where id in
(select nid from cards
where cards.id in %s)""" % ids2str(cardIds)):
            row = []
            # note id
            if self.includeID:
                row.append(str(id))
            # fields
            row.extend([self.escapeText(f) for f in splitFields(flds)])
            # tags
            if self.includeTags:
                row.append(tags.strip())
            data.append("\t".join(row))
        self.count = len(data)
        out = "\n".join(data)
        file.write(out.encode("utf-8"))

# Anki decks
######################################################################
# media files are stored in self.mediaFiles, but not exported.

class AnkiExporter(Exporter):

    key = _("Anki 2.0 Deck")
    ext = ".anki2"

    def __init__(self, col):
        Exporter.__init__(self, col)
        self.includeSched = False
        self.includeMedia = True

    def exportInto(self, path):
        # create a new collection at the target
        try:
            os.unlink(path)
        except (IOError, OSError):
            pass
        self.dst = Collection(path)
        self.src = self.col
        # find cards
        if not self.did:
            cids = self.src.db.list("select id from cards")
        else:
            cids = self.src.decks.cids(self.did, children=True)
        # copy cards, noting used nids
        nids = {}
        data = []
        for row in self.src.db.execute(
            "select * from cards where id in "+ids2str(cids)):
            nids[row[1]] = True
            data.append(row)
        self.dst.db.executemany(
            "insert into cards values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
            data)
        # notes
        strnids = ids2str(nids.keys())
        notedata = []
        for row in self.src.db.all(
            "select * from notes where id in "+strnids):
            # remove system tags if not exporting scheduling info
            if not self.includeSched:
                row = list(row)
                row[5] = self.removeSystemTags(row[5])
            notedata.append(row)
        self.dst.db.executemany(
            "insert into notes values (?,?,?,?,?,?,?,?,?,?,?)",
            notedata)
        # models used by the notes
        mids = self.dst.db.list("select distinct mid from notes where id in "+
                                strnids)
        # card history and revlog
        if self.includeSched:
            data = self.src.db.all(
                "select * from revlog where cid in "+ids2str(cids))
            self.dst.db.executemany(
                "insert into revlog values (?,?,?,?,?,?,?,?,?)",
                data)
        else:
            # need to reset card state
            self.dst.sched.resetCards(cids)
        # models - start with zero
        self.dst.models.models = {}
        for m in self.src.models.all():
            if int(m['id']) in mids:
                self.dst.models.update(m)
        # decks
        if not self.did:
            dids = []
        else:
            dids = [self.did] + [
                x[1] for x in self.src.decks.children(self.did)]
        dconfs = {}
        for d in self.src.decks.all():
            if str(d['id']) == "1":
                continue
            if dids and d['id'] not in dids:
                continue
            if not d['dyn'] and d['conf'] != 1:
                if self.includeSched:
                    dconfs[d['conf']] = True
            if not self.includeSched:
                # scheduling not included, so reset deck settings to default
                d = dict(d)
                d['conf'] = 1
            self.dst.decks.update(d)
        # copy used deck confs
        for dc in self.src.decks.allConf():
            if dc['id'] in dconfs:
                self.dst.decks.updateConf(dc)
        # find used media
        media = {}
        self.mediaDir = self.src.media.dir()
        if self.includeMedia:
            for row in notedata:
                flds = row[6]
                mid = row[2]
                for file in self.src.media.filesInStr(mid, flds):
                    media[file] = True
            if self.mediaDir:
                for fname in os.listdir(self.mediaDir):
                    if fname.startswith("_"):
                        # Scan all models in mids for reference to fname
                        for m in self.src.models.all():
                            if int(m['id']) in mids:
                                if self._modelHasMedia(m, fname):
                                    media[fname] = True
                                    break
        self.mediaFiles = media.keys()
        self.dst.crt = self.src.crt
        # todo: tags?
        self.count = self.dst.cardCount()
        self.dst.setMod()
        self.postExport()
        self.dst.close()

    def postExport(self):
        # overwrite to apply customizations to the deck before it's closed,
        # such as update the deck description
        pass

    def removeSystemTags(self, tags):
        return self.src.tags.remFromStr("marked leech", tags)

    def _modelHasMedia(self, model, fname):
        # First check the styling
        if fname in model["css"]:
            return True
        # If no reference to fname then check the templates as well
        for t in model["tmpls"]:
            if fname in t["qfmt"] or fname in t["afmt"]:
                return True
        return False

# Packaged Anki decks
######################################################################

class AnkiPackageExporter(AnkiExporter):

    key = _("Anki Deck Package")
    ext = ".apkg"

    def __init__(self, col):
        AnkiExporter.__init__(self, col)

    def exportInto(self, path):
        # open a zip file
        z = zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED, allowZip64=True)
        # if all decks and scheduling included, full export
        if self.includeSched and not self.did:
            media = self.exportVerbatim(z)
        else:
            # otherwise, filter
            media = self.exportFiltered(z, path)
        # media map
        z.writestr("media", json.dumps(media))
        z.close()

    def exportFiltered(self, z, path):
        # export into the anki2 file
        colfile = path.replace(".apkg", ".anki2")
        AnkiExporter.exportInto(self, colfile)
        z.write(colfile, "collection.anki2")
        # and media
        self.prepareMedia()
        media = {}
        for c, file in enumerate(self.mediaFiles):
            cStr = str(c)
            mpath = os.path.join(self.mediaDir, file)
            if os.path.exists(mpath):
                z.write(mpath, cStr, zipfile.ZIP_STORED)
                media[cStr] = file
                runHook("exportedMediaFiles", c)
        # tidy up intermediate files
        os.unlink(colfile)
        p = path.replace(".apkg", ".media.db2")
        if os.path.exists(p):
            os.unlink(p)
        os.chdir(self.mediaDir)
        shutil.rmtree(path.replace(".apkg", ".media"))
        return media

    def exportVerbatim(self, z):
        # close our deck & write it into the zip file, and reopen
        self.count = self.col.cardCount()
        self.col.close()
        z.write(self.col.path, "collection.anki2")
        self.col.reopen()
        # copy all media
        if not self.includeMedia:
            return {}
        media = {}
        mdir = self.col.media.dir()
        for c, file in enumerate(os.listdir(mdir)):
            cStr = str(c)
            mpath = os.path.join(mdir, file)
            if os.path.exists(mpath):
                z.write(mpath, cStr, zipfile.ZIP_STORED)
                media[cStr] = file
                runHook("exportedMediaFiles", c)

        return media

    def prepareMedia(self):
        # chance to move each file in self.mediaFiles into place before media
        # is zipped up
        pass

# Export modules
##########################################################################

def exporters():
    def id(obj):
        return ("%s (*%s)" % (obj.key, obj.ext), obj)
    exps = [
        id(AnkiPackageExporter),
        id(TextNoteExporter),
        id(TextCardExporter),
    ]
    runHook("exportersList", exps)
    return exps


text:
<?php

defined('_JEXEC') or die('Restricted access');

	class UniteElementsBaseUG{

		protected $db;
		protected $imageView;

		public function __construct(){

			$this->db = new UniteGalleryDB();
			$this->imageView = new UniteImageViewUG();

		}

	}

?>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Passerina uniflora Drege ex Meisn.

### Remarks
null


text:
extern byte end[];
static byte *bloc = { end };
static Lock memlock;

enum
{
	Round = PAGESIZE-1
};

void*
runtime·SysAlloc(uintptr nbytes, uint64 *stat)
{
	uintptr bl;

	runtime·lock(&memlock);
	// Plan 9 sbrk from /sys/src/libc/9sys/sbrk.c
	bl = ((uintptr)bloc + Round) & ~Round;
	if(runtime·brk_((void*)(bl + nbytes)) < 0) {
		runtime·unlock(&memlock);
		return nil;
	}
	bloc = (byte*)bl + nbytes;
	runtime·unlock(&memlock);
	runtime·xadd64(stat, nbytes);
	return (void*)bl;
}

void
runtime·SysFree(void *v, uintptr nbytes, uint64 *stat)
{
	runtime·xadd64(stat, -(uint64)nbytes);
	runtime·lock(&memlock);
	// from tiny/mem.c
	// Push pointer back if this is a free
	// of the most recent SysAlloc.
	nbytes += (nbytes + Round) & ~Round;
	if(bloc == (byte*)v+nbytes)
		bloc -= nbytes;
	runtime·unlock(&memlock);
}

void
runtime·SysUnused(void *v, uintptr nbytes)
{
	USED(v, nbytes);
}

void
runtime·SysUsed(void *v, uintptr nbytes)
{
	USED(v, nbytes);
}

void
runtime·SysMap(void *v, uintptr nbytes, bool reserved, uint64 *stat)
{
	USED(v, nbytes, reserved, stat);
}

void
runtime·SysFault(void *v, uintptr nbytes)
{
	USED(v, nbytes);
}

void*
runtime·SysReserve(void *v, uintptr nbytes, bool *reserved)
{
	USED(v);
	*reserved = true;
	return runtime·SysAlloc(nbytes, &mstats.heap_sys);
}


text:
include(CheckCXXCompilerFlag)

macro (DEFINE_CXX_11_COMPILER_FLAG _RESULT)
  if(NOT DEFINED "${_RESULT}")

    if(NOT CMAKE_REQUIRED_QUIET)
      message(STATUS "Performing C++11 Test")
    endif()

    # Check for default argument (all newer compilers)
    CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
    if(COMPILER_SUPPORTS_CXX11)
      set(${_RESULT} "-std=c++11" CACHE INTERNAL "C++11 flag")
    else()
      # Check for older version (before 2011)
      CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
      if(COMPILER_SUPPORTS_CXX0X)
	set(${_RESULT} "-std=c++0x" CACHE INTERNAL "C++11 flag")
      else()
	message(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
      endif()
    endif()

  endif()
endmacro()


text:
using namespace dvu;

window::window(const dvu::string& caption, unsigned int x, unsigned int y, unsigned int width, unsigned int height) : with_reference(SDL_CreateWindow(caption.c_str(), x, y, width, height, SDL_WINDOW_OPENGL))
{
	if (ref == nullptr)
	{
		dvu::event_manager::fire_event(DVU_EVENT_ERROR, "Error creating window!");
		throw std::exception(SDL_GetError());
	}
	else
	{
		dvu::event_manager::fire_event(DVU_EVENT_WINDOW_CREATED);
		event_manager::fire_event(DVU_EVENT_LOG, (boost::format("Window: %d created") % id()).str().c_str());
	}
}

window::window(const dvu::string& caption, unsigned int width, unsigned int height) : window(caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height)
{
}

window::~window()
{
	if (ref != nullptr)
		SDL_DestroyWindow(reinterpret_cast<SDL_Window*>(ref));
	dvu::event_manager::fire_event(DVU_EVENT_WINDOW_DESTROYED);
}

void window::set_screensaver(bool enabled)
{
	if (enabled)
	{
		SDL_EnableScreenSaver();
		dvu::event_manager::fire_event(DVU_EVENT_SCREENSAVER_ENABLED);
	}
	else
	{
		SDL_DisableScreenSaver();
		dvu::event_manager::fire_event(DVU_EVENT_SCREENSAVER_DISABLED);
	}
}

void window::set_visibility(bool show) const
{
	if (show)
	{
		SDL_ShowWindow(reinterpret_cast<SDL_Window*>(ref));
	}
	else
	{
		SDL_HideWindow(reinterpret_cast<SDL_Window*>(ref));
	}
}

int window::message_box(const dvu::string& caption, const dvu::string& text, message_box_type type, std::initializer_list<dvu::string> buttons) const
{
	int ret = 0;
	SDL_MessageBoxData data;
	data.colorScheme = nullptr;
	data.numbuttons = buttons.size();

	SDL_MessageBoxButtonData* button_data_array = new SDL_MessageBoxButtonData[data.numbuttons];
	for (int i = buttons.size() - 1; i >= 0; i--)
	{
		button_data_array[buttons.size() - i - 1] = { 0, i, (buttons.begin() + i)->c_str() };
	}
	data.buttons = button_data_array;

	data.window = reinterpret_cast<SDL_Window*>(ref);
	data.flags = static_cast<unsigned int>(type);
	data.title = caption.c_str();
	data.message = text.c_str();
	SDL_ShowMessageBox(&data, &ret);
	dvu::event_manager::fire_event(DVU_EVENT_MESSAGE_BOX_CREATED);
	delete[] data.buttons;
	return ret;
}

dvu::string window::get_caption() const
{
	return dvu::string(SDL_GetWindowTitle(reinterpret_cast<SDL_Window*>(ref)));
}

void window::set_caption(const dvu::string& caption) const
{
	SDL_SetWindowTitle(reinterpret_cast<SDL_Window*>(ref), caption.c_str());
}

int window::get_width() const
{
	int w;
	SDL_GetWindowSize(reinterpret_cast<SDL_Window*>(ref), &w, nullptr);
	return w;
}

int window::get_height() const
{
	int h;
	SDL_GetWindowSize(reinterpret_cast<SDL_Window*>(ref), nullptr, &h);
	return h;
}

void window::set_size(unsigned int width, unsigned int height) const
{
	SDL_SetWindowSize(reinterpret_cast<SDL_Window*>(ref), width, height);
}

void window::set_fullscreen(bool full) const
{
	if (full)
	{
		SDL_SetWindowFullscreen(reinterpret_cast<SDL_Window*>(ref), SDL_WINDOW_FULLSCREEN);
		dvu::event_manager::fire_event(DVU_EVENT_FULLSCREEN_ENABLED);
	}
	else
	{
		SDL_SetWindowFullscreen(reinterpret_cast<SDL_Window*>(ref), 0);
		dvu::event_manager::fire_event(DVU_EVENT_FULLSCREEN_DISABLED);
	}
}

unsigned int window::id() const
{
	return SDL_GetWindowID(reinterpret_cast<SDL_Window*>(ref));
}

void window::show_cursor(bool show)
{
	SDL_ShowCursor(static_cast<int>(show));
}

void window::set_cursor_position(int x, int y) const
{
	SDL_WarpMouseInWindow(reinterpret_cast<SDL_Window*>(ref), x, y);
}

bool window::get_key_state(unsigned int key)
{
	return (SDL_GetKeyboardState(nullptr)[key] != 0);
}

bool window::get_key_state(key k)
{
	return get_key_state(static_cast<unsigned int>(k));
}

int window::get_ticks()
{
	return SDL_GetTicks();
}


text:
maki
====

Markdown wiki


text:
package Google::Ads::Common::OAuth2ServiceAccountsHandler;

use strict;
use warnings;
use version;
use base qw(Google::Ads::Common::OAuth2BaseHandler);

# The following needs to be on one line because CPAN uses a particularly hacky
# eval() to determine module versions.
use Google::Ads::Common::Constants; our $VERSION = ${Google::Ads::Common::Constants::VERSION};

use Crypt::OpenSSL::RSA;
use HTTP::Request;
use JSON::Parse qw(parse_json);
use LWP::UserAgent;
use MIME::Base64 qw(encode_base64 decode_base64);
use utf8;

use constant OAUTH2_BASE_URL => "https://accounts.google.com/o/oauth2";

# Class::Std-style attributes. Need to be kept in the same line.
# These need to go in the same line for older Perl interpreters to understand.
my %email_address_of : ATTR(:name<email_address> :default<>);
my %delegated_email_address_of :
  ATTR(:name<delegated_email_address> :default<>);
my %additional_scopes_of : ATTR(:name<additional_scopes> :default<>);
my %pem_file_of : ATTR(:name<pem_file> :default<>);
my %json_file_of : ATTR(:name<json_file> :default<>);
my %__crypt_module_of : ATTR(:name<__crypt_module> :default<>);

# Constructor
sub START {
  my ($self, $ident) = @_;

  $__crypt_module_of{$ident} ||= "Crypt::OpenSSL::RSA";
}

sub initialize : CUMULATIVE(BASE FIRST) {
  my ($self, $api_client, $properties) = @_;
  my $ident = ident $self;

  $email_address_of{$ident} = $properties->{oAuth2ServiceAccountEmailAddress}
    || $email_address_of{$ident};
  $delegated_email_address_of{$ident} =
       $properties->{oAuth2ServiceAccountDelegateEmailAddress}
    || $delegated_email_address_of{$ident};
  $pem_file_of{$ident} = $properties->{oAuth2ServiceAccountPEMFile}
    || $pem_file_of{$ident};
  $json_file_of{$ident} = $properties->{oAuth2ServiceAccountJSONFile}
    || $json_file_of{$ident};
  $additional_scopes_of{$ident} = $properties->{oAuth2AdditionalScopes}
    || $additional_scopes_of{$ident};
}

sub _refresh_access_token {
  my $self = shift;

  if ($self->get_json_file() and $self->get_pem_file()) {
    warn("Only one of oAuth2ServiceAccountPEMFile or " .
    "oAuth2ServiceAccountJSONFile can be specified in adwords.properties.");
    return 0;
  }

  my $file = $self->__read_certificate_file() || return 0;

  my $iat                     = time;
  my $exp                     = $iat + 3600;
  my $iss                     = $self->get_email_address();
  my $delegated_email_address = $self->get_delegated_email_address();
  my $scope                   = $self->_formatted_scopes();

  my $header = '{"alg":"RS256","typ":"JWT"}';
  my $claims = "{
    \"iss\":\"${iss}\",
    \"sub\":\"${delegated_email_address}\",
    \"scope\":\"${scope}\",
    \"aud\":\"" . OAUTH2_BASE_URL . "/token\",
    \"exp\":${exp},
    \"iat\":${iat}
  }";

  my $encoded_header = __encode_base64_url($header);
  my $encoded_claims = __encode_base64_url($claims);

  my $key = $self->get___crypt_module()->new_private_key($file) || return 0;
  $key->use_pkcs1_padding();
  $key->use_sha256_hash();

  my $signature         = $key->sign("${encoded_header}.${encoded_claims}");
  my $encoded_signature = __encode_base64_url($signature);
  my $assertion = "${encoded_header}.${encoded_claims}.${encoded_signature}";
  my $body =
    "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" .
    "&assertion=" . $assertion;
  push my @headers, "Content-Type" => "application/x-www-form-urlencoded";
  my $request =
    HTTP::Request->new("POST", OAUTH2_BASE_URL . "/token", \@headers, $body);
  my $user_agent = $self->get___user_agent();
  my $res        = $user_agent->request($request);

  if (!$res->is_success()) {
    my $err_msg = $res->decoded_content();
    $self->get_api_client()->get_die_on_faults()
      ? die($err_msg)
      : warn($err_msg);
    return 0;
  }

  my $content_hash = $self->__parse_auth_response($res->decoded_content());

  $self->set_access_token($content_hash->{access_token});
  $self->set_access_token_expires($iat + $content_hash->{expires_in});
}

# Return the private key string from either the PEM file or JSON file specified.
sub __read_certificate_file {
  my $self = shift;
  my $private_key;

  if (!$self->get_pem_file() and !$self->get_json_file()) {
    return 0;
  }

  # JSON File
  if ($self->get_json_file()) {
    my $file_str;
    open(MYFILE, $self->get_json_file()) || return 0;
    while (<MYFILE>) {
      $file_str .= $_;
    }
    my $json_values = parse_json ($file_str);
    $private_key = $json_values->{'private_key'};
    $self->set_email_address($json_values->{'client_email'});
    close(MYFILE);
  }
  # PEM File
  else {
    open(MYFILE, $self->get_pem_file()) || return 0;
    while (<MYFILE>) {
      $private_key .= $_;
    }
    close(MYFILE);
  }

  return $private_key;
}

sub __encode_base64_url($) {
  my ($s) = shift;
  $s = encode_base64($s);
  $s =~ tr{+/}{-_};
  $s =~ s/=*$//;
  $s =~ s/\n//g;
  return $s;
}

sub _scope {
  my $self = shift;
  die "Need to be implemented by subclass";
}

sub _formatted_scopes {
  my $self = shift;
  die "Need to be implemented by subclass";
}

1;

=pod

=head1 NAME

Google::Ads::Common::OAuth2ServiceAccountsHandler

=head1 DESCRIPTION

A generic abstract implementation of L<Google::Ads::Common::OAuth2BaseHandler>
that supports OAuth2 for Service Accounts semantics.

It is meant to be specialized and its L<_scope> and L<_formatted_scopes> methods
be properly implemented.

=head1 ATTRIBUTES

Each of these attributes can be set via
Google::Ads::Common::OAuth2ServiceAccountsHandler->new().

Alternatively, there is a get_ and set_ method associated with each attribute
for retrieving or setting them dynamically.

=head2 api_client

A reference to the API client used to send requests.

=head2 client_id

OAuth2 client id obtained from the Google APIs Console.

=head2 email_address

Service account email address as found in the Google API Console.

=head2 delegated_email_address

Delegated email address of the accounts that has access to the API.

=head2 pem_file

Private key PEM file path. Keep in mind that the Google API Console generates
files in PKCS12 format and it should be converted to PEM format with no password
for this module to function.

=head2 json_file

JOSN file path. This contains the private key and client id needed for
authentication.

=head2 access_token

Stores an OAuth2 access token after the authorization flow is followed or for
you to manually set it in case you had it previously stored.
If this is manually set this handler will verify its validity before preparing
a request.

=head2 additional_scopes

Stores additional OAuth2 scopes as a comma-separated string.
The scope defines which services the tokens
are allowed to access e.g. https://www.googleapis.com/auth/analytics

=head1 METHODS

=head2 initialize

Initializes the handler with properties for generating authorization requests.

=head3 Parameters

=over

=item *

A required I<api_client> with a reference to the API client object handling the
requests against the API.

=item *

A hash reference with the following keys (with this example being for a simple
JSON keyfile):
{
  # Refer to the documentation of the L<delegated_email_address> property.
  oAuth2ServiceAccountDelegateEmailAddress => "delegated-email-address",
  # Refer to the documentation of the L<json_file> property.
  oAuth2ServiceAccountJSONFile => "json-file-path",
}

=back

=head2 is_auth_enabled

Refer to L<Google::Ads::Common::AuthHandlerInterface> documentation of this
method.

=head2 prepare_request

Refer to L<Google::Ads::Common::AuthHandlerInterface> documentation of this
method.

=head1 LICENSE AND COPYRIGHT

Copyright 2013 Google Inc.

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.

=head1 REPOSITORY INFORMATION

 $Rev: $
 $LastChangedBy: $
 $Id: $

=cut


text:
package adrien.common;

import com.google.common.base.MoreObjects;
import java.util.Objects;

public class Pair<F, S> {

    private F first;
    private S second;

    private Pair(final F first, S second) {
        super();

        this.first = first;
        this.second = second;
    }

    public static <F, S> Pair<F, S> of(F first, S second) {
        return new Pair<>(first, second);
    }

    public F getFirst() {
        return first;
    }

    public S getSecond() {
        return second;
    }

    @Override
    public boolean equals(Object object) {
        boolean equals = false;
        if (object instanceof Pair) {
            Pair<?, ?> that = (Pair) object;
            equals = Objects.equals(this.first, that.first) && Objects.equals(this.second, that.second);
        }
        return equals;
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.first, this.second);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(Pair.class)
                .add("first", this.first)
                .add("second", this.second)
            .toString();
    }

}


text:
{% load humanize %}
{% load mathfilters %}

Summary

  {% with net_flow=total_inflow|sub:total_outflow total_money=balance|add:total_inflow|sub:total_outflow %}

    You have received PHP {{ total_inflow|intcomma }} and disbursed PHP {{ total_outflow|intcomma }}. Your net cash flow is PHP {{ net_flow|intcomma }} and you currently have PHP {{ total_money|intcomma }}.

  {% if test_mode %}

The balance of {{ title }} account is PHP {{ total_title|intcomma }}.

The balance of {{ type }} group of accounts is PHP {{ total_type|intcomma }}.

Test value: {{ test }}

  {% endif %}

  {% endwith %}


text:
"""Tests for for_canonicalization module."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.contrib.autograph.converters import converter_test_base
from tensorflow.contrib.autograph.converters import name_scopes
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.platform import test

class FunctionNameScopeTransformer(converter_test_base.TestCase):

  def test_basic(self):

    def test_fn(l):
      """This should stay here."""
      a = 5
      l += a
      return l

    node = self.parse_and_analyze(test_fn, {})
    node = name_scopes.transform(node, self.ctx)

    with self.compiled(node, ops.name_scope) as result:
      result_op = result.test_fn(constant_op.constant(1))
      self.assertIn('test_fn/', result_op.op.name)

      self.assertEqual('This should stay here.', result.test_fn.__doc__)

  def test_long_docstring(self):

    def test_fn(l):
      """Multi-line docstring.

      Args:
        l: A thing.
      Returns:
        l
      """
      return l

    node = self.parse_and_analyze(test_fn, {})
    node = name_scopes.transform(node, self.ctx)

    with self.compiled(node, ops.name_scope) as result:
      self.assertIn('Multi-line', result.test_fn.__doc__)
      self.assertIn('Returns:', result.test_fn.__doc__)

  def test_nested_functions(self):

    def test_fn(l):

      def inner_fn(i):
        return i ** 2

      l += 4
      return inner_fn(l)

    node = self.parse_and_analyze(test_fn, {})
    node = name_scopes.transform(node, self.ctx)

    with self.compiled(node, ops.name_scope) as result:
      result_op = result.test_fn(constant_op.constant(1))
      first_result_input_name = result_op.op.inputs[0].name
      second_result_input_name = result_op.op.inputs[1].name
      self.assertIn('test_fn/', first_result_input_name)
      self.assertNotIn('inner_fn', first_result_input_name)
      self.assertIn('test_fn/inner_fn/', second_result_input_name)

  def test_method(self):

    class TestClass(object):

      def test_fn(self, l):

        def inner_fn(i):
          return i ** 2

        l += 4
        return inner_fn(l)

    # Note that 'TestClass' was needed in the namespace here.
    node = self.parse_and_analyze(
        TestClass, {'TestClass': TestClass}, owner_type=TestClass)
    node = name_scopes.transform(node, self.ctx)

    with self.compiled(node, ops.name_scope) as result:
      result_op = result.TestClass().test_fn(constant_op.constant(1))
      first_result_input_name = result_op.op.inputs[0].name
      second_result_input_name = result_op.op.inputs[1].name
      self.assertIn('TestClass/test_fn/', first_result_input_name)
      self.assertNotIn('inner_fn', first_result_input_name)
      self.assertIn('TestClass/test_fn/inner_fn/', second_result_input_name)

  def test_operator(self):

    class TestClass(object):

      def __call__(self, l):

        def inner_fn(i):
          return i ** 2

        l += 4
        return inner_fn(l)

    # Note that 'TestClass' was needed in the namespace here.
    node = self.parse_and_analyze(
        TestClass.__call__, {'TestClass': TestClass}, owner_type=TestClass)
    node = name_scopes.transform(node, self.ctx)

    with self.compiled(node, ops.name_scope) as result:
      result_op = result.__call__(TestClass(), constant_op.constant(1))
      first_result_input_name = result_op.op.inputs[0].name
      second_result_input_name = result_op.op.inputs[1].name
      self.assertIn('call__/', first_result_input_name)
      self.assertNotIn('inner_fn', first_result_input_name)
      self.assertIn('call__/inner_fn/', second_result_input_name)

if __name__ == '__main__':
  test.main()


text:
title: Authorization
description: This tutorial demonstrates how to add authentication and authorization to an Express.js API
---

<%= include('../../../_includes/_package', {
  org: 'auth0-samples',
  repo: 'auth0-express-api-samples',
  path: '01-Authorization-RS256',
  requirements: [
    'express.js 14.4.0',
    'express-jwt 5.1.0',
    'express-jwt-authz 1.0.0'
  ]
}) %>

<%= include('../_includes/_api_auth_preamble') %>

This sample demonstrates how to check for a JWT in the `Authorization` header of an incoming HTTP request and verify that it is valid. The validity check is done in an Express middleware function which can be applied to any endpoints you wish to protect. If the token is valid, the resources which are served by the endpoint can be released, otherwise a `401 Authorization` error will be returned.

## Install the Dependencies

The **express-jwt** package can be used to verify incoming JWTs. The **jwks-rsa** library can be used alongside it to fetch your Auth0 public key and complete the verification process. The **express-jwt-authz** library can be used to add an authorization middleware to your endpoints. Install these libraries with npm.

```bash
npm install --save express-jwt jwks-rsa express-jwt-authz
```

## Configuration

<%= include('../_includes/_api_jwks_description', { sampleLink: 'https://github.com/auth0-samples/auth0-express-api-samples/tree/master/02-Authorization-HS256' }) %>

Configure the **express-jwt** middleware to use the remote JWKS for your Auth0 account.

```js
// server.js

const express = require('express');
const app = express();
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');

// Authentication middleware. When used, the
// access token must exist and be verified against
// the Auth0 JSON Web Key Set
const checkJwt = jwt({
  // Dynamically provide a signing key
  // based on the kid in the header and
  // the singing keys provided by the JWKS endpoint.
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://${account.namespace}/.well-known/jwks.json`
  }),

  // Validate the audience and the issuer.
  audience: '{API_ID}',
  issuer: `https://${account.namespace}/`,
  algorithms: ['RS256']
});
```

## Configuring Scopes

The `checkJwt` middleware above verifies that the `access_token` included in the request is valid; however, it doesn't yet include any mechanism for checking that the token has the sufficient **scope** to access the requested resources.

Scopes provide a way for you to define which resources should be accessible by the user holding a given `access_token`. For example, you might choose to permit `read` access to a `messages` resource if a user has a **manager** access level, or a `write` access to that resource if they are an **administrator**.

To configure scopes in your Auth0 dashboard, navigate to [your API](${manage_url}/#/apis) and choose the **Scopes** tab. In this area you can apply any scopes you wish, including one called `read:messages`, which will be used in this example.

## Protect Individual Endpoints

Individual routes can be configured to look for a particular `scope` by setting up another middleware with the **express-jwt-authz** package. To do so, provide an array of required scopes and apply the middleware to any routes you wish to add authorization to.

Pass the `checkJwt` and `checkScopes` middlewares to the route you wish to protect.

```js
// server.js

const checkScopes = jwtAuthz([ 'read:messages' ]);

app.get('/api/private', checkJwt, checkScopes, function(req, res) {
  res.json({
    message: "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this."
  });
});
```

With this configuration in place, only `access_token`s which have a scope of `read:messages` will be allowed to access this endpoint.


text:
Phar::startBuffering()/setStub()/stopBuffering() tar-based
--SKIPIF--
<?php
if (!extension_loaded("phar")) die("skip");
if (version_compare(PHP_VERSION, "6.0", ">")) die("skip pre-unicode version of PHP required");
?>
--INI--
phar.readonly=0
--FILE--
<?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar.tar', 0, 'brandnewphar.phar');
var_dump($p->isFileFormat(Phar::TAR));
//var_dump($p->getStub());
var_dump($p->isBuffering());
$p->startBuffering();
var_dump($p->isBuffering());
$p['a.php'] = '<?php var_dump("Hello");';
$p->setStub('<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
include 'phar://brandnewphar.phar/a.php';
var_dump($p->getStub());
$p['b.php'] = '<?php var_dump("World");';
$p->setStub('<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER();');
include 'phar://brandnewphar.phar/b.php';
var_dump($p->getStub());
$p->stopBuffering();
echo "===COMMIT===\n";
var_dump($p->isBuffering());
include 'phar://brandnewphar.phar/a.php';
include 'phar://brandnewphar.phar/b.php';
var_dump($p->getStub());
?>
===DONE===
--CLEAN--
<?php
unlink(dirname(__FILE__) . '/brandnewphar.phar.tar');
?>
--EXPECT--
bool(true)
bool(false)
bool(true)
string(5) "Hello"
string(84) "<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>
"
string(5) "World"
string(85) "<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>
"
===COMMIT===
bool(false)
string(5) "Hello"
string(5) "World"
string(85) "<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>
"
===DONE===