text:
#ifndef NODE_H
#define NODE_H

#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include "Vec2.h"
#include "WindowWrapper.h"

class Node{
public:
    /**Constructor */
    Node();
    Node(Node *that);
    virtual ~Node();

    /**Node Status */
    int getId();
    void show(bool p_show);
    bool show();

    /**Arrangement */
    // position
    virtual void setPosition(Vec2<double> p_position);
    virtual void setVeclocity(Vec2<double> p_velocity);
    virtual void moveBy(Vec2<double> p_movement);
    Vec2<double> getPosition();
    Vec2<double> getVelocity();

    // anchor
    void setAnchor(Vec2<double> p_anchor);
    Vec2<double> getAnchor();

    // size
    void setSize(Vec2<double> p_size);
    Vec2<double> getSize();

    /**Texture */
    void setTexture(SDL_Texture* p_texture);
    SDL_Texture* getTexture();
    SDL_Rect* getTextureSrc();
    SDL_Rect* getTextureDst();

    /** Render Target */
    WindowWrapper* getRenderTarget();

protected:
    // Static Varaibles
    static int s_current_id;

    // Node Status
    int  m_id;
    bool m_show;

    // Arrangement
    Vec2<double> m_position;
    Vec2<double> m_velocity;
    Vec2<double> m_anchor;
    Vec2<double> m_size;

    // Texture
    SDL_Texture* m_texture;
    SDL_Rect* m_texture_src;
    SDL_Rect* m_texture_dst;

    // Render Target
    WindowWrapper* m_render_target;
};

#endif /* NODE_H */


text:
<?php
/**
 * This file has been @generated by a phing task by {@link GeneratePhonePrefixData}.
 * See [README.md](README.md#generating-data) for more information.
 *
 * Pull requests changing data in these files will not be accepted. See the
 * [FAQ in the README](README.md#problems-with-invalid-numbers] on how to make
 * metadata changes.
 *
 * Do not modify this file directly!
 */

return array (
  37525 => 'БеСТ',
  375292 => 'МТС',
  375294 => 'БелСел',
  375295 => 'МТС',
  375297 => 'МТС',
  375298 => 'МТС',
  37533 => 'МТС',
);

redpajama_set_name: RedPajamaGithub


text:
package main

const (
	errorKey    = "error"
	catenaKey   = "catena"
	responseKey = "response"
)


text:
describe('factory: treemendousParser', function() {
  var scope;
  var treemendousParser;

  beforeEach(module('treemendous'));

  beforeEach(inject(function(_$rootScope_, _treemendousParser_) {
    scope = _$rootScope_.$new();
    treemendousParser = _treemendousParser_;

    scope.nodes = [
      {title: 'A', type: 'type1', children: [
        {title: 'Aa', type: 'type2', children: [{title: 'Aaa'}]},
        {title: 'Ab', type: 'type2'}
      ]},
      {title: 'B', type: 'type1', children: [
        {title: 'Ba', type: 'type2', children: [{title: 'Baa'}]},
        {title: 'Bb', type: 'type3'}
      ]}
    ];
  }));

  describe('_nodes_', function() {
    var result;
    var groupBy;

    beforeEach(function() {
      result = treemendousParser.parse(
        'nodes | filter:$filter | orderBy:"title":true'
      );
      groupBy = result.groupBy;
    });

    it('should filter and sort _nodes_', function() {
      var nodes = result.nodes(scope, {$filter: {title: 'a'}});
      expect(nodes).to.have.length(1);
      expect(nodes[0].title).to.equal('A');

      nodes = result.nodes(scope, {$filter: {}});
      expect(nodes).to.have.length(2);
      expect(nodes[0].title).to.equal('B');
    });

    it('should set "groupBy" to false', function() {
      expect(result.groupBy).to.equal(false);
    });

    it('should set "children" to "children"', function() {
      expect(result.children).to.equal('children');
    });
  });

  describe('_nodes_ group by _property_', function() {
    var result;
    var groupBy;

    beforeEach(function() {
      result = treemendousParser.parse(
        'nodes | filter:$filter | orderBy:"title":true group by type'
      );
      groupBy = result.groupBy;
    });

    it('should match the "group by _property_" clause', function() {
      expect(groupBy).to.equal('type');
    });

    it('should filter and sort _nodes_', function() {
      var nodes = result.nodes(scope, {$filter: {title: 'a'}});
      expect(nodes).to.have.length(1);
      expect(nodes[0].title).to.equal('A');

      nodes = result.nodes(scope, {$filter: {}});
      expect(nodes).to.have.length(2);
      expect(nodes[0].title).to.equal('B');
    });
  });

  describe('_nodes_ group by _property_ as _children', function() {

    it ('should match the "as _children_" clause', function() {
      var result = treemendousParser.parse(
        'nodes | filter:$filter | orderBy:"title":true group by type as foo'
      );

      expect(result.children).to.equal('foo');
    });
  })
});


text:
package com.zfxf.douniu.bean;

/**
 * @author Admin
 * @time 2017/4/7 9:44
 * @des ${TODO}
 */

public class LivingContentDetail {
    public String zc_time;//直播时间
    public String zc_id;//直播内容id
    public LivingContentDetailType zc_context;//直播内容类型
}


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

/*=============================================================================
**
** Source: test3.c
**
** Purpose: Positive test for ExitProcess.
**
** Dependencies: PAL_Initialize
**               PAL_Terminate
**

**
**===========================================================================*/
#include <palsuite.h>

int __cdecl main( int argc, char **argv )

{
    /* initialize the PAL */
    if( PAL_Initialize(argc, argv) != 0 )
    {
	    return( FAIL );
    }

    /* terminate the PAL */
    PAL_Terminate();

    /* call ExitProcess() -- should work after PAL_Terminate() */
    ExitProcess( PASS );

    /* return failure if we reach here -- note no attempt at   */
    /* meaningful output because we've called PAL_Terminte().  */
    return FAIL;
}


text:
import types
import json
import sys
import time
import math
from datetime import datetime, timezone
import odc
# getting a problem loading Kafka module - [No module named 'confluent_kafka.cimpl']
# This is due the .cimpl file being installed into the release library .zip file, so is not fund under debug builds.
# Could just copy the C:\Python37\python37.zip to C:\Python37\python37_d.zip, or just use release ODC.
# DO NOT USE Debug build on Windows
# Rather than building your project in DEBUG mode on windows, try building in RELEASE mode with debug symbols and no optimization.
# Full DEBUG mode on windows changes the names of the DLLs python expects to find, so if you wish to truly work in DEBUG mode you will
# need to recompile the entire stack of python modules you work with including NumPy
from confluent_kafka import Producer, Consumer, KafkaError

# Logging Levels
Trace = 0
Debug = 1
Info = 2
Warn = 3
Error = 4
Critical = 5

# Exact string values for Event parameters which are passed as strings
# EventTypes, ConnectState,Binary,Analog,Counter,FrozenCounter,BinaryOutputStatus,AnalogOutputStatus,ControlRelayOutputBlock and others...
# QualityFlags, ONLINE,RESTART,COMM_LOST,REMOTE_FORCED,LOCAL_FORCE,OVERRANGE,REFERENCE_ERR,ROLLOVER,DISCONTINUITY,CHATTER_FILTER
# ConnectState, PORT_UP,CONNECTED,DISCONNECTED,PORT_DOWN
# ControlCode, NUL,NUL_CANCEL,PULSE_ON,PULSE_ON_CANCEL,PULSE_OFF,PULSE_OFF_CANCEL,LATCH_ON,LATCH_ON_CANCEL,LATCH_OFF,LATCH_OFF_CANCEL,
#               CLOSE_PULSE_ON,CLOSE_PULSE_ON_CANCEL,TRIP_PULSE_ON,TRIP_PULSE_ON_CANCEL,UNDEFINED

class SimPortClass:
    ''' Our class to handle an ODC Port. We must have __init__, ProcessJSONConfig, Enable, Disable, EventHander, TimerHandler and
    RestRequestHandler defined, as they will be called by our c/c++ code.
    ODC publishes some functions to this Module (when run) they are part of the odc module(include).
    We currently have odc.log, odc.SetTimer and odc.PublishEvent.
    '''

    # Worker Methods. They need to be high in the code so they are available in the code below. No forward declaration in Python
    def LogTrace(self, message ):
        odc.log(self.guid, Trace, message )
    def LogError(self, message ):
        odc.log(self.guid,Error, message )
    def LogDebug(self, message ):
        odc.log(self.guid, Debug, message )
    def LogInfo(self, message ):
        odc.log(self.guid,Info, message )
    def LogWarn(self, message ):
        odc.log(self.guid, Warn, message )
    def LogCritical(self, message ):
        odc.log(self.guid,Critical, message )

    # Mandatory Methods that are called by ODC PyPort

    def __init__(self, odcportguid, objectname):
        self.objectname = objectname    # Documentation/error use only.
        self.guid = odcportguid         # So that when we call an odc method, ODC can work out which pyport to hand it too.
        self.Enabled = False
        self.MessageIndex = 0
        self.EventQueueSize = 0
        self.QueueErrorState = 0       # 0 - No Error, 1 - Error, Notified,
        self.SendErrorState = 0        # As above
        self.LastMessageIndex = self.MessageIndex
        self.StartTimeSeconds = time.time()
        self.timestart = 1.1 # Used for profiling, setup as a float
        self.measuretimeus = 0
        self.measuretimeus2 = 0
        self.secondcount = 0
        self.ConfigDict = {}      # Config Dictionary
        self.LogInfo("PyPortKafka - SimPortClass Init Called - {}".format(objectname))
        self.LogDebug("Python sys.path - {}".format(sys.path))
        self.producer = None
        return

        # time.perf_counter_ns() (3.6 up) gives the time including include sleeps time.process_time() is overall time.
    def timeusstart(self):
         self.timestart = time.perf_counter() #float fractions of a second

    def timeusstop(self):
        return int((time.perf_counter()-self.timestart)*1000000)

    def minutetimermessage(self):
        DeltaSeconds = time.time() - self.StartTimeSeconds
        self.StartTimeSeconds = time.time()
        DeltaIndex = self.MessageIndex - self.LastMessageIndex
        self.LastMessageIndex = self.MessageIndex
        if (DeltaIndex != 0):
            self.LogError("PyPortKafka status. Event Queue Size {}, Total Messages - {}, Messages/Second - {}".format(self.EventQueueSize, self.MessageIndex, math.floor(DeltaIndex/DeltaSeconds)))
        return

    def Config(self, MainJSON, OverrideJSON):
        """ The JSON values are passed as strings (stripped of comments), which we then load into a dictionary for processing
        Note that this does not handle Inherits JSON entries correctly (Inherits is effectily an Include file entry)"""
        self.LogDebug("Passed Main JSON Config information - Len {} , {}".format(len(MainJSON),MainJSON))
        self.LogDebug("Passed Override JSON Config information - Len {} , {}".format(len(OverrideJSON), OverrideJSON))

        # Load JSON into Dicts
        Override = {}
        try:
            if len(MainJSON) != 0:
                self.ConfigDict = json.loads(MainJSON)
            if len(OverrideJSON) != 0:
                Override = json.loads(OverrideJSON)
        except:
           self.LogError("Exception on parsing JSON Config data - {}".format(sys.exc_info()[0]))
           return

        self.LogDebug("JSON Config strings Parsed")

        # Now use the override config settings to adjust or add to the MainConfig. Only root json values can be adjusted.
        # So you cannot change a single value in a Binary point definition without rewriting the whole "Binaries" json key.
        self.ConfigDict.update(Override)               # Merges with Override doing just that - no recursion into sub dictionaries

        self.LogDebug("Combined (Merged) JSON Config {}".format(json.dumps(self.ConfigDict)))

        # Now extract what is needed for this instance, or just reference the ConfigDict when needed.
        kafkaserver = self.ConfigDict["bootstrap.servers"]
        self.topic = self.ConfigDict["Topic"]

        # The acks can be 0, 1, 2 etc or all. It is the number of nodes that have to have written the message before we get acknoledgement.
        # So a value of 0 is fire and forget. etc.
        # Details of what can be passed see: https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md
        # We require all of the nodes that are configured to ack for the data to be valid - we dont control it here.
        # In the cluster config it is set to 2.
        #
        # Really interesting discussion of how to loose messages in Kafka (but also how not to loose messages!)
        # https://jack-vanlightly.com/blog/2018/9/14/how-to-lose-messages-on-a-kafka-cluster-part1
        #
        # To control batching - the values are the defaults: 'batch.num.messages': 10000 OR 'message.max.bytes' : 1000000,
        # queuing.strategy=fifo an attempt to make sure messages arrive in the order they are sent..
        # max.in.flight.requests.per.connection=5 Usually a very large number, 5 does not seem to slow things down - maybe 1%?
        # request.required.acks are the number of copies of the message pushed to the other nodes. Really dont need any acks, if the primary has the message, it will replicate shortly. Or could require an ack from at least 1 node
        # 'compression.type':'none' - does not seem to make much difference (none,snappy, gzip)
        # 'delivery.report.only.error':False    This does make things quicker from approx 70k/sec to 74k/sec
        # 'message.send.max.retries': 100000 - will not drop the message until this many attempts have been made...
        conf = {'bootstrap.servers': kafkaserver, 'client.id': 'OpenDataCon', 'delivery.report.only.error' : True, 'message.send.max.retries': 10000000, 'request.required.acks' : 0, 'max.in.flight.requests.per.connection' : 100}
        self.producer = Producer(conf)
        return

    def Operational(self):
        """ This is called from ODC once ODC is ready for us to be fully operational - normally after Build is complete"""
        self.LogDebug("Port Operational - {}".format(datetime.now().isoformat(" ")))
        # This is only done once - will self restart from the timer callback.
        odc.SetTimer(self.guid, 1, 500)    # Start the timer cycle
        odc.SetTimer(self.guid, 2, 5000)   # First status message after 5 seconds
        return

    def Enable(self):
        self.LogDebug("Enabled - {}".format(datetime.now().isoformat(" ")))
        self.enabled = True;
        return

    def Disable(self):
        self.LogDebug("Disabled - {}".format(datetime.now().isoformat(" ")))
        self.enabled = False
        self.producer = None
        return

    # Not used
    def delivery_report(self, err, msg):
        """ Called once for each message produced to indicate delivery result. Triggered by poll() or flush(). """
        if err is not None:
            if self.SendErrorState == 0:
                self.LogError("Kafka Send Message Error - {} [{}] - {}".format(msg.topic(), msg.partition(), err))
                self.SendErrorState = 1
        else:
            if self.SendErrorState == 1:
                self.LogError("Kafka Send Message Error Cleared - {} [{}]".format(msg.topic(), msg.partition()))
                self.SendErrorState = 0

    # Needs to return True or False, which will be translated into CommandStatus::SUCCESS or CommandStatus::UNDEFINED
    # EventType (string) Index (int), Time (msSinceEpoch), Quality (string) Payload (string) Sender (string)
    # There is no callback available, the ODC code expects this method to return without delay.
    def EventHandler(self,EventType, Index, Time, Quality, Payload, Sender):
        # self.LogDebug("EventHander: {}, {}, {} {} - {}".format(self.guid,Sender,Index,EventType,Payload))

        if (EventType == "ConnectState"):
            return True

        self.LogError("Events must be queued {}".format(EventType))

        # Always return True - we processed the message - even if we could not pass it to Kafka.
        return True

    def millisdiff(self, starttimedate):
        dt = datetime.now() - starttimedate
        ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
        return ms

    # Will be called at the appropriate time by the ASIO handler system. Will be passed an id for the timeout,
    # so you can have multiple timers running.
    def TimerHandler(self,TimerId):
        # self.LogDebug("TimerHander: ID {}, {}".format(TimerId, self.guid))

        if (self.enabled is False):
            self.LogDebug("TimerHander Called but Port Disabled: ID {}, {}".format(TimerId, self.guid))
            return  # Port is disabled, need to stop processing and dont restart the timers.

        if (self.producer is not None):
            self.producer.poll(0)   # Do any waiting processing, but dont wait!

        if (TimerId == 1):

            MaxMessageCount = 5000
            longwaitmsec = 100
            shortwaitmsec = 5
            EventCount = 0
            starttime = datetime.now()
            self.measuretimeus = 0
            self.measuretimeus2 = 0

            if (self.producer is not None):
                # Get Events from the queue and process them, up until we have an empty queue or MaxMessageCount entries
                # Then trigger the Kafka library to send them.
                while ((EventCount < MaxMessageCount)):

                    self.timeusstart()
                    ### Takes about 3.2usec (old 8.4usec) per call (approx) on DEV server
                    JsonEventstr, empty = odc.GetNextEvent(self.guid)
                    self.measuretimeus += self.timeusstop()

                    # The EventType will be an empty string if the queue is empty.
                    if (empty == True):
                        break

                    EventCount += 1
                    # self.LogDebug("Kafka Message {} : {}".format(self.topic,JsonEventstr))
                    try:
                        self.timeusstart()
                        # Now 32msec/5000, about 5usec per record. (old 45msec/5000 so 9usec/record)
                        # Can we only get a single delivery report per block of up to 5000 messages?
                        # If we set the re-try count to max int, then handling the delivery report does not make much sense - the buffer will just fill up and then we will get an exception
                        # here due to a full buffer. And we fill up the next buffer (in PyPort) (note we need to store the event we were about to send so we dont loose it!)
                        # Eventually we will loose events, but there is nothing we can do about that.
                        self.producer.produce(self.topic, value=JsonEventstr)
                        self.measuretimeus2 += self.timeusstop()
                        if self.QueueErrorState == 1:
                            self.LogError("Kafka Producer Queue Recovered - NOT full ({} messages awaiting delivery)".format(len(self.producer)))
                            self.QueueErrorState = 0

                    except BufferError:
                        if self.QueueErrorState == 0:
                            self.LogError("Kafka Producer Queue is full ({} messages awaiting delivery)".format(len(self.producer)))
                            self.QueueErrorState = 1
                        break

                    if (EventCount % 100 == 0):
                        self.producer.poll(0)   # Do any waiting processing, but dont wait!

                self.EventQueueSize = odc.GetEventQueueSize(self.guid);
                #self.LogDebug("Kafka Produced {} messages. Kafka queue size {}. ODC Event queue size {} Execution time {} msec Timed code {}, {} us".format(EventCount,len(self.producer),self.EventQueueSize,self.millisdiff(starttime),self.measuretimeus,self.measuretimeus2))

                self.MessageIndex += EventCount

            # If we have pushed the maximum number of events in, we need to go faster...
            # If the producer queue hits the limit, this means the kafka cluster is not keeping up.
            if EventCount < MaxMessageCount:
                odc.SetTimer(self.guid, 1, longwaitmsec)    # We do not have messages waiting...
            else:
                odc.SetTimer(self.guid, 1, shortwaitmsec)   # We do have messages waiting

        if (TimerId == 2):
            odc.SetTimer(self.guid, 2, 5000)   # Set to run again in 5 seconds
            self.secondcount += 5
            if self.secondcount >= 30:       # Normally 60 seconds
                self.secondcount = 0
                self.minutetimermessage()

        if (self.producer is not None):
            self.producer.poll(0)   # Do any waiting processing, but dont wait!

        return

    # The Rest response interface - the following method will be called whenever the restful interface (a single interface for all PythonPorts) gets
    # called. It will be decoded sufficiently so that it is passed to the correct PythonPort (us)
    # To make these calls in Python (our test scripts) we can use the library below.
    # https://2.python-requests.org//en/master/
    #
    # We return the response that we want sent back to the caller. This will be a JSON string. A null string would be an error.
    def RestRequestHandler(self, url, content):
        self.LogDebug("RestRequestHander: {}".format(url))

        Response = {}   # Empty Dict
        if ("GET" in url):
            DeltaSeconds = time.time() - self.StartTimeSeconds
            Response["Status"] = "PyPortKafka Processing is running. Messages Processed - {}, Messages/Second - {}".format(self.MessageIndex, math.floor((self.MessageIndex - self.LastMessageIndex)/DeltaSeconds))

            self.StartTimeSeconds = time.time()
            self.LastMessageIndex = self.MessageIndex

        return json.dumps(Response)


text:
require "rails_helper"

describe "/v2/token" do

  describe "get token" do

    let(:auth_mech) { ActionController::HttpAuthentication::Basic }
    let(:password) { "this is a test" }
    let(:user) { create(:user, password: password) }
    let(:registry) { create(:registry) }

    let(:valid_auth_header) do
      { "HTTP_AUTHORIZATION" => auth_mech.encode_credentials(user.username, password) }
    end

    let(:invalid_auth_header) do
      { "HTTP_AUTHORIZATION" => auth_mech.encode_credentials(user.username, "wrong_password") }
    end

    let(:nonexistent_auth_header) do
      { "HTTP_AUTHORIZATION" => auth_mech.encode_credentials("caesar", "password") }
    end

    context "as invalid user" do
      let(:valid_request) do
        {
          service: registry.hostname,
          account: "account",
          scope:   "repository:foo_namespace/me:push"
        }
      end

      it "denies access when the password is wrong" do
        get v2_token_url,
          { service: registry.hostname, account: "account", scope: "repository:foo/me:push" },
          invalid_auth_header

        expect(response.status).to eq 401
      end

      it "denies access when the user does not exist" do
        get v2_token_url,
          { service: registry.hostname, account: "account", scope: "repository:foo/me:push" },
          nonexistent_auth_header

        expect(response.status).to eq 401
      end

      it "denies access when basic auth credentials are not defined" do
        get v2_token_url,
          service: registry.hostname, account: "account", scope: "repository:foo/me:push"
        expect(response.status).to eq 401
      end

      it "denies access to a disabled user" do
        user.update_attributes(enabled: false)
        get v2_token_url, valid_request, valid_auth_header
        expect(response.status).to eq 401
      end
    end

    context "as another user" do
      let(:another) { create(:user, password: password) }

      it "does not allow to pull a private namespace from another team" do
        # It works for the regular user
        get v2_token_url,
          {
            service: registry.hostname,
            account: user.username,
            scope:   "repository:#{user.username}/busybox:push,pull"
          },
          "HTTP_AUTHORIZATION" => auth_mech.encode_credentials(user.username, password)

        expect(response.status).to eq 200

        # But not for another
        get v2_token_url,
          {
            service: registry.hostname,
            account: another.username,
            scope:   "repository:#{user.username}/busybox:push,pull"
          },
          "HTTP_AUTHORIZATION" => auth_mech.encode_credentials(another.username, password)

        expect(response.status).to eq 401
      end
    end

    context "as LDAP user I can authenticate from Docker CLI" do
      before :each do
        APP_CONFIG["ldap"] = { "enabled" => true, "base" => "" }
        allow_any_instance_of(Portus::LDAP).to receive(:authenticate!).and_call_original
        allow_any_instance_of(Net::LDAP).to receive(:bind_as).and_return(true)
        allow_any_instance_of(NamespacePolicy).to receive(:push?).and_return(true)
        allow_any_instance_of(NamespacePolicy).to receive(:pull?).and_return(true)
      end

      it "authenticates if the HTTP Basic Authentication was given" do
        get v2_token_url,
          {
            service: registry.hostname,
            account: "ldapuser",
            scope:   "repository:ldapuser/busybox:push,pull"
          },
          "HTTP_AUTHORIZATION" => auth_mech.encode_credentials("ldapuser", "12341234")

        expect(response.status).to eq 200

        # Check that the user has actually been registered.
        ldapuser = User.find_by(username: "ldapuser")
        expect(ldapuser.username).to eq "ldapuser"
        expect(ldapuser.ldap_name).to eq "ldapuser"
        expect(ldapuser.valid_password?("12341234")).to be true
      end

      it "does not authenticate the LDAP user if not Basic authentication was given" do
        get v2_token_url,
          {
            service: registry.hostname,
            account: "ldapuser",
            scope:   "repository:ldapuser/busybox:push,pull"
          }, {}

        expect(response.status).to eq 401
      end
    end

    context "as valid user" do
      let(:valid_request) do
        {
          service: registry.hostname,
          account: "account",
          scope:   "repository:foo_namespace/me:push"
        }
      end

      before do
        allow_any_instance_of(NamespacePolicy).to receive(:push?).and_return(true)
        allow_any_instance_of(NamespacePolicy).to receive(:pull?).and_return(true)
        create(:namespace, name: "foo_namespace", registry: registry)
      end

      it "performs a request with given data" do
        get v2_token_url, valid_request, valid_auth_header
        expect(response.status).to eq 200
      end

      it "decoded payload should conform with params sent" do
        get v2_token_url, valid_request, valid_auth_header
        token = JSON.parse(response.body)["token"]
        payload = JWT.decode(token, nil, false, leeway: 2)[0]
        expect(payload["sub"]).to eq "account"
        expect(payload["aud"]).to eq registry.hostname
        expect(payload["access"][0]["type"]).to eq "repository"
        expect(payload["access"][0]["name"]).to eq "foo_namespace/me"
        expect(payload["access"][0]["actions"][0]).to eq "push"
      end

      context "no scope requested" do
        before do
          get v2_token_url, { service: registry.hostname, account: "account" }, valid_auth_header
        end

        it "respond with 200" do
          expect(response.status).to eq 200
        end

        it "decoded payload should not contain access key" do
          token = JSON.parse(response.body)["token"]
          payload = JWT.decode(token, nil, false, leeway: 2)[0]
          expect(payload).to_not have_key("access")
        end

      end

      context "unknown scope requested" do
        before do
          get v2_token_url,
            { service: registry.hostname, account: "account", scope: "whale:foo,bar" },
            valid_auth_header
        end

        it "respond with 401" do
          expect(response.status).to eq 401
        end
      end

      context "repository scope" do
        it "delegates authentication to the Namespace policy" do
          personal_namespace = Namespace.find_by(name: user.username)
          expect_any_instance_of(Api::V2::TokensController).to receive(:authorize)
            .with(personal_namespace, :push?)
          expect_any_instance_of(Api::V2::TokensController).to receive(:authorize)
            .with(personal_namespace, :pull?)

          get v2_token_url,
            {
              service: registry.hostname,
              account: user.username,
              scope:   "repository:#{user.username}/busybox:push,pull"
            },
            valid_auth_header
        end

        it "allows to pull an image in which this user is just a viewer"  do
          # Quick way to force a "viewer" policy.
          allow_any_instance_of(NamespacePolicy).to receive(:push?).and_return(false)
          allow_any_instance_of(NamespacePolicy).to receive(:pull?).and_return(true)

          get v2_token_url,
            { service: registry.hostname, account: user.username,
              scope: "repository:#{user.username}/busybox:push,pull" },
            valid_auth_header

          expect(response.status).to eq 200

          # And check that the only authorized scope is "pull"
          token = JSON.parse(response.body)["token"]
          payload = JWT.decode(token, nil, false, leeway: 2)[0]
          expect(payload["access"][0]["name"]).to eq "#{user.username}/busybox"
          expect(payload["access"][0]["actions"]).to match_array ["pull"]
        end
      end

      context "registry scope" do
        let(:valid_request) do
          {
            service: registry.hostname,
            account: "portus",
            scope:   "registry:catalog:*"
          }
        end

        let(:valid_portus_auth_header) do
          {
            "HTTP_AUTHORIZATION" =>
              auth_mech.encode_credentials("portus", Rails.application.secrets.portus_password)
          }
        end

        before do
          User.create!(
            username: "portus",
            password: Rails.application.secrets.portus_password,
            email:    "portus@portus.com",
            admin:    true
          )
        end

        it "allows portus to access the Catalog API" do
          get v2_token_url, valid_request, valid_portus_auth_header
          expect(response.status).to eq 200

          token = JSON.parse(response.body)["token"]
          payload = JWT.decode(token, nil, false, leeway: 2)[0]
          expect(payload["sub"]).to eq "portus"
          expect(payload["aud"]).to eq registry.hostname
          expect(payload["access"][0]["type"]).to eq "registry"
          expect(payload["access"][0]["name"]).to eq "catalog"
          expect(payload["access"][0]["actions"][0]).to eq "*"
        end

        it "forbids unhandled methods from the registry type" do
          wr = valid_request
          wr[:scope] = "registry:catalog:lala"
          get v2_token_url, wr, valid_portus_auth_header
          expect(response.status).to eq 401
        end
      end

      context "unknown scope" do
        it "denies access" do
          get v2_token_url,
              {
                service: registry.hostname,
                account: user.username,
                scope:   "repository:busybox:fork"
              },
              valid_auth_header
          expect(response.status).to eq 401
        end
      end

      context "unknown type" do
        it "denies access" do
          get v2_token_url,
              { service: registry.hostname, account: user.username, scope: "lala:busybox:fork" },
              valid_auth_header
          expect(response.status).to eq 401
        end
      end

      context "unkwnow registry" do
        context "no scope requested" do
          it "respond with 401" do
            get v2_token_url, { service: "does not exist", account: "account" }, valid_auth_header
            expect(response.status).to eq 401
          end
        end

        context "reposity scope" do
          it "it responde with 401" do
            # force creation of the namespace
            namespace = create(:namespace,
                               team:     Team.find_by(name: user.username),
                               registry: registry)
            wrong_registry = create(:registry)

            get(
              v2_token_url,
              {
                service: wrong_registry.hostname,
                account: user.username,
                scope:   "repository:#{namespace.name}/busybox:push,pull"
              },
              valid_auth_header
            )
            expect(response.status).to eq(401)
          end
        end
      end

    end

  end

end


text:
package io.grokery.lab.api.cloud.nodes;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.grokery.lab.api.common.JsonObj;
import io.grokery.lab.api.common.exceptions.InvalidInputException;
import io.grokery.lab.api.common.exceptions.NotAuthorizedException;
import io.grokery.lab.api.common.exceptions.NotFoundException;
import io.grokery.lab.api.common.dao.DAO;
import io.grokery.lab.api.common.context.CloudContext;
import io.grokery.lab.api.cloud.nodes.Node;
import io.grokery.lab.api.cloud.nodes.dao.NodesDAO;

public class NodesService {

	private static final Logger LOG = LoggerFactory.getLogger(NodesService.class);

	public static JsonObj create(String auth, String cloudId, String nodeType, JsonObj data) throws InvalidInputException, NotFoundException, NotAuthorizedException {
		CloudContext context = new CloudContext(cloudId, auth);

		data.put(Node.getNodeTypeName(), nodeType);
		Node newItem = Node.fromJsonObj(data, context);
		newItem.validateValues();

		DAO dao = NodesDAO.getInst(context);
		dao.create(newItem.getNodeType(), newItem.getNodeId(), newItem.toJsonObj());

		newItem.setupExternalResources(context);

		JsonObj result = dao.update(newItem.getNodeType(), newItem.getNodeId(), newItem.toJsonObj());

		return result;
	}

	public static JsonObj update(String auth, String cloudId, String nodeType, String nodeId, JsonObj data) throws InvalidInputException, NotFoundException, NotAuthorizedException {
		CloudContext context = new CloudContext(cloudId, auth);

		DAO dao = NodesDAO.getInst(context);
		JsonObj rawExisting = dao.get(nodeType, nodeId);
		Node existing = Node.fromJsonObj(rawExisting, context);

		String nodeSubType = data.getOrDefault(Node.getNodeSubTypeName(), "").toString();
		if (nodeSubType.equals("") || nodeSubType.equals(existing.getSubType().toString())) {
			existing.updateExternalResources(context, data);
			existing.setValues(data);
			existing.validateValues();
			return dao.update(existing.getNodeType(), existing.getNodeId(), existing.toJsonObj());
		} else {
			Node node = Node.getClassInstance(data);
			node.setNodeId(existing.getNodeId());
			node.setCreated(existing.getCreated());
			node.setValues(existing.toJsonObj());
			node.setValues(data);
			node.validateValues();

			existing.cleanupExternalResources(context);
			dao.delete(existing.getNodeType(), existing.getNodeId());

			dao.create(node.getNodeType(), node.getNodeId(), node.toJsonObj());
			node.setupExternalResources(context);
			return dao.update(node.getNodeType(), node.getNodeId(), node.toJsonObj());
		}
	}

	public static JsonObj delete(String auth, String cloudId, String nodeType, String nodeId) throws NotFoundException, InvalidInputException, NotAuthorizedException {
		CloudContext context = new CloudContext(cloudId, auth);

		DAO dao = NodesDAO.getInst(context);
		Node item = Node.fromJsonObj(dao.get(nodeType, nodeId), context);
		item.cleanupExternalResources(context);
		JsonObj result = dao.delete(nodeType, nodeId);
		return result;
	}

	public static JsonObj read(String auth, String cloudId, String nodeType, String nodeId) throws NotFoundException, InvalidInputException, NotAuthorizedException {
		CloudContext context = new CloudContext(cloudId, auth);

		DAO dao = NodesDAO.getInst(context);
		Node existing = Node.fromJsonObj(dao.get(nodeType, nodeId), context);
		return existing.toJsonObj();
	}

	public static JsonObj readAll(String auth, String cloudId) throws InvalidInputException, NotAuthorizedException {
		CloudContext context = new CloudContext(cloudId, auth);

		DAO dao = NodesDAO.getInst(context);
		// String projection = "nodeId, nodeType, title, description, x, y, upstream, downstream";
		JsonObj results = dao.scan(null);
		return results;
	}

}


text:
#include "DirectXManager.h"
#include "Tetris.h"

// Custom derived class
class CustomWindow : public WindowManager
{
	DirectXScreen		Screen;
	Tetris				tetris;

public:
	// Constructor & Destructor
	CustomWindow (void) {};
	~CustomWindow (void) {};

	void AfterCreate(void);

	// Window manipulation functions
	Bool32 Frame (void);
	static void keyDown(HWND hWindow, WPARAM k);
};


text:
  Franchevelle est
       un village
       localisé dans le département de Haute-Saône en Franche-Comté. Elle comptait 348 habitants en 2008.

À coté de Franchevelle sont localisées les communes de
Bouhans-lès-Lure localisée à 5 km, 268 habitants,
Lantenot située à 3 km, 322 habitants,
Linexert localisée à 1 km, 136 habitants,
Citers localisée à 3 km, 822 habitants,
Ailloncourt à 5 km, 281 habitants,
Magnivray située à 4 km, 160 habitants,
 entre autres. De plus, Franchevelle est située à seulement 26 km de Vesoul.

La commune compte quelques  équipements, elle propose entre autres un terrain de sport.

Si vous envisagez de venir habiter à Franchevelle, vous pourrez aisément trouver une maison à vendre.

Le nombre de logements, à Franchevelle, était réparti en 2011 en sept appartements et 179 maisons soit
 un marché relativement équilibré.


text: \newcommand{\imageleft}[1]{} % drop it


text:
scnShortcodeMeta = {
    attributes: [{
        label: "Style",
        id: "style",
        help: "Values: vertical, horizontal, none (default: vertical)."
    }, {
        label: "Url",
        id: "url",
        help: "Optional. Specify URL directly."
    }, {
        label: "Source",
        id: "source",
        help: "Optional. Username to mention in tweet."
    }, {
        label: "Related",
        id: "related",
        help: "Optional. Related account."
    }, {
        label: "Text",
        id: "text",
        help: "Optional tweet text (defatul: titel of page)."
    }, {
        label: "Float",
        id: "float",
        help: "Values: none, left, right (default: left)."
    }, {
        label: "Lang",
        id: "lang",
        help: "Values: fr, de, es, js (default: english)."
    }],
    defaultContent: "",
    shortcode: "twitter"
};