text:
//-----------------------------------------------------------------------
// <copyright file="DataServiceActivityFixture.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.XPath;
using Activities;
using ActivityTestUtilities;
using DataServiceUtilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;

namespace DataServiceUtilitiesUnitTests
{
    /// Unit tests for the data service activity base class
    [TestClass]
    public class DataServiceActivityFixture
    {
        ///
        /// Test creating a DataServiceActivityBase derived activity instance
        ///
        [TestMethod]
        public void CreateTest()
        {
            var activity = Activity.CreateActivity(
                typeof(TestDataServiceActivity),
                null,
                SubmitActivityRequestHandler);
            Assert.IsNotNull(activity);
            Assert.IsInstanceOfType(activity, typeof(TestDataServiceActivity));
        }

        ///
        /// Test requesting fewer results than are available
        ///
        [TestMethod]
        public void RequestResultSubset()
        {
            var offset = 0;
            var maxResults = 5;
            var availableResults = 10;
            var expectedResults = maxResults;
            TestRequestPagedResults(availableResults, offset, maxResults, expectedResults);
        }

        ///
        /// Test requesting fewer results than are available starting from an offset
        ///
        [TestMethod]
        public void RequestResultSubsetWithOffset()
        {
            var offset = 3;
            var maxResults = 5;
            var availableResults = 10;
            var expectedResults = maxResults;
            TestRequestPagedResults(availableResults, offset, maxResults, expectedResults);
        }

        ///
        /// Test requesting more results than are available
        ///
        [TestMethod]
        public void RequestResultSuperset()
        {
            var offset = 0;
            var maxResults = 10;
            var availableResults = 5;
            var expectedResults = 5;
            TestRequestPagedResults(availableResults, offset, maxResults, expectedResults);
        }

        ///
        /// Test requesting more results than are available starting from an offset
        ///
        [TestMethod]
        public void RequestResultSupersetWithOffset()
        {
            var offset = 10;
            var maxResults = 50;
            var availableResults = 20;
            var expectedResults = availableResults - offset;
            TestRequestPagedResults(availableResults, offset, maxResults, expectedResults);
        }

        ///
        /// Test requesting more results than are available
        ///
        [TestMethod]
        public void RequestNoResultsAvailable()
        {
            var offset = 0;
            var maxResults = 10;
            var availableResults = 0;
            var expectedResults = 0;
            TestRequestPagedResults(availableResults, offset, maxResults, expectedResults);
        }

        ///
        /// Test requesting more results than are available starting from an offset
        ///
        [TestMethod]
        public void RequestNoResultsAvailableWithOffset()
        {
            var offset = 10;
            var maxResults = 50;
            var availableResults = 0;
            var expectedResults = 0;
            TestRequestPagedResults(availableResults, offset, maxResults, expectedResults);
        }

        /// Test requesting the top level nodes of a tree
        [TestMethod]
        public void RequestTopLevelSubtreeResults()
        {
            string subtreePath = null;
            var depth = 1;
            var graphBreadth = 3;
            var graphDepth = 5;
            var expectedResults = 4;

            TestRequestSubtreeResults(subtreePath, depth, graphBreadth, graphDepth, expectedResults);

            // TODO: Verify the node ids in the results match those expected
        }

        /// Test requesting a shallow subtree of one of the top level nodes
        [TestMethod]
        public void RequestShallowTopSubtreeResults()
        {
            string subtreePath = "1";
            var depth = 1;
            var graphBreadth = 4;
            var graphDepth = 5;
            var expectedResults = 4;

            TestRequestSubtreeResults(subtreePath, depth, graphBreadth, graphDepth, expectedResults);

            // TODO: Verify the node ids in the results match those expected
        }

        /// Test requesting a shallow subtree of one of the top level nodes
        [TestMethod]
        public void RequestDeepSubtreeResults()
        {
            string subtreePath = "1:2";
            var depth = 3;
            var graphBreadth = 4;
            var graphDepth = 5;
            var expectedResults = 84;

            TestRequestSubtreeResults(subtreePath, depth, graphBreadth, graphDepth, expectedResults);

            // TODO: Verify the node ids in the results match those expected
        }

        /// Test requesting a full tree
        [TestMethod]
        public void RequestFullTree()
        {
            string subtreePath = null;
            var depth = 4;
            var graphBreadth = 3;
            var graphDepth = 4;
            var expectedResults = 129;

            TestRequestSubtreeResults(subtreePath, depth, graphBreadth, graphDepth, expectedResults);

            // TODO: Verify the node ids in the results match those expected
        }

        /// Test requesting a subtree with unloaded results
        [TestMethod]
        public void RequestUnloadedResults()
        {
            string subtreePath = "100";
            var depth = 3;
            var graphBreadth = 2;
            var graphDepth = depth;
            var expectedResults = 1;

            TestRequestSubtreeResults(subtreePath, depth, graphBreadth, graphDepth, expectedResults);

            // TODO: Verify the node ids in the results match those expected
        }

        /// Test requesting results with a filter
        /// <remarks>TODO: Refactor into helper methods when/if variation tests are added</remarks>
        [TestMethod]
        public void TestRequestFilteredResults()
        {
            // Create the activity
            var activity = (TestDataServiceActivity)Activity.CreateActivity(
                typeof(TestDataServiceActivity),
                null,
                SubmitActivityRequestHandler);
            activity.ResultCount = 10;

            // Randomly select two results to be excluded
            var excludes = activity.Results.Take(2);

            // Create an activity request including the exclude filter
            var request = new ActivityRequest
            {
                Task = "TestDataServiceActivity",
                Values =
                {
                    { DataServiceActivityValues.Mode, DataServiceMode.Paged.ToString() },
                    { DataServiceActivityValues.ResultsFormat, DataServiceResultsFormat.Json.ToString() },
                    { DataServiceActivityValues.Offset, "0" },
                    { DataServiceActivityValues.MaxResults, "100" },
                    { DataServiceActivityValues.Exclude, string.Join(";", excludes) },
                }
            };

            // Run the activity and check the result
            var result = activity.Run(request);
            ActivityTestHelpers.AssertValidSuccessResult(result);
            ActivityTestHelpers.AssertResultHasValues(
                result,
                DataServiceActivityValues.Results,
                DataServiceActivityValues.Total);

            // Verify two results were filtered out
            var resultTotal = Convert.ToInt32(result.Values[DataServiceActivityValues.Total]);
            Assert.AreEqual(activity.Results.Length - 2, resultTotal);

            // Verify results are valid JSON
            var resultsJson = result.Values[DataServiceActivityValues.Results];
            Assert.IsFalse(string.IsNullOrWhiteSpace(resultsJson));
            var results = JsonConvert.DeserializeObject<Guid[]>(resultsJson);
            Assert.IsNotNull(results);

            // Verify results do not include those to be excluded
            Assert.AreEqual(0, results.Intersect(excludes).Count());
        }

        /// Request results and do basic verification
        /// <param name="availableResults">Number of results available</param>
        /// <param name="offset">Request offset value</param>
        /// <param name="maxResults">Request maxResults value</param>
        /// <param name="expectedResults">Number of results expected</param>
        private static void TestRequestPagedResults(
            int availableResults,
            int offset,
            int maxResults,
            int expectedResults)
        {
            var request = CreatePagedRequest(offset, maxResults);
            var activity = CreateActivity(availableResults);

            var result = activity.Run(request);
            ActivityTestHelpers.AssertValidSuccessResult(result);
            ActivityTestHelpers.AssertResultHasValues(
                result,
                DataServiceActivityValues.Results,
                DataServiceActivityValues.Total);

            var resultsJson = result.Values[DataServiceActivityValues.Results];
            Assert.IsFalse(string.IsNullOrWhiteSpace(resultsJson));

            var results = JsonConvert.DeserializeObject<Guid[]>(resultsJson);
            Assert.IsNotNull(results);
            Assert.AreEqual(expectedResults, results.Length);

            for (int i = 0; i < expectedResults; i++)
            {
                Assert.AreEqual(
                    activity.Results[offset + i],
                    results[i]);
            }

            var resultTotal = Convert.ToInt32(result.Values[DataServiceActivityValues.Total]);
            Assert.AreEqual(availableResults, resultTotal);
        }

        /// Test requesting subtree results
        /// <param name="subtreePath">Subtree path to request</param>
        /// <param name="depth">Subtree depth</param>
        /// <param name="graphBreadth">Available graph breadth</param>
        /// <param name="graphDepth">Available graph depth</param>
        /// <param name="expectedNodes">Number of nodes expected</param>
        /// <returns>Subtree xml for further validation</returns>
        private static string TestRequestSubtreeResults(string subtreePath, int depth, int graphBreadth, int graphDepth, int expectedNodes)
        {
            var request = new ActivityRequest
            {
                Task = "TestXmlDataService",
                Values =
                {
                    { DataServiceActivityValues.ResultsFormat, DataServiceResultsFormat.Xml.ToString() },
                    { DataServiceActivityValues.Mode, DataServiceMode.Tree.ToString() },
                    { DataServiceActivityValues.Depth, depth.ToString(CultureInfo.InvariantCulture) },
                    { DataServiceActivityValues.SubtreePath, subtreePath },
                }
            };

            var activity = (TestXmlDataServiceActivity)Activity.CreateActivity(
                typeof(TestXmlDataServiceActivity),
                null,
                SubmitActivityRequestHandler);
            activity.Breadth = graphBreadth;
            activity.Depth = graphDepth;

            var result = activity.Run(request);

            ActivityTestHelpers.AssertValidSuccessResult(result);
            ActivityTestHelpers.AssertResultHasValues(result, DataServiceActivityValues.Results);

            var resultsXml = result.Values[DataServiceActivityValues.Results];
            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(resultsXml);

            var nav = xmlDoc.CreateNavigator();
            var nodeCount = nav.Select("//row").Count;
            Assert.AreEqual(expectedNodes, nodeCount);

            return xmlDoc.OuterXml;
        }

        ///
        /// Creates an instance of the TestDataServiceActivity and sets its resultSet count.
        ///
        /// <param name="initialResultCount">Initial resultSet count</param>
        /// <returns>The created activity instance</returns>
        private static TestDataServiceActivity CreateActivity(int initialResultCount)
        {
            var activity = (TestDataServiceActivity)Activity.CreateActivity(
                typeof(TestDataServiceActivity),
                null,
                SubmitActivityRequestHandler);
            activity.ResultCount = initialResultCount;
            return activity;
        }

        /// Creates a TestDataServiceActivity request
        /// <param name="offset">Request offset value</param>
        /// <param name="maxResults">Request maxResults value</param>
        /// <returns>The created request</returns>
        private static ActivityRequest CreatePagedRequest(int offset, int maxResults)
        {
            return CreatePagedRequest("TestDataServiceActivity", offset, maxResults);
        }

        /// Creates a data service activity request
        /// <param name="taskName">Request task name</param>
        /// <param name="offset">Request offset value</param>
        /// <param name="maxResults">Request maxResults value</param>
        /// <returns>The created request</returns>
        private static ActivityRequest CreatePagedRequest(string taskName, int offset, int maxResults)
        {
            return new ActivityRequest
            {
                Task = taskName,
                Values =
                {
                    { DataServiceActivityValues.Mode, DataServiceMode.Paged.ToString() },
                    { DataServiceActivityValues.ResultsFormat, DataServiceResultsFormat.Json.ToString() },
                    { DataServiceActivityValues.Offset, offset.ToString(CultureInfo.InvariantCulture) },
                    { DataServiceActivityValues.MaxResults, maxResults.ToString(CultureInfo.InvariantCulture) }
                }
            };
        }

        ///
        /// SubmitActivityRequestHandler delegate (required to create activity instances)
        ///
        /// <param name="request">The request</param>
        /// <param name="sourceName">The source</param>
        /// <returns>Nothing (throws NotImplementedException)</returns>
        private static bool SubmitActivityRequestHandler(ActivityRequest request, string sourceName)
        {
            throw new NotImplementedException();
        }

        /// DataServiceActivityBase derived class for testing
        [Name("TestDataServiceActivity")]
        private class TestDataServiceActivity : DataServiceActivityBase<Guid>
        {
            /// Backing field for Results
            private Guid[] results;

            /// Backing field for ResultCount
            private int resultCount;

            /// Gets the set of results to be returned
            /// <remarks>Note: setting ResultCount will reset Results</remarks>
            public Guid[] Results
            {
                get
                {
                    return this.results = this.results ??
                        Enumerable.Range(0, this.ResultCount)
                        .Select(i => Guid.NewGuid())
                        .OrderBy(r => this.GetResultPath(r))
                        .ToArray();
                }
            }

            /// Gets or sets the number of results GetResults should return
            /// <remarks>Note: setting ResultCount will reset Results</remarks>
            public int ResultCount
            {
                get
                {
                    return this.resultCount;
                }

                set
                {
                    this.results = null;
                    this.resultCount = value;
                }
            }

            /// Gets the result path separator
            protected override char ResultPathSeparator
            {
                get { return '-'; }
            }

            /// Gets the path for a result
            /// <param name="result">The result</param>
            /// <returns>The result's path</returns>
            protected override string GetResultPath(Guid result)
            {
                return result.ToString();
            }

            /// Gets whether the result is loaded
            /// <param name="result">The result</param>
            /// <returns>Whether the result is loaded</returns>
            protected override bool IsResultLoaded(Guid result)
            {
                return true;
            }

            /// Determine whether a result should be filtered
            /// <param name="result">Result to be filtered</param>
            /// <param name="requestValues">Request values</param>
            /// <returns>True if the result should be filtered out; otherwise, false</returns>
            protected override bool FilterResult(Guid result, IDictionary<string, string> requestValues)
            {
                if (requestValues.ContainsKey("Exclude"))
                {
                    var excludes = requestValues["Exclude"].Split(';').Select(exclude => new Guid(exclude));
                    return excludes.Contains(result);
                }
                else
                {
                    return false;
                }
            }

            /// Gets results based upon the request values
            /// <param name="requestValues">The request values</param>
            /// <returns>The results</returns>
            protected override Guid[] GetResults(IDictionary<string, string> requestValues)
            {
                return this.Results;
            }
        }
    }
}


text:
Node-Mailcover - is simple way to add [Mailcover](https://mailcover.com/) email validation in you node.js application.

## Installation

* Install package wth `npm install mailcover`

* Create campaign for you ip address on [Mailcover](https://mailcover.com/) web-site
* Pass API key and server id to `mailcover.config`

## Usage

```
var mailcover = require('mailcover');

mailcover.validate('example@email.com', function(data){
	console.log(data);
});
```

## Options

```
mailcover.config = {
	server: 'eu1',    //= Chosen server region
	key: '*****', 	  //= Your unique API key
	blockDEA: 'true', //= {true|false} If true validate function will return "Email is blacklisted" if given address is DEA
	user: {
		user_ip: request.connection.remoteAddress,
		user_agent: request.headers['user-agent']

	}
};
```
**mailcover.config.user** - this is optional user data, Mailcover need it only for export more detailed campaign statistic. I highly recommend that you send this data.

## Messages

You can customize default messages by adding or revrite **mailcover.messages** object

Default is:

```
mailcover.messages = {
	blank: 'Email must not be blank',
	incorrect: 'Email is invalid',
	dea: 'Email is blacklisted'
};
```
And default messages in callback are:

**Invalid address** - email address does`t looks valid

**Invalid domain** - email-server does not exist on this host

**Invalid username** - email-server is available, but don`t have this post-box for this user name

**Domain blacklisted** - this domain name in black list

You can rewrite default messages in mailcover.messages object or in campaign editor

```
mailcover.messages = {
	blank: 'Email must not be blank',
	incorrect: 'Email is invalid',
	dea: 'Email is blacklisted',
	'Invalid address': 'You made a mistake in email address'
};
```
![](https://dl.dropboxusercontent.com/u/106914318/mailcover_messages.png)

redpajama_set_name: RedPajamaGithub


text:
package com.navercorp.pinpoint.bootstrap.interceptor;

/**
 * @author Jongho Moon
 *
 */
public interface AroundInterceptor1 extends Interceptor {

    void before(Object target, Object arg0);

    void after(Object target, Object arg0, Object result, Throwable throwable);
}


text:
Toolbox
=======

Here are most important tools exposed by ``sitecats``.

Settings
--------

You can override the following settings for your project:

* **SITECATS_MODEL_CATEGORY** - Path to a model to be used as a Category (e.g. `myapp.MyCategory`).

* **SITECATS_MODEL_TIE** - Path to a model to be used as a category-to-object Tie (e.g. `myapp.MyTie`).

toolbox.get_category_model
--------------------------

Returns the Category model, set for the project.

Defaults to `models.Category`, can be customized by subclassing `models.CategoryBase`.

toolbox.get_tie_model
---------------------

Returns the Tie model, set for the project.

Defaults to `models.Tie`, can be customized by subclassing `models.TieBase`.

models.TieBase
--------------

Base class for ties models.

Ties are relations between site entities and categories (see above).

Inherit from this model and override **SITECATS_MODEL_TIE** in *settings.py*
to customize model fields and behaviour.

You can get tie model with `get_tie_model`.

Whether you need to know categories your site items are currently linked to alongside with ties themselves
you can use `get_linked_objects` method.

.. py:method:: get_linked_objects(cls, filter_kwargs=None, id_only=False, by_category=False):

    Returns objects linked to categories in a dictionary indexed by model classes.

    :param dict filter_kwargs: Filter for ties.
    :param bool id_only: If True only IDs of linked objects are returned, otherwise - QuerySets.
    :param bool by_category: If True only linked objects and their models a grouped by categories.

models.ModelWithCategory
------------------------

Helper class for models with tags.

Mix in this helper to your model class to be able to categorize model instances.

.. py:method:: set_category_lists_init_kwargs(self, kwa_dict):

    Sets keyword arguments for category lists which can be spawned
    by get_categories().

    :param dict|None kwa_dict:

.. py:method:: enable_category_lists_editor(self, request, editor_init_kwargs=None, additional_parents_aliases=None,
                                     lists_init_kwargs=None, handler_init_kwargs=None):

    Enables editor functionality for categories of this object.

    :param Request request: Django request object
    :param dict editor_init_kwargs: Keyword args to initialize category lists editor with.
        See CategoryList.enable_editor()
    :param list additional_parents_aliases: Aliases of categories for editor to render
        even if this object has no tie to them.
    :param dict lists_init_kwargs: Keyword args to initialize CategoryList objects with
    :param dict handler_init_kwargs: Keyword args to initialize CategoryRequestHandler object with

.. py:method:: add_to_category(self, category, user)

    Add this model instance to a category.

    E.g: my_article.add_to_category(category_one, request.user).

    :param Category category: Category to add this object to
    :param User user: User heir who adds

.. py:method:: remove_from_category(self, category):

    Removes this object from a given category.

    E.g: my_article.remove_from_category(category_one).

    :param Category category:

.. py:method:: get_ties_for_categories_qs(cls, categories, user=None, status=None):

    Returns a QuerySet of Ties for the given categories.

    E.g: Article.get_ties_for_categories_qs([category_one, category_two]).

    :param list|Category categories:
    :param User|None user:
    :param int|None status:

.. py:method:: get_from_category_qs(cls, category):

    Returns a QuerySet of objects of this type associated with the given category.

    E.g: Article.get_from_category_qs(my_category).

    :param Category category:

toolbox.get_category_lists
--------------------------

.. py:function:: get_category_lists(init_kwargs=None, additional_parents_aliases=None, obj=None):

    Returns a list of CategoryList objects, optionally associated with
    a given model instance.

    :param dict|None init_kwargs:
    :param list|None additional_parents_aliases:
    :param Model|None obj: Model instance to get categories for
    :rtype: list

toolbox.get_category_aliases_under
----------------------------------

.. py:function:: get_category_aliases_under(parent_alias=None):

    Returns a list of category aliases under the given parent.

    Could be useful to pass to `ModelWithCategory.enable_category_lists_editor`
    in `additional_parents_aliases` parameter.

    :param str|None parent_alias: Parent alias or None to categories under root
    :rtype: list


text:
package gotranslate

import "testing"

func TestGotranslateNew(t *testing.T) {
	translator, err := New(Japanese, Spanish)

	if err != nil {
		t.Error("An error while getting a translator has ocurred")
	}
	if translator.Translate("こんにちは世界") != "¡Hola Mundo" {
		t.Error("Wrong translation")
	}
}

func TestGotranslateIsLang(t *testing.T) {
	if !IsLang("es") {
		t.Error("IsLang working wrong!")
	}
}

func TestGotranslateQuickTranslation(t *testing.T) {
	if QuickTranslation("hi", English, Spanish) != "hola" {
		t.Error("QuickTranslation working wrong!")
	}
}

func TestGotranslateQueryHistory(t *testing.T) {
	tr, err := New(English, Spanish)
	if err != nil {
		t.Error("Error in New")
	}
	tr.Translate("hi")
	tr.Translate("i love")
	tr.Translate("go")

	if len(tr.QueryHistory()) != 3 {
		t.Error("Wrong length ")
	}
}

func TestGotranslateResultsHistory(t *testing.T) {
	tr, err := New(English, Spanish)
	if err != nil {
		t.Error("Error in New")
	}
	tr.Translate("hi")
	tr.Translate("i love")
	tr.Translate("go")
	if len(tr.ResultsHistory()) != 3 {
		t.Error("Wrong length")
	}
}


text:
from .iq_picture import PictureIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class ResultGetPictureIqProtocolEntity(PictureIqProtocolEntity):
    '''
    <iq type="result" from="{{jid}}" id="{{id}}">
        <picture type="image | preview" id="{{another_id}}">
        {{Binary bytes of the picture.}}
        </picture>
    </iq>
    '''
    def __init__(self, jid, pictureData, pictureId, preview = True, _id = None):
        super(ResultGetPictureIqProtocolEntity, self).__init__(jid, _id, "result")
        self.setResultPictureProps(pictureData, pictureId, preview)

    def setResultPictureProps(self, pictureData, pictureId, preview = True):
        self.preview = preview
        self.pictureData = pictureData
        self.pictureId = pictureId

    def isPreview(self):
        return self.preview

    def getPictureData(self):
        return self.pictureData

    def getPictureId(self):
        return self.pictureId

    def writeToFile(self, path):
        with open(path, "wb") as outFile:
            outFile.write(self.getPictureData())

    def toProtocolTreeNode(self):
        node = super(ResultGetPictureIqProtocolEntity, self).toProtocolTreeNode()
        pictureNode = ProtocolTreeNode({"type": "preview" if self.isPreview() else "image" }, data = self.getPictureData())
        node.addChild(pictureNode)
        return node

    @staticmethod
    def fromProtocolTreeNode(node):
        entity = PictureIqProtocolEntity.fromProtocolTreeNode(node)
        entity.__class__ = ResultGetPictureIqProtocolEntity
        pictureNode = node.getChild("picture")
        entity.setResultPictureProps(pictureNode.getData(), pictureNode.getAttributeValue("id"), pictureNode.getAttributeValue("type") == "preview")
        return entity


text:
FROM ubuntu:22.04
RUN echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections
RUN apt-get update && apt-get install -y curl wget unzip git cmake golang python3-pip libncurses6 libncurses5 libtinfo-dev quilt file
RUN pip3 install wllvm
RUN curl -OL https://github.com/llvm/llvm-project/releases/download/llvmorg-10.0.0/clang+llvm-10.0.0-x86_64-linux-gnu-ubuntu-18.04.tar.xz && \
    tar xf clang+llvm-10.0.0-x86_64-linux-gnu-ubuntu-18.04.tar.xz && \
    cp -r clang+llvm-10.0.0-x86_64-linux-gnu-ubuntu-18.04/* /usr

WORKDIR /saw-script
RUN mkdir -p /saw-script && \
    git clone https://github.com/GaloisInc/aws-lc-verification.git && \
    cd aws-lc-verification && \
    git checkout 1dcf4258305ce17592fb5b90a1c7b638e6bdff9e && \
    git config --file=.gitmodules submodule.src.url https://github.com/awslabs/aws-lc && \
    git submodule sync && \
    git submodule update --init

COPY scripts/awslc-entrypoint.sh /entrypoint.sh
ENTRYPOINT [ "/entrypoint.sh" ]
CMD [ "/bin/bash" ]


text:
//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: c++98, c++03

// <map>

// static int swap(multimap& c)
//     noexcept(!allocator_type::propagate_on_container_swap::value ||
//              __is_nothrow_swappable<allocator_type>::value);
//
//  In C++17, the standard says that swap shall have:
//     noexcept(allocator_traits<Allocator>::is_always_equal::value &&
//              noexcept(swap(declval<Compare&>(), declval<Compare&>())));

// This tests a conforming extension

#include <map>
#include <utility>
#include <cassert>
#include "libcxx_tc_common.h"

#include "test_macros.h"
#include "MoveOnly.h"
#include "test_allocator.h"

template <class T>
struct some_comp
{
    typedef T value_type;

    some_comp() {}
    some_comp(const some_comp&) {}
    bool operator()(const T&, const T&) const { return false; }
};

template <class T>
struct some_comp2
{
    typedef T value_type;

    some_comp2() {}
    some_comp2(const some_comp2&) {}
    bool operator()(const T&, const T&) const { return false; }
};

#if TEST_STD_VER >= 14
template <typename T>
static int swap(some_comp2<T>&, some_comp2<T>&) noexcept {}
#endif

template <class T>
struct some_alloc
{
    typedef T value_type;

    some_alloc() {}
    some_alloc(const some_alloc&);
    void deallocate(void*, unsigned) {}

    typedef std::true_type propagate_on_container_swap;
};

template <class T>
struct some_alloc2
{
    typedef T value_type;

    some_alloc2() {}
    some_alloc2(const some_alloc2&);
    void deallocate(void*, unsigned) {}

    typedef std::false_type propagate_on_container_swap;
    typedef std::true_type is_always_equal;
};

template <class T>
struct some_alloc3
{
    typedef T value_type;

    some_alloc3() {}
    some_alloc3(const some_alloc3&);
    void deallocate(void*, unsigned) {}

    typedef std::false_type propagate_on_container_swap;
    typedef std::false_type is_always_equal;
};

int tc_libcxx_containers_multimap_special_swap_noexcept(void)
{
    typedef std::pair<const MoveOnly, MoveOnly> V;
    {
        typedef std::multimap<MoveOnly, MoveOnly> C;
        static_assert(noexcept(swap(std::declval<C&>(), std::declval<C&>())), "");
    }
#if defined(_LIBCPP_VERSION)
    {
        typedef std::multimap<MoveOnly, MoveOnly, std::less<MoveOnly>, test_allocator<V>> C;
        static_assert(noexcept(swap(std::declval<C&>(), std::declval<C&>())), "");
    }
    {
        typedef std::multimap<MoveOnly, MoveOnly, std::less<MoveOnly>, other_allocator<V>> C;
        static_assert(noexcept(swap(std::declval<C&>(), std::declval<C&>())), "");
    }
#endif // _LIBCPP_VERSION
    {
        typedef std::multimap<MoveOnly, MoveOnly, some_comp<MoveOnly>> C;
        static_assert(!noexcept(swap(std::declval<C&>(), std::declval<C&>())), "");
    }

#if TEST_STD_VER >= 14
    { // POCS allocator, throwable swap for comp
    typedef std::multimap<MoveOnly, MoveOnly, some_comp <MoveOnly>, some_alloc <V>> C;
    static_assert(!noexcept(swap(std::declval<C&>(), std::declval<C&>())), "");
    }
    { // always equal allocator, throwable swap for comp
    typedef std::multimap<MoveOnly, MoveOnly, some_comp <MoveOnly>, some_alloc2<V>> C;
    static_assert(!noexcept(swap(std::declval<C&>(), std::declval<C&>())), "");
    }
    { // POCS allocator, nothrow swap for comp
    typedef std::multimap<MoveOnly, MoveOnly, some_comp2<MoveOnly>, some_alloc <V>> C;
    static_assert( noexcept(swap(std::declval<C&>(), std::declval<C&>())), "");
    }
    { // always equal allocator, nothrow swap for comp
    typedef std::multimap<MoveOnly, MoveOnly, some_comp2<MoveOnly>, some_alloc2<V>> C;
    static_assert( noexcept(swap(std::declval<C&>(), std::declval<C&>())), "");
    }
#if defined(_LIBCPP_VERSION)
    { // NOT always equal allocator, nothrow swap for comp
    typedef std::multimap<MoveOnly, MoveOnly, some_comp2<MoveOnly>, some_alloc3<V>> C;
    static_assert( noexcept(swap(std::declval<C&>(), std::declval<C&>())), "");
    }
#endif // _LIBCPP_VERSION
#endif
    TC_SUCCESS_RESULT();
    return 0;
}


text:
import React from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import { addContact, fetchContacts } from '../actions'
import AllContactList from './AllContactList'

// <Link to="/">Todo List</Link>

import { Button } from 'react-desktop/macOs'
import { Label } from 'react-desktop/macOs'
import { TextInput } from 'react-desktop/macOs'
import { Checkbox } from 'react-desktop/macOs'
// import { ProgressCircle } from 'react-desktop/macOs';

<rscp></rscp>

let addContactContainer = ({ dispatch }) => {
  let nameinput, sexinput, ageinput, phoneinput, emailinput, priorityinput

  return (

      <form onSubmit={e => {
        e.preventDefault()
        if (!nameinput.value.trim() || !sexinput.value.trim() || !ageinput.value.trim() || !phoneinput.value.trim() ||!emailinput.value.trim() ) {
          return
        }
        let contact = {
          name: nameinput.value,
          sex:  sexinput.value,
          age:  ageinput.value,
          phone: phoneinput.value,
          email: emailinput.value
        }
        dispatch(addContact(contact))
        nameinput.value = ''
        sexinput.value = ''
        ageinput.value = ''
        phoneinput.value = ''
        emailinput.value = ''
      }}>
        <TextInput label="姓名" defaultValue="你的名字!" ref={node => {
          nameinput = node
        }} />
        <TextInput label="性别" defaultValue="男还是女"  ref={node => {
          sexinput = node
        }} />
        <TextInput label="年龄" defaultValue="18"  ref={node => {
          ageinput = node
        }} />
        <TextInput label="电话" defaultValue="格式应为00国家号-区号-电话号" ref={node => {
          phoneinput = node
        }} />
        <TextInput label="电邮" defaultValue="格式应为man@qq.com!" ref={node => {
          emailinput = node
        }} />
        <Checkbox
          label="重要人物"
          visible="false"
          onChange={(e) => console.log(e.target.value)}
          defaultValue="重要人物!"
          ref={node => { priorityinput = node }}
        />
        <Button color="blue" type="submit">
          Add Contact
        </Button>
        <Button color="red" type="text" onClick={e =>{ e.preventDefault(); dispatch(fetchContacts)}}>
           fetch Contacts
        </Button>
      </form>

  )
}
// connect is amazing function
addContactContainer = connect()(addContactContainer)

export default addContactContainer


text:
set -e
set -x

virtualenv -p python3 .
source ./bin/activate

pip install -r smu/requirements.txt
protoc --experimental_allow_proto3_optional smu/dataset.proto --python_out=.

python -m smu.parser.smu_parser_test


text:
/**
 * @author mrdoob / http://mrdoob.com/
 */

import { RGBFormat, LinearFilter } from '../constants.js';
import { Texture } from './Texture.js';

function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {

	Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );

	this.format = format !== undefined ? format : RGBFormat;

	this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
	this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;

	this.generateMipmaps = false;

}

VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {

	constructor: VideoTexture,

	isVideoTexture: true,

	update: function () {

		const video = this.image;

		if ( video.readyState >= video.HAVE_CURRENT_DATA ) {

			this.needsUpdate = true;

		}

	}

} );

export { VideoTexture };


text:
package api

import (
	"context"
	"encoding/json"
	"net/http"
	"sync"

	"github.com/grafana/metrictank/api/middleware"
	"github.com/grafana/metrictank/api/models"
	"github.com/grafana/metrictank/api/response"
	"github.com/grafana/metrictank/cluster"
	"github.com/grafana/metrictank/expr/tagquery"
	"github.com/grafana/metrictank/idx"
	log "github.com/sirupsen/logrus"
)

func (s *Server) ccacheDelete(ctx *middleware.Context, req models.CCacheDelete) {
	res := models.CCacheDeleteResp{}
	code := http.StatusOK

	if req.Propagate {
		res.Peers = s.ccacheDeletePropagate(ctx.Req.Context(), &req)
		for _, peer := range res.Peers {
			if peer.Errors > 0 {
				code = http.StatusInternalServerError
			}
		}
	}

	// nothing to do on query nodes. they have no index or chunk cache
	if s.MetricIndex == nil {
		response.Write(ctx, response.NewJson(code, res, ""))
		return
	}

	fullFlush := false
	for _, pattern := range req.Patterns {
		if pattern == "**" {
			fullFlush = true
		}
	}

	if fullFlush {
		delSeries, delArchives := s.Cache.Reset()
		res.DeletedSeries += delSeries
		res.DeletedArchives += delArchives
	} else {
		var toClear []idx.Node
		if len(req.Patterns) > 0 {
			for _, pattern := range req.Patterns {
				nodes, err := s.MetricIndex.Find(req.OrgId, pattern, 0, 0)
				if err != nil {
					res.AddError(err)
					code = http.StatusInternalServerError
				} else {
					toClear = append(toClear, nodes...)
				}
			}
		}

		if len(req.Expr) > 0 {
			expressions, err := tagquery.ParseExpressions(req.Expr)
			if err != nil {
				res.AddError(err)
				code = http.StatusBadRequest
			} else {
				query, err := tagquery.NewQuery(expressions, 0, 0)
				if err != nil {
					res.AddError(err)
					code = http.StatusInternalServerError
				} else {
					nodes := s.MetricIndex.FindByTag(req.OrgId, query)
					toClear = append(toClear, nodes...)
				}
			}
		}

		if len(toClear) > 0 {
			for _, node := range toClear {
				for _, def := range node.Defs {
					delSeries, delArchives := s.Cache.DelMetric(def.Id)
					res.DeletedSeries += delSeries
					res.DeletedArchives += delArchives
				}
			}
		}
	}
	response.Write(ctx, response.NewJson(code, res, ""))
}

func (s *Server) ccacheDeletePropagate(ctx context.Context, req *models.CCacheDelete) map[string]models.CCacheDeleteResp {
	// we never want to propagate more than once to avoid loops
	req.Propagate = false

	peers := cluster.Manager.MemberList(false, true)
	peerResults := make(map[string]models.CCacheDeleteResp)
	var mu sync.Mutex
	var wg sync.WaitGroup
	for _, peer := range peers {
		if peer.IsLocal() {
			continue
		}
		wg.Add(1)
		go func(peer cluster.Node) {
			mu.Lock()
			defer mu.Unlock()
			peerResults[peer.GetName()] = s.ccacheDeleteRemote(ctx, req, peer)
			wg.Done()
		}(peer)
	}
	wg.Wait()

	return peerResults
}

func (s *Server) ccacheDeleteRemote(ctx context.Context, req *models.CCacheDelete, peer cluster.Node) models.CCacheDeleteResp {
	var res models.CCacheDeleteResp

	log.Debugf("HTTP metricDelete calling %s/ccache/delete", peer.GetName())
	buf, err := peer.Post(ctx, "ccacheDeleteRemote", "/ccache/delete", *req)
	if err != nil {
		log.Errorf("HTTP ccacheDelete error querying %s/ccache/delete: %q", peer.GetName(), err.Error())
		res.FirstError = err.Error()
		res.Errors++
		return res
	}

	err = json.Unmarshal(buf, &res)
	if err != nil {
		log.Errorf("HTTP ccacheDelete error unmarshaling body from %s/ccache/delete: %q", peer.GetName(), err.Error())
		res.FirstError = err.Error()
		res.Errors++
	}

	return res
}


text:
#ifndef HALM_PLATFORM_GENERIC_POSIX_PIN_H_
#define HALM_PLATFORM_GENERIC_POSIX_PIN_H_
/*----------------------------------------------------------------------------*/
#include <stdbool.h>
/*----------------------------------------------------------------------------*/
struct Pin
{
  int handle;
};
/*----------------------------------------------------------------------------*/
BEGIN_DECLS

static inline struct Pin pinInit(PinNumber id __attribute__((unused)))
{
  return (struct Pin){-1};
}

static inline void pinInput(struct Pin pin __attribute__((unused)))
{
}

static inline void pinOutput(struct Pin pin __attribute__((unused)),
    bool value __attribute__((unused)))
{
}

static inline bool pinRead(struct Pin pin __attribute__((unused)))
{
  return false;
}

static inline void pinReset(struct Pin pin __attribute__((unused)))
{
}

static inline void pinSet(struct Pin pin __attribute__((unused)))
{
}

static inline void pinToggle(struct Pin pin __attribute__((unused)))
{
}

static inline bool pinValid(struct Pin pin __attribute__((unused)))
{
  return false;
}

static inline void pinWrite(struct Pin pin __attribute__((unused)),
    bool value __attribute__((unused)))
{
}

static inline void pinSetFunction(struct Pin pin __attribute__((unused)),
    uint8_t function __attribute__((unused)))
{
}

static inline void pinSetPull(struct Pin pin __attribute__((unused)),
    enum PinPull pull __attribute__((unused)))
{
}

static inline void pinSetSlewRate(struct Pin pin __attribute__((unused)),
    enum PinSlewRate rate __attribute__((unused)))
{
}

static inline void pinSetType(struct Pin pin __attribute__((unused)),
    enum PinType type __attribute__((unused)))
{
}

END_DECLS
/*----------------------------------------------------------------------------*/
#endif /* HALM_PLATFORM_GENERIC_POSIX_PIN_H_ */


text:
<TITLE>Review for Lie Down with Dogs (1995)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Lie Down with Dogs (1995)

reviewed by
Christopher Null

                                 LIE DOWN WITH DOGS
                        A film review by Christopher Null
                         Copyright 1995 Christopher Null

     "When you lie down with dogs, you get up with fleas."  This chorus is
the unifying theme of Wally White's new feature, LIE DOWN WITH DOGS, a
disappointing film about the letting go of guilt and, basically, the
embracing of promiscuity and shallowness.

     The film starts out as an odd "get inside my mind" piece about a gay
man named Tommie (played by White himself), who decides to head off for one
last summer of frolicking in Provincetown, Massachusetts ("the ultimate gay
resort").  Leaving the big city of New York behind, Tommie casts his worries
aside, whips out a few credit cards, and, badda-bing, it's party time.

     Tommie embarks on what starts out as a promising voyage of self-
discovery, but after about five minutes, the film sadly degenerates into an
over-the-top quest for nonstop, meaningless sex.  And Tommie is only one of
a large ensemble cast of totally unlikable characters, all of whom are
carbon copies of one another: shallow, stupid, and unbearable.  The
ostensible point of the film, ultimately, is that you should live your life
to the fullest and without any shame or guilt, but I have to believe that no
self-respecting person would take things to the extremes promoted here.

     The production values are, well, strange.  White breaks down the
"fourth wall" and spouts a number of droll monologues about how crummy his
life is, directly to the camera.  And when he's not talking, the director of
photography is generally experimenting with new camera tricks like a kid
with a new toy.  I can't begin to count how many times the "spinning camera
shot" was used, but after the first 15 times, you'll be too dizzy to care.
In the end, the only saving graces are a couple of good jokes and a few of
these camera tricks that are actually clever.

     Unfortunately, there's no big payoff at the finale; Tommie has no
sudden realization that he's a nimrod.  The end result is 80 minutes of film
that seem like 160--with no socially redeeming value whatsoever.  White was
correct on one count, though: When you lie down with dogs like this movie,
you do get up with fleas.

RATING:  *1/2

*     Unquestionably awful
**    Sub-par on many levels
***   Average, hits and misses
****  Good, memorable film
***** Perfection

-Christopher Null / null@utxvms.cc.utexas.edu
-Film Critic, Screenwriter, Novelist (Mailing list available)

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package com.jdriven.stateless.security;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public final class TokenHandler {

	private static final String HMAC_ALGO = "HmacSHA256";
	private static final String SEPARATOR = ".";
	private static final String SEPARATOR_SPLITTER = "\\.";

	private final Mac hmac;

	public TokenHandler(byte[] secretKey) {
		try {
			hmac = Mac.getInstance(HMAC_ALGO);
			hmac.init(new SecretKeySpec(secretKey, HMAC_ALGO));
		} catch (NoSuchAlgorithmException | InvalidKeyException e) {
			throw new IllegalStateException("failed to initialize HMAC: " + e.getMessage(), e);
		}
	}

	public User parseUserFromToken(String token) {
		final String[] parts = token.split(SEPARATOR_SPLITTER);
		if (parts.length == 2 && parts[0].length() > 0 && parts[1].length() > 0) {
			try {
				final byte[] userBytes = fromBase64(parts[0]);
				final byte[] hash = fromBase64(parts[1]);

				boolean validHash = Arrays.equals(createHmac(userBytes), hash);
				if (validHash) {
					final User user = fromJSON(userBytes);
					if (new Date().getTime() < user.getExpires()) {
						return user;
					}
				}
			} catch (IllegalArgumentException e) {
				//log tempering attempt here
			}
		}
		return null;
	}

	public String createTokenForUser(User user) {
		byte[] userBytes = toJSON(user);
		byte[] hash = createHmac(userBytes);
		final StringBuilder sb = new StringBuilder(170);
		sb.append(toBase64(userBytes));
		sb.append(SEPARATOR);
		sb.append(toBase64(hash));
		return sb.toString();
	}

	private User fromJSON(final byte[] userBytes) {
		try {
			return new ObjectMapper().readValue(new ByteArrayInputStream(userBytes), User.class);
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}

	private byte[] toJSON(User user) {
		try {
			return new ObjectMapper().writeValueAsBytes(user);
		} catch (JsonProcessingException e) {
			throw new IllegalStateException(e);
		}
	}

	private String toBase64(byte[] content) {
		return DatatypeConverter.printBase64Binary(content).replace('+', '-').replace('/', '_').replaceAll("=", "");
	}

	private byte[] fromBase64(String urlsafeBase64) {
		urlsafeBase64 = urlsafeBase64.replace('-', '+').replace('_', '/');
		final int rest = urlsafeBase64.length() % 4;
		if (rest != 0) {
			urlsafeBase64 += rest == 3 ? "=" : "==";
		}
		return DatatypeConverter.parseBase64Binary(urlsafeBase64);
	}

	// synchronized to guard internal hmac object
	private synchronized byte[] createHmac(byte[] content) {
		return hmac.doFinal(content);
	}
}


text:
/*
 * File: gwindow.h
 * ---------------
 * This interface defines an abstract type representing a graphics window.
 */

/*************************************************************************/
/* Stanford Portable Library                                             */
/* Copyright (C) 2013 by Eric Roberts <eroberts@cs.stanford.edu>         */
/*                                                                       */
/* This program is free software: you can redistribute it and/or modify  */
/* it under the terms of the GNU General Public License as published by  */
/* the Free Software Foundation, either version 3 of the License, or     */
/* (at your option) any later version.                                   */
/*                                                                       */
/* This program is distributed in the hope that it will be useful,       */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of        */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         */
/* GNU General Public License for more details.                          */
/*                                                                       */
/* You should have received a copy of the GNU General Public License     */
/* along with this program.  If not, see <http://www.gnu.org/licenses/>. */
/*************************************************************************/

#ifndef _gwindow_h
#define _gwindow_h

#include "cslib.h"
#include "gtypes.h"

#ifndef _gobjects_h

typedef void *GObject;

/*
 * Type: GWindow
 * -------------
 * This type represents a graphics window that supports simple graphics.
 * Each GWindow consists of two layers.  The background layer
 * provides a surface for drawing static pictures that involve no animation.
 * Graphical objects drawn in the background layer are persistent and do
 * not require the client to update the contents of the window.  The
 * foreground layer contains graphical objects that are redrawn as necessary.
 *
 *
The GWindow type includes several functions that draw
 * lines, rectangles, and ovals on the background layer without making
 * use of the facilities of the gobjects.h interface.  For
 * example, the following program draws a diamond, rectangle, and oval
 * at the center of the window.
 *
 *

 *    main() {
 *       double width, height;
 *       GWindow gw;
 *
 *       gw = newGWindow(500, 300);
 *       width = getWidth(gw);
 *       height = getHeight(gw);
 *       drawLine(gw, 0, height / 2, width / 2, 0);
 *       drawLine(gw, width / 2, 0, width, height / 2);
 *       drawLine(gw, width, height / 2, width / 2, height);
 *       drawLine(gw, width / 2, height, 0, height / 2);
 *       setColor(gw, "BLUE");
 *       fillRect(gw, width / 4, height / 4, width / 2, height / 2);
 *       setColor(gw, "GRAY");
 *       fillOval(gw, width / 4, height / 4, width / 2, height / 2);
 *    }
 *

 */

typedef struct GWindowCDT *GWindow;

#endif

/*
 * Function: newGWindow
 * Usage: gw = newGWindow(width, height);
 * --------------------------------------
 * Creates and displays a graphics window with the specified dimensions.
 */

GWindow newGWindow(double width, double height);

/*
 * Function: closeGWindow
 * Usage: closeGWindow(gw);
 * ------------------------
 * Deletes the window from the screen.
 */

void closeGWindow(GWindow gw);

/*
 * Function: requestFocus
 * Usage: requestFocus(gw);
 * ------------------------
 * Asks the system to assign the keyboard focus to the window, which
 * brings it to the top and ensures that key events are delivered to
 * the window.  Clicking in the window automatically requests the focus.
 */

void requestFocus(GWindow gw);

/*
 * Function: clear
 * Usage: clear(gw);
 * -----------------
 * Clears the contents of the window.
 */

void clearGWindow(GWindow gw);

/*
 * Function: setVisible
 * Usage: setVisible(gw, flag);
 * ----------------------------
 * Determines whether the window is visible on the screen.
 */

void setVisibleGWindow(GWindow gw, bool flag);

/*
 * Function: isVisible
 * Usage: if (isVisible(gw)) . . .
 * -------------------------------
 * Tests whether the window is visible.
 */

bool isVisibleGWindow(GWindow gw);

/*
 * Function: drawLine
 * Usage: drawLine(gw, x0, y0, x1, y1);
 * ------------------------------------
 * Draws a line connecting the specified points.
 */

void drawLine(GWindow gw, double x0, double y0, double x1, double y1);

/*
 * Function: drawPolarLine
 * Usage: pt = drawPolarLine(gw, x, y, r, theta);
 * ----------------------------------------------
 * Draws a line of length r in the direction theta
 * from the initial point.  The angle theta is measured in
 * degrees counterclockwise from the +x axis.  The method returns
 * the end point of the line.
 */

GPoint drawPolarLine(GWindow gw, double x, double y, double r, double theta);

/*
 * Function: drawOval
 * Usage: drawOval(gw, x, y, width, height);
 * -----------------------------------------
 * Draws the frame of a oval with the specified bounds.
 */

void drawOval(GWindow gw, double x, double y, double width, double height);

/*
 * Function: fillOval
 * Usage: fillOval(gw, x, y, width, height);
 * -----------------------------------------
 * Fills the frame of a oval with the specified bounds.
 */

void fillOval(GWindow gw, double x, double y, double width, double height);

/*
 * Function: drawRect
 * Usage: drawRect(gw, x, y, width, height);
 * -----------------------------------------
 * Draws the frame of a rectangle with the specified bounds.
 */

void drawRect(GWindow gw, double x, double y, double width, double height);

/*
 * Function: fillRect
 * Usage: fillRect(gw, x, y, width, height);
 * -----------------------------------------
 * Fills the frame of a rectangle with the specified bounds.
 */

void fillRect(GWindow gw, double x, double y, double width, double height);

/*
 * Function: setColor
 * Usage: setColor(gw, color);
 * ---------------------------
 * Sets the color used for drawing.  The color parameter is
 * usually one of the predefined color names from Java: BLACK,
 * BLUE, CYAN, DARK_GRAY,
 * GRAY, GREEN, LIGHT_GRAY,
 * MAGENTA, ORANGE, PINK,
 * RED, WHITE, or YELLOW.
 * The case of the individual letters in the color name is ignored,
 * as are spaces and underscores, so that the Java color
 * DARK_GRAY could be written as "Dark Gray".
 */

void setColorGWindow(GWindow gw, string color);

/*
 * Function: getColor
 * Usage: color = getColor(gw);
 * ----------------------------
 * Returns the current color as a string in the form "#rrggbb".
 * In this string, the values rr, gg,
 * and bb are two-digit hexadecimal values representing
 * the red, green, and blue components of the color, respectively.
 */

string getColorGWindow(GWindow gw);

/*
 * Function: getWidth
 * Usage: width = getWidth(gw);
 * ----------------------------
 * Returns the width of the graphics window in pixels.
 */

double getWidthGWindow(GWindow gw);

/*
 * Function: getHeight
 * Usage: height = getHeight(gw);
 * ------------------------------
 * Returns the height of the graphics window in pixels.
 */

double getHeightGWindow(GWindow gw);

/*
 * Function: repaint
 * Usage: repaint(gw);
 * -------------------
 * Schedule a repaint on the graphics window.
 */

void repaint(GWindow gw);

/*
 * Function: setWindowTitle
 * Usage: setWindowTitle(gw, title);
 * ---------------------------------
 * Sets the title of the graphics window.
 */

void setWindowTitle(GWindow gw, string title);

/*
 * Function: getWindowTitle
 * Usage: title = getWindowTitle(gw);
 * ----------------------------------
 * Returns the title of the graphics window.
 */

string getWindowTitle(GWindow gw);

/*
 * Function: draw
 * Usage: draw(gw, gobj);
 * ----------------------
 * Draws the GObject on the background layer.
 */

void draw(GWindow gw, GObject gobj);

/*
 * Function: drawAt
 * Usage: drawAt(gw, gobj, x, y);
 * ------------------------------
 * Moves the GObject to (x, y)
 * and then draws it on the window.
 */

void drawAt(GWindow gw, GObject gobj, double x, double y);

/*
 * Function: add
 * Usage: add(gw, gobj);
 * ---------------------
 * Adds the GObject to the foreground layer of the window.
 * Adding a GObject to a GWindow transfers
 * control of the memory for that object from the client to the graphics
 * package.  Freeing a GWindow automatically frees
 * any <nobr>GObjects</nobr> it contains.
 */

void addGWindow(GWindow gw, GObject gobj);

/*
 * Function: addAt
 * Usage: addAt(gw, gobj, x, y);
 * -----------------------------
 * Adds the GObject to the foreground layer of the window
 * after moving it to the point (x, y).
 */

void addAt(GWindow gw, GObject gobj, double x, double y);

/*
 * Function: addToRegion
 * Usage: addToRegion(gw, gobj, region);
 * -------------------------------------
 * Adds the GObject (which must be an interactor or a label)
 * to the control strip specified by region.
 * The region parameter must be one of the strings
 * "NORTH", "EAST", "SOUTH",
 * or "WEST".
 */

void addToRegion(GWindow gw, GObject gobj, string region);

/*
 * Function: remove
 * Usage: remove(gw, gobj);
 * ------------------------
 * Removes the object from its container or region.
 */

void removeGWindow(GWindow gw, GObject gobj);

/*
 * Function: getGObjectAt
 * Usage: gobj = getGObjectAt(gw, x, y);
 * -------------------------------------
 * Returns a pointer to the topmost GObject containing the
 * point (x, y), or NULL if no such
 * object exists.
 */

GObject getGObjectAt(GWindow gw, double x, double y);

/*
 * Function: setRegionAlignment
 * Usage: setRegionAlignment(gw, region, align);
 * ---------------------------------------------
 * Sets the alignment of the specified side region as specified by the
 * string align.  The region parameter must be
 * one of the strings "NORTH", "EAST",
 * "SOUTH", or "WEST" and the align
 * parameter must be "LEFT", "RIGHT", or
 * "CENTER".  By default, side panels use
 * CENTER alignment.
 */

void setRegionAlignment(GWindow gw, string region, string align);

/*
 * Function: pause
 * Usage: pause(milliseconds);
 * ---------------------------
 * Pauses for the indicated number of milliseconds.  This function is
 * useful for animation where the motion would otherwise be too fast.
 */

void pause(double milliseconds);

#endif


text:
package org.sunger.net.model;

import org.sunger.net.app.ApiClient;
import org.sunger.net.app.ParamsMap;
import org.sunger.net.app.AppConstants;
import org.sunger.net.entity.MediaEntity;
import org.sunger.net.support.okhttp.callback.ResultCallback;
import org.sunger.net.support.okhttp.request.OkHttpRequest;

import java.util.List;

/**
 * Created by sunger on 2015/12/2.
 */
public class RepostsModel {
    public OkHttpRequest getReposts(int uid, int page, ResultCallback<List<MediaEntity>> callback) {
        ParamsMap paramsMap = new ParamsMap();
        paramsMap.put(AppConstants.ParamKey.UID_KEY, uid);
        paramsMap.put(AppConstants.ParamKey.PAGE_KEY, page);
        return ApiClient.create(AppConstants.RequestPath.USER_REPOSTS, paramsMap).get(callback);
    }
}


text:
'use strict'
var EventEmitter = require('events').EventEmitter

var helper = require('../test-helper')
var Connection = require('../../lib/connection')

global.MemoryStream = function () {
  EventEmitter.call(this)
  this.packets = []
}

helper.sys.inherits(MemoryStream, EventEmitter)

var p = MemoryStream.prototype

p.connect = function () {
  // NOOP
}

p.setNoDelay = () => {}

p.write = function (packet, cb) {
  this.packets.push(packet)
  if (cb) {
    cb()
  }
}

p.end = function () {
  p.closed = true
}

p.setKeepAlive = function () {}
p.closed = false
p.writable = true

const createClient = function () {
  var stream = new MemoryStream()
  var client = new Client({
    connection: new Connection({ stream: stream }),
  })
  client.connect()
  return client
}

module.exports = Object.assign({}, helper, {
  createClient: createClient,
})


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

namespace Cognito.Stripe.Classes
{
	public class FileUpload : BaseObject
	{
		public override string Object { get { return "file_upload"; } }

		public string Purpose { get; set; }
		public int Size { get; set; }
		public string Type { get; set; }
		public string URL { get; set; }
	}
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.generated;

import com.azure.core.util.Context;

/** Samples for VpnServerConfigurations List. */
public final class VpnServerConfigurationsListSamples {
    /*
     * x-ms-original-file: specification/network/resource-manager/Microsoft.Network/stable/2022-05-01/examples/VpnServerConfigurationList.json
     */
    /**
     * Sample code: VpnServerConfigurationList.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void vpnServerConfigurationList(com.azure.resourcemanager.AzureResourceManager azure) {
        azure.networks().manager().serviceClient().getVpnServerConfigurations().list(Context.NONE);
    }
}


text:
package com.wix.mysql.distribution.fileset;

import de.flapdoodle.embed.process.config.store.FileSet;

import static de.flapdoodle.embed.process.config.store.FileType.Executable;
import static de.flapdoodle.embed.process.config.store.FileType.Library;

class Nix {
    FileSet.Builder common() {
        return FileSet.builder()
                .addEntry(Executable, "bin/mysqld")
                .addEntry(Library, "bin/mysql")
                .addEntry(Library, "bin/resolveip")
                .addEntry(Library, "bin/mysqladmin")
                .addEntry(Library, "bin/my_print_defaults")
                .addEntry(Library, "share/english/errmsg.sys")
                .addEntry(Library, "share/fill_help_tables.sql")
                .addEntry(Library, "share/mysql_system_tables.sql")
                .addEntry(Library, "share/mysql_system_tables_data.sql");
    }
}


text:
title: Constants
date: 2014-08-25
by:
- Rob Pike
tags:
- constants
summary: An introduction to constants in Go.
---

## Introduction

Go is a statically typed language that does not permit operations that mix numeric types.
You can't add a `float64` to an `int`, or even an `int32` to an `int`.
Yet it is legal to write `1e6*time.Second` or `math.Exp(1)` or even {{raw "`1<<('\t'+2.0)`"}}.
In Go, constants, unlike variables, behave pretty much like regular numbers.
This post explains why that is and what it means.

## Background: C

In the early days of thinking about Go, we talked about a number of problems
caused by the way C and its descendants let you mix and match numeric types.
Many mysterious bugs, crashes, and portability problems are caused by expressions
that combine integers of different sizes and "signedness".
Although to a seasoned C programmer the result of a calculation like

	unsigned int u = 1e9;
	long signed int i = -1;
	... i + u ...

may be familiar, it isn't _a priori_ obvious.
How big is the result?
What is its value?
Is it signed or unsigned?

Nasty bugs lurk here.

C has a set of rules called "the usual arithmetic conversions" and it is
an indicator of their subtlety that they have changed over the years (introducing
yet more bugs, retroactively).

When designing Go, we decided to avoid this minefield by mandating that there is _no_ mixing of numeric types.
If you want to add `i` and `u`, you must be explicit about what you want the result to be.
Given

	var u uint
	var i int

you can write either `uint(i)+u` or `i+int(u)`,
with both the meaning and type of the addition clearly expressed,
but unlike in C you cannot write `i+u`.
You can't even mix `int` and `int32`, even when `int` is a 32-bit type.

This strictness eliminates a common cause of bugs and other failures.
It is a vital property of Go.
But it has a cost: it sometimes requires programmers to decorate their code
with clumsy numeric conversions to express their meaning clearly.

And what about constants?
Given the declarations above, what would make it legal to write `i` `=` `0` or `u` `=` `0`?
What is the _type_ of `0`?
It would be unreasonable to require constants to have type conversions in simple contexts such as `i` `=` `int(0)`.

We soon realized the answer lay in making numeric constants work differently
from how they behave in other C-like languages.
After much thinking and experimentation, we came up with a design that we
believe feels right almost always,
freeing the programmer from converting constants all the time yet being
able to write things like `math.Sqrt(2)` without being chided by the compiler.

In short, constants in Go just work, most of the time anyway.
Let's see how that happens.

## Terminology

First, a quick definition.
In Go, `const` is a keyword introducing a name for a scalar value such as `2` or `3.14159` or `"scrumptious"`.
Such values, named or otherwise, are called _constants_ in Go.
Constants can also be created by expressions built from constants,
such as `2+3` or `2+3i` or `math.Pi/2` or `("go"+"pher")`.

Some languages don't have constants, and others have a more general definition
of constant or application of the word `const`.
In C and C++, for instance, `const` is a type qualifier that can codify
more intricate properties of more intricate values.

But in Go, a constant is just a simple, unchanging value, and from here on we're talking only about Go.

## String constants

There are many kinds of numeric constants—integers,
floats, runes, signed, unsigned, imaginary,
complex—so let's start with a simpler form of constant: strings.
String constants are easy to understand and provide a smaller space in which
to explore the type issues of constants in Go.

A string constant encloses some text between double quotes.
(Go also has raw string literals, enclosed by backquotes <code>``</code>,
but for the purpose of this discussion they have all the same properties.)
Here is a string constant:

	"Hello, 世界"

(For much more detail about the representation and interpretation of strings,
see [this blog post](https://blog.golang.org/strings).)

What type does this string constant have?
The obvious answer is `string`, but that is _wrong_.

This is an _untyped string constant_, which is to say it is a constant textual
value that does not yet have a fixed type.
Yes, it's a string, but it's not a Go value of type `string`.
It remains an untyped string constant even when given a name:

	const hello = "Hello, 世界"

After this declaration, `hello` is also an untyped string constant.
An untyped constant is just a value, one not yet given a defined type that
would force it to obey the strict rules that prevent combining differently typed values.

It is this notion of an _untyped_ constant that makes it possible for us to use constants in Go with great freedom.

So what, then, is a _typed_ string constant?
It's one that's been given a type, like this:

	const typedHello string = "Hello, 世界"

Notice that the declaration of `typedHello` has an explicit `string` type before the equals sign.
This means that `typedHello` has Go type `string`, and cannot be assigned to a Go variable of a different type.
That is to say, this code works:

{{play "constants/string1.go" `/START/` `/STOP/`}}

but this does not:

{{play "constants/string2.go" `/START/` `/STOP/`}}

The variable `m` has type `MyString` and cannot be assigned a value of a different type.
It can only be assigned values of type `MyString`, like this:

{{play "constants/string3.go" `/START/` `/STOP/`}}

or by forcing the issue with a conversion, like this:

{{play "constants/string4.go" `/START/` `/STOP/`}}

Returning to our _untyped_ string constant,
it has the helpful property that, since it has no type,
assigning it to a typed variable does not cause a type error.
That is, we can write

	m = "Hello, 世界"

or

	m = hello

because, unlike the typed constants `typedHello` and `myStringHello`,
the untyped constants `"Hello, 世界"` and `hello` _have no type_.
Assigning them to a variable of any type compatible with strings works without error.

These untyped string constants are strings,
of course, so they can only be used where a string is allowed,
but they do not have _type_ `string`.

## Default type

As a Go programmer, you have certainly seen many declarations like

	str := "Hello, 世界"

and by now you might be asking, "if the constant is untyped, how does `str` get a type in this variable declaration?"
The answer is that an untyped constant has a default type,
an implicit type that it transfers to a value if a type is needed where none is provided.
For untyped string constants, that default type is obviously `string`, so

	str := "Hello, 世界"

or

	var str = "Hello, 世界"

means exactly the same as

	var str string = "Hello, 世界"

One way to think about untyped constants is that they live in a kind of
ideal space of values,
a space less restrictive than Go's full type system.
But to do anything with them, we need to assign them to variables,
and when that happens the _variable_ (not the constant itself) needs a type,
and the constant can tell the variable what type it should have.
In this example, `str` becomes a value of type `string` because the untyped
string constant gives the declaration its default type, `string`.

In such a declaration, a variable is declared with a type and initial value.
Sometimes when we use a constant, however, the destination of the value is not so clear.
For instance consider this statement:

{{play "constants/default1.go" `/START/` `/STOP/`}}

The signature of `fmt.Printf` is

	func Printf(format string, a ...interface{}) (n int, err error)

which is to say its arguments (after the format string) are interface values.
What happens when `fmt.Printf` is called with an untyped constant is that an interface value is created
to pass as an argument, and the concrete type stored for that argument is the default type of the constant.
This process is analogous to what we saw earlier when declaring an initialized value using an untyped string constant.

You can see the result in this example, which uses the format `%v` to print
the value and `%T` to print the type of the value being passed to `fmt.Printf`:

{{play "constants/default2.go" `/START/` `/STOP/`}}

If the constant has a type, that goes into the interface, as this example shows:

{{play "constants/default3.go" `/START/` `/STOP/`}}

(For more information about how interface values work,
see the first sections of [this blog post](https://blog.golang.org/laws-of-reflection).)

In summary, a typed constant obeys all the rules of typed values in Go.
On the other hand, an untyped constant does not carry a Go type in the same
way and can be mixed and matched more freely.
It does, however, have a default type that is exposed when, and only when, no other type information is available.

## Default type determined by syntax

The default type of an untyped constant is determined by its syntax.
For string constants, the only possible implicit type is `string`.
For [numeric constants](/ref/spec#Numeric_types), the implicit type has more variety.
Integer constants default to `int`, floating-point constants `float64`,
rune constants to `rune` (an alias for `int32`),
and imaginary constants to `complex128`.
Here's our canonical print statement used repeatedly to show the default types in action:

{{play "constants/syntax.go" `/START/` `/STOP/`}}

(Exercise: Explain the result for `'x'`.)

## Booleans

Everything we said about untyped string constants can be said for untyped boolean constants.
The values `true` and `false` are untyped boolean constants that can be assigned to any boolean variable,
but once given a type, boolean variables cannot be mixed:

{{play "constants/bool.go" `/START/` `/STOP/`}}

Run the example and see what happens, then comment out the "Bad" line and run it again.
The pattern here follows exactly that of string constants.

## Floats

Floating-point constants are just like boolean constants in most respects.
Our standard example works as expected in translation:

{{play "constants/float1.go" `/START/` `/STOP/`}}

One wrinkle is that there are _two_ floating-point types in Go: `float32` and `float64`.
The default type for a floating-point constant is `float64`, although an untyped floating-point
constant can be assigned to a `float32` value just fine:

{{play "constants/float2.go" `/START/` `/STOP/`}}

Floating-point values are a good place to introduce the concept of overflow, or the range of values.

Numeric constants live in an arbitrary-precision numeric space; they are just regular numbers.
But when they are assigned to a variable the value must be able to fit in the destination.
We can declare a constant with a very large value:

{{code "constants/float3.go" `/Huge/`}}

—that's just a number, after all—but we can't assign it or even print it. This statement won't even compile:

{{play "constants/float3.go" `/Println/`}}

The error is, "constant 1.00000e+1000 overflows float64", which is true.
But `Huge` might be useful: we can use it in expressions with other constants
and use the value of those expressions if the result
can be represented in the range of a `float64`.
The statement,

{{play "constants/float4.go" `/Println/`}}

prints `10`, as one would expect.

In a related way, floating-point constants may have very high precision,
so that arithmetic involving them is more accurate.
The constants defined in the [math](/pkg/math) package are given with many more digits than are
available in a `float64`. Here is the definition of `math.Pi`:

	Pi	= 3.14159265358979323846264338327950288419716939937510582097494459

When that value is assigned to a variable,
some of the precision will be lost;
the assignment will create the `float64` (or `float32`)
value closest to the high-precision value. This snippet

{{play "constants/float5.go" `/START/` `/STOP/`}}

prints `3.141592653589793`.

Having so many digits available means that calculations like `Pi/2` or other
more intricate evaluations can carry more precision
until the result is assigned, making calculations involving constants easier to write without losing precision.
It also means that there is no occasion in which the floating-point corner cases like infinities,
soft underflows, and `NaNs` arise in constant expressions.
(Division by a constant zero is a compile-time error,
and when everything is a number there's no such thing as "not a number".)

## Complex numbers

Complex constants behave a lot like floating-point constants.
Here's a version of our now-familiar litany translated into complex numbers:

{{play "constants/complex1.go" `/START/` `/STOP/`}}

The default type of a complex number is `complex128`, the larger-precision version composed of two `float64` values.

For clarity in our example, we wrote out the full expression `(0.0+1.0i)`,
but this value can be shortened to `0.0+1.0i`,
`1.0i` or even `1i`.

Let's play a trick.
We know that in Go, a numeric constant is just a number.
What if that number is a complex number with no imaginary part, that is, a real?
Here's one:

{{code "constants/complex2.go" `/const Two/`}}

That's an untyped complex constant.
Even though it has no imaginary part, the _syntax_ of the expression defines it to have default type `complex128`.
Therefore, if we use it to declare a variable, the default type will be `complex128`. The snippet

{{play "constants/complex2.go" `/START/` `/STOP/`}}

prints `complex128:` `(2+0i)`.
But numerically, `Two` can be stored in a scalar floating-point number,
a `float64` or `float32`, with no loss of information.
Thus we can assign `Two` to a `float64`, either in an initialization or an assignment, without problems:

{{play "constants/complex3.go" `/START/` `/STOP/`}}

The output is `2` `and` `2`.
Even though `Two` is a complex constant, it can be assigned to scalar floating-point variables.
This ability for a constant to "cross" types like this will prove useful.

## Integers

At last we come to integers.
They have more moving parts—[many sizes, signed or unsigned, and more](/ref/spec#Numeric_types)—but
they play by the same rules.
For the last time, here is our familiar example, using just `int` this time:

{{play "constants/int1.go" `/START/` `/STOP/`}}

The same example could be built for any of the integer types, which are:

	int int8 int16 int32 int64
	uint uint8 uint16 uint32 uint64
	uintptr

(plus the aliases `byte` for `uint8` and `rune` for `int32`).
That's a lot, but the pattern in the way constants work should be familiar
enough by now that you can see how things will play out.

As mentioned above, integers come in a couple of forms and each form has
its own default type:
`int` for simple constants like `123` or `0xFF` or `-14`
and `rune` for quoted characters like 'a', '世' or '\r'.

No constant form has as its default type an unsigned integer type.
However, the flexibility of untyped constants means we can initialize unsigned
integer variables using simple constants as long as we are clear about the type.
It's analogous to how we can initialize a `float64` using a complex number with zero imaginary part.
Here are several different ways to initialize a `uint`;
all are equivalent, but all must mention the type explicitly for the result to be unsigned.

	var u uint = 17
	var u = uint(17)
	u := uint(17)

Similarly to the range issue mentioned in the section on floating-point values,
not all integer values can fit in all integer types.
There are two problems that might arise: the value might be too large,
or it might be a negative value being assigned to an unsigned integer type.
For instance, `int8` has range -128 through 127,
so constants outside of that range can never be assigned to a variable of type `int8`:

{{play "constants/int2.go" `/var/`}}

Similarly, `uint8`, also known as `byte`,
has range 0 through 255, so a large or negative constant cannot be assigned to a `uint8`:

{{play "constants/int3.go" `/var/`}}

This type-checking can catch mistakes like this one:

{{play "constants/int4.go" `/START/` `/STOP/`}}

If the compiler complains about your use of a constant, it's likely a real bug like this.

## An exercise: The largest unsigned int

Here is an informative little exercise.
How do we express a constant representing the largest value that fits in a `uint`?
If we were talking about `uint32` rather than `uint`, we could write

{{raw `
	const MaxUint32 = 1<<32 - 1
`}}

but we want `uint`, not `uint32`.
The `int` and `uint` types have equal unspecified numbers of bits, either 32 or 64.
Since the number of bits available depends on the architecture, we can't just write down a single value.

Fans of [two's-complement arithmetic](http://en.wikipedia.org/wiki/Two's_complement),
which Go's integers are defined to use, know that the representation of `-1` has all its bits set to 1,
so the bit pattern of `-1` is internally the same as that of the
largest unsigned integer.
We therefore might think we could write

{{play "constants/exercise1.go" `/const/`}}

but that is illegal because -1 cannot be represented by an unsigned variable;
`-1` is not in the range of unsigned values.
A conversion won't help either, for the same reason:

{{play "constants/exercise2.go" `/const/`}}

Even though at run-time a value of -1 can be converted to an unsigned integer, the rules
for constant [conversions](/ref/spec#Conversions) forbid this kind of coercion at compile time.
That is to say, this works:

{{play "constants/exercise3.go" `/START/` `/STOP/`}}

but only because `v` is a variable; if we made `v` a constant,
even an untyped constant, we'd be back in forbidden territory:

{{play "constants/exercise4.go" `/START/` `/STOP/`}}

We return to our previous approach, but instead of `-1` we try `^0`,
the bitwise negation of an arbitrary number of zero bits.
But that fails too, for a similar reason:
In the space of numeric values,
`^0` represents an infinite number of ones, so we lose information if we assign that to any fixed-size integer:

{{play "constants/exercise5.go" `/const/`}}

How then do we represent the largest unsigned integer as a constant?

The key is to constrain the operation to the number of bits in a `uint` and avoiding
values, such as negative numbers, that are not representable in a `uint`.
The simplest `uint` value is the typed constant `uint(0)`.
If `uints` have 32 or 64 bits, `uint(0)` has 32 or 64 zero bits accordingly.
If we invert each of those bits, we'll get the correct number of one bits, which is the largest `uint` value.

Therefore we don't flip the bits of the untyped constant `0`, we flip the bits of the typed constant `uint(0)`.
Here, then, is our constant:

{{play "constants/exercise6.go" `/START/` `/STOP/`}}

Whatever the number of bits it takes to represent a `uint` in the current execution environment
(on the [playground](https://blog.golang.org/playground), it's 32),
this constant correctly represents the largest value a variable of type `uint` can hold.

If you understand the analysis that got us to this result,
you understand all the important points about constants in Go.

## Numbers

The concept of untyped constants in Go means that all the numeric constants,
whether integer, floating-point, complex,
or even character values,
live in a kind of unified space.
It's when we bring them to the computational world of variables,
assignments, and operations that the actual types matter.
But as long as we stay in the world of numeric constants, we can mix and match values as we like.
All these constants have numeric value 1:

	1
	1.000
	1e3-99.0*10-9
	'\x01'
	'\u0001'
	'b' - 'a'
	1.0+3i-3.0i

Therefore, although they have different implicit default types,
written as untyped constants they can be assigned to a variable of any numeric type:

{{play "constants/numbers1.go" `/START/` `/STOP/`}}

The output from this snippet is: `1 1 1 1 1 (1+0i) 1`.

You can even do nutty stuff like

{{play "constants/numbers2.go" `/START/` `/STOP/`}}

which yields 145.5, which is pointless except to prove a point.

But the real point of these rules is flexibility.
That flexibility means that, despite the fact that in Go it is illegal in
the same expression to mix floating-point and integer variables,
or even `int` and `int32` variables, it is fine to write

	sqrt2 := math.Sqrt(2)

or

	const millisecond = time.Second/1e3

or

	bigBufferWithHeader := make([]byte, 512+1e6)

and have the results mean what you expect.

Because in Go, numeric constants work as you expect: like numbers.


text:
package com.lidroid.xutils.bitmap;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.lidroid.xutils.bitmap.core.BitmapSize;

import java.lang.reflect.Field;

public class BitmapCommonUtils {

    private BitmapCommonUtils() {
    }

    private static BitmapSize screenSize = null;

    public static BitmapSize getScreenSize(Context context) {
        if (screenSize == null) {
            DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
            screenSize = new BitmapSize(displayMetrics.widthPixels, displayMetrics.heightPixels);
        }
        return screenSize;
    }

    /**
     * @param view
     * @param maxImageWidth
     * @param maxImageHeight
     * 设置显示View的大小
     * @return
     */
    public static BitmapSize optimizeMaxSizeByView(View view, int maxImageWidth, int maxImageHeight) {
        int width = maxImageWidth;
        int height = maxImageHeight;

        if (width > 0 && height > 0) { //当设置不为0的时候
            return new BitmapSize(width, height);
        }

        final ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params != null) {
            if (params.width > 0) {  //如果布局文件中配置了大小
                width = params.width;
            } else if (params.width != ViewGroup.LayoutParams.WRAP_CONTENT) {
                width = view.getWidth();
            }

            if (params.height > 0) {
                height = params.height;
            } else if (params.height != ViewGroup.LayoutParams.WRAP_CONTENT) {
                height = view.getHeight();
            }
        }

        if (width <= 0) width = getImageViewFieldValue(view, "mMaxWidth");
        if (height <= 0) height = getImageViewFieldValue(view, "mMaxHeight");

        BitmapSize screenSize = getScreenSize(view.getContext());
        if (width <= 0) width = screenSize.getWidth();
        if (height <= 0) height = screenSize.getHeight();

        return new BitmapSize(width, height);
    }

    private static int getImageViewFieldValue(Object object, String fieldName) {
        int value = 0;
        if (object instanceof ImageView) {
            try {
                Field field = ImageView.class.getDeclaredField(fieldName);
                field.setAccessible(true);
                int fieldValue = (Integer) field.get(object);
                if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE) {
                    value = fieldValue;
                }
            } catch (Throwable e) {
            }
        }
        return value;
    }
}


text:
#include "redis.h"
#include "endianconv.h"

/* -----------------------------------------------------------------------------
 * DUMP, RESTORE and MIGRATE commands
 * -------------------------------------------------------------------------- */

/* Generates a DUMP-format representation of the object 'o', adding it to the
 * io stream pointed by 'rio'. This function can't fail. */
//将给定的robj以固定格式写到rio中
void createDumpPayload(rio *payload, robj *o) {
    unsigned char buf[2];
    uint64_t crc;

    /* Serialize the object in a RDB-like format. It consist of an object type
     * byte followed by the serialized object. This is understood by RESTORE. */
    //初始化rio
    rioInitWithBuffer(payload,sdsempty());
    //保存类型
    redisAssert(rdbSaveObjectType(payload,o));
    //保存对象
    redisAssert(rdbSaveObject(payload,o));

    /* Write the footer, this is how it looks like:
     * ----------------+---------------------+---------------+
     * ... RDB payload | 2 bytes RDB version | 8 bytes CRC64 |
     * ----------------+---------------------+---------------+
     * RDB version and CRC are both in little endian.
     */

    /* RDB version */
    buf[0] = REDIS_RDB_VERSION & 0xff;
    buf[1] = (REDIS_RDB_VERSION >> 8) & 0xff;
    //保存版本
    payload->io.buffer.ptr = sdscatlen(payload->io.buffer.ptr,buf,2);

    /* CRC64 */
    crc = crc64(0,(unsigned char*)payload->io.buffer.ptr,
                sdslen(payload->io.buffer.ptr));
    memrev64ifbe(&crc);
    //保存crc
    payload->io.buffer.ptr = sdscatlen(payload->io.buffer.ptr,&crc,8);
}

/* Verify that the RDB version of the dump payload matches the one of this Redis
 * instance and that the checksum is ok.
 * If the DUMP payload looks valid REDIS_OK is returned, otherwise REDIS_ERR
 * is returned. */
//检查rbd的版本和crc64的正确性
int verifyDumpPayload(unsigned char *p, size_t len) {
    unsigned char *footer;
    uint16_t rdbver;
    uint64_t crc;

    /* At least 2 bytes of RDB version and 8 of CRC64 should be present. */
    if (len < 10) return REDIS_ERR;
    footer = p+(len-10);

    /* Verify RDB version */
    //验证rbd版本
    rdbver = (footer[1] << 8) | footer[0];
    if (rdbver != REDIS_RDB_VERSION) return REDIS_ERR;

    /* Verify CRC64 */
    //验证数据的crc
    crc = crc64(0,p,len-8);
    memrev64ifbe(&crc);
    return (memcmp(&crc,footer+2,8) == 0) ? REDIS_OK : REDIS_ERR;
}

/* DUMP keyname
 * DUMP is actually not used by Redis Cluster but it is the obvious
 * complement of RESTORE and can be useful for different applications. */
//dump命令的实现
void dumpCommand(redisClient *c) {
    robj *o, *dumpobj;
    rio payload;

    /* Check if the key is here. */
    if ((o = lookupKeyRead(c->db,c->argv[1])) == NULL) {
        addReply(c,shared.nullbulk);
        return;
    }

    /* Create the DUMP encoded representation. */
    createDumpPayload(&payload,o);

    /* Transfer to the client */
    dumpobj = createObject(REDIS_STRING,payload.io.buffer.ptr);
    addReplyBulk(c,dumpobj);
    decrRefCount(dumpobj);
    return;
}

/* RESTORE key ttl serialized-value */
//restore命令的实现
void restoreCommand(redisClient *c) {
    long long ttl;
    rio payload;
    int type;
    robj *obj;

    /* Make sure this key does not already exist here... */
    if (lookupKeyWrite(c->db,c->argv[1]) != NULL) {
        addReplyError(c,"Target key name is busy.");
        return;
    }

    /* Check if the TTL value makes sense */
    //验证ttl是否有效
    if (getLongLongFromObjectOrReply(c,c->argv[2],&ttl,NULL) != REDIS_OK) {
        return;
    } else if (ttl < 0) {
        addReplyError(c,"Invalid TTL value, must be >= 0");
        return;
    }

    /* Verify RDB version and data checksum. */
    //验证RDB版本和数据校验和有效
    if (verifyDumpPayload(c->argv[3]->ptr,sdslen(c->argv[3]->ptr)) == REDIS_ERR)
    {
        addReplyError(c,"DUMP payload version or checksum are wrong");
        return;
    }

    rioInitWithBuffer(&payload,c->argv[3]->ptr);
    //调用RDB的API从数据中恢复出robj
    if (((type = rdbLoadObjectType(&payload)) == -1) ||
        ((obj = rdbLoadObject(type,&payload)) == NULL))
    {
        addReplyError(c,"Bad data format");
        return;
    }

    /* Create the key and set the TTL if any */
    //将key添加到db中
    dbAdd(c->db,c->argv[1],obj);
    if (ttl) setExpire(c->db,c->argv[1],mstime()+ttl);
    signalModifiedKey(c->db,c->argv[1]);
    addReply(c,shared.ok);
    server.dirty++;
}

/* MIGRATE host port key dbid timeout */
//migrate命令的实现
void migrateCommand(redisClient *c) {
    int fd;
    long timeout;
    long dbid;
    long long ttl = 0, expireat;
    robj *o;
    rio cmd, payload;

    /* Sanity check */
    if (getLongFromObjectOrReply(c,c->argv[5],&timeout,NULL) != REDIS_OK)
        return;
    if (getLongFromObjectOrReply(c,c->argv[4],&dbid,NULL) != REDIS_OK)
        return;
    if (timeout <= 0) timeout = 1;

    /* Check if the key is here. If not we reply with success as there is
     * nothing to migrate (for instance the key expired in the meantime), but
     * we include such information in the reply string. */
    if ((o = lookupKeyRead(c->db,c->argv[3])) == NULL) {
        addReplySds(c,sdsnew("+NOKEY\r\n"));
        return;
    }

    /* Connect */
    //连接到给定host的端口
    fd = anetTcpNonBlockConnect(server.neterr,c->argv[1]->ptr,
                atoi(c->argv[2]->ptr));
    if (fd == -1) {
        addReplyErrorFormat(c,"Can't connect to target node: %s",
            server.neterr);
        return;
    }

    //等待该套接字可写
    if ((aeWait(fd,AE_WRITABLE,timeout*1000) & AE_WRITABLE) == 0) {
        addReplySds(c,sdsnew("-IOERR error or timeout connecting to the client\r\n"));
        return;
    }

    /* Create RESTORE payload and generate the protocol to call the command. */
    //将恢复该key的restore命令的形式写到rio中
    rioInitWithBuffer(&cmd,sdsempty());
    //写进 "*2\r\n$6\r\nSELECT\r\n$len\r\ndbid\r\n"
    redisAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',2));
    redisAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"SELECT",6));
    redisAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,dbid));

    expireat = getExpire(c->db,c->argv[3]);
    if (expireat != -1) {
        ttl = expireat-mstime();
        if (ttl < 1) ttl = 1;
    }

    //写进"*4\r\n$7\r\nRESTORE\r\n$kenlen\r\nkey\r\n$ttllen\r\nttl\r\n"
    redisAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',4));
    redisAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"RESTORE",7));
    redisAssertWithInfo(c,NULL,c->argv[3]->encoding == REDIS_ENCODING_RAW);
    redisAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,c->argv[3]->ptr,sdslen(c->argv[3]->ptr)));
    redisAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,ttl));

    /* Finally the last argument that is the serailized object payload
     * in the DUMP format. */
    //将key的数据以RDB形式存到缓冲区中
    createDumpPayload(&payload,o);
    //将缓冲区写到rio
    redisAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,payload.io.buffer.ptr,
                                sdslen(payload.io.buffer.ptr)));
    sdsfree(payload.io.buffer.ptr);

    /* Tranfer the query to the other node in 64K chunks. */
    //将rio缓冲区数据写到socket中
    {
        sds buf = cmd.io.buffer.ptr;
        size_t pos = 0, towrite;
        int nwritten = 0;

        while ((towrite = sdslen(buf)-pos) > 0) {
        	//每次最多写64KB
            towrite = (towrite > (64*1024) ? (64*1024) : towrite);
            nwritten = syncWrite(fd,buf+pos,towrite,timeout);
            if (nwritten != (signed)towrite) goto socket_wr_err;
            pos += nwritten;
        }
    }

    /* Read back the reply. */
    //从套接字中读出响应
    {
        char buf1[1024];
        char buf2[1024];

        /* Read the two replies */
        if (syncReadLine(fd, buf1, sizeof(buf1), timeout) <= 0)
            goto socket_rd_err;
        if (syncReadLine(fd, buf2, sizeof(buf2), timeout) <= 0)
            goto socket_rd_err;
        if (buf1[0] == '-' || buf2[0] == '-') {
            addReplyErrorFormat(c,"Target instance replied with error: %s",
                (buf1[0] == '-') ? buf1+1 : buf2+1);
        } else {
            robj *aux;

            dbDelete(c->db,c->argv[3]);
            signalModifiedKey(c->db,c->argv[3]);
            addReply(c,shared.ok);
            server.dirty++;

            /* Translate MIGRATE as DEL for replication/AOF. */
            aux = createStringObject("DEL",3);
            rewriteClientCommandVector(c,2,aux,c->argv[3]);
            decrRefCount(aux);
        }
    }

    sdsfree(cmd.io.buffer.ptr);
    close(fd);
    return;

socket_wr_err:
    addReplySds(c,sdsnew("-IOERR error or timeout writing to target instance\r\n"));
    sdsfree(cmd.io.buffer.ptr);
    close(fd);
    return;

socket_rd_err:
    addReplySds(c,sdsnew("-IOERR error or timeout reading from target node\r\n"));
    sdsfree(cmd.io.buffer.ptr);
    close(fd);
    return;
}


text:
package org.apache.asterix.metadata.entities;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.asterix.common.metadata.DataverseName;
import org.apache.asterix.common.transactions.TxnId;
import org.apache.asterix.metadata.MetadataNode;
import org.apache.asterix.om.types.BuiltinType;
import org.apache.asterix.om.types.IAType;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;

/**
 * Maps from a string representation of an Asterix type to an Asterix type.
 */
public class BuiltinTypeMap {

    private static final Map<String, BuiltinType> _builtinTypeMap = new HashMap<>();

    static {
        // Builtin types with deprecated names.
        _builtinTypeMap.put("int8", BuiltinType.AINT8);
        _builtinTypeMap.put("int16", BuiltinType.AINT16);
        _builtinTypeMap.put("int32", BuiltinType.AINT32);
        _builtinTypeMap.put("int64", BuiltinType.AINT64);
        _builtinTypeMap.put("year-month-duration", BuiltinType.AYEARMONTHDURATION);
        _builtinTypeMap.put("day-time-duration", BuiltinType.ADAYTIMEDURATION);

        // Builtin types.
        _builtinTypeMap.put("boolean", BuiltinType.ABOOLEAN);
        _builtinTypeMap.put("tinyint", BuiltinType.AINT8);
        _builtinTypeMap.put("smallint", BuiltinType.AINT16);
        _builtinTypeMap.put("integer", BuiltinType.AINT32);
        _builtinTypeMap.put("int", BuiltinType.AINT32);
        _builtinTypeMap.put("bigint", BuiltinType.AINT64);
        _builtinTypeMap.put("float", BuiltinType.AFLOAT);
        _builtinTypeMap.put("double", BuiltinType.ADOUBLE);
        _builtinTypeMap.put("double precision", BuiltinType.ADOUBLE);
        _builtinTypeMap.put("string", BuiltinType.ASTRING);
        _builtinTypeMap.put("binary", BuiltinType.ABINARY);
        _builtinTypeMap.put("date", BuiltinType.ADATE);
        _builtinTypeMap.put("time", BuiltinType.ATIME);
        _builtinTypeMap.put("datetime", BuiltinType.ADATETIME);
        _builtinTypeMap.put("timestamp", BuiltinType.ADATETIME);
        _builtinTypeMap.put("duration", BuiltinType.ADURATION);
        _builtinTypeMap.put("year_month_duration", BuiltinType.AYEARMONTHDURATION);
        _builtinTypeMap.put("day_time_duration", BuiltinType.ADAYTIMEDURATION);
        _builtinTypeMap.put("interval", BuiltinType.AINTERVAL);
        _builtinTypeMap.put("point", BuiltinType.APOINT);
        _builtinTypeMap.put("point3d", BuiltinType.APOINT3D);
        _builtinTypeMap.put("line", BuiltinType.ALINE);
        _builtinTypeMap.put("polygon", BuiltinType.APOLYGON);
        _builtinTypeMap.put("circle", BuiltinType.ACIRCLE);
        _builtinTypeMap.put("rectangle", BuiltinType.ARECTANGLE);
        _builtinTypeMap.put("missing", BuiltinType.AMISSING);
        _builtinTypeMap.put("null", BuiltinType.ANULL);
        _builtinTypeMap.put("uuid", BuiltinType.AUUID);
        _builtinTypeMap.put("shortwithouttypeinfo", BuiltinType.SHORTWITHOUTTYPEINFO);
        _builtinTypeMap.put("geometry", BuiltinType.AGEOMETRY);
    }

    private BuiltinTypeMap() {
    }

    public static BuiltinType getBuiltinType(String typeName) {
        return _builtinTypeMap.get(typeName.toLowerCase());
    }

    public static Set<BuiltinType> getAllBuiltinTypes() {
        return new HashSet<>(_builtinTypeMap.values());
    }

    public static IAType getTypeFromTypeName(MetadataNode metadataNode, TxnId txnId, DataverseName dataverseName,
            String typeName) throws AlgebricksException {
        IAType type = _builtinTypeMap.get(typeName);
        if (type == null) {
            Datatype dt = metadataNode.getDatatype(txnId, dataverseName, typeName);
            if (dt != null) {
                type = dt.getDatatype();
            }
        }
        return type;
    }
}