text:
using Converter.Emitter.OutputFunctions.HelperFunctions;
using Converter.Emitter.OutputFunctions.RootEmitters;
using ICSharpCode.NRefactory.CSharp;
using System;
using System.Linq;

namespace Converter.Emitter.OutputFunctions
{
    static class ExpressionEmitter
    {
        /// <summary>
        /// Evaluates given expression and adds the corresponding typescript code to the output
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="arguments"></param>
        internal static void Output(Expression expression, EmitterArguments arguments){
            var output = arguments.Output;
            switch (expression.GetType().Name)
            {
                case "AnonymousMethodExpression":
                    var ame = (AnonymousMethodExpression)expression;
                    ParameterEmitter.Output(ame.Parameters, arguments);
                    output.Add("=>");
                    Emitter.ProcessNode(ame.Body,arguments);
                    break;
                case "AsExpression":
                    var ase = (AsExpression)expression;
                    output.AddWithoutSpace("Statements.As(");
                    Output(ase.Expression,arguments);
                    output.AddWithoutSpace(",");
                    output.AddWithoutSpace(AstTypeToStringConverter.Convert(ase.Type,arguments));
                    output.AddWithoutSpace(")");
                    break;
                case "AssignmentExpression":
                    var ae = (AssignmentExpression)expression;
                    Output(ae.Left,arguments);
                    AssignmentOperatorEmitter.Output(ae.Operator,output);
                    Output(ae.Right,arguments);
                    break;
                case "BaseReferenceExpression":
                    var bre = (BaseReferenceExpression)expression;
                    output.AddWithoutSpace("super");
                    break;
                case "BinaryOperatorExpression":
                    var binopExp = (BinaryOperatorExpression)expression;
                    Output(binopExp.Left,arguments);
                    BinaryOperatorEmitter.Output(binopExp.Operator,output);
                    Output(binopExp.Right,arguments);
                    break;
                //example : var a= (ISomething)someThingElse;
                case "CastExpression":
                    var castExpr = (CastExpression)expression;
                    output.AddWithoutSpace("<");
                    output.AddWithoutSpace(AstTypeToStringConverter.Convert(castExpr.Type,arguments));
                    output.AddWithoutSpace(">");
                    Output(castExpr.Expression,arguments);
                    break;
                case "ConditionalExpression":
                    var ce = (ConditionalExpression)expression;
                    Output(ce.Condition, arguments);
                    output.Add(" ?");
                    Output(ce.TrueExpression,arguments);
                    output.Add(" :");
                    Output(ce.FalseExpression,arguments);
                    break;
                case "DirectionExpression":
                    //example : {ref someThing}
                    //example : {out someThing}
                    var de = (DirectionExpression)expression;
                    //TODO : skip ref/out ..
                    Output(de.Expression,arguments);
                    break;
                case "IdentifierExpression":
                    //check if Identifier is a locally known identifier (which needs "this." prefix).
                    string identStr = expression.ToString();

                    if (arguments.TypeTree.ActiveType.NameExists(identStr))
                    {
                        output.AddWithoutSpace("this.");
                    }
                    output.AddWithoutSpace(identStr);
                    break;
                case "InvocationExpression":
                    var ie = (InvocationExpression)expression;
                    Output(ie.Target,arguments);
                    output.Add("(");
                    for (int i = 0; i < ie.Arguments.Count; i++)
                    {
                        Output(ie.Arguments.ElementAt(i),arguments);
                        if (i < ie.Arguments.Count - 1) { output.Add(","); }
                    }
                    output.Add(")");
                    break;
                case "IndexerExpression":
                    var indexExpr = (IndexerExpression)expression;
                    Output(indexExpr.Target,arguments);
                    output.AddWithoutSpace("[");
                    new ArgumentsEmitter(arguments).Output(indexExpr.Arguments);
                    output.AddWithoutSpace("]");
                    break;
                case "IsExpression":
                    var isExpr = (IsExpression)expression;
                    output.AddWithoutSpace("System.Statements.is(");
                    Output(isExpr.Expression,arguments);
                    output.AddWithoutSpace(@",""");
                    output.AddWithoutSpace(AstTypeToStringConverter.Convert(isExpr.Type,arguments));
                    output.AddWithoutSpace(@""")");
                    break;
                case "MemberReferenceExpression":
                    var mre = (MemberReferenceExpression)expression;
                    Output(mre.Target,arguments);
                    output.AddWithoutSpace(".");
                    output.AddWithoutSpace(mre.MemberName);
                    break;
                case "NullExpression":
                    output.Add("null");
                    break;
                case "NullReferenceExpression":
                    output.Add("null");
                    break;
                case "ObjectCreateExpression":
                    var oce = (ObjectCreateExpression)expression;
                    //TODO : find out if we need to use the static-Create on internal objects or the New ;
                    string objectNameSpace;
                    if (arguments.TypeTree.DefaultNamespace.ExistsType(oce.Type.ToString()))
                    {
                        objectNameSpace = arguments.TypeTree.DefaultNamespace.Namespace;
                    }
                    else
                    {
                        objectNameSpace =
                            arguments.ReferencedNamespaces.FirstOrDefault(
                                ns => arguments.TypeTree.ExistsTypeInNamespace(oce.Type.ToString(), ns));
                    }
                    if (objectNameSpace != null)
                    {
                        output.Add("new " + objectNameSpace + "." + oce.Type + "(");
                        for (var i = 0; i < oce.Arguments.Count(); i++)
                        {
                            if (i > 0)
                            {
                                output.Add(", ");
                            }
                            Output(oce.Arguments.ElementAt(i), arguments);
                        }
                        output.Add(")");
                    }
                    else
                    {
                        var type = TypeDeclarationExtractor.ExtractFromNamespaces(oce.Type.ToString(), arguments);
                        output.Add("new " + type + "(");
                        for(var i = 0; i < oce.Arguments.Count(); i++)
                        {
                            if (i > 0)
                            {
                                output.Add(", ");
                            }
                            Output(oce.Arguments.ElementAt(i), arguments);
                        }
                        output.Add(")");
                    }
                    break;
                case "ParenthesizedExpression":
                    var pe = (ParenthesizedExpression)expression;
                    output.AddWithoutSpace("(");
                    Output(pe.Expression,arguments);
                    output.AddWithoutSpace(")");
                    break;
                case "PrimitiveExpression":
                    PrimitiveValueEmitter.Output(((PrimitiveExpression)expression).Value,output);
                    break;
                case "TypeOfExpression":
                    var toe = (TypeOfExpression)expression;
                    output.AddWithoutSpace("System.Statements.typeOf(");
                    output.AddWithoutSpace(AstTypeToStringConverter.Convert(toe.Type,arguments));
                    output.AddWithoutSpace(")");
                    break;
                case "TypeReferenceExpression":
                    //TODO : better
                    //FIND type
                    string typeNameSpace;
                    if (arguments.TypeTree.DefaultNamespace.ExistsType(expression.ToString()))
                    {
                        typeNameSpace = arguments.TypeTree.DefaultNamespace.Namespace;
                    }
                    else
                    {
                        typeNameSpace =
                            arguments.ReferencedNamespaces.FirstOrDefault(
                                ns => arguments.TypeTree.ExistsTypeInNamespace(expression.ToString(), ns));
                    }
                    if (typeNameSpace != null)
                    {
                        output.AddWithoutSpace(typeNameSpace + "." + expression);
                    }
                    else
                    {
                        output.AddWithoutSpace(expression.ToString());
                    }
                    break;
                case "ThisReferenceExpression":
                    output.AddWithoutSpace("this");
                    break;
                case "UnaryOperatorExpression":
                    var uoe = (UnaryOperatorExpression)expression;
                    Output(uoe.Expression,arguments);
                    UnaryOperatorEmitter.Output(uoe.Operator,output);
                    break;
                //array stuff
                case "ArrayInitializerExpression":
                    //example : int[] x = {1,2,3,4};
                    var aie = (ArrayInitializerExpression)expression;
                    output.AddWithoutSpace("[");
                    Output(aie.Elements.ElementAt(0),arguments);
                    foreach (var item in aie.Elements.Skip(1))
                    {
                        output.AddWithoutSpace(",");
                        Output(item,arguments);
                    }
                    output.AddWithoutSpace("]");
                    break;
                case "CheckedExpression":
                    var che = (CheckedExpression)expression;
                    Output(che.Expression,arguments);
                    break;
                case "ArrayCreateExpression":
                    var ace = (ArrayCreateExpression)expression;
                    //when initializer is given forget creating an array and only use initialiser;
                    if (!ace.Initializer.IsNull)
                    {
                        Output(ace.Initializer,arguments);
                    }
                    else
                    // given is : int[] x = new int[3];
                    // problem with multidimensional array's is , that js knows a really bad new Array(??) .. thats ambigous
                    // Read  http://bonsaiden.github.io/JavaScript-Garden/#arrayctor
                    {
                        if (ace.Arguments.Count > 1)
                        {
                            //ToDo find uit hoew to initialize : var x = new int[3,4]; in typescript/js.
                            output.AddWithoutSpace("$TS.createArray(");
                            for (int i = 0; i < ace.Arguments.Count; i++)
                            {
                                Output(ace.Arguments.ElementAt(i),arguments);
                                if (i < ace.Arguments.Count - 1) { output.Add(","); }
                            }
                        }
                        else
                        {
                            output.AddWithoutSpace("new Array(");
                            Output(ace.Arguments.ElementAt(0),arguments);
                            output.AddWithoutSpace(")");
                        }
                    }
                    break;
                case "DefaultValueExpression":
                    //default operator not supported in typescript since no type information is available at runtime
                    //since javascript handles null as false in boolean expressions and as 0 in math expressions it is less critical in javascript.
                    output.Add("null");
                    break;
                default:
                    throw new NotImplementedException();
            }
        }
    }
}


text:
package org.odk.collect.android.spatial;

/**
 * @author jonnordling@gmail.com
 */

import org.osmdroid.ResourceProxy.string;
import org.osmdroid.tileprovider.MapTile;
import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase;

public class GoogleEarthMarkTileSource extends OnlineTileSourceBase {
    public GoogleEarthMarkTileSource(String name, String[] baseurl) {
        super(name, string.unknown, 0, 20, 256, ".png", baseurl);
    }

    @Override
    public String getTileURLString(MapTile aTile) {
        return String.format(getBaseUrl(), aTile.getX(), aTile.getY(),
                aTile.getZoomLevel());
    }

}

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "routing/edge_estimator.hpp"
#include "routing/geometry.hpp"
#include "routing/index_graph.hpp"
#include "routing/joint_segment.hpp"
#include "routing/road_graph.hpp"
#include "routing/route.hpp"
#include "routing/routing_options.hpp"
#include "routing/segment.hpp"
#include "routing/transit_info.hpp"

#include "routing_common/num_mwm_id.hpp"

#include "geometry/point2d.hpp"

#include <functional>
#include <memory>
#include <set>
#include <string>
#include <vector>

namespace routing
{
enum class WorldGraphMode
{
  LeapsOnly,       // Mode for building a cross mwm route containing only leaps. In case of start and
                   // finish they (start and finish) will be connected with all transition segments of
                   // their mwm with leap (fake) edges.
  NoLeaps,         // Mode for building route and getting outgoing/ingoing edges without leaps at all.
  SingleMwm,       // Mode for building route and getting outgoing/ingoing edges within mwm source
                   // segment belongs to.
  Joints,          // Mode for building route with jumps between Joints.
  JointSingleMwm,  // Like |SingleMwm|, but in |Joints| mode.

  Undefined        // Default mode, until initialization.
};

class WorldGraph
{
public:
  // AStarAlgorithm and CheckGraphConnectivity() types aliases:
  using Vertex = IndexGraph::Vertex;
  using Edge = IndexGraph::Edge;
  using Weight = IndexGraph::Weight;

  virtual ~WorldGraph() = default;

  virtual void GetEdgeList(Segment const & segment, bool isOutgoing, bool useRoutingOptions,
                           std::vector<SegmentEdge> & edges) = 0;
  virtual void GetEdgeList(JointSegment const & vertex, Segment const & segment, bool isOutgoing,
                           std::vector<JointEdge> & edges, std::vector<RouteWeight> & parentWeights) = 0;

  // Checks whether path length meets restrictions. Restrictions may depend on the distance from
  // start to finish of the route.
  virtual bool CheckLength(RouteWeight const & weight, double startToFinishDistanceM) const = 0;

  virtual Junction const & GetJunction(Segment const & segment, bool front) = 0;
  virtual m2::PointD const & GetPoint(Segment const & segment, bool front) = 0;
  virtual bool IsOneWay(NumMwmId mwmId, uint32_t featureId) = 0;

  // Checks whether feature is allowed for through passage.
  virtual bool IsPassThroughAllowed(NumMwmId mwmId, uint32_t featureId) = 0;

  // Clear memory used by loaded graphs.
  virtual void ClearCachedGraphs() = 0;
  virtual void SetMode(WorldGraphMode mode) = 0;
  virtual WorldGraphMode GetMode() const = 0;

  virtual void GetOutgoingEdgesList(Segment const & segment, std::vector<SegmentEdge> & edges) = 0;
  virtual void GetIngoingEdgesList(Segment const & segment, std::vector<SegmentEdge> & edges) = 0;

  virtual RouteWeight HeuristicCostEstimate(Segment const & from, Segment const & to) = 0;
  virtual RouteWeight HeuristicCostEstimate(m2::PointD const & from, m2::PointD const & to) = 0;
  virtual RouteWeight HeuristicCostEstimate(Segment const & from, m2::PointD const & to) = 0;

  virtual RouteWeight CalcSegmentWeight(Segment const & segment,
                                        EdgeEstimator::Purpose purpose) = 0;

  virtual RouteWeight CalcLeapWeight(m2::PointD const & from, m2::PointD const & to) const = 0;

  virtual RouteWeight CalcOffroadWeight(m2::PointD const & from, m2::PointD const & to,
                                        EdgeEstimator::Purpose purpose) const = 0;

  virtual double CalculateETA(Segment const & from, Segment const & to) = 0;
  virtual double CalculateETAWithoutPenalty(Segment const & segment) = 0;

  /// \returns transitions for mwm with id |numMwmId|.
  virtual std::vector<Segment> const & GetTransitions(NumMwmId numMwmId, bool isEnter);

  virtual bool IsRoutingOptionsGood(Segment const & /* segment */);
  virtual RoutingOptions GetRoutingOptions(Segment const & /* segment */);
  virtual void SetRoutingOptions(RoutingOptions /* routingOptions */);

  using ParentSegments = std::map<Segment, Segment>;
  using ParentJoints = std::map<JointSegment, JointSegment>;

  virtual void SetAStarParents(bool forward, ParentSegments & parents);
  virtual void SetAStarParents(bool forward, ParentJoints & parents);
  virtual void DropAStarParents();

  virtual bool AreWavesConnectible(ParentSegments & forwardParents, Segment const & commonVertex,
                                  ParentSegments & backwardParents,
                                  std::function<uint32_t(Segment const &)> && fakeFeatureConverter);
  virtual bool AreWavesConnectible(ParentJoints & forwardParents, JointSegment const & commonVertex,
                                  ParentJoints & backwardParents,
                                  std::function<uint32_t(JointSegment const &)> && fakeFeatureConverter);

  /// \returns transit-specific information for segment. For nontransit segments returns nullptr.
  virtual std::unique_ptr<TransitInfo> GetTransitInfo(Segment const & segment) = 0;

  virtual std::vector<RouteSegment::SpeedCamera> GetSpeedCamInfo(Segment const & segment);

  virtual IndexGraph & GetIndexGraph(NumMwmId numMwmId) = 0;

protected:
  void GetTwins(Segment const & segment, bool isOutgoing, bool useRoutingOptions,
                std::vector<SegmentEdge> & edges);
  virtual void GetTwinsInner(Segment const & segment, bool isOutgoing,
                             std::vector<Segment> & twins) = 0;
};

std::string DebugPrint(WorldGraphMode mode);
}  // namespace routing


text:
TYPE=$1
NAME=$2
NOW=`date "+%Y-%m-%d %H:%M:%S"`
NEWSTATE=$3
OLDSTATE=$(cat /var/run/keepalived.state)

echo "$NEWSTATE" > /var/run/keepalived.state

case $NEWSTATE in
        "FAULT") echo "$NOW Trying to restart haproxy to get out"\
                  "of faulty state" >> /var/log/keepalived-notifications.log
                 /etc/init.d/haproxy stop
                 /etc/init.d/haproxy start
                 exit 0
                 ;;
        *) echo "$NOW Unknown state" >> /var/log/keepalived-notifications.log
           exit 1
           ;;
esac


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace Umbraco.Web.Mvc
{

    /// <summary>
    /// Custom json result using newtonsoft json.net
    /// </summary>
    public class JsonNetResult : ActionResult
    {
        public Encoding ContentEncoding { get; set; }
        public string ContentType { get; set; }
        public object Data { get; set; }

        public JsonSerializerSettings SerializerSettings { get; set; }
        public Formatting Formatting { get; set; }

        /// <summary>
        /// Default, unchanged JsonSerializerSettings
        /// </summary>
        public static readonly JsonSerializerSettings DefaultJsonSerializerSettings = new JsonSerializerSettings();

        public JsonNetResult()
        {
            SerializerSettings = new JsonSerializerSettings();
        }
        public JsonNetResult(JsonSerializerSettings jsonSerializerSettings)
        {
            SerializerSettings = jsonSerializerSettings;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = string.IsNullOrEmpty(ContentType) == false
              ? ContentType
              : "application/json";

            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            if (Data != null)
            {
                var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };

                var serializer = JsonSerializer.Create(SerializerSettings);
                serializer.Serialize(writer, Data);

                writer.Flush();
            }
        }
    }

}


text:
Behaviour.addLoadEvent(function() {
    var targetDiv = document.querySelector('#usage-stats-div');
    var statData = targetDiv.getAttribute('data-inserted-from-java');
    loadScript('https://usage.jenkins.io/usage-stats.js?'+statData);
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="1">
        <file>
            <url>src/Encuesta/FrontendBundle/Resources/views/Votacion/votaciones.html.twig</url>
            <bookmark id="1">
                <name/>
                <line>27</line>
                <key/>
            </bookmark>
        </file>
    </editor-bookmarks>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/C:/Users/Jose/Documents/inspector/src/Encuesta/DashboardBundle/Resources/config/routing.yml</file>
            <file>file:/C:/Users/Jose/Documents/inspector/src/Encuesta/ModeloBundle/Form/CanalType.php</file>
            <file>file:/C:/Users/Jose/Documents/inspector/src/Encuesta/ModeloBundle/Entity/Consulta.php</file>
            <file>file:/C:/Users/Jose/Documents/inspector/src/Encuesta/ModeloBundle/Form/ConsultaType.php</file>
            <file>file:/C:/Users/Jose/Documents/inspector/src/Encuesta/ModeloBundle/Controller/DefaultController.php</file>
            <file>file:/C:/Users/Jose/Documents/inspector/web/js/dashboard/table-canal.js</file>
            <file>file:/C:/Users/Jose/Documents/inspector/src/Encuesta/DashboardBundle/Resources/views/Canal/detalle.html.twig</file>
            <file>file:/C:/Users/Jose/Documents/inspector/src/Encuesta/ModeloBundle/Entity/Canal.php</file>
            <file>file:/C:/Users/Jose/Documents/inspector/src/Encuesta/DashboardBundle/Controller/TrivagoController.php</file>
            <file>file:/C:/Users/Jose/Documents/inspector/web/js/dashboard/table-consulta.js</file>
            <file>file:/C:/Users/Jose/Documents/inspector/src/Encuesta/DashboardBundle/Controller/UserController.php</file>
            <file>file:/C:/Users/Jose/Documents/inspector/src/Encuesta/DashboardBundle/Controller/CanalController.php</file>
        </group>
    </open-files>
</project-private>


text:
import nltk
from math import log
from collections import Counter

class TFIDFCalculator:

    def __init__(self, documents):
        documents_dict = {}
        for document in documents:
            title = document[0]
            comments = document[1]
            doc_counter = Counter()
            total = 0
            for comment in comments:
                for word in nltk.word_tokenize(comment):
                    doc_counter[word.lower()] += 1
                    total += 1
            documents_dict[title] = {"counter": doc_counter,"total": total}
        self.documents = documents_dict

    def word_tf_idf_in_doc(self, word, document):

        doc_counter = self.documents[document[0]]["counter"]
        count = doc_counter[word.lower()]
        total = self.documents[document[0]]["total"]
        tf = count / float(total)

        total_docs = len(self.documents)
        all_docs_occurrences = 0
        for doc in self.documents:
            all_docs_occurrences += 1 if word.lower() in self.documents[doc] else 0
        all_docs_occurrences = 1 if all_docs_occurrences == 0 else all_docs_occurrences
        idf = log(total_docs / float(all_docs_occurrences))

        return tf / idf


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

from .common import BaseTest

import fnmatch
import os
import time

from c7n.exceptions import PolicyExecutionError

class TestEcsService(BaseTest):

    def test_ecs_cluster_tag_augment(self):
        session_factory = self.replay_flight_data(
            'test_ecs_cluster_tag_augment')
        p = self.load_policy({
            'name': 'ctags', 'resource': 'ecs',
            'filters': [{'tag:Data': 'Magic'}]},
            session_factory=session_factory)
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(
            resources[0]['Tags'],
            [{'Key': 'Env', 'Value': 'Dev'},
             {'Key': 'Data', 'Value': 'Magic'}])

    def test_ecs_service_tag_augment(self):
        session_factory = self.replay_flight_data(
            'test_ecs_service_tag_augment')
        p = self.load_policy({
            'name': 'ctags', 'resource': 'ecs-service'},
            session_factory=session_factory)
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(
            resources[0]['Tags'],
            [{'Key': 'Name', 'Value': 'Dev'}])

    def test_ecs_service_by_arn(self):
        session_factory = self.replay_flight_data('test_ecs_service_by_arn')

        p = self.load_policy({
            'name': 'ecs-svc', 'resource': 'ecs-service'},
            session_factory=session_factory)
        svcs = p.resource_manager.get_resources(
            ["arn:aws:ecs:us-east-1:644160558196:service/test/test-no-delete"])
        self.assertEqual(len(svcs), 1)
        self.assertEqual(
            {t['Key']: t['Value'] for t in svcs[0]['Tags']},
            {'Env': 'Dev', 'Owner': '1'})

        self.assertRaises(
            PolicyExecutionError,
            p.resource_manager.get_resources,
            ["arn:aws:ecs:us-east-1:644160558196:service/test-no-delete"])

    def test_ecs_service_resource(self):
        session_factory = self.replay_flight_data("test_ecs_service")
        p = self.load_policy(
            {"name": "all-ecs", "resource": "ecs-service"},
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(resources[0]["serviceName"], "home-web")

    def test_ecs_service_metrics(self):
        session_factory = self.replay_flight_data("test_ecs_service_metrics")
        p = self.load_policy(
            {
                "name": "all-ecs",
                "resource": "ecs-service",
                "filters": [
                    {"serviceName": "home-web"},
                    {
                        "type": "metrics",
                        "name": "MemoryUtilization",
                        "op": "less-than",
                        "value": 1,
                    },
                ],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertTrue("c7n.metrics" in resources[0])

    def test_ecs_service_update(self):
        session_factory = self.replay_flight_data("test_ecs_service_update")
        test_service_name = 'custodian-service-update-test'

        p = self.load_policy(
            {
                "name": "all-ecs-to-update",
                "resource": "ecs-service",
                "filters": [
                    {"networkConfiguration.awsvpcConfiguration.assignPublicIp": "ENABLED"},
                    {"serviceName": test_service_name}
                ],
                "actions": [
                    {
                        'type': 'modify',
                        'update': {
                            'networkConfiguration': {
                                'awsvpcConfiguration': {
                                    'assignPublicIp': 'DISABLED',
                                }
                            },
                        }
                    }
                ],
            },
            session_factory=session_factory,
        )
        result = p.run()
        self.assertEqual(len(result), 1)

        client = session_factory().client("ecs")
        svc_current = client.describe_services(
            cluster="arn:aws:ecs:us-east-1:644160558196:cluster/test-cluster",
            services=[test_service_name]
        )["services"][0]
        self.assertEqual(svc_current['networkConfiguration'][
            'awsvpcConfiguration']['assignPublicIp'], 'DISABLED')

    def test_ecs_service_delete(self):
        session_factory = self.replay_flight_data("test_ecs_service_delete")
        p = self.load_policy(
            {
                "name": "all-ecs",
                "resource": "ecs-service",
                "filters": [{"serviceName": "web"}],
                "actions": ["delete"],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        svc = resources.pop()
        self.assertEqual(svc["serviceName"], "web")
        if self.recording:
            time.sleep(1)
        client = session_factory().client("ecs")
        svc_current = client.describe_services(
            cluster=svc["clusterArn"], services=[svc["serviceName"]]
        )[
            "services"
        ][
            0
        ]
        self.assertEqual(svc_current["serviceArn"], svc["serviceArn"])
        self.assertNotEqual(svc_current["status"], svc["status"])

    def test_ecs_service_task_def_filter(self):
        session_factory = self.replay_flight_data("test_ecs_task_def_filter")
        p = self.load_policy(
            {
                "name": "services-using-nginx",
                "resource": "ecs-service",
                "filters": [
                    {
                        "type": "task-definition",
                        "key": "containerDefinitions[].image",
                        "op": "in",
                        "value_type": "swap",
                        "value": "nginx:latest",
                    }
                ],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(resources[0]["serviceName"], "home-web")

    def test_ecs_service_taggable(self):
        services = [
            {"serviceArn": "arn:aws:ecs:us-east-1:644160558196:service/test/test-yes-tag",
             "serviceName": "test-yes-tag",
             "clusterArn": "arn:aws:ecs:us-east-1:644160558196:cluster/test"},
            {"serviceArn": "arn:aws:ecs:us-east-1:644160558196:service/test-no-tag",
             "serviceName": "test-no-tag",
             "clusterArn": "arn:aws:ecs:us-east-1:644160558196:cluster/test"}]
        p = self.load_policy({
            "name": "ecs-service-taggable",
            "resource": "ecs-service",
            "filters": [
                {"type": "taggable", "state": True}]})
        resources = p.resource_manager.filter_resources(services)
        self.assertEqual(len(resources), 1)
        self.assertTrue(resources[0]['serviceName'], 'test-yes-tag')

class TestEcsTaskDefinition(BaseTest):

    def test_task_definition_resource(self):
        session_factory = self.replay_flight_data("test_ecs_task_def")
        p = self.load_policy(
            {"name": "task-defs", "resource": "ecs-task-definition"},
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 3)
        images = set()
        for r in resources:
            for c in r["containerDefinitions"]:
                images.add(c["image"])
        self.assertEqual(
            sorted(images), ["nginx:latest", "postgres:latest", "redis:latest"]
        )

    def test_task_definition_delete(self):
        session_factory = self.replay_flight_data("test_ecs_task_def_delete")
        p = self.load_policy(
            {
                "name": "task-defs",
                "resource": "ecs-task-definition",
                "filters": [{"family": "launch-me"}],
                "actions": ["delete"],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(
            resources[0]["containerDefinitions"][0]["image"], "postgres:latest"
        )
        self.assertEqual(resources[0]["status"], "ACTIVE")
        arns = session_factory().client("ecs").list_task_definitions(
            familyPrefix="launch-me", status="ACTIVE"
        ).get(
            "taskDefinitionArns"
        )
        self.assertEqual(arns, [])

    def test_task_definition_get_resources(self):
        session_factory = self.replay_flight_data("test_ecs_task_def_query")
        p = self.load_policy(
            {"name": "task-defs", "resource": "ecs-task-definition"},
            session_factory=session_factory,
        )
        arn = "arn:aws:ecs:us-east-1:644160558196:task-definition/ecs-read-only-root:1"
        resources = p.resource_manager.get_resources([arn])
        self.assertEqual(len(resources), 1)
        self.assertEqual(resources[0]["taskDefinitionArn"], arn)
        self.assertEqual(
            len(
                fnmatch.filter(
                    os.listdir(
                        os.path.join(self.placebo_dir, "test_ecs_task_def_query")
                    ),
                    "*.json",
                )
            ),
            1,
        )

    def test_ecs_task_def_tags(self):
        session_factory = self.replay_flight_data(
            "test_ecs_task_def_tags"
        )
        arn = "arn:aws:ecs:us-east-1:644160558196:task-definition/c7n:1"
        p = self.load_policy(
            {
                "name": "tag-ecs-task-def",
                "resource": "ecs-task-definition",
                "filters": [
                    {"taskDefinitionArn": arn},
                    {"tag:Role": "present"}
                ],
                "actions": [
                    {"type": "tag", "key": "TestKey", "value": "TestValue"},
                    {"type": "tag", "key": "c7n-tag", "value": "present"},
                    {"type": "remove-tag", "tags": ["Role"]}
                ],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

        client = session_factory().client("ecs")
        tags = {t['key']: t['value'] for t in
                client.list_tags_for_resource(
                    resourceArn=resources[0]["taskDefinitionArn"]).get("tags")}
        self.assertEqual(tags, {"TestKey": "TestValue", "c7n-tag": "present"})

class TestEcsTask(BaseTest):

    def test_task_by_arn(self):
        session_factory = self.replay_flight_data('test_ecs_task_by_arn')
        p = self.load_policy({
            'name': 'tasks', 'resource': 'ecs-task'}, session_factory=session_factory)
        tasks = p.resource_manager.get_resources([
            'arn:aws:ecs:us-east-1:644160558196:task/devx/21b23041dec947b996fcc7a8aa606d64'])
        self.assertEqual(len(tasks), 1)
        self.assertEqual(tasks[0]['launchType'], 'FARGATE')
        self.assertEqual(tasks[0]['lastStatus'], 'STOPPED')

        self.assertRaises(
            PolicyExecutionError,
            p.resource_manager.get_resources,
            ['arn:aws:ecs:us-east-1:644160558196:task/21b23041dec947b996fcc7a8aa606d64'])

    def test_task_resource(self):
        session_factory = self.replay_flight_data("test_ecs_task")
        p = self.load_policy(
            {"name": "tasks", "resource": "ecs-task"}, session_factory=session_factory
        )
        resources = p.run()
        self.assertEqual(len(resources), 4)

    def test_task_delete(self):
        session_factory = self.replay_flight_data("test_ecs_task_delete")
        p = self.load_policy(
            {
                "name": "tasks",
                "resource": "ecs-task",
                "filters": [{"group": "service:home-web"}, {"startedBy": "present"}],
                "actions": ["stop"],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 2)
        client = session_factory().client("ecs")
        tasks = client.list_tasks(cluster=resources[0]["clusterArn"])["taskArns"]
        self.assertFalse(set([r["taskArn"] for r in resources]).intersection(tasks))

class TestEcsContainerInstance(BaseTest):

    def test_container_instance_resource(self):
        session_factory = self.replay_flight_data("test_ecs_container_instance")
        p = self.load_policy(
            {"name": "container-instances", "resource": "ecs-container-instance"},
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

    def test_container_instance_update_agent(self):
        session_factory = self.replay_flight_data(
            "test_ecs_container_instance_update_agent"
        )
        p = self.load_policy(
            {
                "name": "container-instance-update-agent",
                "resource": "ecs-container-instance",
                "actions": [{"type": "update-agent"}],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        if self.recording:
            time.sleep(60)
        client = session_factory().client("ecs")
        updated_version = client.describe_container_instances(
            cluster="default",
            containerInstances=["a8a469ef-009f-40f8-9639-3a0d9c6a9b9e"],
        )[
            "containerInstances"
        ][
            0
        ][
            "versionInfo"
        ][
            "agentVersion"
        ]
        self.assertNotEqual(
            updated_version, resources[0]["versionInfo"]["agentVersion"]
        )

    def test_container_instance_set_state(self):
        session_factory = self.replay_flight_data(
            "test_ecs_container_instance_set_state"
        )
        p = self.load_policy(
            {
                "name": "container-instance-update-agent",
                "resource": "ecs-container-instance",
                "actions": [{"type": "set-state", "state": "DRAINING"}],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        client = session_factory().client("ecs")
        state = client.describe_container_instances(
            cluster="default", containerInstances=[resources[0]["containerInstanceArn"]]
        )[
            "containerInstances"
        ][
            0
        ][
            "status"
        ]
        self.assertEqual(state, "DRAINING")


text:
"""
Deutsch-Jozsa Algorithm is one of the first examples of a quantum
algorithm that is exponentially faster than any possible deterministic
classical algorithm

Premise:
We are given a hidden Boolean function f,
which takes as input a string of bits, and returns either 0 or 1:

f({x0,x1,x2,...}) -> 0 or 1, where xn is 0 or 1

The property of the given Boolean function is that it is guaranteed to
either be balanced or constant. A constant function returns all 0's
or all 1's for any input, while a balanced function returns  0's for
exactly half of all inputs and 1's for the other half. Our task is to
determine whether the given function is balanced or constant.

References:
- https://en.wikipedia.org/wiki/Deutsch-Jozsa_algorithm
- https://qiskit.org/textbook/ch-algorithms/deutsch-jozsa.html
"""

import numpy as np
import qiskit

def dj_oracle(case: str, num_qubits: int) -> qiskit.QuantumCircuit:
    """
    Returns a Quantum Circuit for the Oracle function.
    The circuit returned can represent balanced or constant function,
    according to the arguments passed
    """
    # This circuit has num_qubits+1 qubits: the size of the input,
    # plus one output qubit
    oracle_qc = qiskit.QuantumCircuit(num_qubits + 1)

    # First, let's deal with the case in which oracle is balanced
    if case == "balanced":
        # First generate a random number that tells us which CNOTs to
        # wrap in X-gates:
        b = np.random.randint(1, 2**num_qubits)
        # Next, format 'b' as a binary string of length 'n', padded with zeros:
        b_str = format(b, f"0{num_qubits}b")
        # Next, we place the first X-gates. Each digit in our binary string
        # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
        # we apply an X-gate to that qubit:
        for index, bit in enumerate(b_str):
            if bit == "1":
                oracle_qc.x(index)
        # Do the controlled-NOT gates for each qubit, using the output qubit
        # as the target:
        for index in range(num_qubits):
            oracle_qc.cx(index, num_qubits)
        # Next, place the final X-gates
        for index, bit in enumerate(b_str):
            if bit == "1":
                oracle_qc.x(index)

    # Case in which oracle is constant
    if case == "constant":
        # First decide what the fixed output of the oracle will be
        # (either always 0 or always 1)
        output = np.random.randint(2)
        if output == 1:
            oracle_qc.x(num_qubits)

    oracle_gate = oracle_qc.to_gate()
    oracle_gate.name = "Oracle"  # To show when we display the circuit
    return oracle_gate

def dj_algorithm(
    oracle: qiskit.QuantumCircuit, num_qubits: int
) -> qiskit.QuantumCircuit:
    """
    Returns the complete Deutsch-Jozsa Quantum Circuit,
    adding Input & Output registers and Hadamard & Measurement Gates,
    to the Oracle Circuit passed in arguments
    """
    dj_circuit = qiskit.QuantumCircuit(num_qubits + 1, num_qubits)
    # Set up the output qubit:
    dj_circuit.x(num_qubits)
    dj_circuit.h(num_qubits)
    # And set up the input register:
    for qubit in range(num_qubits):
        dj_circuit.h(qubit)
    # Let's append the oracle gate to our circuit:
    dj_circuit.append(oracle, range(num_qubits + 1))
    # Finally, perform the H-gates again and measure:
    for qubit in range(num_qubits):
        dj_circuit.h(qubit)

    for i in range(num_qubits):
        dj_circuit.measure(i, i)

    return dj_circuit

def deutsch_jozsa(case: str, num_qubits: int) -> qiskit.result.counts.Counts:
    """
    Main function that builds the circuit using other helper functions,
    runs the experiment 1000 times & returns the resultant qubit counts
    >>> deutsch_jozsa("constant", 3)
    {'000': 1000}
    >>> deutsch_jozsa("balanced", 3)
    {'111': 1000}
    """
    # Use Aer's simulator
    simulator = qiskit.Aer.get_backend("aer_simulator")

    oracle_gate = dj_oracle(case, num_qubits)
    dj_circuit = dj_algorithm(oracle_gate, num_qubits)

    # Execute the circuit on the simulator
    job = qiskit.execute(dj_circuit, simulator, shots=1000)

    # Return the histogram data of the results of the experiment.
    return job.result().get_counts(dj_circuit)

if __name__ == "__main__":
    print(f"Deutsch Jozsa - Constant Oracle: {deutsch_jozsa('constant', 3)}")
    print(f"Deutsch Jozsa - Balanced Oracle: {deutsch_jozsa('balanced', 3)}")


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ip::basic_resolver_query::basic_resolver_query</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../ip__basic_resolver_query.html" title="ip::basic_resolver_query">
<link rel="prev" href="all_matching.html" title="ip::basic_resolver_query::all_matching">
<link rel="next" href="basic_resolver_query/overload1.html" title="ip::basic_resolver_query::basic_resolver_query (1 of 4 overloads)">

Home
Libraries
People
FAQ
More

ip::basic_resolver_query::basic_resolver_query

Construct
          with specified service name for any protocol.

basic_resolver_query(
    const std::string & service,
    resolver_query_base::flags resolve_flags = passive|address_configured);
  » more...

          Construct with specified service name for a given protocol.

basic_resolver_query(
    const protocol_type & protocol,
    const std::string & service,
    resolver_query_base::flags resolve_flags = passive|address_configured);
  » more...

          Construct with specified host name and service name for any protocol.

basic_resolver_query(
    const std::string & host,
    const std::string & service,
    resolver_query_base::flags resolve_flags = address_configured);
  » more...

          Construct with specified host name and service name for a given protocol.

basic_resolver_query(
    const protocol_type & protocol,
    const std::string & host,
    const std::string & service,
    resolver_query_base::flags resolve_flags = address_configured);
  » more...

Copyright © 2003-2021 Christopher
      M. Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Routiner</title>
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="app.css" />
<link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">

              Routiner

                   Fork me on GitHub

  <routines-list></routines-list>


text:
@implementation CocoaListView : NSScrollView

-(id) initWith:(phoenix::ListView&)listViewReference {
  if(self = [super initWithFrame:NSMakeRect(0, 0, 0, 0)]) {
    listView = &listViewReference;
    content = [[CocoaListViewContent alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)];

    [self setDocumentView:content];
    [self setBorderType:NSBezelBorder];
    [self setHasVerticalScroller:YES];

    [content setDataSource:self];
    [content setDelegate:self];
    [content setTarget:self];
    [content setDoubleAction:@selector(doubleAction:)];

    [content setAllowsColumnReordering:NO];
    [content setAllowsColumnResizing:YES];
    [content setAllowsColumnSelection:NO];
    [content setAllowsEmptySelection:YES];
    [content setAllowsMultipleSelection:NO];
    [content setColumnAutoresizingStyle:NSTableViewLastColumnOnlyAutoresizingStyle];

    font = nil;
    [self setFont:nil];
  }
  return self;
}

-(void) dealloc {
  [content release];
  [font release];
  [super dealloc];
}

-(CocoaListViewContent*) content {
  return content;
}

-(NSFont*) font {
  return font;
}

-(void) setFont:(NSFont*)fontPointer {
  if(!fontPointer) fontPointer = [NSFont systemFontOfSize:12];
  [fontPointer retain];
  if(font) [font release];
  font = fontPointer;

  unsigned fontHeight = phoenix::pFont::size(font, " ").height;
  [content setFont:font];
  [content setRowHeight:fontHeight];
  [self reloadColumns];
}

-(void) reloadColumns {
  while([[content tableColumns] count]) {
    [content removeTableColumn:[[content tableColumns] lastObject]];
  }

  if(listView->state.checkable) {
    NSTableColumn *tableColumn = [[NSTableColumn alloc] initWithIdentifier:@"check"];
    NSTableHeaderCell *headerCell = [[NSTableHeaderCell alloc] initTextCell:@""];
    NSButtonCell *dataCell = [[NSButtonCell alloc] initTextCell:@""];

    [dataCell setButtonType:NSSwitchButton];
    [dataCell setControlSize:NSSmallControlSize];
    [dataCell setRefusesFirstResponder:YES];

    [tableColumn setResizingMask:NSTableColumnNoResizing];
    [tableColumn setHeaderCell:headerCell];
    [tableColumn setDataCell:dataCell];
    [tableColumn setWidth:20.0];

    [content addTableColumn:tableColumn];
  }

  lstring headers = listView->state.headerText;
  if(headers.size() == 0) headers.append("");
  [content setUsesAlternatingRowBackgroundColors:headers.size() >= 2];

  for(unsigned column = 0; column < headers.size(); column++) {
    NSTableColumn* tableColumn = [[NSTableColumn alloc] initWithIdentifier:[[NSNumber numberWithInteger:column] stringValue]];
    NSTableHeaderCell* headerCell = [[NSTableHeaderCell alloc] initTextCell:[NSString stringWithUTF8String:headers(column)]];
    CocoaListViewCell* dataCell = [[CocoaListViewCell alloc] initTextCell:@""];

    [dataCell setEditable:NO];

    [tableColumn setResizingMask:NSTableColumnAutoresizingMask | NSTableColumnUserResizingMask];
    [tableColumn setHeaderCell:headerCell];
    [tableColumn setDataCell:dataCell];

    [content addTableColumn:tableColumn];
  }
}

-(NSInteger) numberOfRowsInTableView:(NSTableView*)table {
  return listView->state.text.size();
}

-(id) tableView:(NSTableView*)table objectValueForTableColumn:(NSTableColumn*)tableColumn row:(NSInteger)row {
  if([[tableColumn identifier] isEqualToString:@"check"]) {
    auto checked = listView->state.checked(row) ? NSOnState : NSOffState;
    return [NSNumber numberWithInteger:checked];
  }

  NSInteger column = [[tableColumn identifier] integerValue];
  unsigned height = [table rowHeight];

  NSString* text = [NSString stringWithUTF8String:listView->state.text(row)(column)];
  NSImage* image = NSMakeImage(listView->state.image(row)(column), height, height);

  if(image) return @{ @"text":text, @"image":image };
  return @{ @"text":text };
}

-(BOOL) tableView:(NSTableView*)table shouldShowCellExpansionForTableColumn:(NSTableColumn*)tableColumn row:(NSInteger)row {
  return NO;
}

-(NSString*) tableView:(NSTableView*)table toolTipForCell:(NSCell*)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn*)tableColumn row:(NSInteger)row mouseLocation:(NSPoint)mouseLocation {
  return nil;
}

-(void) tableView:(NSTableView*)table setObjectValue:(id)object forTableColumn:(NSTableColumn*)tableColumn row:(NSInteger)row {
  if([[tableColumn identifier] isEqualToString:@"check"]) {
    listView->state.checked(row) = [object integerValue] != NSOffState;
    if(listView->onToggle) listView->onToggle(row);
  }
}

-(void) tableView:(NSTableView*)tableView willDisplayCell:(id)cell forTableColumn:(NSTableColumn*)tableColumn row:(NSInteger)row {
  [cell setFont:[self font]];
}

-(void) tableViewSelectionDidChange:(NSNotification*)notification {
  listView->state.selected = true;
  listView->state.selection = [content selectedRow];
  if(listView->onChange) listView->onChange();
}

-(IBAction) activate:(id)sender {
  if(listView->onActivate) listView->onActivate();
}

-(IBAction) doubleAction:(id)sender {
  if([content clickedRow] >= 0) {
    [self activate:self];
  }
}

@end

@implementation CocoaListViewContent : NSTableView

-(void) keyDown:(NSEvent*)event {
  auto character = [[event characters] characterAtIndex:0];
  if(character == NSEnterCharacter || character == NSCarriageReturnCharacter) {
    if([self selectedRow] >= 0) {
      [[self delegate] activate:self];
      return;
    }
  }

  [super keyDown:event];
}

@end

@implementation CocoaListViewCell : NSTextFieldCell

//used by type-ahead
-(NSString*) stringValue {
  return [[self objectValue] objectForKey:@"text"];
}

-(void) drawWithFrame:(NSRect)frame inView:(NSView*)view {
  NSString* text = [[self objectValue] objectForKey:@"text"];
  NSImage* image = [[self objectValue] objectForKey:@"image"];
  unsigned textDisplacement = 0;

  if(image) {
    [[NSGraphicsContext currentContext] saveGraphicsState];

    NSRect targetRect = NSMakeRect(frame.origin.x, frame.origin.y, frame.size.height, frame.size.height);
    NSRect sourceRect = NSMakeRect(0, 0, [image size].width, [image size].height);
    [image drawInRect:targetRect fromRect:sourceRect operation:NSCompositeSourceOver fraction:1.0 respectFlipped:YES hints:nil];

    [[NSGraphicsContext currentContext] restoreGraphicsState];
    textDisplacement = frame.size.height + 2;
  }

  NSRect textRect = NSMakeRect(
    frame.origin.x + textDisplacement, frame.origin.y,
    frame.size.width - textDisplacement, frame.size.height
  );

  NSColor* textColor = [self isHighlighted]
  ? [NSColor alternateSelectedControlTextColor]
  : [NSColor textColor];

  [text drawInRect:textRect withAttributes:@{
    NSForegroundColorAttributeName:textColor,
    NSFontAttributeName:[self font]
  }];
}

@end

namespace phoenix {

void pListView::append(const lstring& text) {
  @autoreleasepool {
    [[cocoaView content] reloadData];
  }
}

void pListView::autoSizeColumns() {
  @autoreleasepool {
    if(listView.state.checkable) {
      NSTableColumn* tableColumn = [[cocoaView content] tableColumnWithIdentifier:@"check"];
      [tableColumn setWidth:20.0];
    }

    unsigned height = [[cocoaView content] rowHeight];
    for(unsigned column = 0; column < max(1u, listView.state.headerText.size()); column++) {
      NSTableColumn* tableColumn = [[cocoaView content] tableColumnWithIdentifier:[[NSNumber numberWithInteger:column] stringValue]];
      unsigned minimumWidth = pFont::size([[tableColumn headerCell] font], listView.state.headerText(column)).width + 4;
      for(unsigned row = 0; row < listView.state.text.size(); row++) {
        unsigned width = pFont::size([cocoaView font], listView.state.text(row)(column)).width + 2;
        if(listView.state.image(row)(height).empty() == false) width += height + 2;
        if(width > minimumWidth) minimumWidth = width;
      }
      [tableColumn setWidth:minimumWidth];
    }

    [[cocoaView content] sizeLastColumnToFit];
  }
}

void pListView::remove(unsigned selection) {
  @autoreleasepool {
    [[cocoaView content] reloadData];
  }
}

void pListView::reset() {
  @autoreleasepool {
    [[cocoaView content] reloadData];
  }
}

void pListView::setCheckable(bool checkable) {
  @autoreleasepool {
    [cocoaView reloadColumns];
  }
}

void pListView::setChecked(unsigned selection, bool checked) {
  @autoreleasepool {
    [[cocoaView content] reloadData];
  }
}

void pListView::setFont(string font) {
  @autoreleasepool {
    [cocoaView setFont:pFont::cocoaFont(font)];
  }
}

void pListView::setHeaderText(const lstring& text) {
  @autoreleasepool {
    [cocoaView reloadColumns];
  }
}

void pListView::setHeaderVisible(bool visible) {
  @autoreleasepool {
    if(visible) {
      [[cocoaView content] setHeaderView:[[[NSTableHeaderView alloc] init] autorelease]];
    } else {
      [[cocoaView content] setHeaderView:nil];
    }
  }
}

void pListView::setImage(unsigned selection, unsigned position, const image& image) {
  @autoreleasepool {
    [[cocoaView content] reloadData];
  }
}

void pListView::setSelected(bool selected) {
  @autoreleasepool {
    if(selected == false) {
      [[cocoaView content] deselectAll:nil];
    }
  }
}

void pListView::setSelection(unsigned selection) {
  @autoreleasepool {
    [[cocoaView content] selectRowIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(selection, 1)] byExtendingSelection:NO];
  }
}

void pListView::setText(unsigned selection, unsigned position, const string text) {
  @autoreleasepool {
    [[cocoaView content] reloadData];
  }
}

void pListView::constructor() {
  @autoreleasepool {
    cocoaView = cocoaListView = [[CocoaListView alloc] initWith:listView];
    setHeaderVisible(listView.state.headerVisible);
    setHeaderText(listView.state.headerText);
  }
}

void pListView::destructor() {
  @autoreleasepool {
    [cocoaView release];
  }
}

}


text:
package com.hazelcast.simulator.test.annotations;

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

/**
 * Annotates {@link com.hazelcast.core.HazelcastInstance} fields.
 *
 * @deprecated use {@link InjectVendor} instead. Will be removed in Simulator 0.11.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface InjectHazelcastInstance {
}


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

import com.google.common.collect.ImmutableMap;
import org.testng.annotations.Test;

import java.util.Map;

import static io.airlift.configuration.testing.ConfigAssertions.assertFullMapping;
import static io.airlift.configuration.testing.ConfigAssertions.assertRecordedDefaults;
import static io.airlift.configuration.testing.ConfigAssertions.recordDefaults;

public class TestEmbeddedDiscoveryConfig
{
    @Test
    public void testDefaults()
    {
        assertRecordedDefaults(recordDefaults(EmbeddedDiscoveryConfig.class)
                .setEnabled(true));
    }

    @Test
    public void testExplicitPropertyMappings()
    {
        Map<String, String> properties = ImmutableMap.<String, String>builder()
                .put("discovery-server.enabled", "false")
                .buildOrThrow();

        EmbeddedDiscoveryConfig expected = new EmbeddedDiscoveryConfig()
                .setEnabled(false);

        assertFullMapping(properties, expected);
    }
}


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

<!-- A global CamelContext configuration which declares camel transformer endpoint -->
<camelContext xmlns="http://camel.apache.org/schema/spring">
  <endpoint id="xml2json" uri="dozer:xml2json?sourceModel=org.switchyard.quickstarts.transform.datamapper.abcorder.ABCOrder&targetModel=org.switchyard.quickstarts.transform.datamapper.xyzorder.XyzOrder&marshalId=transform-json&unmarshalId=abcorder&mappingFile=transformation.xml"/>
  <dataFormats>
    <jaxb contextPath="org.switchyard.quickstarts.transform.datamapper.abcorder" id="abcorder"/>
    <json id="transform-json" library="Jackson"/>
  </dataFormats>
</camelContext>


text:
Hello world!
p>


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

//
// Scenario5_ApplicationTriggerTask.xaml.h
// Declaration of the ApplicationTriggerTask class
//

#pragma once

#include <ppltasks.h>
#include "pch.h"
#include "Scenario5_ApplicationTriggerTask.g.h"
#include "MainPage.xaml.h"

namespace BackgroundTask
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    [Windows::Foundation::Metadata::WebHostHidden]
    public ref class ApplicationTriggerTask sealed
    {
    public:
        ApplicationTriggerTask();

    protected:
        virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
    private:
        SDKTemplate::MainPage^ rootPage;
        ApplicationTrigger^ trigger = nullptr;

        void AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^ task);
        void RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
        void UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
        void SignalBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
        void UpdateUI();
    };
}


text:
A discord bot for navigating user biographies

## Getting Started

* [setup your discord application](https://github.com/SinisterRectus/Discordia/wiki/Setting-up-a-Discord-application)
* [install luvit](https://luvit.io/install.html)
* clone this repo
* cd to this repos's directory
* start the bot with ```luvit bot.lua YOUR_BOT_TOKEN```

## Usage

* Users can interact with the bot from any channel.
* The bot fetches the latest available message from the desired target in the #bio channels the user has access to.
* Deleting and updating messages will preserve this guarantee.

## Screenshots

![screenshot](https://cdn.discordapp.com/attachments/283214314444423168/284469349824331776/unknown.png)

![help](https://cdn.discordapp.com/attachments/283214314444423168/284469603374071838/unknown.png)

![info](https://cdn.discordapp.com/attachments/283214314444423168/285769699621601280/unknown.png)


text:
function asSetAllTitlesToImageString
global asObjs
for i = 1 : length(asObjs)
    asObjs(i).toggleTitleAsImageText;
end


text:
#ifndef __GTK_TRASH_MONITOR_H__
#define __GTK_TRASH_MONITOR_H__

#include <gio/gio.h>

G_BEGIN_DECLS

#define GTK_TYPE_TRASH_MONITOR			(_gtk_trash_monitor_get_type ())
#define GTK_TRASH_MONITOR(obj)			(G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_TRASH_MONITOR, GtkTrashMonitor))
#define GTK_TRASH_MONITOR_CLASS(klass)		(G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_TRASH_MONITOR, GtkTrashMonitorClass))
#define GTK_IS_TRASH_MONITOR(obj)		(G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_TYPE_TRASH_MONITOR))
#define GTK_IS_TRASH_MONITOR_CLASS(klass)	(G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_TRASH_MONITOR))
#define GTK_TRASH_MONITOR_GET_CLASS(obj)	(G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_TRASH_MONITOR, GtkTrashMonitorClass))

typedef struct _GtkTrashMonitor GtkTrashMonitor;
typedef struct _GtkTrashMonitorClass GtkTrashMonitorClass;

GType _gtk_trash_monitor_get_type (void);
GtkTrashMonitor *_gtk_trash_monitor_get (void);

GIcon *_gtk_trash_monitor_get_icon (GtkTrashMonitor *monitor);

gboolean _gtk_trash_monitor_get_has_trash (GtkTrashMonitor *monitor);

G_END_DECLS

#endif /* __GTK_TRASH_MONITOR_H__ */


text:
id: data_docs
title: Data Docs
---
import UniversalMap from '/docs/images/universal_map/_universal_map.mdx';
import TechnicalTag from '../term_tags/_tag.mdx';
import SetupHeader from '/docs/images/universal_map/_um_setup_header.mdx'
import CreateHeader from '/docs/images/universal_map/_um_create_header.mdx';
import ValidateHeader from '/docs/images/universal_map/_um_validate_header.mdx';

<UniversalMap setup='active' connect='inactive' create='active' validate='active'/>

## Overview

### Definition

Data Docs are human readable documentation generated from Great Expectations metadata detailing <TechnicalTag relative="../" tag="expectation" text="Expectations" />, <TechnicalTag relative="../" tag="validation_result" text="Validation Results" />, etc.

### Features and promises

Data Docs translate Expectations, Validation Results, and other metadata into clean, human-readable documentation. Automatically compiling your data documentation from your data tests in the form of Data Docs guarantees that your documentation will never go stale.

### Relationship to other objects

Data Docs can be used to view <TechnicalTag relative="../" tag="expectation_suite" text="Expectation Suites" /> and Validation Results.  With a customized <TechnicalTag relative="../" tag="renderer" text="Renderer" />, you can extend what they display and how.  You can issue a command to update your Data Docs from your <TechnicalTag relative="../" tag="data_context" text="Data Context" />.  Alternatively, you can include the `UpdateDataDocsAction` <TechnicalTag relative="../" tag="action" text="Action" /> in a <TechnicalTag relative="../" tag="checkpoint" text="Checkpoint's" /> `action_list` to trigger an update of your Data Docs with the Validation Results that were generated by that Checkpoint being run.

## Use cases

<SetupHeader/>

You can configure multiple Data Docs sites while setting up your Great Expectations project.  This allows you to tailor the information that is displayed by Data Docs as well as how they are hosted.  For more information on setting up your Data Docs, please reference our [guides on how to configure them for specific hosting environments](../guides/setup/index.md#data-docs).

<CreateHeader/>

You can view your saved Expectation Suites in Data Docs.

<ValidateHeader/>

Saved Validation Results will be displayed in any Data Docs site that is configured to show them.  If you build your Data Docs from the Data Context, the process will render Data Docs for all of your Validation Results.  Alternatively, you can use the `UpdateDataDocsAction` Action in a Checkpoint's `action_list` to update your Data Docs with just the Validation Results generated by that checkpoint.

## Features

### Readability

Data Docs provide a clean, human-readable way to view your Expectation Suites and Validation Results without you having to manually parse their stored values and configurations.  You can also [add comments to your Expectations that will be displayed in your Data Docs](../guides/expectations/advanced/how_to_add_comments_to_expectations_and_display_them_in_data_docs.md), if you feel they need further explanation.

### Versatility

There are multiple use cases for displaying information in your Data Docs.  Three common ones are:

1. Visualize all Great Expectations artifacts from the local repository of a project as HTML: Expectation Suites,
   Validation Results and profiling results.
1. Maintain a "shared source of truth" for a team working on a data project. Such documentation renders all the
   artifacts committed in the source control system (Expectation Suites and profiling results) and a continuously
   updating data quality report, built from a chronological list of validations by run id.
1. Share a spec of a dataset with a client or a partner. This is similar to API documentation in software development.
   This documentation would include profiling results of the dataset to give the reader a quick way to grasp what the
   data looks like, and one or more Expectation Suites that encode what is expected from the data to be considered
   valid.

To support these (and possibly other) use cases Great Expectations has a concept of a "data documentation site". Multiple sites can be configured inside a project, each suitable for a particular data documentation use case.

## API basics

### How to access

Data Docs are rendered as HTML files.  As such, you can open them with any browser.

### How to create

If your Data Docs have not yet been rendered, you can create them from your Data Context.

From the root folder of your project (where you initialized your Data Context), you can build your Data Docs with the CLI command:

```bash title="Terminal command"
great_expectations docs build
```

Alternatively, you can use your Data Context to build your Data Docs in python with the command:
```python title="Python code"
import great_expectations as ge
context = ge.get_context()
context.build_data_docs()
```

### Configuration

Data Docs sites are configured under the `data_docs_sites` key in your deployment's `great_expectations.yml` file. Users can specify:

- which <TechnicalTag relative="../" tag="datasource" text="Datasources" /> to document (by default, all)
- whether to include Expectations, validations and profiling results sections
- where the Expectations and validations should be read from (filesystem, S3, Azure, or GCS)
- where the HTML files should be written (filesystem, S3, Azure, or GCS)
- which <TechnicalTag relative="../" tag="renderer" text="Renderer" /> and view class should be used to render each section

For more information, please see our guides for [how to host and share Data Docs in specific environments](../guides/setup/index.md#data-docs).


text:
<FrameLayout
    android:id="@+id/container"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="hotchemi.instapets.activity.ShowPhotoActivity"
    tools:ignore="MergeRootFrame"/>


text:
package org.kie.workbench.common.dmn.client.editors.expressions.types.dtable;

import java.util.Optional;
import java.util.function.Supplier;

import org.kie.workbench.common.dmn.api.definition.model.DecisionRule;
import org.kie.workbench.common.dmn.api.definition.model.DecisionTable;
import org.kie.workbench.common.dmn.client.editors.expressions.types.dtable.DecisionTableUIModelMapperHelper.DecisionTableSection;
import org.kie.workbench.common.dmn.client.widgets.grid.controls.list.ListSelectorView;
import org.kie.workbench.common.dmn.client.widgets.grid.model.BaseUIModelMapper;
import org.uberfire.ext.wires.core.grids.client.model.GridCellValue;
import org.uberfire.ext.wires.core.grids.client.model.GridData;
import org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridCellValue;
import org.uberfire.ext.wires.core.grids.client.widget.grid.selections.impl.RowSelectionStrategy;

public class DecisionTableUIModelMapper extends BaseUIModelMapper<DecisionTable> {

    private final ListSelectorView.Presenter listSelector;
    private final double lineHeight;

    public DecisionTableUIModelMapper(final Supplier<GridData> uiModel,
                                      final Supplier<Optional<DecisionTable>> dmnModel,
                                      final ListSelectorView.Presenter listSelector,
                                      final double lineHeight) {
        super(uiModel,
              dmnModel);
        this.listSelector = listSelector;
        this.lineHeight = lineHeight;
    }

    @Override
    public void fromDMNModel(final int rowIndex,
                             final int columnIndex) {
        dmnModel.get().ifPresent(dtable -> {
            final DecisionRule rule = dtable.getRule().get(rowIndex);
            final DecisionTableSection section = DecisionTableUIModelMapperHelper.getSection(dtable, columnIndex);
            switch (section) {
                case ROW_INDEX:
                    uiModel.get().setCell(rowIndex,
                                          columnIndex,
                                          () -> new DecisionTableGridCell<>(new BaseGridCellValue<>(rowIndex + 1),
                                                                            listSelector,
                                                                            lineHeight));
                    uiModel.get().getCell(rowIndex,
                                          columnIndex).setSelectionStrategy(RowSelectionStrategy.INSTANCE);
                    break;
                case INPUT_CLAUSES:
                    final int iei = DecisionTableUIModelMapperHelper.getInputEntryIndex(dtable, columnIndex);
                    uiModel.get().setCell(rowIndex,
                                          columnIndex,
                                          () -> new DecisionTableGridCell<>(new BaseGridCellValue<>(rule.getInputEntry().get(iei).getText().getValue()),
                                                                            listSelector,
                                                                            lineHeight));
                    break;
                case OUTPUT_CLAUSES:
                    final int oei = DecisionTableUIModelMapperHelper.getOutputEntryIndex(dtable, columnIndex);
                    uiModel.get().setCell(rowIndex,
                                          columnIndex,
                                          () -> new DecisionTableGridCell<>(new BaseGridCellValue<>(rule.getOutputEntry().get(oei).getText().getValue()),
                                                                            listSelector,
                                                                            lineHeight));
                    break;
                case ANNOTATION_CLAUSES:
                    final int annotationIndex = DecisionTableUIModelMapperHelper.getAnnotationEntryIndex(dtable, columnIndex);
                    final String textValue = rule.getAnnotationEntry().get(annotationIndex).getText().getValue();
                    uiModel.get().setCell(rowIndex,
                                          columnIndex,
                                          () -> new DecisionTableGridCell<>(new BaseGridCellValue<>(textValue),
                                                                            listSelector,
                                                                            lineHeight));

                    break;
            }
        });
    }

    @Override
    public void toDMNModel(final int rowIndex,
                           final int columnIndex,
                           final Supplier<Optional<GridCellValue<?>>> cell) {
        dmnModel.get().ifPresent(dtable -> {
            final DecisionRule rule = dtable.getRule().get(rowIndex);
            final DecisionTableSection section = DecisionTableUIModelMapperHelper.getSection(dtable, columnIndex);
            switch (section) {
                case ROW_INDEX:
                    break;
                case INPUT_CLAUSES:
                    final int iei = DecisionTableUIModelMapperHelper.getInputEntryIndex(dtable, columnIndex);
                    rule.getInputEntry().get(iei).getText().setValue(cell.get().orElse(new BaseGridCellValue<>("")).getValue().toString());
                    break;
                case OUTPUT_CLAUSES:
                    final int oei = DecisionTableUIModelMapperHelper.getOutputEntryIndex(dtable, columnIndex);
                    rule.getOutputEntry().get(oei).getText().setValue(cell.get().orElse(new BaseGridCellValue<>("")).getValue().toString());
                    break;
                case ANNOTATION_CLAUSES:
                    final int annotationIndex = DecisionTableUIModelMapperHelper.getAnnotationEntryIndex(dtable, columnIndex);
                    rule.getAnnotationEntry().get(annotationIndex).getText().setValue(cell.get().orElse(new BaseGridCellValue<>("")).getValue().toString());
                    break;
            }
        });
    }
}


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

import com.google.common.collect.ImmutableList;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static java.util.Locale.ENGLISH;
import static java.util.Objects.requireNonNull;

public final class Cast
        extends Expression
{
    private final Expression expression;
    private final String type;
    private final boolean safe;
    private final boolean typeOnly;

    public Cast(Expression expression, String type)
    {
        this(Optional.empty(), expression, type, false, false);
    }

    public Cast(Expression expression, String type, boolean safe)
    {
        this(Optional.empty(), expression, type, safe, false);
    }

    public Cast(Expression expression, String type, boolean safe, boolean typeOnly)
    {
        this(Optional.empty(), expression, type, safe, typeOnly);
    }

    public Cast(NodeLocation location, Expression expression, String type)
    {
        this(Optional.of(location), expression, type, false, false);
    }

    public Cast(NodeLocation location, Expression expression, String type, boolean safe)
    {
        this(Optional.of(location), expression, type, safe, false);
    }

    public Cast(NodeLocation location, Expression expression, String type, boolean safe, boolean typeOnly)
    {
        this(Optional.of(location), expression, type, safe, typeOnly);
    }

    public Cast(Optional<NodeLocation> location, Expression expression, String type, boolean safe, boolean typeOnly)
    {
        super(location);
        requireNonNull(expression, "expression is null");
        requireNonNull(type, "type is null");

        this.expression = expression;
        this.type = type.toLowerCase(ENGLISH);
        this.safe = safe;
        this.typeOnly = typeOnly;
    }

    public Expression getExpression()
    {
        return expression;
    }

    public String getType()
    {
        return type;
    }

    public boolean isSafe()
    {
        return safe;
    }

    public boolean isTypeOnly()
    {
        return typeOnly;
    }

    @Override
    public <R, C> R accept(AstVisitor<R, C> visitor, C context)
    {
        return visitor.visitCast(this, context);
    }

    @Override
    public List<Node> getChildren()
    {
        return ImmutableList.of(expression);
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        Cast o = (Cast) obj;
        return Objects.equals(this.expression, o.expression) &&
                Objects.equals(this.type, o.type) &&
                Objects.equals(this.safe, o.safe) &&
                Objects.equals(this.typeOnly, o.typeOnly);
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(expression, type, safe, typeOnly);
    }
}


text:
using System;

namespace Lucene.Net.Search.Payloads
{

	/// <summary> Calculate the final score as the average score of all payloads seen.
	/// <p/>
	/// Is thread safe and completely reusable.
	///
	///
	/// </summary>
	//[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300
	public class AveragePayloadFunction:PayloadFunction
	{

		public override float CurrentScore(int docId, System.String field, int start, int end, int numPayloadsSeen, float currentScore, float currentPayloadScore)
		{
			return currentPayloadScore + currentScore;
		}

		public override float DocScore(int docId, System.String field, int numPayloadsSeen, float payloadScore)
		{
			return numPayloadsSeen > 0?(payloadScore / numPayloadsSeen):1;
		}

		public override int GetHashCode()
		{
			int prime = 31;
			int result = 1;
			result = prime * result + this.GetType().GetHashCode();
			return result;
		}

		public  override bool Equals(System.Object obj)
		{
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (GetType() != obj.GetType())
				return false;
			return true;
		}
	}
}


text:
using System;
using System.Reflection;
using Studiotaiha.Toolkit.Composition;

namespace Studiotaiha.Toolkit.Settings
{
	public class SettingsComponent : IComponent
	{
		public static Guid ComponentId { get; } = new Guid("08A8CBB0-CBCE-4FEE-9F6D-439E9B3AB1B6");

		#region Singleton

		static SettingsComponent instance_;
		public static SettingsComponent Instance => instance_ = (instance_ = new SettingsComponent());

		#endregion // Singleton

		public Type[] CriticalExceptionTypes { get; } = new Type[] { };

		public Assembly Assembly => GetType().GetTypeInfo().Assembly;
		public Guid Id => ComponentId;
	}
}


text:
Meteor.startup(()=>{
	Spectra._ensureIndex({uid:1}, {background:true});
	SOM._ensureIndex({uid: 1, created_at:1}, {background: true});
});


text:
#import "NSObject.h"

@class DAMessageMoveRequest, NSString;

@interface DAMoveResponse : NSObject
{
    int _status;
    NSString *_sourceID;
    NSString *_destID;
    DAMessageMoveRequest *_origRequest;
}

@property(retain) DAMessageMoveRequest *origRequest; // @synthesize origRequest=_origRequest;
@property(readonly) NSString *destID; // @synthesize destID=_destID;
@property(readonly) NSString *sourceID; // @synthesize sourceID=_sourceID;
@property(readonly) int status; // @synthesize status=_status;
- (void)dealloc;
- (id)description;
- (id)initWithStatus:(int)arg1 sourceID:(id)arg2 destID:(id)arg3;

@end


text:
package org.apereo.portal.jpa;

import org.apereo.portal.version.dao.VersionDao;

/**
 * Runs steps needed to init/upgrade/update the database based on the version information retrieved
 * from {@link VersionDao}
 *
 * @author Eric Dalquist
 */
public interface VersionedDataUpdater {

    /** Run post-initialize steps for the versioned product */
    void postInitDatabase(String product);

    /** Run the pre-update steps for the versioned product */
    void preUpdateDatabase(String product);

    /** Run the post-update steps for the versioned product */
    void postUpdateDatabase(String product);
}


text:
package spread;

/**
 * A MessageFactory object is used to create any number of messages based on a default message.
 * The default message is first specified in the constructor:
 *

 * messageFactory = new MessageFactory(message);
 *

 * The default message can later be changed using {@link MessageFactory#setDefault(SpreadMessage)}:
 *

 * messageFactory.setDefault(message);
 *

 * To get a message from the factory, use {@link MessageFactory#createMessage()}:
 *

 * SpreadMessage message = messageFactory.createMessage();
 *

 * Classes that extend MessageFactory can override {@link MessageFactory#createMessage()}
 * to provide behaviors other than simply cloning the default message.  One example is a factory that
 * sets a time-stamp in the message:
 *

 * public class TimeStampMessageFactory extends MessageFactory
 * {
 *     public SpreadMessage createMessage()
 *     {
 *         SpreadMessage message = super.createMessage();
 *         message.setObject(new Long(System.currentTimeMillis()));
 *         return message;
 *     }
 * }
 *

 */
public class MessageFactory
{
	// The default message.
	///////////////////////
	protected SpreadMessage defaultMessage;

	// Creates a new message factory with the default message.
	////////////////////////////////////////////////////////////////
	/**
	 * Constructs a new MessageFactory and sets the default message.
	 *
	 * @param  message  the default message
	 */
	public MessageFactory(SpreadMessage message)
	{
		setDefault(message);
	}

	// Sets the default message to message.
	///////////////////////////////////////
	/**
	 * Sets a new default message for this factory.
	 *
	 * @param  message  the new default message
	 */
	public void setDefault(SpreadMessage message)
	{
		// Check for null.
		//////////////////
		if(message == null)
		{
			defaultMessage = null;
		}
		else
		{
			defaultMessage = (SpreadMessage)message.clone();
		}
	}

	// Returns a new Message provided by the object implementing the class.
	///////////////////////////////////////////////////////////////////////
	/**
	 * Returns a new message.  The message is a clone of the default message.
	 * If the default message has been specified as null, null is returned.
	 *
	 * @return  a new message
	 */
	public SpreadMessage createMessage()
	{
		// Check for null.
		//////////////////
		if(defaultMessage == null)
		{
			return null;
		}

		return (SpreadMessage)defaultMessage.clone();
	}
}


text:
Arrow Matchers
==========

This page lists all current matchers in the KotlinTest arrow matchers extension library. To use this library
 you need to add `kotlintest-assertions-arrow` to your build.

| Option | |
| -------- | ---- |
| `option.shouldBeSome(v)` | Asserts that the option is of type Some with value v |
| `option.shouldBeNone()` | Asserts that the option is of type None |

| Either | |
| -------- | ---- |
| `either.shouldBeRight()` | Asserts that the either is of type Right |
| `either.shouldBeRight(v)` | Asserts that the either is of type Right with specified value v |
| `either.shouldBeLeft()` | Asserts that the either is of type Left |
| `either.shouldBeLeft(v)` | Asserts that the either is of type Left with specific value v |
| `either.shouldBeLeftOfType<A>()` | Asserts that the either is of type Left with a specified type A |

| NonEmptyList | |
| -------- | ---- |
| `nel.shouldContain(e)` | Asserts that the NonEmptyList contains the given element e |
| `nel.shouldContainAll(e1,e2,...,en)` | Asserts that the NonEmptyList contains all the given elements e1,e2,...,en |
| `nel.shouldContainNull()` | Asserts that the NonEmptyList contains at least one null |
| `nel.shouldContainNoNulls()` | Asserts that the NonEmptyList contains no nulls |
| `nel.shouldContainOnlyNulls()` | Asserts that the NonEmptyList contains only nulls or is empty |
| `nel.shouldHaveDuplicates()` | Asserts that the NonEmptyList has at least one duplicate |
| `nel.shouldBeSingleElement(e)` | Asserts that the NonEmptyList has a single element which is e |
| `nel.shouldBeSorted()` | Asserts that the NonEmptyList is sorted |

| Validated | |
| -------- | ---- |
| `validated.shouldBeValid()` | Asserts that the validated is of type Valid |
| `validated.shouldBeValid(v)` | Asserts that the validated is of type Valid with specific value v |
| `validated.shouldBeInvalid()` | Asserts that the validated is of type Invalid |


text:
package org.jsondoc.springmvc.scanner.builder;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Set;
import java.util.TreeSet;

import org.jsondoc.core.pojo.ApiObjectDoc;
import org.jsondoc.core.pojo.ApiObjectFieldDoc;
import org.jsondoc.core.scanner.DefaultJSONDocScanner;
import org.jsondoc.core.util.JSONDocHibernateValidatorProcessor;
import org.jsondoc.core.util.JSONDocType;
import org.jsondoc.core.util.JSONDocTypeBuilder;

public class SpringObjectBuilder {

	public static ApiObjectDoc buildObject(Class<?> clazz) {
		ApiObjectDoc apiObjectDoc = new ApiObjectDoc();
		apiObjectDoc.setName(clazz.getSimpleName());

		Set<ApiObjectFieldDoc> fieldDocs = new TreeSet<ApiObjectFieldDoc>();

		for (Field field : clazz.getDeclaredFields()) {
			ApiObjectFieldDoc fieldDoc = new ApiObjectFieldDoc();
			fieldDoc.setName(field.getName());
			fieldDoc.setOrder(Integer.MAX_VALUE);
			fieldDoc.setRequired(DefaultJSONDocScanner.UNDEFINED.toUpperCase());
			fieldDoc.setJsondocType(JSONDocTypeBuilder.build(new JSONDocType(), field.getType(), field.getGenericType()));

			JSONDocHibernateValidatorProcessor.processHibernateValidatorAnnotations(field, fieldDoc);

			fieldDocs.add(fieldDoc);
		}

		Class<?> superclass = clazz.getSuperclass();
		if (superclass != null) {
			ApiObjectDoc parentObjectDoc = buildObject(superclass);
			fieldDocs.addAll(parentObjectDoc.getFields());
		}

		if (clazz.isEnum()) {
			apiObjectDoc.setAllowedvalues(DefaultJSONDocScanner.enumConstantsToStringArray(clazz.getEnumConstants()));
		}

		apiObjectDoc.setFields(fieldDocs);
		if(Modifier.isAbstract(clazz.getModifiers())) {
			apiObjectDoc.setShow(false);
		}

		return apiObjectDoc;
	}

}


text:
Genoverse.Track.View.Gene.Ensembl = Genoverse.Track.View.Gene.extend({
  setFeatureColor: function (feature) {
    var processed_transcript = {
      'sense_intronic'           : 1,
      'sense_overlapping'        : 1,
      'processed_transcript'     : 1,
      'nonsense_mediated_decay'  : 1,
      'non_stop_decay'           : 1,
      'antisense'                : 1,
      'retained_intron'          : 1,
      'tec'                      : 1,
      'non_coding'               : 1,
      'ambiguous_orf'            : 1,
      'disrupted_domain'         : 1,
      '3prime_overlapping_ncrna' : 1
    };

    feature.color = '#000000';

    if (feature.logic_name.indexOf('ensembl_havana') === 0) {
      feature.color  = '#CD9B1D';
      feature.legend = 'Merged Ensembl/Havana';
    } else if (processed_transcript[feature.biotype]) {
      feature.color  = '#0000FF';
      feature.legend = 'Processed transcript';
    } else if (feature.biotype === 'protein_coding') {
      feature.color  = '#A00000';
      feature.legend = 'Protein coding';
    } else if (feature.biotype.indexOf('pseudogene') > -1) {
      feature.color  = '#666666';
      feature.legend = 'Pseudogene';
    } else if (/rna/i.test(feature.biotype)) {
      feature.color  = '#8B668B';
      feature.legend = 'RNA gene';
    } else if (/^tr_.+_gene$/i.test(feature.biotype)) {
      feature.color  = '#CD6600';
      feature.legend = 'TR gene';
    } else if (/^ig_.+_gene$/i.test(feature.biotype)) {
      feature.color  = '#8B4500';
      feature.legend = 'IG gene';
    }

    feature.labelColor = feature.color;
  }
});


text:
@interface FLTGoogleMapCircleController ()

@property(nonatomic, strong) GMSCircle *circle;
@property(nonatomic, weak) GMSMapView *mapView;

@end

@implementation FLTGoogleMapCircleController

- (instancetype)initCircleWithPosition:(CLLocationCoordinate2D)position
                                radius:(CLLocationDistance)radius
                              circleId:(NSString *)circleIdentifier
                               mapView:(GMSMapView *)mapView
                               options:(NSDictionary *)options {
  self = [super init];
  if (self) {
    _circle = [GMSCircle circleWithPosition:position radius:radius];
    _mapView = mapView;
    _circle.userData = @[ circleIdentifier ];
    [self interpretCircleOptions:options];
  }
  return self;
}

- (void)removeCircle {
  self.circle.map = nil;
}

- (void)setConsumeTapEvents:(BOOL)consumes {
  self.circle.tappable = consumes;
}
- (void)setVisible:(BOOL)visible {
  self.circle.map = visible ? self.mapView : nil;
}
- (void)setZIndex:(int)zIndex {
  self.circle.zIndex = zIndex;
}
- (void)setCenter:(CLLocationCoordinate2D)center {
  self.circle.position = center;
}
- (void)setRadius:(CLLocationDistance)radius {
  self.circle.radius = radius;
}

- (void)setStrokeColor:(UIColor *)color {
  self.circle.strokeColor = color;
}
- (void)setStrokeWidth:(CGFloat)width {
  self.circle.strokeWidth = width;
}
- (void)setFillColor:(UIColor *)color {
  self.circle.fillColor = color;
}

- (void)interpretCircleOptions:(NSDictionary *)data {
  NSNumber *consumeTapEvents = data[@"consumeTapEvents"];
  if (consumeTapEvents && consumeTapEvents != (id)[NSNull null]) {
    [self setConsumeTapEvents:consumeTapEvents.boolValue];
  }

  NSNumber *visible = data[@"visible"];
  if (visible && visible != (id)[NSNull null]) {
    [self setVisible:[visible boolValue]];
  }

  NSNumber *zIndex = data[@"zIndex"];
  if (zIndex && zIndex != (id)[NSNull null]) {
    [self setZIndex:[zIndex intValue]];
  }

  NSArray *center = data[@"center"];
  if (center && center != (id)[NSNull null]) {
    [self setCenter:[FLTGoogleMapJSONConversions locationFromLatLong:center]];
  }

  NSNumber *radius = data[@"radius"];
  if (radius && radius != (id)[NSNull null]) {
    [self setRadius:[radius floatValue]];
  }

  NSNumber *strokeColor = data[@"strokeColor"];
  if (strokeColor && strokeColor != (id)[NSNull null]) {
    [self setStrokeColor:[FLTGoogleMapJSONConversions colorFromRGBA:strokeColor]];
  }

  NSNumber *strokeWidth = data[@"strokeWidth"];
  if (strokeWidth && strokeWidth != (id)[NSNull null]) {
    [self setStrokeWidth:[strokeWidth intValue]];
  }

  NSNumber *fillColor = data[@"fillColor"];
  if (fillColor && fillColor != (id)[NSNull null]) {
    [self setFillColor:[FLTGoogleMapJSONConversions colorFromRGBA:fillColor]];
  }
}

@end

@interface FLTCirclesController ()

@property(strong, nonatomic) FlutterMethodChannel *methodChannel;
@property(weak, nonatomic) GMSMapView *mapView;
@property(strong, nonatomic) NSMutableDictionary *circleIdToController;

@end

@implementation FLTCirclesController

- (instancetype)init:(FlutterMethodChannel *)methodChannel
             mapView:(GMSMapView *)mapView
           registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
  self = [super init];
  if (self) {
    _methodChannel = methodChannel;
    _mapView = mapView;
    _circleIdToController = [NSMutableDictionary dictionaryWithCapacity:1];
  }
  return self;
}

- (void)addCircles:(NSArray *)circlesToAdd {
  for (NSDictionary *circle in circlesToAdd) {
    CLLocationCoordinate2D position = [FLTCirclesController getPosition:circle];
    CLLocationDistance radius = [FLTCirclesController getRadius:circle];
    NSString *circleId = [FLTCirclesController getCircleId:circle];
    FLTGoogleMapCircleController *controller =
        [[FLTGoogleMapCircleController alloc] initCircleWithPosition:position
                                                              radius:radius
                                                            circleId:circleId
                                                             mapView:self.mapView
                                                             options:circle];
    self.circleIdToController[circleId] = controller;
  }
}

- (void)changeCircles:(NSArray *)circlesToChange {
  for (NSDictionary *circle in circlesToChange) {
    NSString *circleId = [FLTCirclesController getCircleId:circle];
    FLTGoogleMapCircleController *controller = self.circleIdToController[circleId];
    if (!controller) {
      continue;
    }
    [controller interpretCircleOptions:circle];
  }
}

- (void)removeCircleWithIdentifiers:(NSArray *)identifiers {
  for (NSString *identifier in identifiers) {
    FLTGoogleMapCircleController *controller = self.circleIdToController[identifier];
    if (!controller) {
      continue;
    }
    [controller removeCircle];
    [self.circleIdToController removeObjectForKey:identifier];
  }
}

- (bool)hasCircleWithIdentifier:(NSString *)identifier {
  if (!identifier) {
    return false;
  }
  return self.circleIdToController[identifier] != nil;
}

- (void)didTapCircleWithIdentifier:(NSString *)identifier {
  if (!identifier) {
    return;
  }
  FLTGoogleMapCircleController *controller = self.circleIdToController[identifier];
  if (!controller) {
    return;
  }
  [self.methodChannel invokeMethod:@"circle#onTap" arguments:@{@"circleId" : identifier}];
}

+ (CLLocationCoordinate2D)getPosition:(NSDictionary *)circle {
  NSArray *center = circle[@"center"];
  return [FLTGoogleMapJSONConversions locationFromLatLong:center];
}

+ (CLLocationDistance)getRadius:(NSDictionary *)circle {
  NSNumber *radius = circle[@"radius"];
  return [radius floatValue];
}

+ (NSString *)getCircleId:(NSDictionary *)circle {
  return circle[@"circleId"];
}

@end


text:
FROM ubuntu:latest

MAINTAINER Eelke van den Bos "eelkevdbos@gmail.com"

RUN apt-get update -y
RUN apt-get install -y python-pip python-dev build-essential
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
ENTRYPOINT ["python"]
CMD ["hello.py"]


text:
package org.mashti.jetson.exception;

public class InvalidResponseException extends ParseException {

    private static final long serialVersionUID = 5797975215122969810L;

    public InvalidResponseException() {

        super();
    }

    public InvalidResponseException(final Throwable cause) {

        super(cause);
    }

    public InvalidResponseException(final String message) {

        super(message);
    }

    public InvalidResponseException(final String message, final Throwable cause) {

        super(message, cause);
    }

    public static InvalidResponseException fromMessage(final Object... messages) {

        return new InvalidResponseException(toString(messages));
    }
}


text:
package eu.lunisolar.magma.func.supp;

import javax.annotation.Nonnull; // NOSONAR
import javax.annotation.Nullable; // NOSONAR
import java.lang.reflect.*; // NOSONAR
import java.util.*; // NOSONAR
import java.util.Objects; // NOSONAR
import eu.lunisolar.magma.basics.*; // NOSONAR
import eu.lunisolar.magma.basics.builder.*; // NOSONAR
import eu.lunisolar.magma.basics.exceptions.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR
import eu.lunisolar.magma.func.*; // NOSONAR
import eu.lunisolar.magma.func.supp.opt.*; // NOSONAR
import eu.lunisolar.magma.func.supp.value.*; // NOSONAR
import eu.lunisolar.magma.func.tuple.*; // NOSONAR
import eu.lunisolar.magma.basics.fluent.*; //NOSONAR

import eu.lunisolar.magma.func.action.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR
import eu.lunisolar.magma.func.function.*; // NOSONAR
import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR
import eu.lunisolar.magma.func.function.from.*; // NOSONAR
import eu.lunisolar.magma.func.function.to.*; // NOSONAR
import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR
import eu.lunisolar.magma.func.predicate.*; // NOSONAR
import eu.lunisolar.magma.func.supplier.*; // NOSONAR

/**
* @see {@link Is}{@link Are}{@link Do}{@link Does}{@link Be}{@link Has}{@link Have}{@link As}{@link P}
*/
@MethodReferences
public final class Have extends Predicates {

}


text:
import React from "react"
import qs from "qs"
import { Banner, Sans } from "@artsy/palette"

/** Flash messages triggered by a url `flash_message` query param
 * A message can be a string or a React Component that takes no props
 * (that is, use relay or context if necessary)
 */
const messageByQueryParam: { [k: string]: string | React.FC } = {
  confirmed: "Your email has been confirmed.",
  already_confirmed: "You have already confirmed your email.",
  invalid_token: "An error has occurred. Please contact support@artsy.net.",
  blank_token: "An error has occurred. Please contact support@artsy.net.",
  expired_token: "Link expired. Resend verification email.",
}

/**
 * The component responsible for selecting a flash message key from the `flash_message` url query param
 */
export const FlashBanner: React.FunctionComponent<{
  messageCode?: string
}> = props => {
  const [messageCode, setMessageCode] = React.useState(props.messageCode)

  React.useEffect(() => {
    if (!messageCode) {
      const query = qs.parse(window.location.search.slice(1))
      if (query["flash_message"]) setMessageCode(query["flash_message"])
    }
  }, [])

  if (!messageCode) return null
  const Message = messageByQueryParam[messageCode]
  if (!Message) return null

  return (
    <Banner dismissable backgroundColor="black100">
      <Sans color="white100" size="3" lineHeight={1} weight="medium">
        {typeof Message === "string" ? Message : <Message />}
      </Sans>
    </Banner>
  )
}