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

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyDescription;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.TopologyTestDriverWrapper;
import org.apache.kafka.streams.TopologyWrapper;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Predicate;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.ValueJoiner;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.apache.kafka.streams.kstream.ValueMapperWithKey;
import org.apache.kafka.streams.kstream.ValueTransformerWithKeySupplier;
import org.apache.kafka.streams.processor.internals.InternalTopologyBuilder;
import org.apache.kafka.streams.processor.internals.SinkNode;
import org.apache.kafka.streams.processor.internals.SourceNode;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.test.ConsumerRecordFactory;
import org.apache.kafka.test.MockAggregator;
import org.apache.kafka.test.MockInitializer;
import org.apache.kafka.test.MockMapper;
import org.apache.kafka.test.MockProcessor;
import org.apache.kafka.test.MockProcessorSupplier;
import org.apache.kafka.test.MockReducer;
import org.apache.kafka.test.MockValueJoiner;
import org.apache.kafka.test.StreamsTestUtils;
import org.junit.Before;
import org.junit.Test;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Properties;

import static org.easymock.EasyMock.mock;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

public class KTableImplTest {

    private final Consumed<String, String> consumed = Consumed.with(Serdes.String(), Serdes.String());
    private final Produced<String, String> produced = Produced.with(Serdes.String(), Serdes.String());
    private final Properties props = StreamsTestUtils.topologyTestConfig(Serdes.String(), Serdes.String());
    private final ConsumerRecordFactory<String, String> recordFactory = new ConsumerRecordFactory<>(new StringSerializer(), new StringSerializer());

    private StreamsBuilder builder;
    private KTable<String, String> table;

    @Before
    public void setUp() {
        builder = new StreamsBuilder();
        table = builder.table("test");
    }

    @Test
    public void testKTable() {
        final StreamsBuilder builder = new StreamsBuilder();

        String topic1 = "topic1";
        String topic2 = "topic2";

        final KTable<String, String> table1 = builder.table(topic1, consumed);

        final MockProcessorSupplier<String, Object> supplier = new MockProcessorSupplier<>();
        table1.toStream().process(supplier);

        final KTable<String, Integer> table2 = table1.mapValues(new ValueMapper<String, Integer>() {
            @Override
            public Integer apply(String value) {
                return new Integer(value);
            }
        });

        table2.toStream().process(supplier);

        final KTable<String, Integer> table3 = table2.filter(new Predicate<String, Integer>() {
            @Override
            public boolean test(String key, Integer value) {
                return (value % 2) == 0;
            }
        });

        table3.toStream().process(supplier);

        table1.toStream().to(topic2, produced);
        final KTable<String, String> table4 = builder.table(topic2, consumed);

        table4.toStream().process(supplier);

        try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) {
            driver.pipeInput(recordFactory.create(topic1, "A", "01"));
            driver.pipeInput(recordFactory.create(topic1, "B", "02"));
            driver.pipeInput(recordFactory.create(topic1, "C", "03"));
            driver.pipeInput(recordFactory.create(topic1, "D", "04"));
        }

        final List<MockProcessor<String, Object>> processors = supplier.capturedProcessors(4);
        assertEquals(Utils.mkList("A:01", "B:02", "C:03", "D:04"), processors.get(0).processed);
        assertEquals(Utils.mkList("A:1", "B:2", "C:3", "D:4"), processors.get(1).processed);
        assertEquals(Utils.mkList("A:null", "B:2", "C:null", "D:4"), processors.get(2).processed);
        assertEquals(Utils.mkList("A:01", "B:02", "C:03", "D:04"), processors.get(3).processed);
    }

    @Test
    public void testValueGetter() {
        final StreamsBuilder builder = new StreamsBuilder();

        final String topic1 = "topic1";
        final String topic2 = "topic2";

        final KTableImpl<String, String, String> table1 =
                (KTableImpl<String, String, String>) builder.table(topic1, consumed);
        final KTableImpl<String, String, Integer> table2 = (KTableImpl<String, String, Integer>) table1.mapValues(
                new ValueMapper<String, Integer>() {
                    @Override
                    public Integer apply(String value) {
                        return new Integer(value);
                    }
                });
        final KTableImpl<String, Integer, Integer> table3 = (KTableImpl<String, Integer, Integer>) table2.filter(
                new Predicate<String, Integer>() {
                    @Override
                    public boolean test(String key, Integer value) {
                        return (value % 2) == 0;
                    }
                });

        table1.toStream().to(topic2, produced);
        final KTableImpl<String, String, String> table4 = (KTableImpl<String, String, String>) builder.table(topic2, consumed);

        final Topology topology = builder.build();

        final KTableValueGetterSupplier<String, String> getterSupplier1 = table1.valueGetterSupplier();
        final KTableValueGetterSupplier<String, Integer> getterSupplier2 = table2.valueGetterSupplier();
        final KTableValueGetterSupplier<String, Integer> getterSupplier3 = table3.valueGetterSupplier();
        final KTableValueGetterSupplier<String, String> getterSupplier4 = table4.valueGetterSupplier();

        final InternalTopologyBuilder topologyBuilder = TopologyWrapper.getInternalTopologyBuilder(topology);
        topologyBuilder.connectProcessorAndStateStores(table1.name, getterSupplier1.storeNames());
        topologyBuilder.connectProcessorAndStateStores(table2.name, getterSupplier2.storeNames());
        topologyBuilder.connectProcessorAndStateStores(table3.name, getterSupplier3.storeNames());
        topologyBuilder.connectProcessorAndStateStores(table4.name, getterSupplier4.storeNames());

        try (final TopologyTestDriverWrapper driver = new TopologyTestDriverWrapper(topology, props)) {

            assertEquals(2, driver.getAllStateStores().size());

            final KTableValueGetter<String, String> getter1 = getterSupplier1.get();
            final KTableValueGetter<String, Integer> getter2 = getterSupplier2.get();
            final KTableValueGetter<String, Integer> getter3 = getterSupplier3.get();
            final KTableValueGetter<String, String> getter4 = getterSupplier4.get();

            getter1.init(driver.setCurrentNodeForProcessorContext(table1.name));
            getter2.init(driver.setCurrentNodeForProcessorContext(table2.name));
            getter3.init(driver.setCurrentNodeForProcessorContext(table3.name));
            getter4.init(driver.setCurrentNodeForProcessorContext(table4.name));

            driver.pipeInput(recordFactory.create(topic1, "A", "01"));
            driver.pipeInput(recordFactory.create(topic1, "B", "01"));
            driver.pipeInput(recordFactory.create(topic1, "C", "01"));

            assertEquals("01", getter1.get("A"));
            assertEquals("01", getter1.get("B"));
            assertEquals("01", getter1.get("C"));

            assertEquals(new Integer(1), getter2.get("A"));
            assertEquals(new Integer(1), getter2.get("B"));
            assertEquals(new Integer(1), getter2.get("C"));

            assertNull(getter3.get("A"));
            assertNull(getter3.get("B"));
            assertNull(getter3.get("C"));

            assertEquals("01", getter4.get("A"));
            assertEquals("01", getter4.get("B"));
            assertEquals("01", getter4.get("C"));

            driver.pipeInput(recordFactory.create(topic1, "A", "02"));
            driver.pipeInput(recordFactory.create(topic1, "B", "02"));

            assertEquals("02", getter1.get("A"));
            assertEquals("02", getter1.get("B"));
            assertEquals("01", getter1.get("C"));

            assertEquals(new Integer(2), getter2.get("A"));
            assertEquals(new Integer(2), getter2.get("B"));
            assertEquals(new Integer(1), getter2.get("C"));

            assertEquals(new Integer(2), getter3.get("A"));
            assertEquals(new Integer(2), getter3.get("B"));
            assertNull(getter3.get("C"));

            assertEquals("02", getter4.get("A"));
            assertEquals("02", getter4.get("B"));
            assertEquals("01", getter4.get("C"));

            driver.pipeInput(recordFactory.create(topic1, "A", "03"));

            assertEquals("03", getter1.get("A"));
            assertEquals("02", getter1.get("B"));
            assertEquals("01", getter1.get("C"));

            assertEquals(new Integer(3), getter2.get("A"));
            assertEquals(new Integer(2), getter2.get("B"));
            assertEquals(new Integer(1), getter2.get("C"));

            assertNull(getter3.get("A"));
            assertEquals(new Integer(2), getter3.get("B"));
            assertNull(getter3.get("C"));

            assertEquals("03", getter4.get("A"));
            assertEquals("02", getter4.get("B"));
            assertEquals("01", getter4.get("C"));

            driver.pipeInput(recordFactory.create(topic1, "A", (String) null));

            assertNull(getter1.get("A"));
            assertEquals("02", getter1.get("B"));
            assertEquals("01", getter1.get("C"));

            assertNull(getter2.get("A"));
            assertEquals(new Integer(2), getter2.get("B"));
            assertEquals(new Integer(1), getter2.get("C"));

            assertNull(getter3.get("A"));
            assertEquals(new Integer(2), getter3.get("B"));
            assertNull(getter3.get("C"));

            assertNull(getter4.get("A"));
            assertEquals("02", getter4.get("B"));
            assertEquals("01", getter4.get("C"));
        }
    }

    @Test
    public void testStateStoreLazyEval() {
        final String topic1 = "topic1";
        final String topic2 = "topic2";

        final StreamsBuilder builder = new StreamsBuilder();

        final KTableImpl<String, String, String> table1 =
                (KTableImpl<String, String, String>) builder.table(topic1, consumed);
        builder.table(topic2, consumed);

        final KTableImpl<String, String, Integer> table1Mapped = (KTableImpl<String, String, Integer>) table1.mapValues(
                new ValueMapper<String, Integer>() {
                    @Override
                    public Integer apply(String value) {
                        return new Integer(value);
                    }
                });
        table1Mapped.filter(
                new Predicate<String, Integer>() {
                    @Override
                    public boolean test(String key, Integer value) {
                        return (value % 2) == 0;
                    }
                });

        try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) {
            assertEquals(2, driver.getAllStateStores().size());
        }
    }

    @Test
    public void testStateStore() {
        final String topic1 = "topic1";
        final String topic2 = "topic2";

        final StreamsBuilder builder = new StreamsBuilder();

        final KTableImpl<String, String, String> table1 =
                (KTableImpl<String, String, String>) builder.table(topic1, consumed);
        final KTableImpl<String, String, String> table2 =
                (KTableImpl<String, String, String>) builder.table(topic2, consumed);

        final KTableImpl<String, String, Integer> table1Mapped = (KTableImpl<String, String, Integer>) table1.mapValues(
                new ValueMapper<String, Integer>() {
                    @Override
                    public Integer apply(String value) {
                        return new Integer(value);
                    }
                });
        final KTableImpl<String, Integer, Integer> table1MappedFiltered = (KTableImpl<String, Integer, Integer>) table1Mapped.filter(
                new Predicate<String, Integer>() {
                    @Override
                    public boolean test(String key, Integer value) {
                        return (value % 2) == 0;
                    }
                });
        table2.join(table1MappedFiltered,
                new ValueJoiner<String, Integer, String>() {
                    @Override
                    public String apply(String v1, Integer v2) {
                        return v1 + v2;
                    }
                });

        try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) {
            assertEquals(2, driver.getAllStateStores().size());
        }
    }

    private void assertTopologyContainsProcessor(final Topology topology, final String processorName) {
        for (final TopologyDescription.Subtopology subtopology: topology.describe().subtopologies()) {
            for (final TopologyDescription.Node node: subtopology.nodes()) {
                if (node.name().equals(processorName)) {
                    return;
                }
            }
        }
        throw new AssertionError("No processor named '" + processorName + "'"
                + "found in the provided Topology:\n" + topology.describe());
    }

    @Test
    public void shouldCreateSourceAndSinkNodesForRepartitioningTopic() throws NoSuchFieldException, IllegalAccessException {
        final String topic1 = "topic1";
        final String storeName1 = "storeName1";

        final StreamsBuilder builder = new StreamsBuilder();

        final KTableImpl<String, String, String> table1 =
                (KTableImpl<String, String, String>) builder.table(topic1,
                                                                   consumed,
                                                                   Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as(storeName1)
                                                                           .withKeySerde(Serdes.String())
                                                                           .withValueSerde(Serdes.String())
                );

        table1.groupBy(MockMapper.<String, String>noOpKeyValueMapper())
            .aggregate(MockInitializer.STRING_INIT, MockAggregator.TOSTRING_ADDER, MockAggregator.TOSTRING_REMOVER, Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("mock-result1"));

        table1.groupBy(MockMapper.<String, String>noOpKeyValueMapper())
            .reduce(MockReducer.STRING_ADDER, MockReducer.STRING_REMOVER, Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("mock-result2"));

        final Topology topology = builder.build();
        try (final TopologyTestDriverWrapper driver = new TopologyTestDriverWrapper(topology, props)) {

            assertEquals(3, driver.getAllStateStores().size());

            assertTopologyContainsProcessor(topology, "KSTREAM-SINK-0000000003");
            assertTopologyContainsProcessor(topology, "KSTREAM-SOURCE-0000000004");
            assertTopologyContainsProcessor(topology, "KSTREAM-SINK-0000000007");
            assertTopologyContainsProcessor(topology, "KSTREAM-SOURCE-0000000008");

            Field valSerializerField = ((SinkNode) driver.getProcessor("KSTREAM-SINK-0000000003")).getClass().getDeclaredField("valSerializer");
            Field valDeserializerField = ((SourceNode) driver.getProcessor("KSTREAM-SOURCE-0000000004")).getClass().getDeclaredField("valDeserializer");
            valSerializerField.setAccessible(true);
            valDeserializerField.setAccessible(true);

            assertNotNull(((ChangedSerializer) valSerializerField.get(driver.getProcessor("KSTREAM-SINK-0000000003"))).inner());
            assertNotNull(((ChangedDeserializer) valDeserializerField.get(driver.getProcessor("KSTREAM-SOURCE-0000000004"))).inner());
            assertNotNull(((ChangedSerializer) valSerializerField.get(driver.getProcessor("KSTREAM-SINK-0000000007"))).inner());
            assertNotNull(((ChangedDeserializer) valDeserializerField.get(driver.getProcessor("KSTREAM-SOURCE-0000000008"))).inner());
        }
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullSelectorOnToStream() {
        table.toStream(null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullPredicateOnFilter() {
        table.filter(null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullPredicateOnFilterNot() {
        table.filterNot(null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullMapperOnMapValues() {
        table.mapValues((ValueMapper) null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullMapperOnMapValueWithKey() {
        table.mapValues((ValueMapperWithKey) null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullSelectorOnGroupBy() {
        table.groupBy(null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullOtherTableOnJoin() {
        table.join(null, MockValueJoiner.TOSTRING_JOINER);
    }

    @Test
    public void shouldAllowNullStoreInJoin() {
        table.join(table, MockValueJoiner.TOSTRING_JOINER);
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullJoinerJoin() {
        table.join(table, null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullOtherTableOnOuterJoin() {
        table.outerJoin(null, MockValueJoiner.TOSTRING_JOINER);
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullJoinerOnOuterJoin() {
        table.outerJoin(table, null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullJoinerOnLeftJoin() {
        table.leftJoin(table, null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullOtherTableOnLeftJoin() {
        table.leftJoin(null, MockValueJoiner.TOSTRING_JOINER);
    }

    @Test(expected = NullPointerException.class)
    public void shouldThrowNullPointerOnFilterWhenMaterializedIsNull() {
        table.filter(new Predicate<String, String>() {
            @Override
            public boolean test(final String key, final String value) {
                return false;
            }
        }, (Materialized) null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldThrowNullPointerOnFilterNotWhenMaterializedIsNull() {
        table.filterNot(new Predicate<String, String>() {
            @Override
            public boolean test(final String key, final String value) {
                return false;
            }
        }, (Materialized) null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldThrowNullPointerOnJoinWhenMaterializedIsNull() {
        table.join(table, MockValueJoiner.TOSTRING_JOINER, (Materialized) null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldThrowNullPointerOnLeftJoinWhenMaterializedIsNull() {
        table.leftJoin(table, MockValueJoiner.TOSTRING_JOINER, (Materialized) null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldThrowNullPointerOnOuterJoinWhenMaterializedIsNull() {
        table.outerJoin(table, MockValueJoiner.TOSTRING_JOINER, (Materialized) null);
    }

    @Test(expected = NullPointerException.class)
    public void shouldThrowNullPointerOnTransformValuesWithKeyWhenTransformerSupplierIsNull() {
        table.transformValues((ValueTransformerWithKeySupplier) null);
    }

    @SuppressWarnings("unchecked")
    @Test(expected = NullPointerException.class)
    public void shouldThrowNullPointerOnTransformValuesWithKeyWhenMaterializedIsNull() {
        final ValueTransformerWithKeySupplier<String, String, ?> valueTransformerSupplier = mock(ValueTransformerWithKeySupplier.class);
        table.transformValues(valueTransformerSupplier, (Materialized) null);
    }

    @SuppressWarnings("unchecked")
    @Test(expected = NullPointerException.class)
    public void shouldThrowNullPointerOnTransformValuesWithKeyWhenStoreNamesNull() {
        final ValueTransformerWithKeySupplier<String, String, ?> valueTransformerSupplier = mock(ValueTransformerWithKeySupplier.class);
        table.transformValues(valueTransformerSupplier, (String[]) null);
    }
}


text:
from unittest import TestCase

import mock

from hpOneView.connection import connection
from hpOneView.image_streamer.resources.build_plans import BuildPlans
from hpOneView.resources.resource import ResourceClient

class BuildPlansTest(TestCase):
    def setUp(self):
        self.host = '127.0.0.1'
        self.connection = connection(self.host)
        self._client = BuildPlans(self.connection)

    @mock.patch.object(ResourceClient, 'get_all')
    def test_get_all_called_once(self, mock_get_all):
        filter = 'name=TestName'
        sort = 'name:ascending'

        self._client.get_all(2, 500, filter, sort)

        mock_get_all.assert_called_once_with(2, 500, filter=filter, sort=sort)

    @mock.patch.object(ResourceClient, 'get_all')
    def test_get_all_called_once_with_default_values(self, mock_get_all):
        self._client.get_all()

        mock_get_all.assert_called_once_with(0, -1, filter='', sort='')

    @mock.patch.object(ResourceClient, 'get_by')
    def test_get_by_called_once(self, mock_get_by):
        self._client.get_by('name', 'Build Plan Name')

        mock_get_by.assert_called_once_with(
            'name', 'Build Plan Name')

    @mock.patch.object(ResourceClient, 'get')
    def test_get_called_once(self, mock_get):
        self._client.get('3518be0e-17c1-4189-8f81-83f3724f6155')

        mock_get.assert_called_once_with(
            '3518be0e-17c1-4189-8f81-83f3724f6155')

    @mock.patch.object(ResourceClient, 'get')
    def test_get_with_uri_called_once(self, mock_get):
        uri = '/rest/build-plans/3518be0e-17c1-4189-8f81-83f3724f6155'
        self._client.get(uri)

        mock_get.assert_called_once_with(uri)

    @mock.patch.object(ResourceClient, 'create')
    def test_create_called_once_with_default_type(self, mock_create):
        information = {
            "name": "OS Build Plan Name",
        }
        mock_create.return_value = {}

        self._client.create(information)
        mock_create.assert_called_once_with(information, timeout=-1, default_values=self._client.DEFAULT_VALUES)

    @mock.patch.object(ResourceClient, 'create')
    def test_create_called_once_with_provided_type(self, mock_create):
        information = {
            "name": "OS Build Plan Name",
        }
        mock_create.return_value = {}

        self._client.create(information)
        mock_create.assert_called_once_with(information, timeout=-1, default_values=self._client.DEFAULT_VALUES)

    @mock.patch.object(ResourceClient, 'update')
    def test_update_called_once(self, mock_update):
        information = {
            "type": "OeBuildPlan",
            "name": "OS Build Plan Name",
            "description": "Description of the build plan",
        }
        expected_data = information.copy()
        mock_update.return_value = {}

        self._client.update(information)
        mock_update.assert_called_once_with(expected_data, timeout=-1)

    @mock.patch.object(ResourceClient, 'delete')
    def test_delete_called_once(self, mock_delete):
        id = 'ad28cf21-8b15-4f92-bdcf-51cb2042db32'
        self._client.delete(id, force=False)

        mock_delete.assert_called_once_with(id, force=False, timeout=-1)

    @mock.patch.object(ResourceClient, 'delete')
    def test_delete_called_once_with_force(self, mock_delete):
        id = 'ad28cf21-8b15-4f92-bdcf-51cb2042db32'
        self._client.delete(id, force=True)

        mock_delete.assert_called_once_with(id, force=True, timeout=-1)

redpajama_set_name: RedPajamaGithub


text:
package androidx.camera.video;

import android.media.AudioFormat;
import android.media.MediaRecorder;
import android.util.Range;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.annotation.RestrictTo.Scope;

import com.google.auto.value.AutoValue;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Audio specification that is options to config audio source and encoding.
 * @hide
 */
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
@RestrictTo(Scope.LIBRARY)
@AutoValue
public abstract class AudioSpec {

    /**
     * The audio source format representing no preference for audio source format.
     */
    public static final int SOURCE_FORMAT_AUTO = -1;
    /**
     * The PCM 16 bit per sample audio source format. Guaranteed to be supported by all devices.
     */
    public static final int SOURCE_FORMAT_PCM_16BIT = AudioFormat.ENCODING_PCM_16BIT;

    @IntDef({SOURCE_FORMAT_AUTO, SOURCE_FORMAT_PCM_16BIT})
    @Retention(RetentionPolicy.SOURCE)
    @interface SourceFormat {
    }

    /**
     * Allows the audio source to choose the appropriate number of channels.
     */
    public static final int CHANNEL_COUNT_AUTO = -1;
    /**
     * A channel count which is equivalent to no audio.
     */
    public static final int CHANNEL_COUNT_NONE = 0;
    /**
     * A channel count corresponding to a single audio channel.
     */
    public static final int CHANNEL_COUNT_MONO = 1;
    /**
     * A channel count corresponding to two audio channels.
     */
    public static final int CHANNEL_COUNT_STEREO = 2;

    /** @hide */
    @IntDef(open = true,
            value = {CHANNEL_COUNT_AUTO, CHANNEL_COUNT_NONE, CHANNEL_COUNT_MONO,
                    CHANNEL_COUNT_STEREO})
    @Retention(RetentionPolicy.SOURCE)
    @RestrictTo(RestrictTo.Scope.LIBRARY)
    public @interface ChannelCount {
    }

    /**
     * The audio source representing no preference for audio source.
     */
    public static final int SOURCE_AUTO = -1;
    /**
     * Microphone audio source tuned for video recording, with the same orientation as the camera
     * if available.
     */
    public static final int SOURCE_CAMCORDER = MediaRecorder.AudioSource.CAMCORDER;

    /** @hide */
    @IntDef({SOURCE_AUTO, SOURCE_CAMCORDER})
    @Retention(RetentionPolicy.SOURCE)
    @RestrictTo(RestrictTo.Scope.LIBRARY)
    public @interface Source {
    }

    /**
     * Bitrate range representing no preference for bitrate.
     *
     *
Using this value with {@link AudioSpec.Builder#setBitrate(Range)} informs the device it
     * should choose any appropriate bitrate given the device and codec constraints.
     */
    @NonNull
    public static final Range<Integer> BITRATE_RANGE_AUTO = new Range<>(0,
            Integer.MAX_VALUE);

    /**
     * Sample rate range representing no preference for sample rate.
     *
     *
Using this value with {@link AudioSpec.Builder#setSampleRate(Range)} informs the device it
     * should choose any appropriate sample rate given the device and codec constraints.
     */
    @NonNull
    public static final Range<Integer> SAMPLE_RATE_RANGE_AUTO = new Range<>(0,
            Integer.MAX_VALUE);

    // Restrict constructor to same package
    AudioSpec() {
    }

    /** Returns a build for this config. */
    @NonNull
    public static Builder builder() {
        return new AutoValue_AudioSpec.Builder()
                .setSourceFormat(SOURCE_FORMAT_AUTO)
                .setSource(SOURCE_AUTO)
                .setChannelCount(CHANNEL_COUNT_AUTO)
                .setBitrate(BITRATE_RANGE_AUTO)
                .setSampleRate(SAMPLE_RATE_RANGE_AUTO);
    }

    /** Gets the bitrate. */
    @NonNull
    public abstract Range<Integer> getBitrate();

    // Configurations for AudioRecord.
    // *********************************************************************************************

    /** Gets the audio format. */
    @SourceFormat
    public abstract int getSourceFormat();

    /** Gets the audio source. */
    @Source
    public abstract int getSource();

    /** Gets the sample bitrate. */
    @NonNull
    public abstract Range<Integer> getSampleRate();

    /** Gets the channel count. */
    @ChannelCount
    public abstract int getChannelCount();

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

    /**
     * Returns a {@link Builder} instance with the same property values as this instance.
     */
    @NonNull
    public abstract Builder toBuilder();

    /**
     * The builder of the {@link AudioSpec}.
     * @hide
     */
    @RestrictTo(Scope.LIBRARY)
    @SuppressWarnings("StaticFinalBuilder")
    @AutoValue.Builder
    public abstract static class Builder {
        // Restrict construction to same package
        Builder() {
        }

        /**
         * Sets the desired range of bitrates to be used by the encoder.
         *
         *
If not set, defaults to {@link #BITRATE_RANGE_AUTO}.
         */
        @NonNull
        public abstract Builder setBitrate(@NonNull Range<Integer> bitrate);

        // Configurations for AudioRecord.
        // *****************************************************************************************

        /**
         * Sets the audio source format.
         *
         *
Available values for source format are {@link #SOURCE_FORMAT_AUTO} and
         * {@link #SOURCE_FORMAT_PCM_16BIT}.
         *
         *
If not set, defaults to {@link #SOURCE_FORMAT_AUTO}.
         */
        @NonNull
        public abstract Builder setSourceFormat(@SourceFormat int audioFormat);

        /**
         * Sets the audio source.
         *
         *
Available values for source are {@link #SOURCE_AUTO} and {@link #SOURCE_CAMCORDER}.
         *
         *
If not set, defaults to {@link #SOURCE_AUTO}.
         */
        @NonNull
        public abstract Builder setSource(@Source int source);

        /**
         * Sets the desired range of sample rates to be used by the encoder.
         *
         *
If not set, defaults to {@link #SAMPLE_RATE_RANGE_AUTO}.
         */
        @NonNull
        public abstract Builder setSampleRate(@NonNull Range<Integer> sampleRate);

        /**
         * Sets the desired number of audio channels.
         *
         *
If not set, defaults to {@link #CHANNEL_COUNT_AUTO}. Other common channel counts
         * include {@link #CHANNEL_COUNT_MONO} or {@link #CHANNEL_COUNT_STEREO}.
         *
         *
Setting to {@link #CHANNEL_COUNT_NONE} is equivalent to requesting that no audio
         * should be present.
         */
        @NonNull
        public abstract Builder setChannelCount(@ChannelCount int channelCount);

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

        /** Builds the AudioSpec instance. */
        @NonNull
        public abstract AudioSpec build();
    }

    /**
     * An audio specification that corresponds to no audio.
     *
     *
This is equivalent to creating an {@link AudioSpec} with channel count set to
     * {@link #CHANNEL_COUNT_NONE}.
     */
    public static final AudioSpec NO_AUDIO = builder().setChannelCount(CHANNEL_COUNT_NONE).build();
}


text:
using GraphSharp.Controls;
using GraphSharp.Sample;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236

namespace GraphSharpSampleCore
{
    public sealed partial class PocVertexView : UserControl
    {
        public static readonly DependencyProperty BBrushProperty =
            DependencyProperty.Register("BBrush", typeof(Brush), typeof(PocVertexView), new PropertyMetadata(null));// bcz: new UIPropertyMetadata( null ) );
        public static readonly DependencyProperty BThicknessProperty =
            DependencyProperty.Register("BThickness", typeof(Thickness), typeof(PocVertexView), new PropertyMetadata(null));// bcz: new UIPropertyMetadata( null ) );
        VertexControl VC => VisualTreeHelper.GetParent(CP) as VertexControl;
        ContentPresenter CP => VisualTreeHelper.GetParent(this) as ContentPresenter;
        public PocVertexView()
        {
            this.InitializeComponent();
        }

        public Brush BBrush
        {
            get { return (Brush)GetValue(BBrushProperty); }
            set { SetValue(BBrushProperty, value); }
        }
        public Thickness BThickness
        {
            get { return (Thickness)GetValue(BThicknessProperty); }
            set { SetValue(BThicknessProperty, value); }
        }

        Point delta = new Point();
        void MyVertex_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            PointerMoved    -= MyVertex_PointerMoved;
            PointerMoved    += MyVertex_PointerMoved;
            PointerReleased -= MyVertex_PointerReleased;
            PointerReleased += MyVertex_PointerReleased;
            var pos = e.GetCurrentPoint(VisualTreeHelper.GetParent(VC) as UIElement).Position;
            delta = new Point(pos.X - Canvas.GetLeft(VC), pos.Y - Canvas.GetTop(VC));
            e.Handled = true;
            this.CapturePointer(e.Pointer);
        }

        private void MyVertex_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            PointerReleased -= MyVertex_PointerReleased;
            PointerMoved -= MyVertex_PointerMoved;
            e.Handled = true;
            this.ReleasePointerCapture(e.Pointer);
        }

        private void MyVertex_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            var pos = e.GetCurrentPoint(VisualTreeHelper.GetParent(VC) as UIElement).Position;
            Canvas.SetLeft(VC, pos.X-delta.X);
            Canvas.SetTop(VC, pos.Y-delta.Y);
            e.Handled = true;
        }

        private void Parameters_Click(object sender, RoutedEventArgs e)
        {
            var hyperParams = (DataContext as PocVertex).HyperParams;
            vFlyyout.ItemsSource = hyperParams;
            vFlyyout.Height = hyperParams.Count * 50;
        }
    }
}


text:
Lex lex;
int main() {
	lex.ReadFromFile("WeakScript.lex");
	lex.outDFA("WeakScript.dfa");
	lex.outDef("WeakScriptLex.h");
	return 0;
}


text:
import java.io.*;
import java.util.ArrayList;

public abstract class ReportThread extends Thread implements Serializable{
	int Status;
	String Result;
	int SliceNum;

	int getStatus(){
		return Status;
	}

	void setStatus(int status){
		Status = status;
	}

	String getResult(){
		return Result;
	}

	final int getSliceNum(){
		return SliceNum;
	}

	final void uploadResults(){
		setStatus(2);
	}

	abstract String processResult(ArrayList<ReportThread> results);

}


text:
/**
 * @module util
 */

'use strict'

const child = require('child_process')
const fs = require('fs')
const path = require('path')

const Promise = require('bluebird')

const debug = require('debug')

/**
 * This callback is used across signing and flattening.
 * @callback RequestCallback
 * @param {?Error} err
 */

/** @function */
const debuglog = module.exports.debuglog = debug('electron-osx-sign')
debuglog.log = console.log.bind(console)

/** @function */
const debugwarn = module.exports.debugwarn = debug('electron-osx-sign:warn')
debugwarn.log = console.warn.bind(console)

/** @function */
const debugerror = module.exports.debugerror = debug('electron-osx-sign:error')
debugerror.log = console.error.bind(console)

/** @function */
const isBinaryFileAsync = module.exports.isBinaryFileAsync = Promise.promisify(require('isbinaryfile'))

/** @function */
module.exports.execFileAsync = Promise.promisify(child.execFile)

/** @function */
const lstatAsync = module.exports.lstatAsync = Promise.promisify(fs.lstat)

/** @function */
const readdirAsync = module.exports.readdirAsync = Promise.promisify(fs.readdir)

/** @function */
module.exports.readFileAsync = Promise.promisify(fs.readFile)

/** @function */
module.exports.writeFileAsync = Promise.promisify(fs.writeFile)

/**
 * This function returns a flattened list of elements from an array of lists.
 * @function
 * @param {*} list - List.
 * @returns Flattened list.
 */
var flatList = module.exports.flatList = function (list) {
  function populateResult (list) {
    if (!Array.isArray(list)) {
      result.push(list)
    } else if (list.length > 0) {
      for (let item of list) if (item) populateResult(item)
    }
  }

  var result = []
  populateResult(list)
  return result
}

/**
 * This function returns the path to app contents.
 * @function
 * @param {Object} opts - Options.
 * @returns {string} App contents path.
 */
var getAppContentsPath = module.exports.getAppContentsPath = function (opts) {
  return path.join(opts.app, 'Contents')
}

/**
 * This function returns the path to app frameworks within contents.
 * @function
 * @param {Object} opts - Options.
 * @returns {string} App frameworks path.
 */
var getAppFrameworksPath = module.exports.getAppFrameworksPath = function (opts) {
  return path.join(getAppContentsPath(opts), 'Frameworks')
}

/**
 * This function returns a promise copying a file from the source to the target.
 * @function
 * @param {string} source - Source path.
 * @param {string} target - Target path.
 * @returns {Promise} Promise.
 */
module.exports.copyFileAsync = function (source, target) {
  debuglog('Copying file...', '\n',
    '> Source:', source, '\n',
    '> Target:', target)
  return new Promise(function (resolve, reject) {
    var readStream = fs.createReadStream(source)
    readStream.on('error', reject)
    var writeStream = fs.createWriteStream(target)
    writeStream.on('error', reject)
    writeStream.on('close', resolve)
    readStream.pipe(writeStream)
  })
}

/**
 * This function returns a promise with platform resolved.
 * @function
 * @param {Object} opts - Options.
 * @returns {Promise} Promise resolving platform.
 */
var detectElectronPlatformAsync = module.exports.detectElectronPlatformAsync = function (opts) {
  return new Promise(function (resolve) {
    var appFrameworksPath = getAppFrameworksPath(opts)
    // The presence of Squirrel.framework identifies a Mac App Store build as used in https://github.com/atom/electron/blob/master/docs/tutorial/mac-app-store-submission-guide.md
    return lstatAsync(path.join(appFrameworksPath, 'Squirrel.framework'))
      .then(function () {
        resolve('darwin')
      })
      .catch(function () {
        resolve('mas')
      })
  })
}

/**
 * This function returns a promise resolving the file path if file binary.
 * @function
 * @param {string} filePath - Path to file.
 * @returns {Promise} Promise resolving file path or undefined.
 */
var getFilePathIfBinaryAsync = module.exports.getFilePathIfBinaryAsync = function (filePath) {
  return isBinaryFileAsync(filePath)
    .then(function (isBinary) {
      return isBinary ? filePath : undefined
    })
}

/**
 * This function returns a promise validating opts.app, the application to be signed or flattened.
 * @function
 * @param {Object} opts - Options.
 * @returns {Promise} Promise.
 */
module.exports.validateOptsAppAsync = function (opts) {
  return new Promise(function (resolve, reject) {
    if (!opts.app) {
      reject(new Error('Path to aplication must be specified.'))
      return
    }
    if (path.extname(opts.app) !== '.app') {
      reject(new Error('Extension of application must be `.app`.'))
      return
    }
    return lstatAsync(opts.app)
      .then(function () {
        resolve(undefined)
      })
      .catch(function (err) {
        debugerror(err)
        reject(new Error('Application not found. See details in debug log. (electron-osx-sign:error)'))
      })
  })
}

/**
 * This function returns a promise validating opts.platform, the platform of Electron build. It allows auto-discovery if no opts.platform is specified.
 * @function
 * @param {Object} opts - Options.
 * @returns {Promise} Promise.
 */
module.exports.validateOptsPlatformAsync = function (opts) {
  return new Promise(function (resolve, reject) {
    if (opts.platform) {
      if (opts.platform === 'mas' || opts.platform === 'darwin') {
        resolve()
        return
      } else {
        debugwarn('`platform` passed in arguments not supported, checking Electron platform...')
      }
    } else {
      debugwarn('No `platform` passed in arguments, checking Electron platform...')
    }
    return detectElectronPlatformAsync(opts)
      .then(function (platform) {
        opts.platform = platform
        resolve()
      })
      .catch(function (err) {
        // NB: This should logically not happen as detectElectronPlatformAsync should not give any rejections. However, it is put here just in case.
        debugerror(err)
        reject(new Error('Unable to decide Electron platform. See details in debug log. (electron-osx-sign:error)'))
      })
  })
}

/**
 * This function returns a promise resolving all child paths within the directory specified.
 * @function
 * @param {string} dirPath - Path to directory.
 * @returns {Promise} Promise resolving child paths needing signing in order.
 */
module.exports.walkAsync = function (dirPath) {
  debuglog('Walking... ' + dirPath)

  var unlinkAsync = Promise.promisify(fs.unlink)

  function _walkAsync (dirPath) {
    return readdirAsync(dirPath)
      .then(function (names) {
        return Promise.map(names, function (name) {
          var filePath = path.join(dirPath, name)
          return lstatAsync(filePath)
            .then(function (stat) {
              if (stat.isFile()) {
                switch (path.extname(filePath)) {
                  case '': // Binary
                    if (path.basename(filePath)[0] !== '.') {
                      return getFilePathIfBinaryAsync(filePath)
                    } // Else reject hidden file
                    break
                  case '.dylib': // Dynamic library
                  case '.node': // Native node addon
                    return filePath
                  case '.cstemp': // Temporary file generated from past codesign
                    debuglog('Removing... ' + filePath)
                    return unlinkAsync(filePath)
                      .thenReturn(undefined)
                  default:
                    if (path.extname(filePath).indexOf(' ') >= 0) {
                      // Still consider the file as binary if extension seems invalid
                      return getFilePathIfBinaryAsync(filePath)
                    }
                }
              } else if (stat.isDirectory() && !stat.isSymbolicLink()) {
                return _walkAsync(filePath)
                  .then(function (result) {
                    switch (path.extname(filePath)) {
                      case '.app': // Application
                      case '.framework': // Framework
                        result.push(filePath)
                    }
                    return result
                  })
              }
              return undefined
            })
        })
      })
  }

  return _walkAsync(dirPath)
    .then(flatList)
}


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

using System;
using osu.Framework.Configuration;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using OpenTK.Input;
using OpenTK;
using System.Diagnostics;

namespace osu.Framework.Graphics.UserInterface
{
    public abstract class SliderBar<T> : Container, IHasCurrentValue<T>
        where T : struct
    {
        /// <summary>
        /// Range padding reduces the range of movement a slider bar is allowed to have
        /// while still receiving input in the padded region. This behavior is necessary
        /// for finite-sized nubs and can not be achieved (currently) by existing
        /// scene graph padding / margin functionality.
        /// </summary>
        public float RangePadding;

        public float UsableWidth => DrawWidth - 2 * RangePadding;

        /// <summary>
        /// A custom step value for each key press which actuates a change on this control.
        /// </summary>
        public float KeyboardStep;

        protected readonly BindableNumber<T> CurrentNumber;

        public Bindable<T> Current => CurrentNumber;

        protected SliderBar()
        {
            if (typeof(T) == typeof(int))
                CurrentNumber = new BindableInt() as BindableNumber<T>;
            else if (typeof(T) == typeof(long))
                CurrentNumber = new BindableLong() as BindableNumber<T>;
            else if (typeof(T) == typeof(double))
                CurrentNumber = new BindableDouble() as BindableNumber<T>;

            if (CurrentNumber == null) throw new NotImplementedException($"We don't support the generic type of {nameof(BindableNumber<T>)}.");

            CurrentNumber.ValueChanged += v => UpdateValue(NormalizedValue);
        }

        protected float NormalizedValue
        {
            get
            {
                if (Current == null)
                    return 0;
                var min = Convert.ToSingle(CurrentNumber.MinValue);
                var max = Convert.ToSingle(CurrentNumber.MaxValue);
                var val = Convert.ToSingle(CurrentNumber.Value);
                return (val - min) / (max - min);
            }
        }

        protected abstract void UpdateValue(float value);

        protected override void LoadComplete()
        {
            base.LoadComplete();
            UpdateValue(NormalizedValue);
        }

        protected override bool OnClick(InputState state)
        {
            handleMouseInput(state);
            return true;
        }

        protected override bool OnDrag(InputState state)
        {
            handleMouseInput(state);
            return true;
        }

        protected override bool OnDragStart(InputState state)
        {
            Trace.Assert(state.Mouse.PositionMouseDown.HasValue,
                $@"Can not start a {nameof(SliderBar<T>)} drag without knowing the mouse down position.");

            Vector2 posDiff = state.Mouse.PositionMouseDown.Value - state.Mouse.Position;

            return Math.Abs(posDiff.X) > Math.Abs(posDiff.Y);
        }

        protected override bool OnDragEnd(InputState state) => true;

        protected override bool OnKeyDown(InputState state, KeyDownEventArgs args)
        {
            if (!Hovering)
                return false;

            var step = KeyboardStep != 0 ? KeyboardStep : (Convert.ToSingle(CurrentNumber.MaxValue) - Convert.ToSingle(CurrentNumber.MinValue)) / 20;
            if (CurrentNumber.IsInteger) step = (float)Math.Ceiling(step);

            switch (args.Key)
            {
                case Key.Right:
                    CurrentNumber.Add(step);
                    OnUserChange();
                    return true;
                case Key.Left:
                    CurrentNumber.Add(-step);
                    OnUserChange();
                    return true;
                default:
                    return false;
            }
        }

        private void handleMouseInput(InputState state)
        {
            var xPosition = ToLocalSpace(state.Mouse.NativeState.Position).X - RangePadding;

            if (!CurrentNumber.Disabled)
                CurrentNumber.SetProportional(xPosition / UsableWidth);

            OnUserChange();
        }

        /// <summary>
        /// Triggered when the value is changed based on end-user input to this control.
        /// </summary>
        protected virtual void OnUserChange() { }
    }
}


text:
// Copyright (c) Source Tree Solutions, LLC. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Author:                  Joe Audette
// Created:                 2016-04-25
// Last Modified:           2018-08-20
//

using cloudscribe.SimpleContent.Models;
using Microsoft.Extensions.Logging;
using NoDb;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace cloudscribe.SimpleContent.Storage.NoDb
{
    public class PostXmlSerializer : IStringSerializer<Post>
    {
        public PostXmlSerializer(
            ILogger<PostXmlSerializer> logger)
        {
            log = logger;
        }

        private ILogger log;

        public string ExpectedFileExtension { get; } = ".xml";

        public string Serialize(Post post)
        {
            var doc = new XDocument(
                            new XElement("post",
                                new XElement("id", post.Id),
                                new XElement("title", post.Title),
                                new XElement("slug", post.Slug),
                                new XElement("correlationkey", post.CorrelationKey),
                                new XElement("author", post.Author),
                                new XElement("pubDate", post.PubDate?.ToString("O")),
                                new XElement("lastModified", post.LastModified.ToString("s")),
                                new XElement("excerpt", post.MetaDescription),
                                new XElement("content", post.Content),
                                new XElement("contentType", post.ContentType),
                                new XElement("imageUrl", post.ImageUrl),
                                new XElement("thumbnailUrl", post.ThumbnailUrl),

                                new XElement("createdUtc", post.CreatedUtc.ToString("s")),
                                new XElement("createdByUser", post.CreatedByUser),
                                new XElement("lastModifiedByUser", post.LastModifiedByUser),
                                new XElement("draftAuthor", post.DraftAuthor),
                                new XElement("draftContent", post.DraftContent),
                                new XElement("draftPubDate", post.DraftPubDate?.ToString("O")),
                                new XElement("templateKey", post.TemplateKey),
                                new XElement("serializedModel", post.SerializedModel),
                                new XElement("draftSerializedModel", post.DraftSerializedModel),
                                new XElement("serializer", post.Serializer),
                                new XElement("blogId", post.BlogId),

                                new XElement("ispublished", post.IsPublished),
                                new XElement("isFeatured", post.IsFeatured),
                                new XElement("autoTeaser", post.AutoTeaser),
                                new XElement("teaserOverride", post.TeaserOverride),
                                new XElement("suppressTeaser", post.SuppressTeaser),
                                new XElement("categories", string.Empty),
                                new XElement("comments", string.Empty),
                                new XElement("showcomments", post.ShowComments)
                            ));

            //XElement categories = doc.XPathSelectElement("post/categories");
            var categories = doc.Descendants("categories").FirstOrDefault();
            foreach (string category in post.Categories)
            {
                categories.Add(new XElement("category", category));
            }

            //XElement comments = doc.XPathSelectElement("post/comments");
            if (post.Comments != null)
            {
                var comments = doc.Descendants("comments").FirstOrDefault();
                foreach (Comment comment in post.Comments)
                {
                    try
                    {
                        comments.Add(
                        new XElement("comment",
                            new XElement("author", comment.Author),
                            new XElement("email", comment.Email),
                            new XElement("website", comment.Website),
                            new XElement("ip", comment.Ip),
                            new XElement("userAgent", comment.UserAgent),
                            new XElement("date", comment.PubDate.ToString("O")),
                            new XElement("content", comment.Content),
                            new XAttribute("isAdmin", comment.IsAdmin),
                            new XAttribute("isApproved", comment.IsApproved),
                            new XAttribute("id", comment.Id)
                        ));
                    }
                    catch (Exception ex)
                    {
                        log.LogError("error adding comment", ex);
                    }

                }
            }

            using (StringWriter s = new StringWriter())
            {
                doc.Save(s, SaveOptions.None);

                return s.GetStringBuilder().ToString();
            }

        }

        public Post Deserialize(string xmlString, string key)
        {
            // we need the key passed in here because the xml format adopted from MiniBlog/BlogEngine
            // does not store the post id in the xml but only as part of the file name

            var doc = XDocument.Parse(xmlString);

            Post post = new Post()
            {
                Id = key,
                BlogId = ReadValue(doc.Root, "blogId"),
                Title = ReadValue(doc.Root, "title"),
                Author = ReadValue(doc.Root, "author"),
                CorrelationKey = ReadValue(doc.Root, "correlationkey"),
                MetaDescription = ReadValue(doc.Root, "excerpt"),
                Content = ReadValue(doc.Root, "content"),
                ContentType = ReadValue(doc.Root, "contentType"),
                Slug = ReadValue(doc.Root, "slug").ToLowerInvariant(),
                ImageUrl = ReadValue(doc.Root, "imageUrl"),
                ThumbnailUrl = ReadValue(doc.Root, "thumbnailUrl"),
                PubDate = GetNullableDate(doc.Root, "pubDate"),
                LastModified = GetDate(doc.Root, "lastModified"),
                IsPublished = bool.Parse(ReadValue(doc.Root, "ispublished", "true")),
                IsFeatured = bool.Parse(ReadValue(doc.Root, "isFeatured", "false")),
                AutoTeaser = ReadValue(doc.Root, "autoTeaser"),
                TeaserOverride = ReadValue(doc.Root, "teaserOverride"),
                SuppressTeaser = bool.Parse(ReadValue(doc.Root, "suppressTeaser", "false")),

                CreatedUtc = GetDate(doc.Root, "createdUtc"),
                CreatedByUser = ReadValue(doc.Root, "createdByUser"),
                LastModifiedByUser = ReadValue(doc.Root, "lastModifiedByUser"),
                DraftAuthor = ReadValue(doc.Root, "draftAuthor"),
                DraftContent = ReadValue(doc.Root, "draftContent"),
                DraftPubDate = GetNullableDate(doc.Root, "draftPubDate"),
                TemplateKey = ReadValue(doc.Root, "templateKey"),
                SerializedModel = ReadValue(doc.Root, "serializedModel"),
                DraftSerializedModel = ReadValue(doc.Root, "draftSerializedModel"),
                Serializer = ReadValue(doc.Root, "serializer"),
                ShowComments = bool.Parse(ReadValue(doc.Root, "showcomments", "true"))

            };

            LoadCategories(post, doc.Root);
            LoadComments(post, doc.Root);

            return post;

        }

        protected void LoadCategories(Post post, XElement doc)
        {
            XElement categories = doc.Element("categories");
            if (categories == null)
                return;

            List<string> list = new List<string>();

            foreach (var node in categories.Elements("category"))
            {
                list.Add(node.Value);
            }

            post.Categories = list;
        }

        protected void LoadComments(Post post, XElement doc)
        {
            var comments = doc.Element("comments");

            if (comments == null)
                return;

            foreach (var node in comments.Elements("comment"))
            {
                Comment comment = new Comment()
                {
                    Id = ReadAttribute(node, "id"),
                    Author = ReadValue(node, "author"),
                    Email = ReadValue(node, "email"),
                    Website = ReadValue(node, "website"),
                    Ip = ReadValue(node, "ip"),
                    UserAgent = ReadValue(node, "userAgent"),
                    IsAdmin = bool.Parse(ReadAttribute(node, "isAdmin", "false")),
                    IsApproved = bool.Parse(ReadAttribute(node, "isApproved", "true")),
                    Content = ReadValue(node, "content").Replace("\n", "<br />"),
                    PubDate = DateTime.Parse(ReadValue(node, "date", "2000-01-01")),
                };

                post.Comments.Add(comment);
            }
        }

        protected DateTime GetDate(XElement doc, XName name)
        {
            if (doc.Element(name) == null)
                return DateTime.UtcNow;

            DateTime d;
            try
            {
                d = DateTime.ParseExact(
                    ReadValue(doc, name, DateTime.UtcNow.ToString()),
                    "O",
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.AssumeUniversal |
                    DateTimeStyles.AdjustToUniversal
                );
            }
            catch (FormatException)
            {
                try
                {
                    d = DateTime.Parse(ReadValue(doc, name));
                }
                catch(Exception ex)
                {
                    log.LogError($"failed to parse date so returning current date/time error: {ex.Message}: {ex.StackTrace}");
                    d = DateTime.UtcNow;
                }

            }

            return d;
        }

        protected DateTime? GetNullableDate(XElement doc, XName name)
        {
            if (doc.Element(name) == null)
                return null;

            var val = ReadValue(doc, name);
            if(string.IsNullOrWhiteSpace(val)) { return null; }

            DateTime? d;
            try
            {
                d = DateTime.ParseExact(
                    val,
                    "O",
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.AssumeUniversal |
                    DateTimeStyles.AdjustToUniversal
                );
            }
            catch (FormatException)
            {
                try
                {
                    d = DateTime.Parse(val);
                }
                catch (Exception ex)
                {
                    log.LogError($"failed to parse date from {val} so returning null error: {ex.Message}: {ex.StackTrace}");
                    d = null;
                }

            }

            return d;
        }

        protected string ReadValue(XElement doc, XName name, string defaultValue = "")
        {
            if (doc.Element(name) != null)
                return doc.Element(name).Value;

            return defaultValue;
        }

        protected string ReadAttribute(XElement element, XName name, string defaultValue = "")
        {
            if (element.Attribute(name) != null)
                return element.Attribute(name).Value;

            return defaultValue;
        }
    }
}


text:
<?php

/**
  * @package sfLucenePlugin
  * @subpackage Test
  * @author Carl Vondrick
  * @version SVN: $Id: sfLuceneSimpleFormTest.php 7108 2008-01-20 07:44:42Z Carl.Vondrick $
  */

require dirname(__FILE__) . '/../../bootstrap/unit.php';

$t = new limeade_test(12, limeade_output::get());
$limeade = new limeade_sf($t);
$app = $limeade->bootstrap();

$t->diag('testing constructor');

try {
  $form = new sfLuceneSimpleForm();
  $t->pass('__construct() with no arguments does not throw an exception');
} catch (Exception $e) {
  $t->fail('__construct() with no arguments does not throw an exception');
}

$t->diag('testing initialization');

$t->isa_ok($form->getWidgetSchema(), 'sfWidgetFormSchema', 'widget schema is appropriate type');
$t->isa_ok($form->getValidatorSchema(), 'sfValidatorSchema', 'validator schema is appropriate type');

$t->isa_ok($form->getWidgetSchema()->getFormFormatter(), 'sfLuceneWidgetFormatterSimple', 'formatter is appropriate type');

$t->diag('testing categories');

$categories = array('foo','bar','baz','foobar');

$form->setCategories($categories);

$t->ok($form->getWidgetSchema()->offsetExists('category'), '->setCategories() adds "category" key to widget schema');
$t->is_deeply($form->getWidgetSchema()->offsetGet('category')->getOption('choices'), $categories, '->setCategories() configures widget with correct choices');

$t->ok($form->getValidatorSchema()->offsetExists('category'), '->setCategories() adds "category" key to validator schema');
$t->is_deeply($form->getValidatorSchema()->offsetGet('category')->getOption('choices'), $categories, '->setCategories() configures validator with correct choices');

$form->setCategories(array());

$t->ok(!$form->getWidgetSchema()->offsetExists('category'), '->setCategories() removes "category" key from widget schema');
$t->ok(!$form->getValidatorSchema()->offsetExists('category'), '->setCategories() removes "category" key from validator schema');

$t->diag('testing url string generation');

$form = new sfLuceneSimpleForm;
$form->setCategories(array('baz'));
$form->bind(array('query' => 'foobar', 'category' => 'baz', 'page' => 2));

$t->is($form->getQueryString(), 'form%5Bquery%5D=foobar&form%5Bcategory%5D=baz&form%5Bpage%5D=2', '->getQueryString() returns querystring');
$t->is($form->getQueryString(5), 'form%5Bquery%5D=foobar&form%5Bcategory%5D=baz&form%5Bpage%5D=5', '->getQueryString() returns querystring with altered page');


text:
var onboarding = {};

onboarding.advance = function () {
    window.location = $('button.onboarding_next').data('onboarding_next');
};

onboarding.allow_advancement = function () {
    $('.onboarding .advancement').find('.button_overlay, .skip_step').hide();
};

onboarding.update_quota = function () {
    var remaining = onboarding.quota - onboarding.quota_fulfillment();

    if (remaining <= 0) {
        onboarding.allow_advancement();
    } else {
        $('.quota').text(remaining);
        $('.quota_plurality').text(remaining > 1 ? 's' : '');
    }
};

$(function () {
    if (!$('.onboarding').length) {
        return;
    }

    $('button.onboarding_next').click(function (event) {
        event.preventDefault();
        onboarding.advance();
    });

    if ($('.quota').length && onboarding.quota_fulfillment) {
        onboarding.quota = parseInt($('.quota').text(), 10);
        onboarding.update_quota();
    }
});


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Utility functions — vt-py  documentation</title>

  <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="prev" title="Iterator" href="iterator.html" />

             vt-py

  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Contents:

How to install

Overview

Quickstart

API reference

Client

Feed

Object

Iterator

Utilities

          vt-py

Docs »

API reference »

Utility functions

             View page source

Utility functions¶

vt.url_id(url)[source]

Generates the object ID for an URL.

The ID generated by this function can be used in calls that expect a URL ID
like client.get_object('/urls/<id>')

         Previous

        © Copyright 2019, VirusTotal

  Built with Sphinx using a theme provided by Read the Docs.


text:
"""A module for authenticating against and communicating with selected
parts of the Garmin Connect REST API.
"""

import json
import logging
import os
import os.path
import re
import sys
import zipfile
from datetime import timedelta, datetime
from builtins import range
from functools import wraps
from io import BytesIO

import dateutil
import dateutil.parser

#
# By default we use the requests library to create http clients. If built with
# the 'cloudflare' extra, we use cloudscraper to circumvent CloudFlare's
# anti-bot protection pages.
#
import requests
session_factory = requests.session
try:
    import cloudscraper
    session_factory = cloudscraper.create_scraper
except (ImportError):
    pass

from garminexport.retryer import Retryer, ExponentialBackoffDelayStrategy, MaxRetriesStopStrategy

#
# Note: For more detailed information about the API services
# used by this module, log in to your Garmin Connect account
# through the web browser and visit the API documentation page
# for the REST service of interest. For example:
#   https://connect.garmin.com/proxy/activity-service-1.3/index.html
#   https://connect.garmin.com/proxy/activity-search-service-1.2/index.html
#

#
# Other useful references:
#   https://github.com/cpfair/tapiriik/blob/master/tapiriik/services/GarminConnect/garminconnect.py
#   https://forums.garmin.com/showthread.php?72150-connect-garmin-com-signin-question/page2
#

log = logging.getLogger(__name__)

# reduce logging noise from requests library
logging.getLogger("requests").setLevel(logging.ERROR)

SSO_LOGIN_URL = "https://sso.garmin.com/sso/login"
"""Garmin Connect's Single-Sign On login URL."""
SSO_SIGNIN_URL = "https://sso.garmin.com/sso/signin"
"""The Garmin Connect Single-Sign On sign-in URL. This is where the login form
gets POSTed."""

def require_session(client_function):
    """Decorator that is used to annotate :class:`GarminClient`
    methods that need an authenticated session before being called.
    """

    @wraps(client_function)
    def check_session(*args, **kwargs):
        client_object = args[0]
        if not client_object.session:
            raise Exception("Attempt to use GarminClient without being connected. Call connect() before first use.'")
        return client_function(*args, **kwargs)

    return check_session

class GarminClient(object):
    """A client class used to authenticate with Garmin Connect and
    extract data from the user account.

    Since this class implements the context manager protocol, this object
    can preferably be used together with the with-statement. This will
    automatically take care of logging in to Garmin Connect before any
    further interactions and logging out after the block completes or
    a failure occurs.

    Example of use: ::
      with GarminClient("my.sample@sample.com", "secretpassword") as client:
          ids = client.list_activity_ids()
          for activity_id in ids:
               gpx = client.get_activity_gpx(activity_id)

    """

    def __init__(self, username, password, user_agent_fn=None):
        """Initialize a :class:`GarminClient` instance.

        :param username: Garmin Connect user name or email address.
        :type username: str
        :param password: Garmin Connect account password.
        :type password: str
        :keyword user_agent_fn: A function that, when called, produces a
        `User-Agent` string to be used as `User-Agent` for the remainder of the
        session. If set to None, the default user agent of the http request
        library is used.
        :type user_agent_fn: Callable[[], str]

        """
        self.username = username
        self.password = password
        self._user_agent_fn = user_agent_fn

        self.session = None

    def __enter__(self):
        self.connect()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.disconnect()

    def connect(self):
        log.debug("using session factory: %s", session_factory.__module__)
        self.session = session_factory()
        self._authenticate()

    def disconnect(self):
        if self.session:
            self.session.close()
            self.session = None

    def _authenticate(self):
        log.info("authenticating user ...")

        form_data = {
            "username": self.username,
            "password": self.password,
            "embed": "false",
            "_csrf": self._get_csrf_token(),
        }
        headers = {
            'origin': 'https://sso.garmin.com',
        }
        if self._user_agent_fn:
            user_agent = self._user_agent_fn()
            if not user_agent:
                raise ValueError("user_agent_fn didn't produce a value")
            headers['User-Agent'] = user_agent

        auth_response = self.session.post(
            SSO_SIGNIN_URL, headers=headers, params=self._auth_params(), data=form_data)
        log.debug("got auth response: %s", auth_response.text)
        if auth_response.status_code != 200:
            raise ValueError("authentication failure: did you enter valid credentials?")
        auth_ticket_url = self._extract_auth_ticket_url(auth_response.text)
        log.debug("auth ticket url: '%s'", auth_ticket_url)

        log.info("claiming auth ticket ...")
        response = self.session.get(auth_ticket_url)
        if response.status_code != 200:
            raise RuntimeError(
                "auth failure: failed to claim auth ticket: {}: {}\n{}".format(
                    auth_ticket_url, response.status_code, response.text))

        # appears like we need to touch base with the main page to complete the
        # login ceremony.
        self.session.get('https://connect.garmin.com/modern')

    def _get_csrf_token(self):
        """Retrieves a Cross-Site Request Forgery (CSRF) token from Garmin's login
        page. The token is passed along in the login form for increased
        security."""
        log.info("fetching CSRF token ...")
        resp = self.session.get(SSO_LOGIN_URL, params=self._auth_params())
        if resp.status_code != 200:
            raise ValueError("auth failure: could not load {}".format(SSO_LOGIN_URL))
        # extract CSRF token
        csrf_token = re.search(r'<input type="hidden" name="_csrf" value="(\w+)"',
                               resp.content.decode('utf-8'))
        if not csrf_token:
            raise ValueError("auth failure: no CSRF token in {}".format(SSO_LOGIN_URL))
        return csrf_token.group(1)

    def _auth_params(self):
        """A set of request query parameters that need to be present for Garmin to
        accept our login attempt.
        """
        return {
            "service": "https://connect.garmin.com/modern/",
            "gauthHost": "https://sso.garmin.com/sso",
        }

    @staticmethod
    def _extract_auth_ticket_url(auth_response):
        """Extracts an authentication ticket URL from the response of an
        authentication form submission. The auth ticket URL is typically
        of form:

          https://connect.garmin.com/modern?ticket=ST-0123456-aBCDefgh1iJkLmN5opQ9R-cas

        :param auth_response: HTML response from an auth form submission.
        """
        match = re.search(r'response_url\s*=\s*"(https:[^"]+)"', auth_response)
        if not match:
            raise RuntimeError(
                "auth failure: unable to extract auth ticket URL. did you provide a correct username/password?")
        auth_ticket_url = match.group(1).replace("\\", "")
        return auth_ticket_url

    @require_session
    def list_activities(self):
        """Return all activity ids stored by the logged in user, along
        with their starting timestamps.

        :returns: The full list of activity identifiers (along with their starting timestamps).
        :rtype: tuples of (int, datetime)
        """
        ids = []
        batch_size = 100
        # fetch in batches since the API doesn't allow more than a certain
        # number of activities to be retrieved on every invocation
        for start_index in range(0, sys.maxsize, batch_size):
            next_batch = self._fetch_activity_ids_and_ts(start_index, batch_size)
            if not next_batch:
                break
            ids.extend(next_batch)
        return ids

    @require_session
    def _fetch_activity_ids_and_ts(self, start_index, max_limit=100):
        """Return a sequence of activity ids (along with their starting
        timestamps) starting at a given index, with index 0 being the user's
        most recently registered activity.

        Should the index be out of bounds or the account empty, an empty list is returned.

        :param start_index: The index of the first activity to retrieve.
        :type start_index: int
        :param max_limit: The (maximum) number of activities to retrieve.
        :type max_limit: int

        :returns: A list of activity JSON dicts describing the activity
        :rtype: tuples of (int, datetime)
        """
        log.debug("fetching activities %d through %d ...", start_index, start_index + max_limit - 1)
        response = self.session.get(
            "https://connect.garmin.com/proxy/activitylist-service/activities/search/activities",
            params={"start": start_index, "limit": max_limit})
        if response.status_code != 200:
            raise Exception(
                u"failed to fetch activities {} to {} types: {}\n{}".format(
                    start_index, (start_index + max_limit - 1), response.status_code, response.text))
        activities = json.loads(response.text)
        if not activities:
            # index out of bounds or empty account
            return []

        entries = []
        for activity in activities:
            id = int(activity["activityId"])
            timestamp_utc = dateutil.parser.parse(activity["startTimeGMT"])
            # make sure UTC timezone gets set
            timestamp_utc = timestamp_utc.replace(tzinfo=dateutil.tz.tzutc())
            entries.append((id, timestamp_utc))
        log.debug("got %d activities.", len(entries))
        return entries

    @require_session
    def get_activity_summary(self, activity_id):
        """Return a summary about a given activity.
        The summary contains several statistics, such as duration, GPS starting
        point, GPS end point, elevation gain, max heart rate, max pace, max speed, etc).

        :param activity_id: Activity identifier.
        :type activity_id: int
        :returns: The activity summary as a JSON dict.
        :rtype: dict
        """
        response = self.session.get(
            "https://connect.garmin.com/proxy/activity-service/activity/{}".format(activity_id))
        if response.status_code != 200:
            log.error(u"failed to fetch json summary for activity %s: %d\n%s",
                      activity_id, response.status_code, response.text)
            raise Exception(u"failed to fetch json summary for activity {}: {}\n{}".format(
                activity_id, response.status_code, response.text))
        return json.loads(response.text)

    @require_session
    def get_activity_details(self, activity_id):
        """Return a JSON representation of a given activity including
        available measurements such as location (longitude, latitude),
        heart rate, distance, pace, speed, elevation.

        :param activity_id: Activity identifier.
        :type activity_id: int
        :returns: The activity details as a JSON dict.
        :rtype: dict
        """
        # mounted at xml or json depending on result encoding
        response = self.session.get(
            "https://connect.garmin.com/proxy/activity-service/activity/{}/details".format(activity_id))
        if response.status_code != 200:
            raise Exception(u"failed to fetch json activityDetails for {}: {}\n{}".format(
                activity_id, response.status_code, response.text))
        return json.loads(response.text)

    @require_session
    def get_activity_gpx(self, activity_id):
        """Return a GPX (GPS Exchange Format) representation of a
        given activity. If the activity cannot be exported to GPX
        (not yet observed in practice, but that doesn't exclude the
        possibility), a :obj:`None` value is returned.

        :param activity_id: Activity identifier.
        :type activity_id: int
        :returns: The GPX representation of the activity as an XML string
          or ``None`` if the activity couldn't be exported to GPX.
        :rtype: str
        """
        response = self.session.get(
            "https://connect.garmin.com/proxy/download-service/export/gpx/activity/{}".format(activity_id))
        # An alternate URL that seems to produce the same results
        # and is the one used when exporting through the Garmin
        # Connect web page.
        # response = self.session.get("https://connect.garmin.com/proxy/activity-service-1.1/gpx/activity/{}?full=true".format(activity_id))

        # A 404 (Not Found) or 204 (No Content) response are both indicators
        # of a gpx file not being available for the activity. It may, for
        # example be a manually entered activity without any device data.
        if response.status_code in (404, 204):
            return None
        if response.status_code != 200:
            raise Exception(u"failed to fetch GPX for activity {}: {}\n{}".format(
                activity_id, response.status_code, response.text))
        return response.text

    @require_session
    def get_activity_tcx(self, activity_id):
        """Return a TCX (Training Center XML) representation of a
        given activity. If the activity doesn't have a TCX source (for
        example, if it was originally uploaded in GPX format, Garmin
        won't try to synthesize a TCX file) a :obj:`None` value is
        returned.

        :param activity_id: Activity identifier.
        :type activity_id: int
        :returns: The TCX representation of the activity as an XML string
          or ``None`` if the activity cannot be exported to TCX.
        :rtype: str
        """

        response = self.session.get(
            "https://connect.garmin.com/proxy/download-service/export/tcx/activity/{}".format(activity_id))
        if response.status_code == 404:
            return None
        if response.status_code != 200:
            raise Exception(u"failed to fetch TCX for activity {}: {}\n{}".format(
                activity_id, response.status_code, response.text))
        return response.text

    def get_original_activity(self, activity_id):
        """Return the original file that was uploaded for an activity.
        If the activity doesn't have any file source (for example,
        if it was entered manually rather than imported from a Garmin
        device) then :obj:`(None,None)` is returned.

        :param activity_id: Activity identifier.
        :type activity_id: int
        :returns: A tuple of the file type (e.g. 'fit', 'tcx', 'gpx') and
          its contents, or :obj:`(None,None)` if no file is found.
        :rtype: (str, str)
        """
        response = self.session.get(
            "https://connect.garmin.com/proxy/download-service/files/activity/{}".format(activity_id))
        # A 404 (Not Found) response is a clear indicator of a missing .fit
        # file. As of lately, the endpoint appears to have started to
        # respond with 500 "NullPointerException" on attempts to download a
        # .fit file for an activity without one.
        if response.status_code in [404, 500]:
            # Manually entered activity, no file source available
            return None, None
        if response.status_code != 200:
            raise Exception(
                u"failed to get original activity file for {}: {}\n{}".format(
                    activity_id, response.status_code, response.text))

        # return the first entry from the zip archive where the filename is
        # activity_id (should be the only entry!)
        zip_file = zipfile.ZipFile(BytesIO(response.content), mode="r")
        for path in zip_file.namelist():
            fn, ext = os.path.splitext(path)
            if fn.startswith(str(activity_id)):
                return ext[1:], zip_file.open(path).read()
        return None, None

    def get_activity_fit(self, activity_id):
        """Return a FIT representation for a given activity. If the activity
        doesn't have a FIT source (for example, if it was entered manually
        rather than imported from a Garmin device) a :obj:`None` value is
        returned.

        :param activity_id: Activity identifier.
        :type activity_id: int
        :returns: A string with a FIT file for the activity or :obj:`None`
          if no FIT source exists for this activity (e.g., entered manually).
        :rtype: str
        """
        fmt, orig_file = self.get_original_activity(activity_id)
        # if the file extension of the original activity file isn't 'fit',
        # this activity was uploaded in a different format (e.g. gpx/tcx)
        # and cannot be exported to fit
        return orig_file if fmt == 'fit' else None

    @require_session
    def _poll_upload_completion(self, uuid, creation_date):
        """Poll for completion of an upload. If Garmin connect returns
        HTTP status 202 ("Accepted") after initial upload, then we must poll
        until the upload has either succeeded or failed. Raises an
        :class:`Exception` if the upload has failed.

        :param uuid: uploadUuid returned on initial upload.
        :type uuid: str
        :param creation_date: creationDate returned from initial upload (e.g.
          "2020-01-01 12:34:56.789 GMT")
        :type creation_date: str
        :returns: Garmin's internalId for the newly-created activity, or
          :obj:`None` if upload is still processing.
        :rtype: int
        """
        response = self.session.get("https://connect.garmin.com/proxy/activity-service/activity/status/{}/{}?_={}".format(
            creation_date[:10], uuid.replace("-",""), int(datetime.now().timestamp()*1000)), headers={"nk": "NT"})
        if response.status_code == 201 and response.headers["location"]:
            # location should be https://connectapi.garmin.com/activity-service/activity/ACTIVITY_ID
            return int(response.headers["location"].split("/")[-1])
        elif response.status_code == 202:
            return None # still processing
        else:
            response.raise_for_status()

    @require_session
    def upload_activity(self, file, format=None, name=None, description=None, activity_type=None, private=None):
        """Upload a GPX, TCX, or FIT file for an activity.

        :param file: Path or open file
        :param format: File format (gpx, tcx, or fit); guessed from filename if :obj:`None`
        :type format: str
        :param name: Optional name for the activity on Garmin Connect
        :type name: str
        :param description: Optional description for the activity on Garmin Connect
        :type description: str
        :param activity_type: Optional activityType key (lowercase: e.g. running, cycling)
        :type activityType: str
        :param private: If true, then activity will be set as private.
        :type private: bool
        :returns: ID of the newly-uploaded activity
        :rtype: int
        """

        if isinstance(file, str):
            file = open(file, "rb")

        # guess file type if unspecified
        fn = os.path.basename(file.name)
        _, ext = os.path.splitext(fn)
        if format is None:
            if ext.lower() in ('.gpx', '.tcx', '.fit'):
                format = ext.lower()[1:]
            else:
                raise Exception(u"could not guess file type for {}".format(fn))

        # upload it
        files = dict(data=(fn, file))
        response = self.session.post("https://connect.garmin.com/proxy/upload-service/upload/.{}".format(format),
                                     files=files, headers={"nk": "NT"})

        # check response and get activity ID
        try:
            j = response.json()["detailedImportResult"]
        except (json.JSONDecodeError, KeyError):
            raise Exception(u"failed to upload {} for activity: {}\n{}".format(
                format, response.status_code, response.text))

        # single activity, immediate success
        if len(j["successes"]) == 1 and len(j["failures"]) == 0:
            activity_id = j["successes"][0]["internalId"]

        # duplicate of existing activity
        elif len(j["failures"]) == 1 and len(j["successes"]) == 0 and response.status_code == 409:
            log.info(u"duplicate activity uploaded, continuing")
            activity_id = j["failures"][0]["internalId"]

        # need to poll until success/failure
        elif len(j["failures"]) == 0 and len(j["successes"]) == 0 and response.status_code == 202:
            retryer = Retryer(
                returnval_predicate=bool,
                delay_strategy=ExponentialBackoffDelayStrategy(initial_delay=timedelta(seconds=1)),
                stop_strategy=MaxRetriesStopStrategy(6), # wait for up to 64 seconds (2**6)
                error_strategy=None
            )
            activity_id = retryer.call(self._poll_upload_completion, j["uploadUuid"]["uuid"], j["creationDate"])

        # don't know how to handle multiple activities
        elif len(j["successes"]) > 1:
            raise Exception(u"uploading {} resulted in multiple activities ({})".format(
                format, len(j["successes"])))

        # all other errors
        else:
            raise Exception(u"failed to upload {} for activity: {}\n{}".format(
                format, response.status_code, j["failures"]))

        # add optional fields
        data = {}
        if name is not None:
            data['activityName'] = name
        if description is not None:
            data['description'] = description
        if activity_type is not None:
            data['activityTypeDTO'] = {"typeKey": activity_type}
        if private:
            data['privacy'] = {"typeKey": "private"}
        if data:
            data['activityId'] = activity_id
            encoding_headers = {"Content-Type": "application/json; charset=UTF-8"}  # see Tapiriik
            response = self.session.put(
                "https://connect.garmin.com/proxy/activity-service/activity/{}".format(activity_id),
                data=json.dumps(data), headers=encoding_headers)
            if response.status_code != 204:
                raise Exception(u"failed to set metadata for activity {}: {}\n{}".format(
                    activity_id, response.status_code, response.text))

        return activity_id


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 System.Linq;
using Microsoft.Azure.Batch;
using Microsoft.Azure.Commands.Batch.Models;
using Microsoft.Azure.Commands.Batch.Properties;
using System;
using System.Collections.Generic;

namespace Microsoft.Azure.Commands.Batch.Models
{
    public partial class BatchClient
    {
        /// <summary>
        /// Creates a new compute node user.
        /// </summary>
        /// <param name="options">The options to use when creating the compute node user.</param>
        public void CreateComputeNodeUser(NewComputeNodeUserParameters options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            ComputeNodeUser user = null;
            string computeNodeId = null;
            if (options.ComputeNode != null)
            {
                user = options.ComputeNode.omObject.CreateComputeNodeUser();
                computeNodeId = options.ComputeNode.Id;
            }
            else
            {
                PoolOperations poolOperations = options.Context.BatchOMClient.PoolOperations;
                user = poolOperations.CreateComputeNodeUser(options.PoolId, options.ComputeNodeId);
                computeNodeId = options.ComputeNodeId;
            }

            user.Name = options.ComputeNodeUserName;
            user.Password = options.Password;
            user.ExpiryTime = options.ExpiryTime;
            user.IsAdmin = options.IsAdmin;

            WriteVerbose(string.Format(Resources.NBU_CreatingUser, user.Name, computeNodeId));

            user.Commit(ComputeNodeUserCommitSemantics.AddUser, options.AdditionalBehaviors);
        }

        /// <summary>
        /// Deletes the specified compute node user.
        /// </summary>
        /// <param name="parameters">The parameters indicating which compute node user to delete.</param>
        public void DeleteComputeNodeUser(ComputeNodeUserOperationParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            PoolOperations poolOperations = parameters.Context.BatchOMClient.PoolOperations;
            poolOperations.DeleteComputeNodeUser(parameters.PoolId, parameters.ComputeNodeId, parameters.ComputeNodeUserName, parameters.AdditionalBehaviors);
        }
    }
}


text:
using System;

namespace Myrtille.Fleck
{
    public class SubProtocolNegotiationFailureException : Exception
    {
        public SubProtocolNegotiationFailureException() : base() { }

        public SubProtocolNegotiationFailureException(string message) : base(message) {}

        public SubProtocolNegotiationFailureException(string message, Exception innerException) : base(message, innerException) {}
    }
}