text:
import pyglet
from pyglet import window, image
from pyglet.gl import *
from math import *

win=window.Window(fullscreen=True)

brush_size = 10
def Trails():
    def draw_circle(x,y,diameter):
        glBegin(GL_TRIANGLE_FAN)
        glVertex2f(x, y)
        for angle in range(361):
            glVertex2f( x+sin(angle)*(diameter/2.0), y+cos(angle)*(diameter/
    2.0) )
        glEnd()

    def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
        glColor3f(1,1,1)
        for i in range(2):
            draw_circle(x,y,brush_size)
            draw_circle(x-dx,y-dy,brush_size)
            win.flip()

    win.on_mouse_drag = on_mouse_drag

    def on_mouse_press(x,y,buttons,modifiers):
        for i in range(2):
            draw_circle(x,y,brush_size)
            win.flip()

    win.on_mouse_press=on_mouse_press

    while True:
        win.dispatch_events()

def runTrails(win2):
    win2.winHandle.minimize() #minimize the PsychoPy window
    win2.fullscr = False #disable fullscreen
    win2.flip() #redraw the (minimized) window
    try:
        Trails()#launch external program
    except WindowsError: #catch an error if the program can't be launched
        print "External application couldn't be launched!"
    win2.winHandle.maximize() #when external program closes, maximize PsychoPy window again
    win2.fullscr = True
    win2.winHandle.activate() #re-activate window


text:
<?php

namespace UserBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RestoreType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder

            ->add('email', TextType::class, array('required' => false, 'label' => '_email',
                'attr'=>['placeholder'=>'_email']
            ))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'UserBundle\Entity\Restore'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'userbundle_restore';
    }

}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe 'Serializer' do

  context 'given some arbitrary models' do

    Person = Struct.new :name, :updated_at

    before :each do
      @names = ['Adrian', 'Audrey', 'Jerene', 'X', 'Inez', 'John']
      @people = @names.map { |name| Person.new name, Time.now }
    end

    it 'should format array as data' do

      json = Reaction::Rails::Serializer.format_data @people
      hash = JSON.parse json

      hash['type'].should eql 'data'
      hash['items'].should_not be_nil
      hash['items'].each { |item|
        @names.should include(item['name'])
        @names.delete item['name']
      }

      @names.should be_empty

    end

    it 'should format object as datum' do

      @person = Person.new 'batman'
      json = Reaction::Rails::Serializer.format_data @person
      hash = JSON.parse json

      hash['type'].should eql 'datum'
      hash['item'].should_not be_nil
      hash['item']['name'].should eql @person.name

    end

    it 'should handle null objects' do
      expected = {type: 'datum', item: nil}.to_json
      Reaction::Rails::Serializer.format_data(nil).should eql(expected)
    end

    it 'should accept custom fields' do

      json = Reaction::Rails::Serializer.format_data @people, action: 'x'
      hash = JSON.parse json
      hash['action'].should eql 'x'

      @person = Person.new 'xman'
      json = Reaction::Rails::Serializer.format_data @person, action: 'y'
      hash = JSON.parse json
      hash['action'].should eql 'y'

    end

    it 'should add errors if any' do

      @person = {name: 'batman'}
      def @person.errors
        return ['xyz']
      end

      json = Reaction::Rails::Serializer.format_data @person
      hash = JSON.parse json
      hash['errors'].should eql @person.errors

    end

    it 'should handle frozen objects' do

      @person = Person.new 'batman'
      @person.freeze

      json = Reaction::Rails::Serializer.format_data @person
      hash = JSON.parse json
      hash['item']['name'].should eql @person.name

    end

    it 'should convert updated_at to float' do

      @person = Person.new 'batman', Time.now

      json = Reaction::Rails::Serializer.format_data @person
      hash = JSON.parse json

      hash['item']['updated_at'].should eql @person.updated_at

    end

  end

  context 'given an array of models and a sync request' do

    Car = Struct.new :id, :name, :updated_at

    before(:each) do
      @cars = [ Car.new(256, 'X', Time.now),
                Car.new(111, 'Y', Time.now)]
    end

    it 'should format the diff containing new cars' do

      json = Reaction::Rails::Serializer.format_diff @cars, {}
      deltas = JSON.parse(json)['deltas']

      deltas.size.should be(2)
      deltas.each do |d|
        d.should include('action')
        d['action'].should eq('create')
        d.should include('item')
        @cars.delete_if { |c| c.id == d['item']['id'] }
      end
      @cars.size.should be(0)

    end

    it 'should format the diff containing deleted persons' do

      cached = { '5' => 1.day.ago.to_i }

      json = Reaction::Rails::Serializer.format_diff @cars, cached: cached
      deltas = JSON.parse(json)['deltas']

      deltas.size.should be(3)
      deltas.any? do |d|
        d.include? 'action' and
        d['action'] == 'destroy' and
        d.include? 'item' and
        d['item']['id'].to_i == 5
      end.should be(true)

    end

    it 'should format the diff containing updated persons' do

      cached = { '111' => 1.day.ago.to_i }

      json = Reaction::Rails::Serializer.format_diff @cars, cached: cached
      deltas = JSON.parse(json)['deltas']

      deltas.size.should be(2)
      deltas.any? do |d|
        d.include? 'action' and
        d['action'] == 'update' and
        d.include? 'item' and
        d['item']['id'].to_i == 111
      end.should be(true)

    end

  end

end


text:
<html>
    hello
    <a
        href="https://www.box.com/api/oauth2/authorize?response_type=code&client_id={{client_id}}&redirect_uri={{redir_url}}&state=foo">auth
        to box</a>
</html>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Edinb. J. Bot. 54(1): 115 (1997)

#### Original name
Cortinarius violaceomaculatus Brandrud

### Remarks
null


text:
import { Injectable } from '@angular/core';
import { IAppState } from '../Store/Reducers/index';
import { Store } from '@ngrx/store';
import { AssignmentActions } from '../Store/Actions/assignment.actions';
import { Assignment } from '../Store/Models/assignment';
import { Response } from '@angular/http';
import { CustomHttp } from './customHttp';
import { BASE_URL } from '../Constants/settings';
import { Observable } from 'rxjs/Rx';
import { GameSettings } from "../Store/Models/game-settings";

@Injectable()
export class AssignmentService {

  constructor(private store: Store<IAppState>, private chttp: CustomHttp) {

  }
  // NOTE: Do we need this? it is only used to auto load
  public getAll(): void {
    this.store.dispatch(AssignmentActions.getAll());
  }

  public get(assignment_id: number):void {
    this.store.dispatch(AssignmentActions.get(assignment_id));
  }

  public get$(assignment_id: number): Observable<Response> {
    return this.chttp.get(`${BASE_URL}/assignments/${assignment_id}?includes=unit,iterations&compact=true`)
      .map(res => res.json())
      .map(json => json.assignment)
      .do(assignment => this.store.dispatch(AssignmentActions.getSuccess(assignment)))
      .catch(err => {
        this.store.dispatch(AssignmentActions.getFail());
        return Observable.throw(err);
      })
  }

  public getAllForUnit(unit_id: number): void {
    this.store.dispatch(AssignmentActions.getAllForUnit(unit_id));
  }

  public getAllForUnit$(unit_id: number): Observable<Response> {
    return this.chttp.get(`${BASE_URL}/assignments?unit_id=${unit_id}&includes=unit,iterations`)
      .map(res => res.json())
      .do(json => this.store.dispatch(AssignmentActions.getAllForUnitSuccess(json.assignments, unit_id)))
      .catch(err => {
        this.store.dispatch(AssignmentActions.getAllForUnitFail(unit_id));
        return Observable.throw(err);
      })
  }

  public create(new_assignment: Assignment): void {
    let data = {
      id: new_assignment.id,
      unit_id: new_assignment.unit_id,
      name: new_assignment.name,
      start_date: new_assignment.start_date,
      end_date: new_assignment.end_date,
      iterations_attributes: new_assignment.iterations
    };

    this.store.dispatch(AssignmentActions.create(data));
  }

  public create$(new_assignment: Assignment): Observable<Response> {

    let data = {
      unit_id: new_assignment.unit_id,
      name: new_assignment.name,
      start_date: new_assignment.start_date,
      end_date: new_assignment.end_date,
      iterations_attributes: new_assignment.iterations
    };

    let json = JSON.stringify(data);

    return this.chttp.post(`${BASE_URL}/assignments`, json)
      .map(res => res.json())
      .map(json => json.assignment)
      .do(assignment => this.store.dispatch(AssignmentActions.createSuccess(assignment)))
      .catch(err => {
        this.store.dispatch(AssignmentActions.createFail(JSON.parse(err._body)));
        return Observable.throw(err);
      });
  }

  public getIterations(assignment_id: number): void {
    this.store.dispatch(AssignmentActions.getIterations(assignment_id));
  }
  public getIterations$(assignment_id: number): Observable<Response> {
    this.store.dispatch(AssignmentActions.getIterations(assignment_id));

    return this.chttp.get(`${BASE_URL}/iterations?assignment_id=${assignment_id}`)
      .map(res => res.json())
      .map(json => json.iterations)
      .do(iterations => this.store.dispatch(AssignmentActions.getIterationsSuccess(iterations, assignment_id)))
      .catch(err => {
        this.store.dispatch(AssignmentActions.getIterationsFail(err));
        return Observable.throw(err);
      })
  }

  public getGameSettings$(assignment_id: number): Observable<GameSettings> {
    return this.chttp.get(`${BASE_URL}/assignments/${assignment_id}/game_settings`)
      .map(res => res.json())
      .map(json => json.game_settings)
  }

  public updateGameSettings$(game_settings: GameSettings, assignment_id: number) {
    let data = JSON.stringify(game_settings);

    return this.chttp.post(`${BASE_URL}/assignments/${assignment_id}/game_settings`, data)
      .map(res => res.json())
      .map(json => json.game_settings);
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.apache.poi.xslf.usermodel.XSLFShape (POI API Documentation)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.poi.xslf.usermodel.XSLFShape

Packages that use XSLFShape

org.apache.poi.xslf.model

org.apache.poi.xslf.usermodel

Uses of XSLFShape in org.apache.poi.xslf.model

Methods in org.apache.poi.xslf.model with parameters of type XSLFShape

 boolean
TextBodyPropertyFetcher.fetch(XSLFShape shape)

abstract  boolean
PropertyFetcher.fetch(XSLFShape shape)

 boolean
ParagraphPropertyFetcher.fetch(XSLFShape shape)

Uses of XSLFShape in org.apache.poi.xslf.usermodel

Subclasses of XSLFShape in org.apache.poi.xslf.usermodel

 class
XSLFAutoShape

          Represents a shape with a preset geometry.

 class
XSLFBackground

          Background shape

 class
XSLFConnectorShape

          Specifies a connection shape.

 class
XSLFFreeformShape

          Represents a custom geometric shape.

 class
XSLFGraphicFrame

 class
XSLFGroupShape

          Represents a group shape that consists of many shapes grouped together.

 class
XSLFPictureShape

          Represents a picture shape

 class
XSLFShadow

          Represents a shadow of a shape.

 class
XSLFSimpleShape

          Represents a single (non-group) shape in a .pptx slide show

 class
XSLFTable

          Represents a table in a .pptx presentation

 class
XSLFTableCell

          Represents a cell of a table in a .pptx presentation

 class
XSLFTextBox

 class
XSLFTextShape

          Represents a shape that can hold text.

Methods in org.apache.poi.xslf.usermodel that return types with arguments of type XSLFShape

protected static java.util.List<XSLFShape>
XSLFSheet.buildShapes(org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape spTree,
            XSLFSheet sheet)

 MasterSheet<XSLFShape,XSLFTextParagraph>
XMLSlideShow.createMasterSheet()

 MasterSheet<XSLFShape,XSLFTextParagraph>
XSLFNotesMaster.getMasterSheet()

 java.util.List<XSLFShape>
XSLFSheet.getShapes()

          Returns an array containing all of the shapes in this sheet

 java.util.List<XSLFShape>
XSLFGroupShape.getShapes()

 java.util.Iterator<XSLFShape>
XSLFSheet.iterator()

          Returns an iterator over the shapes in this sheet

 java.util.Iterator<XSLFShape>
XSLFGroupShape.iterator()

          Returns an iterator over the shapes in this sheet

Methods in org.apache.poi.xslf.usermodel with parameters of type XSLFShape

 void
XSLFSheet.addShape(XSLFShape shape)

 void
XSLFGroupShape.addShape(XSLFShape shape)

protected  boolean
XSLFSlideMaster.canDraw(XSLFShape shape)

          Render this sheet into the supplied graphics object

protected  boolean
XSLFSlideLayout.canDraw(XSLFShape shape)

          Render this sheet into the supplied graphics object

protected  boolean
XSLFSheet.canDraw(XSLFShape shape)

          Checks if this sheet displays the specified shape.

 boolean
XSLFSheet.removeShape(XSLFShape xShape)

          Removes the specified shape from this sheet, if it is present
 (optional operation).

 boolean
XSLFGroupShape.removeShape(XSLFShape xShape)

          Remove the specified shape from this group

Method parameters in org.apache.poi.xslf.usermodel with type arguments of type XSLFShape

 void
XSLFHyperlink.linkToSlide(Slide<XSLFShape,XSLFTextParagraph> slide)

 void
XSLFSlide.setNotes(Notes<XSLFShape,XSLFTextParagraph> notes)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

                Copyright 2016 The Apache Software Foundation or
        its licensors, as applicable.


text:
import { on, off, trigger, Symbolic } from '@chialab/proteins';

const LISTENERS_SYM = Symbolic('listeners');

export const CallbackMixin =
    (SuperClass) => class extends SuperClass {
        constructor(...args) {
            super(...args);
            if (!this[LISTENERS_SYM]) {
                this[LISTENERS_SYM] = [];
            }
        }

        on(name, callback) {
            return on(this, name, callback);
        }

        off(name, callback) {
            return off(this, name, callback);
        }

        trigger(name, ...args) {
            let res = trigger(this, name, ...args);
            if (!(res instanceof Promise)) {
                res = Promise.resolve(res);
            }
            return res;
        }

        listen(obj, name, callback) {
            let destroyer = on(obj, name, callback);
            this[LISTENERS_SYM].push(destroyer);
            return destroyer;
        }

        unlisten(obj, name, callback) {
            if (obj) {
                off(obj, name, callback);
            } else {
                this[LISTENERS_SYM].forEach((offListener) => offListener());
                this[LISTENERS_SYM] = [];
            }
        }

        destroy() {
            this.off();
            this.unlisten();
            return super.destroy ? super.destroy() : Promise.resolve();
        }
    };


text:
require 'gui/dialogpanel'

function quitDialogTask()
    console.setVisible(false)
    mouse.show()

    local w = 400
    local h = 170
    local x = gui.screen.width/2 - w/2
    local y = gui.screen.height/2 - h/2

    local layer = gui.mainLayer

    local window = DialogPanel( layer, x, y, w, h )

    local text = Text( layer, x + w/2, y+h*0.40, "Are you sure?", 20  )
    local icon = Widget( layer, x + 8, y + 8, 32, 32 )
    icon:background "icon.exit"

    local by = y + h * 0.6

    local btnOK = Button( layer, x + (w*2/8)-40, by, "okay" )
    btnOK:setClickAction( function () window.OK=true end )
    btnOK:setKeyCode( KeyCodes.KC_RETURN )

    local btnCancel = Button( layer, x + (w*6/8)-40, by, "cancel" )
    btnCancel:setClickAction( function () window.Cancel=true end )
    btnCancel:setKeyCode( KeyCodes.KC_ESCAPE )

    window:addChild( text )
    window:addChild( icon )
    window:addChild( btnOK )
    window:addChild( btnCancel )

    gui.pushModal( window )

    window.OK, window.Cancel = false, false
    while window.OK == false and window.Cancel == false do
        yield()
    end

    gui.popModal()

    window:destroy()

    mouse.hide()

    if window.OK==true then
        quitProgram()
    end

    quitting = false
end

function quit()
    if quitting == true then
        return
    end
    quitting = true
    createTask(quitDialogTask)
end


text:
package controllers

import play.api.i18n.Messages
import play.api.i18n.Lang

case class SelectionItem(text: String,
                         icon: Option[String] = None,
                         localized: Boolean = true) {

  def localizedText(implicit lang: Lang, messages: Messages) = {
    if (localized) {
      Messages(text)
    } else {
      text
    }
  }
}


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 dk.statsbiblioteket.summa.common.lucene.analysis;

import dk.statsbiblioteket.util.qa.QAInfo;

import java.io.IOException;
import java.io.Reader;

/**
 * Helper class for testing reuse of Analyzers.
 */
@QAInfo(level = QAInfo.Level.NORMAL,
        state = QAInfo.State.IN_DEVELOPMENT,
        author = "te")
public class ReusableReader extends Reader {
    private CharSequence source = null;
    private int pos = 0;

    public ReusableReader(CharSequence source) {
        this.source = source;
    }

    @Override
    public synchronized int read(char[] cbuf, int off, int len) throws IOException {
        if (rest() == 0) {
            return -1;
        }
        int read = 0;
        for (int i = 0 ; i < len && rest() > 0 ; i++) {
            cbuf[off + i] = source.charAt(pos++);
            read++;
        }
        return read;
    }

    @Override
    public void close() throws IOException {
        pos = 0;
    }

    @Override
    public void reset() throws IOException {
        pos = 0;
    }

    @Override
    public long skip(long n) throws IOException {
        if (rest() >= n) {
            pos += n;
            return n;
        }
        int r = rest();
        pos = source.length();
        return r;
    }

    public synchronized void set(CharSequence source) {
        this.source = source;
        pos = 0;
    }

    private int rest() {
        return source == null ? 0 : source.length() - pos;
    }
}


text:
using namespace std;

class URDriver_receiver : public RTT::TaskContext{
public:
	URDriver_receiver(std::string const& name);
	bool configureHook();
	bool startHook();
	void updateHook();
	void stopHook();
	void cleanupHook();

private:

	//!@name Properties
	///@{
	int port_number;
	string prop_address;
	///@}

	RTT::extras::FileDescriptorActivity* act;
	int sockfd;

	struct sockaddr_in serv_addr;
	struct hostent *server;

	URdata::Ptr data_pointer;

	vector<double> v6; ///<internal vector of length 6
	RTT::OutputPort<int > bytes_outport;

	//!@name Ports in service robot_mode_value
	///@{
	RTT::OutputPort<bool > isProgramRunning;
	RTT::OutputPort<bool > isProgramPaused;
	RTT::OutputPort<bool > IsEmergencyStopped;
	///@}

};

#endif


text:
.class Lorg/apache/cordova/CoreAndroid$2;
.super Ljava/lang/Object;
.source "CoreAndroid.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lorg/apache/cordova/CoreAndroid;->clearCache()V
.end annotation

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

# instance fields
.field final synthetic this$0:Lorg/apache/cordova/CoreAndroid;

# direct methods
.method constructor <init>(Lorg/apache/cordova/CoreAndroid;)V
    .locals 0
    .param p1, "this$0"    # Lorg/apache/cordova/CoreAndroid;

    .prologue
    .line 139
    iput-object p1, p0, Lorg/apache/cordova/CoreAndroid$2;->this$0:Lorg/apache/cordova/CoreAndroid;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 2

    .prologue
    .line 141
    iget-object v0, p0, Lorg/apache/cordova/CoreAndroid$2;->this$0:Lorg/apache/cordova/CoreAndroid;

    iget-object v0, v0, Lorg/apache/cordova/CoreAndroid;->webView:Lorg/apache/cordova/CordovaWebView;

    const/4 v1, 0x1

    invoke-interface {v0, v1}, Lorg/apache/cordova/CordovaWebView;->clearCache(Z)V

    .line 142
    return-void
.end method


text:
ActiveAdmin.register_page "Dashboard" do

  IMAGE_SCALING = 0.38

  menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") }

  content do
    div class: "blank_slate_container" do
      height= (865 * IMAGE_SCALING).to_i.to_s
      width= (960 * IMAGE_SCALING).to_i.to_s
      image= '<img src="/osra_logo.jpg" height="' + height + '" width="' + width + '" alt="Welcome to OSRA" />'
      text_node image.html_safe
    end
  end
end


text:
package opsworksiface

import (
	"github.com/awslabs/aws-sdk-go/service/opsworks"
)

// OpsWorksAPI is the interface type for opsworks.OpsWorks.
type OpsWorksAPI interface {
	AssignInstance(*opsworks.AssignInstanceInput) (*opsworks.AssignInstanceOutput, error)

	AssignVolume(*opsworks.AssignVolumeInput) (*opsworks.AssignVolumeOutput, error)

	AssociateElasticIP(*opsworks.AssociateElasticIPInput) (*opsworks.AssociateElasticIPOutput, error)

	AttachElasticLoadBalancer(*opsworks.AttachElasticLoadBalancerInput) (*opsworks.AttachElasticLoadBalancerOutput, error)

	CloneStack(*opsworks.CloneStackInput) (*opsworks.CloneStackOutput, error)

	CreateApp(*opsworks.CreateAppInput) (*opsworks.CreateAppOutput, error)

	CreateDeployment(*opsworks.CreateDeploymentInput) (*opsworks.CreateDeploymentOutput, error)

	CreateInstance(*opsworks.CreateInstanceInput) (*opsworks.CreateInstanceOutput, error)

	CreateLayer(*opsworks.CreateLayerInput) (*opsworks.CreateLayerOutput, error)

	CreateStack(*opsworks.CreateStackInput) (*opsworks.CreateStackOutput, error)

	CreateUserProfile(*opsworks.CreateUserProfileInput) (*opsworks.CreateUserProfileOutput, error)

	DeleteApp(*opsworks.DeleteAppInput) (*opsworks.DeleteAppOutput, error)

	DeleteInstance(*opsworks.DeleteInstanceInput) (*opsworks.DeleteInstanceOutput, error)

	DeleteLayer(*opsworks.DeleteLayerInput) (*opsworks.DeleteLayerOutput, error)

	DeleteStack(*opsworks.DeleteStackInput) (*opsworks.DeleteStackOutput, error)

	DeleteUserProfile(*opsworks.DeleteUserProfileInput) (*opsworks.DeleteUserProfileOutput, error)

	DeregisterElasticIP(*opsworks.DeregisterElasticIPInput) (*opsworks.DeregisterElasticIPOutput, error)

	DeregisterInstance(*opsworks.DeregisterInstanceInput) (*opsworks.DeregisterInstanceOutput, error)

	DeregisterRDSDBInstance(*opsworks.DeregisterRDSDBInstanceInput) (*opsworks.DeregisterRDSDBInstanceOutput, error)

	DeregisterVolume(*opsworks.DeregisterVolumeInput) (*opsworks.DeregisterVolumeOutput, error)

	DescribeApps(*opsworks.DescribeAppsInput) (*opsworks.DescribeAppsOutput, error)

	DescribeCommands(*opsworks.DescribeCommandsInput) (*opsworks.DescribeCommandsOutput, error)

	DescribeDeployments(*opsworks.DescribeDeploymentsInput) (*opsworks.DescribeDeploymentsOutput, error)

	DescribeElasticIPs(*opsworks.DescribeElasticIPsInput) (*opsworks.DescribeElasticIPsOutput, error)

	DescribeElasticLoadBalancers(*opsworks.DescribeElasticLoadBalancersInput) (*opsworks.DescribeElasticLoadBalancersOutput, error)

	DescribeInstances(*opsworks.DescribeInstancesInput) (*opsworks.DescribeInstancesOutput, error)

	DescribeLayers(*opsworks.DescribeLayersInput) (*opsworks.DescribeLayersOutput, error)

	DescribeLoadBasedAutoScaling(*opsworks.DescribeLoadBasedAutoScalingInput) (*opsworks.DescribeLoadBasedAutoScalingOutput, error)

	DescribeMyUserProfile(*opsworks.DescribeMyUserProfileInput) (*opsworks.DescribeMyUserProfileOutput, error)

	DescribePermissions(*opsworks.DescribePermissionsInput) (*opsworks.DescribePermissionsOutput, error)

	DescribeRAIDArrays(*opsworks.DescribeRAIDArraysInput) (*opsworks.DescribeRAIDArraysOutput, error)

	DescribeRDSDBInstances(*opsworks.DescribeRDSDBInstancesInput) (*opsworks.DescribeRDSDBInstancesOutput, error)

	DescribeServiceErrors(*opsworks.DescribeServiceErrorsInput) (*opsworks.DescribeServiceErrorsOutput, error)

	DescribeStackProvisioningParameters(*opsworks.DescribeStackProvisioningParametersInput) (*opsworks.DescribeStackProvisioningParametersOutput, error)

	DescribeStackSummary(*opsworks.DescribeStackSummaryInput) (*opsworks.DescribeStackSummaryOutput, error)

	DescribeStacks(*opsworks.DescribeStacksInput) (*opsworks.DescribeStacksOutput, error)

	DescribeTimeBasedAutoScaling(*opsworks.DescribeTimeBasedAutoScalingInput) (*opsworks.DescribeTimeBasedAutoScalingOutput, error)

	DescribeUserProfiles(*opsworks.DescribeUserProfilesInput) (*opsworks.DescribeUserProfilesOutput, error)

	DescribeVolumes(*opsworks.DescribeVolumesInput) (*opsworks.DescribeVolumesOutput, error)

	DetachElasticLoadBalancer(*opsworks.DetachElasticLoadBalancerInput) (*opsworks.DetachElasticLoadBalancerOutput, error)

	DisassociateElasticIP(*opsworks.DisassociateElasticIPInput) (*opsworks.DisassociateElasticIPOutput, error)

	GetHostnameSuggestion(*opsworks.GetHostnameSuggestionInput) (*opsworks.GetHostnameSuggestionOutput, error)

	RebootInstance(*opsworks.RebootInstanceInput) (*opsworks.RebootInstanceOutput, error)

	RegisterElasticIP(*opsworks.RegisterElasticIPInput) (*opsworks.RegisterElasticIPOutput, error)

	RegisterInstance(*opsworks.RegisterInstanceInput) (*opsworks.RegisterInstanceOutput, error)

	RegisterRDSDBInstance(*opsworks.RegisterRDSDBInstanceInput) (*opsworks.RegisterRDSDBInstanceOutput, error)

	RegisterVolume(*opsworks.RegisterVolumeInput) (*opsworks.RegisterVolumeOutput, error)

	SetLoadBasedAutoScaling(*opsworks.SetLoadBasedAutoScalingInput) (*opsworks.SetLoadBasedAutoScalingOutput, error)

	SetPermission(*opsworks.SetPermissionInput) (*opsworks.SetPermissionOutput, error)

	SetTimeBasedAutoScaling(*opsworks.SetTimeBasedAutoScalingInput) (*opsworks.SetTimeBasedAutoScalingOutput, error)

	StartInstance(*opsworks.StartInstanceInput) (*opsworks.StartInstanceOutput, error)

	StartStack(*opsworks.StartStackInput) (*opsworks.StartStackOutput, error)

	StopInstance(*opsworks.StopInstanceInput) (*opsworks.StopInstanceOutput, error)

	StopStack(*opsworks.StopStackInput) (*opsworks.StopStackOutput, error)

	UnassignInstance(*opsworks.UnassignInstanceInput) (*opsworks.UnassignInstanceOutput, error)

	UnassignVolume(*opsworks.UnassignVolumeInput) (*opsworks.UnassignVolumeOutput, error)

	UpdateApp(*opsworks.UpdateAppInput) (*opsworks.UpdateAppOutput, error)

	UpdateElasticIP(*opsworks.UpdateElasticIPInput) (*opsworks.UpdateElasticIPOutput, error)

	UpdateInstance(*opsworks.UpdateInstanceInput) (*opsworks.UpdateInstanceOutput, error)

	UpdateLayer(*opsworks.UpdateLayerInput) (*opsworks.UpdateLayerOutput, error)

	UpdateMyUserProfile(*opsworks.UpdateMyUserProfileInput) (*opsworks.UpdateMyUserProfileOutput, error)

	UpdateRDSDBInstance(*opsworks.UpdateRDSDBInstanceInput) (*opsworks.UpdateRDSDBInstanceOutput, error)

	UpdateStack(*opsworks.UpdateStackInput) (*opsworks.UpdateStackOutput, error)

	UpdateUserProfile(*opsworks.UpdateUserProfileInput) (*opsworks.UpdateUserProfileOutput, error)

	UpdateVolume(*opsworks.UpdateVolumeInput) (*opsworks.UpdateVolumeOutput, error)
}


text:
from .tokenbox import Tokenbox

__all__ = ['Tokenbox']


text:
Spree::Variant.class_eval do

  has_many :variant_shipping_rates

end


text:
package getter

import (
	"errors"
	"fmt"
	"github.com/goharbor/harbor/src/lib/orm"
	"github.com/goharbor/harbor/src/pkg/joblog"

	"github.com/goharbor/harbor/src/jobservice/errs"
)

// DBGetter is responsible for retrieving DB log data
type DBGetter struct {
}

// NewDBGetter is constructor of DBGetter
func NewDBGetter() *DBGetter {
	return &DBGetter{}
}

// Retrieve implements @Interface.Retrieve
func (dbg *DBGetter) Retrieve(logID string) ([]byte, error) {
	if len(logID) == 0 {
		return nil, errors.New("empty log identify")
	}

	jobLog, err := joblog.Mgr.Get(orm.Context(), logID)
	if err != nil {
		// Other errors have been ignored by GetJobLog()
		return nil, errs.NoObjectFoundError(fmt.Sprintf("log entity: %s", logID))
	}

	return []byte(jobLog.Content), nil
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Interface org.springframework.jms.support.converter.MessageConverter (Spring Framework API 2.5)
</TITLE>

<META NAME="date" CONTENT="2007-11-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
org.springframework.jms.support.converter.MessageConverter

Packages that use MessageConverter

org.springframework.jms.core
Core package of the JMS support.

org.springframework.jms.listener.adapter
Message listener adapter mechanism that delegates to target listener
methods, converting messages to appropriate message content types
(such as String or byte array) that get passed into listener methods.

org.springframework.jms.remoting
Remoting classes for transparent Java-to-Java remoting via a JMS provider.

org.springframework.jms.support.converter
Provides a MessageConverter abstraction to convert
between Java objects and JMS messages.

Uses of MessageConverter in org.springframework.jms.core

Methods in org.springframework.jms.core that return MessageConverter

 MessageConverter
JmsTemplate.getMessageConverter()

          Return the message converter for this template.

Methods in org.springframework.jms.core with parameters of type MessageConverter

 void
JmsTemplate.setMessageConverter(MessageConverter messageConverter)

          Set the message converter for this template.

Uses of MessageConverter in org.springframework.jms.listener.adapter

Methods in org.springframework.jms.listener.adapter that return MessageConverter

protected  MessageConverter
MessageListenerAdapter.getMessageConverter()

          Return the converter that will convert incoming JMS messages to
 listener method arguments, and objects returned from listener
 methods back to JMS messages.

Methods in org.springframework.jms.listener.adapter with parameters of type MessageConverter

 void
MessageListenerAdapter.setMessageConverter(MessageConverter messageConverter)

          Set the converter that will convert incoming JMS messages to
 listener method arguments, and objects returned from listener
 methods back to JMS messages.

Uses of MessageConverter in org.springframework.jms.remoting

Methods in org.springframework.jms.remoting with parameters of type MessageConverter

 void
JmsInvokerClientInterceptor.setMessageConverter(MessageConverter messageConverter)

          Specify the MessageConverter to use for turning
 RemoteInvocation
 objects into request messages, as well as response messages into
 RemoteInvocationResult objects.

 void
JmsInvokerServiceExporter.setMessageConverter(MessageConverter messageConverter)

          Specify the MessageConverter to use for turning request messages into
 RemoteInvocation objects,
 as well as RemoteInvocationResult
 objects into response messages.

Uses of MessageConverter in org.springframework.jms.support.converter

Classes in org.springframework.jms.support.converter that implement MessageConverter

 class
SimpleMessageConverter

          A simple message converter which is able to handle TextMessages, BytesMessages,
 MapMessages, and ObjectMessages.

 class
SimpleMessageConverter102

          A subclass of SimpleMessageConverter for the JMS 1.0.2 specification,
 not relying on JMS 1.1 methods like SimpleMessageConverter itself.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2002-2007 The Spring Framework.


text:
var gulp = require('gulp'),
	path = require('path'),
	jshintReporter = require('jshint-stylish'),
	plugins = require('gulp-load-plugins')({
		config: path.join(__dirname, 'package.json')
	});

var path = {
	src: {
		files: ['src/**/*.js']
	},
	lib: {
		files: [
			'bower_components/string-mask/src/string-mask.js',
			'bower_components/br-validations/releases/br-validations.js'
		]
	}
}

gulp.task('jshint', function() {
	gulp.src(path.src.files)
	.pipe(plugins.jshint('.jshintrc'))
	.pipe(plugins.jshint.reporter(jshintReporter));
});

gulp.task('build', function() {
	var pkg = require('./package.json');

	var header = ['/**',
		' * <%= pkg.name %>',
		' * <%= pkg.description %>',
		' * @version v<%= pkg.version %>',
		' * @link <%= pkg.homepage %>',
		' * @license <%= pkg.license %>',
		' */',
		'(function (angular) {',
		'',
		''].join('\n');

	var footer = [
		'',
		'})(angular);',
		''].join('\n');

	gulp.src(
		path.lib.files.concat(path.src.files)
	)
	.pipe(plugins.concat('masks.js'))
	.pipe(plugins.header(header, {pkg: pkg}))
	.pipe(plugins.footer(footer))
	.pipe(gulp.dest('./releases/'))
	.pipe(plugins.uglify())
	.pipe(plugins.concat('masks.min.js'))
	.pipe(gulp.dest('./releases/'));
});

gulp.task('default', ['jshint', 'build'], function() {
	gulp.watch(path.src.files, ['jshint', 'build']);
});

gulp.task('webdriver_update', require('gulp-protractor').webdriver_update);
gulp.task('webdriver_standalone', ['webdriver_update'], require('gulp-protractor').webdriver_standalone);

gulp.task('serve', ['build'], function() {
	var express = require('express');
	var server = express();

	server.use(express.static('./'));
	server.listen(8000, function() {
		console.log('Server running in port 8000');
	});
});

gulp.task('test', ['webdriver_update', 'serve'], function() {
	var protractor = require('gulp-protractor').protractor;

	gulp.src(['./test/spec.js'])
	.pipe(protractor({
		configFile: 'test/conf.js'
	}))
	.on('error', function(e) { throw e });
});


text:
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.*;

/**
 * 类名     :CallableFuture1
 * 项目名称 :java8-tutorial
 * 创建时间 :2017/5/2
 * 作     者:sd-wangtaicheng@sdcncsi.com.cn
 * 版     本:v1
 */
public class CallableFuture1 {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        Future<Integer> result = executor.submit(task);
        executor.shutdown();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        System.out.println("主线程在执行任务");

        try {
            System.out.println("task运行结果" + result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }
}

class Task implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("子线程在进行计算");
        Thread.sleep(3000);
        int sum = 0;
        for (int i = 0; i < 100; i++)
            sum += i;
        return sum;
    }
}


text:
"""ASCII Printer"""
from ..utils.singleton import Singleton
from ..algebra.core.exceptions import BasisNotSetError
from .base import QnetBasePrinter
from .sympy import SympyStrPrinter
from ._precedence import precedence, PRECEDENCE

__all__ = []
__private__ = ['QnetAsciiPrinter', 'QnetAsciiDefaultPrinter']

class QnetAsciiPrinter(QnetBasePrinter):
    """Printer for a string (ASCII) representation.

    Attributes:
        _parenth_left (str): String to use for a left parenthesis
            (e.g. '\left(' in LaTeX). Used by :meth:`_split_op`
        _parenth_left (str): String to use for a right parenthesis
        _dagger_sym (str): Symbol that indicates the complex conjugate of an
            operator. Used by :meth:`_split_op`
        _tensor_sym (str): Symbol to use for tensor products. Used by
            :meth:`_render_hs_label`.
    """
    sympy_printer_cls = SympyStrPrinter
    printmethod = '_ascii'

    _default_settings = {
        'show_hs_label': True,  # alternatively: False, 'subscript'
        'sig_as_ketbra': True,
    }

    _parenth_left = '('
    _parenth_right = ')'
    _bracket_left = '['
    _bracket_right = ']'
    _dagger_sym = 'H'
    _tensor_sym = '*'
    _product_sym = '*'
    _circuit_series_sym = "<<"
    _circuit_concat_sym = "+"
    _cid = 'cid(%d)'
    _sum_sym = 'Sum'
    _element_sym = 'in'
    _ellipsis = '...'
    _set_delim_left = '{'
    _set_delim_right = '}'

    @property
    def _spaced_product_sym(self):
        if len(self._product_sym.strip()) == 0:
            return self._product_sym
        else:
            return " %s " % self._product_sym

    def _split_identifier(self, identifier):
        """Split the given identifier at the first underscore into (rendered)
        name and subscript. Both `name` and `subscript` are rendered as
        strings"""
        try:
            name, subscript = identifier.split("_", 1)
        except (TypeError, ValueError, AttributeError):
            name = identifier
            subscript = ''
        return self._render_str(name), self._render_str(subscript)

    def _split_op(
            self, identifier, hs_label=None, dagger=False, args=None):
        """Return `name`, total `subscript`, total `superscript` and
        `arguments` str. All of the returned strings are fully rendered.

        Args:
            identifier (str or SymbolicLabelBase): A (non-rendered/ascii)
                identifier that may include a subscript. The output `name` will
                be the `identifier` without any subscript
            hs_label (str): The rendered label for the Hilbert space of the
                operator, or None. Returned unchanged.
            dagger (bool): Flag to indicate whether the operator is daggered.
                If True, :attr:`dagger_sym` will be included in the
                `superscript` (or  `subscript`, depending on the settings)
            args (list or None): List of arguments (expressions). Each element
                will be rendered with :meth:`doprint`. The total list of args
                will then be joined with commas, enclosed
                with :attr:`_parenth_left` and :attr:`parenth_right`, and
                returnd as the `arguments` string
        """
        if self._isinstance(identifier, 'SymbolicLabelBase'):
            identifier = QnetAsciiDefaultPrinter()._print_SCALAR_TYPES(
                identifier.expr)
        name, total_subscript = self._split_identifier(identifier)
        total_superscript = ''
        if (hs_label not in [None, '']):
            if self._settings['show_hs_label'] == 'subscript':
                if len(total_subscript) == 0:
                    total_subscript = '(' + hs_label + ')'
                else:
                    total_subscript += ',(' + hs_label + ')'
            else:
                total_superscript += '(' + hs_label + ')'
        if dagger:
            total_superscript += self._dagger_sym
        args_str = ''
        if (args is not None) and (len(args) > 0):
            args_str = (self._parenth_left +
                        ",".join([self.doprint(arg) for arg in args]) +
                        self._parenth_right)
        return name, total_subscript, total_superscript, args_str

    @classmethod
    def _is_single_letter(cls, label):
        return len(label) == 1

    def _render_hs_label(self, hs):
        """Return the label of the given Hilbert space as a string"""
        if isinstance(hs.__class__, Singleton):
            return self._render_str(hs.label)
        else:
            return self._tensor_sym.join(
                [self._render_str(ls.label) for ls in hs.local_factors])

    def _render_state_label(self, label):
        if self._isinstance(label, 'SymbolicLabelBase'):
            return self._print_SCALAR_TYPES(label.expr)
        else:
            return self._render_str(label)

    def _braket_fmt(self, expr_type):
        """Return a format string for printing an `expr_type`
        ket/bra/ketbra/braket"""
        mapping = {
            'bra': {
                True: '<{label}|^({space})',
                'subscript': '<{label}|_({space})',
                False:  '<{label}|'},
            'ket': {
                True: '|{label}>^({space})',
                'subscript': '|{label}>_({space})',
                False:  '|{label}>'},
            'ketbra': {
                True: '|{label_i}><{label_j}|^({space})',
                'subscript': '|{label_i}><{label_j}|_({space})',
                False:  '|{label_i}><{label_j}|'},
            'braket': {
                True: '<{label_i}|{label_j}>^({space})',
                'subscript': '<{label_i}|{label_j}>_({space})',
                False:  '<{label_i}|{label_j}>'},
        }
        hs_setting = bool(self._settings['show_hs_label'])
        if self._settings['show_hs_label'] == 'subscript':
            hs_setting = 'subscript'
        return mapping[expr_type][hs_setting]

    def _render_op(
            self, identifier, hs=None, dagger=False, args=None, superop=False):
        """Render an operator

        Args:
            identifier (str or SymbolicLabelBase): The identifier (name/symbol)
                of the operator. May include a subscript, denoted by '_'.
            hs (qnet.algebra.hilbert_space_algebra.HilbertSpace): The Hilbert
                space in which the operator is defined
            dagger (bool): Whether the operator should be daggered
            args (list): A list of expressions that will be rendered with
                :meth:`doprint`, joined with commas, enclosed in parenthesis
            superop (bool): Whether the operator is a super-operator
        """
        hs_label = None
        if hs is not None and self._settings['show_hs_label']:
            hs_label = self._render_hs_label(hs)
        name, total_subscript, total_superscript, args_str \
            = self._split_op(identifier, hs_label, dagger, args)
        res = name
        if len(total_subscript) > 0:
            res += "_" + total_subscript
        if len(total_superscript) > 0:
            res += "^" + total_superscript
        if len(args_str) > 0:
            res += args_str
        return res

    def parenthesize(self, expr, level, *args, strict=False, **kwargs):
        """Render `expr` and wrap the result in parentheses if the precedence
        of `expr` is below the given `level` (or at the given `level` if
        `strict` is True. Extra `args` and `kwargs` are passed to the internal
        `doit` renderer"""
        needs_parenths = (
            (precedence(expr) < level) or
            (strict and precedence(expr) == level))
        if needs_parenths:
            return (
                self._parenth_left + self.doprint(expr, *args, **kwargs) +
                self._parenth_right)
        else:
            return self.doprint(expr, *args, **kwargs)

    def _print_tuple(self, expr):
        return (
            self._parenth_left + ", ".join([self.doprint(c) for c in expr])
            + self._parenth_right)

    def _print_list(self, expr):
        return (
            self._bracket_left + ", ".join([self.doprint(c) for c in expr])
            + self._bracket_right)

    def _print_CircuitSymbol(self, expr):
        res = self._render_str(expr.label)
        if len(expr.sym_args) > 0:
            res += (
                self._parenth_left +
                ", ".join([self.doprint(arg) for arg in expr.sym_args]) +
                self._parenth_right)
        return res

    def _print_CPermutation(self, expr):
        return r'Perm(%s)' % (
                ", ".join(map(self._render_str, expr.permutation)))

    def _print_SeriesProduct(self, expr):
        prec = precedence(expr)
        circuit_series_sym = " " + self._circuit_series_sym + " "
        return circuit_series_sym.join(
            [self.parenthesize(op, prec) for op in expr.operands])

    def _print_Concatenation(self, expr):
        prec = precedence(expr)
        reduced_operands = []  # reduce consecutive identities to a str
        id_count = 0
        for o in expr.operands:
            if self._isinstance(o, 'CIdentity'):
                id_count += 1
            else:
                if id_count > 0:
                    reduced_operands.append(self._cid % id_count)
                    id_count = 0
                reduced_operands.append(o)
        if id_count > 0:
            reduced_operands.append(self._cid % id_count)
        circuit_concat_sym = " " + self._circuit_concat_sym + " "
        parts = []
        for op in reduced_operands:
            if self._isinstance(op, 'SeriesProduct'):
                # while a SeriesProduct has a higher precedence than a
                # Concatenation, for most readers, extra parentheses will be
                # helpful
                # TODO: make this an option
                parts.append(
                    self._parenth_left + self.doprint(op) +
                    self._parenth_right)
            else:
                parts.append(self.parenthesize(op, prec))
        return circuit_concat_sym.join(parts)

    def _print_Feedback(self, expr):
        o, i = expr.out_in_pair
        return '[{operand}]_{{{output}->{input}}}'.format(
            operand=self.doprint(expr.operand), output=o, input=i)

    def _print_SeriesInverse(self, expr):
        return r'[{operand}]^{{-1}}'.format(
            operand=self.doprint(expr.operand))

    def _print_HilbertSpace(self, expr):
        return r'H_{label}'.format(
            label=self._render_hs_label(expr))

    def _print_ProductSpace(self, expr):
        tensor_sym = " " + self._tensor_sym + " "
        return tensor_sym.join(
            [self.doprint(op) for op in expr.operands])

    def _print_OperatorSymbol(self, expr, adjoint=False):
        res = self._render_op(expr.label, expr._hs, dagger=adjoint)
        if len(expr.sym_args) > 0:
            res += (
                self._parenth_left +
                ", ".join([self.doprint(arg) for arg in expr.sym_args]) +
                self._parenth_right)
        return res

    def _print_LocalOperator(self, expr, adjoint=False):
        if adjoint:
            dagger = not expr._dagger
        else:
            dagger = expr._dagger
        return self._render_op(
            expr.identifier, expr._hs, dagger=dagger, args=expr.args)

    def _print_LocalSigma(self, expr, adjoint=False):
        if self._settings['sig_as_ketbra']:
            fmt = self._braket_fmt('ketbra')
            if adjoint:
                return fmt.format(
                    label_i=self._render_state_label(expr.k),
                    label_j=self._render_state_label(expr.j),
                    space=self._render_hs_label(expr.space))
            else:
                return fmt.format(
                    label_i=self._render_state_label(expr.j),
                    label_j=self._render_state_label(expr.k),
                    space=self._render_hs_label(expr.space))
        else:
            if expr.j == expr.k:
                identifier = "%s_%s" % (expr._identifier_projector, expr.j)
            else:
                if adjoint:
                    identifier = "%s_%s,%s" % (expr.identifier, expr.k, expr.j)
                else:
                    identifier = "%s_%s,%s" % (expr.identifier, expr.j, expr.k)
            return self._render_op(identifier, expr._hs, dagger=adjoint)

    def _print_IdentityOperator(self, expr):
        return "1"

    def _print_ZeroOperator(self, expr):
        return "0"

    def _print_ScalarValue(self, expr, **kwargs):
        return self.doprint(expr.val, **kwargs)

    def _print_Zero(self, expr, **kwargs):
        return "0"

    def _print_One(self, expr, **kwargs):
        return "1"

    def _print_ScalarTimesQuantumExpression(self, expr, **kwargs):
        prec = PRECEDENCE['Mul']
        coeff, term = expr.coeff, expr.term
        term_str = self.doprint(term, **kwargs)
        if precedence(term) < prec:
            term_str = self._parenth_left + term_str + self._parenth_right

        if coeff == -1:
            if term_str.startswith(self._parenth_left):
                return "- " + term_str
            else:
                return "-" + term_str
        if 'adjoint' in kwargs:
            coeff_str = self.doprint(coeff, adjoint=kwargs['adjoint'])
        else:
            coeff_str = self.doprint(coeff)

        if term_str in [
                '1', self._print_IdentityOperator(expr),
                self._print_IdentitySuperOperator]:
            return coeff_str
        else:
            coeff_str = coeff_str.strip()
            if precedence(coeff) < prec and precedence(-coeff) < prec:
                # the above precedence check catches on only for true sums
                coeff_str = (
                    self._parenth_left + coeff_str + self._parenth_right)
            return coeff_str + self._spaced_product_sym + term_str.strip()

    def _print_QuantumPlus(self, expr, adjoint=False, superop=False):
        prec = precedence(expr)
        l = []
        kwargs = {}
        if adjoint:
            kwargs['adjoint'] = adjoint
        if superop:
            kwargs['superop'] = superop
        for term in expr.args:
            t = self.doprint(term, **kwargs)
            if t.startswith('-'):
                sign = "-"
                t = t[1:].strip()
            else:
                sign = "+"
            if precedence(term) < prec:
                l.extend([sign, self._parenth_left + t + self._parenth_right])
            else:
                l.extend([sign, t])
        try:
            sign = l.pop(0)
            if sign == '+':
                sign = ""
        except IndexError:
            sign = ""
        return sign + ' '.join(l)

    def _print_QuantumTimes(self, expr, **kwargs):
        prec = precedence(expr)
        return self._spaced_product_sym.join(
            [self.parenthesize(op, prec, **kwargs) for op in expr.operands])

    def _print_Commutator(self, expr, adjoint=False):
        res = "[" + self.doprint(expr.A) + ", " + self.doprint(expr.B) + "]"
        if adjoint:
            res += "^" + self._dagger_sym
        return res

    def _print_OperatorTrace(self, expr, adjoint=False):
        s = self._render_hs_label(expr._over_space)
        kwargs = {}
        if adjoint:
            kwargs['adjoint'] = adjoint
        o = self.doprint(expr.operand, **kwargs)
        return r'tr_({space})[{operand}]'.format(space=s, operand=o)

    def _print_Adjoint(self, expr, adjoint=False):
        o = expr.operand
        if self._isinstance(o, 'LocalOperator'):
            if adjoint:
                dagger = o._dagger
            else:
                dagger = not o._dagger
            return self._render_op(
                o.identifier, hs=o.space, dagger=dagger, args=o.args[1:])
        elif self._isinstance(o, 'OperatorSymbol'):
            return self._render_op(
                o.label, hs=o.space, dagger=(not adjoint))
        else:
            if adjoint:
                return self.doprint(o)
            else:
                return (
                    self._parenth_left + self.doprint(o) +
                    self._parenth_right + "^" + self._dagger_sym)

    def _print_OperatorPlusMinusCC(self, expr):
        prec = precedence(expr)
        o = expr.operand
        sign_str = ' + '
        if expr._sign < 0:
            sign_str = ' - '
        return self.parenthesize(o, prec) + sign_str + "c.c."

    def _print_PseudoInverse(self, expr):
        prec = precedence(expr)
        return self.parenthesize(expr.operand, prec) + "^+"

    def _print_NullSpaceProjector(self, expr, adjoint=False):
        null_space_proj_sym = 'P_Ker'
        return self._render_op(
            null_space_proj_sym, hs=None, args=expr.operands, dagger=adjoint)

    def _print_KetSymbol(self, expr, adjoint=False):
        if adjoint:
            fmt = self._braket_fmt('bra')
        else:
            fmt = self._braket_fmt('ket')
        label = self._render_state_label(expr.label)
        if len(expr.sym_args) > 0:
            label += (
                self._parenth_left +
                ", ".join([self.doprint(arg) for arg in expr.sym_args]) +
                self._parenth_right)
        return fmt.format(
            label=label, space=self._render_hs_label(expr.space))

    def _print_ZeroKet(self, expr, adjoint=False):
        return "0"

    def _print_TrivialKet(self, expr, adjoint=False):
        return "1"

    def _print_CoherentStateKet(self, expr, adjoint=False):
        if adjoint:
            fmt = self._braket_fmt('bra')
        else:
            fmt = self._braket_fmt('ket')
        label = self._render_state_label('alpha=') + self.doprint(expr._ampl)
        space = self._render_hs_label(expr.space)
        return fmt.format(label=label, space=space)

    def _print_TensorKet(self, expr, adjoint=False):
        if all(self._isinstance(o, 'BasisKet') for o in expr.operands):
            labels = [self._render_state_label(o.label) for o in expr.operands]
            single_letters = all([self._is_single_letter(l) for l in labels])
            try:
                small_hs = all(
                    [(o.space.dimension < 10) for o in expr.operands])
            except BasisNotSetError:
                small_hs = False
            if small_hs and single_letters:
                joiner = ""
            else:
                joiner = ","
            label = joiner.join(labels)
            fmt = self._braket_fmt('ket')
            if adjoint:
                fmt = self._braket_fmt('bra')
            space = self._render_hs_label(expr.space)
            return fmt.format(label=label, space=space)
        else:
            prec = precedence(expr)
            kwargs = {}
            if adjoint:
                kwargs['adjoint'] = adjoint
            tensor_sym = " %s " % self._tensor_sym
            return tensor_sym.join([
                self.parenthesize(op, prec, **kwargs)
                for op in expr.operands])

    def _print_OperatorTimesKet(self, expr, adjoint=False):
        prec = precedence(expr)
        op, ket = expr.operator, expr.ket
        kwargs = {}
        if adjoint:
            kwargs['adjoint'] = adjoint
        rendered_op = self.parenthesize(op, prec, **kwargs)
        rendered_ket = self.parenthesize(ket, prec, **kwargs)
        if adjoint:
            return rendered_ket + " " + rendered_op
        else:
            return rendered_op + " " + rendered_ket

    def _print_IndexedSum(self, expr, adjoint=False):
        prec = precedence(expr)
        kwargs = {}
        if adjoint:
            kwargs['adjoint'] = adjoint
        indices = []
        bottom_rhs = None
        top = None
        res = ''
        # ranges with the same limits are grouped into the same sum symbol
        for index_range in expr.ranges:
            current_index = self.doprint(index_range, which='bottom_index')
            current_bottom_rhs = self.doprint(index_range, which='bottom_rhs')
            current_top = self.doprint(index_range, which='top')
            if top is not None:  # index_ranges after the first one
                if current_top != top or current_bottom_rhs != bottom_rhs:
                    res += self._sum_sym
                    bottom = ",".join(indices) + bottom_rhs
                    if len(bottom) > 0:
                        res += '_{%s}' % bottom
                    if len(top) > 0:
                        res += '^{%s}' % top
                    res += " "
                    indices = [current_index, ]
                    top = current_top
                    bottom_rhs = current_bottom_rhs
                else:
                    indices.append(current_index)
            else:  # first range
                indices.append(current_index)
                top = current_top
                bottom_rhs = current_bottom_rhs
        # add the final accumulated sum symbol
        res += self._sum_sym
        bottom = ",".join(indices) + bottom_rhs
        if len(bottom) > 0:
            res += '_{%s}' % bottom
        if len(top) > 0:
            res += '^{%s}' % top
        res += " " + self.parenthesize(expr.term, prec, strict=True, **kwargs)
        return res

    def _print_IndexRangeBase(self, expr, which='bottom'):
        assert which in ['bottom', 'bottom_index', 'bottom_rhs', 'top']
        if which in ['bottom', 'bottom_index']:
            return self.doprint(expr.index_symbol)
        else:
            return ''

    def _print_IndexOverFockSpace(self, expr, which='bottom'):
        assert which in ['bottom', 'bottom_index', 'bottom_rhs', 'top']
        if 'bottom' in which:
            bottom_index = self.doprint(expr.index_symbol)
            bottom_rhs = " " + self._element_sym + " " + self.doprint(expr.hs)
            if which == 'bottom_index':
                return bottom_index
            elif which == 'bottom_rhs':
                return bottom_rhs
            else:
                return bottom_index + bottom_rhs
        elif which == 'top':
            return ''
        else:
            raise ValueError("invalid `which`: %s" % which)

    def _print_IndexOverList(self, expr, which='bottom'):
        assert which in ['bottom', 'bottom_index', 'bottom_rhs', 'top']
        if 'bottom' in which:
            bottom_index = self.doprint(expr.index_symbol)
            bottom_rhs = (
                " " + self._element_sym + " " + self._set_delim_left +
                ",".join([self.doprint(val) for val in expr.values]) +
                self._set_delim_right)
            if which == 'bottom_index':
                return bottom_index
            elif which == 'bottom_rhs':
                return bottom_rhs
            else:
                return bottom_index + bottom_rhs
        elif which == 'top':
            return ''
        else:
            raise ValueError("invalid `which`: %s" % which)

    def _print_IndexOverRange(self, expr, which='bottom'):
        assert which in ['bottom', 'bottom_index', 'bottom_rhs', 'top']
        if 'bottom' in which:
            bottom_index = self.doprint(expr.index_symbol)
            bottom_rhs = "=%s" % expr.start_from
            if abs(expr.step) > 1:
                bottom_rhs += ", %s" % expr.start_from + expr.step
                bottom_rhs += ", " + self._ellipsis
            if which == 'bottom_index':
                return bottom_index
            elif which == 'bottom_rhs':
                return bottom_rhs
            else:
                return bottom_index + bottom_rhs
        elif which == 'top':
            return str(expr.to)
        else:
            raise ValueError("invalid `which`: %s" % which)

    def _print_BaseLabel(self, expr):
        return self.doprint(expr.expr)

    def _print_Bra(self, expr, adjoint=False):
        return self.doprint(expr.ket, adjoint=(not adjoint))

    def _print_BraKet(self, expr, adjoint=False):
        trivial = True
        try:
            bra_label = self._render_state_label(expr.bra.label)
            bra = expr.bra.ket
            if hasattr(bra, 'sym_args') and len(bra.sym_args) > 0:
                bra_label += (
                    self._parenth_left +
                    ", ".join([self.doprint(arg) for arg in bra.sym_args]) +
                    self._parenth_right)
        except AttributeError:
            trivial = False
        try:
            ket_label = self._render_state_label(expr.ket.label)
            if hasattr(expr.ket, 'sym_args') and len(expr.ket.sym_args) > 0:
                ket_label += (
                    self._parenth_left +
                    ", ".join(
                        [self.doprint(arg) for arg in expr.ket.sym_args]) +
                    self._parenth_right)
        except AttributeError:
            trivial = False
        if trivial:
            fmt = self._braket_fmt('braket')
            if adjoint:
                return fmt.format(
                    label_i=ket_label, label_j=bra_label,
                    space=self._render_hs_label(expr.ket.space))
            else:
                return fmt.format(
                    label_i=bra_label, label_j=ket_label,
                    space=self._render_hs_label(expr.ket.space))
        else:
            prec = precedence(expr)
            rendered_bra = self.parenthesize(expr.bra, prec, adjoint=adjoint)
            rendered_ket = self.parenthesize(expr.ket, prec, adjoint=adjoint)
            if adjoint:
                return rendered_ket + self._spaced_product_sym + rendered_bra
            else:
                return rendered_bra + self._spaced_product_sym + rendered_ket

    def _print_KetBra(self, expr, adjoint=False):
        trivial = True
        try:
            bra_label = self._render_state_label(expr.bra.label)
            bra = expr.bra.ket
            if hasattr(bra, 'sym_args') and len(bra.sym_args) > 0:
                bra_label += (
                    self._parenth_left +
                    ", ".join([self.doprint(arg) for arg in bra.sym_args]) +
                    self._parenth_right)
        except AttributeError:
            trivial = False
        try:
            ket_label = self._render_state_label(expr.ket.label)
            if hasattr(expr.ket, 'sym_args') and len(expr.ket.sym_args) > 0:
                ket_label += (
                    self._parenth_left +
                    ", ".join(
                        [self.doprint(arg) for arg in expr.ket.sym_args]) +
                    self._parenth_right)
        except AttributeError:
            trivial = False
        if trivial:
            fmt = self._braket_fmt('ketbra')
            if adjoint:
                return fmt.format(
                    label_i=bra_label, label_j=ket_label,
                    space=self._render_hs_label(expr.ket.space))
            else:
                return fmt.format(
                    label_i=ket_label, label_j=bra_label,
                    space=self._render_hs_label(expr.ket.space))
        else:
            prec = precedence(expr)
            rendered_bra = self.parenthesize(expr.bra, prec, adjoint=adjoint)
            rendered_ket = self.parenthesize(expr.ket, prec, adjoint=adjoint)
            if adjoint:
                return rendered_bra + rendered_ket
            else:
                return rendered_ket + rendered_bra

    def _print_SuperOperatorSymbol(self, expr, adjoint=False, superop=True):
        res = self._render_op(
            expr.label, expr._hs, dagger=adjoint, superop=True)
        if len(expr.sym_args) > 0:
            res += (
                self._parenth_left +
                ", ".join([self.doprint(arg) for arg in expr.sym_args]) +
                self._parenth_right)
        return res

    def _print_IdentitySuperOperator(self, expr, superop=True):
        return "1"

    def _print_ZeroSuperOperator(self, expr, superop=True):
        return "0"

    def _print_SuperOperatorPlus(self, expr, adjoint=False, superop=True):
        return self._print_QuantumPlus(expr, adjoint=adjoint, superop=True)

    def _print_SuperOperatorTimes(self, expr, adjoint=False, superop=True):
        kwargs = {}
        if adjoint:
            kwargs['adjoint'] = True
        return self._print_QuantumTimes(expr, superop=True, **kwargs)

    def _print_SuperAdjoint(self, expr, adjoint=False, superop=True):
        o = expr.operand
        if self._isinstance(o, 'SuperOperatorSymbol'):
            return self._render_op(
                o.label, hs=o.space, dagger=(not adjoint), superop=True)
        else:
            if adjoint:
                return self.doprint(o)
            else:
                return (
                    self._parenth_left + self.doprint(o) +
                    self._parenth_right + "^" + self._dagger_sym)

    def _print_SPre(self, expr, superop=True):
        return (
            "SPre" + self._parenth_left + self.doprint(expr.operands[0]) +
            self._parenth_right)

    def _print_SPost(self, expr, superop=True):
        return (
            "SPost" + self._parenth_left + self.doprint(expr.operands[0]) +
            self._parenth_right)

    def _print_SuperOperatorTimesOperator(self, expr):
        prec = precedence(expr)
        sop, op = expr.sop, expr.op
        cs = self.parenthesize(sop, prec)
        ct = self.doprint(op)
        return "%s[%s]" % (cs, ct)

    def _print_QuantumDerivative(self, expr):
        res = ""
        for sym, n in expr.derivs.items():
            sym_str = self.doprint(sym)
            if " " in sym_str:
                sym_str = "(%s)" % sym_str
            if n == 1:
                res += "D_%s " % sym_str
            else:
                res += "D_%s^%s " % (sym_str, n)
        res += self.parenthesize(expr.operand, PRECEDENCE['Mul'], strict=True)
        if expr.vals:
            evaluation_strs = []
            for sym, val in expr.vals.items():
                evaluation_strs.append(
                    "%s=%s" % (self.doprint(sym), self.doprint(val)))
            res += " |_(%s)" % ", ".join(evaluation_strs)
        return res

    def _print_Matrix(self, expr):
        matrix_left_sym = '['
        matrix_right_sym = ']'
        matrix_row_left_sym = '['
        matrix_row_right_sym = ']'
        matrix_col_sep_sym = ', '
        matrix_row_sep_sym = ', '
        row_strs = []
        if len(expr.matrix) == 0:
            row_strs.append(matrix_row_left_sym + matrix_row_right_sym)
            row_strs.append(matrix_row_left_sym + matrix_row_right_sym)
        else:
            for row in expr.matrix:
                row_strs.append(
                    matrix_row_left_sym +
                    matrix_col_sep_sym.join(
                        [self.doprint(entry) for entry in row]) +
                    matrix_row_right_sym)
        return (
            matrix_left_sym + matrix_row_sep_sym.join(row_strs) +
            matrix_right_sym)

    def _print_Eq(self, expr):
        # print for qnet.algebra.toolbox.equality.Eq, but also works for any
        # Eq class that has the minimum requirement to have an `lhs` and `rhs`
        # attribute
        try:
            return expr._render_str(renderer=self.doprint)
        except AttributeError:
            return (self.doprint(expr.lhs) + ' = ' + self.doprint(expr.rhs))

class QnetAsciiDefaultPrinter(QnetAsciiPrinter):
    """Printer for an ASCII representation that accepts no settings. This can
    be used internally when a well-defined, static representation is needed
    (e.g. as a sort key)"""
    _default_settings = {}

    def __init__(self):
        super().__init__(cache=None, settings=None)
        self._settings = {
            'show_hs_label': True,
            'sig_as_ketbra': True}


text:
import {TwingNodeExpression} from "../expression";

import {TwingCompiler} from "../../compiler";
import {TwingNodeType} from "../../node";

export class TwingNodeExpressionParent extends TwingNodeExpression {
    constructor(name: string, lineno: number) {
        let attributes = new Map();

        attributes.set('output', false);
        attributes.set('name', name);

        super(new Map(), attributes, lineno);

        this.type = TwingNodeType.EXPRESSION_PARENT;
    }

    compile(compiler: TwingCompiler) {
        let name = this.getAttribute('name');

        if (this.getAttribute('output')) {
            compiler
                .write(`await this.traceableDisplayParentBlock(${this.getTemplateLine()}, this.getSourceContext())(`)
                .string(name)
                .raw(", context, blocks);\n")
            ;
        }
        else {
            compiler
                .raw(`this.traceableRenderParentBlock(${this.getTemplateLine()}, this.getSourceContext())(`)
                .string(name)
                .raw(', context, blocks)')
            ;
        }
    }
}


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

using Hydra.Framework;
using Hydra.Framework.Helpers;
using Hydra.Framework.Conversions;
using DataModel = Hydra.Data.Model;
using DomainModel = Hydra.DomainModel;

namespace Hydra.Domain.Mapping
{
    public class IdentitySubscriptionMapping
        : IEntityMapper<DataModel.IdentitySubscription, DomainModel.InternalIdentitySubscription>
    {
        #region Implementation of IEntityMapper
        /// <summary>
        /// Convert Domain Model Entity to Data Model Entity
        /// </summary>
        /// <param name="entity">Domain Model Entity</param>
        /// <returns></returns>
        public DataModel.IdentitySubscription MapDomainEntityToDataEntity(DomainModel.InternalIdentitySubscription entity)
        {
            DataModel.IdentitySubscription item = entity == null
                ? null
                : new DataModel.IdentitySubscription()
                {
                    ID = entity.ID,
                    HashKey = entity.HashKey,
                    Token = entity.Token,
                    UserName = entity.UserName
                };

            return item;
        }

        /// <summary>
        /// Convert Data Model Entity to Domain Model Entity
        /// </summary>
        /// <param name="entity">Data Model Entity</param>
        /// <returns>Domain Model Entity</returns>
        public DomainModel.InternalIdentitySubscription MapDataEntityToDomainEntity(DataModel.IdentitySubscription entity)
        {
            return entity == null
                ? null
                : new DomainModel.InternalIdentitySubscription()
                {
                    ID = entity.ID,
                    HashKey = entity.HashKey,
                    Token = entity.Token,
                    UserName = entity.UserName
                };
        }
        #endregion
    }
}


text:
package internalversion

import (
	build "github.com/openshift/origin/pkg/build/apis/build"
	scheme "github.com/openshift/origin/pkg/build/generated/internalclientset/scheme"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	rest "k8s.io/client-go/rest"
)

// BuildsGetter has a method to return a BuildResourceInterface.
// A group's client should implement this interface.
type BuildsGetter interface {
	Builds(namespace string) BuildResourceInterface
}

// BuildResourceInterface has methods to work with BuildResource resources.
type BuildResourceInterface interface {
	Create(*build.Build) (*build.Build, error)
	Update(*build.Build) (*build.Build, error)
	UpdateStatus(*build.Build) (*build.Build, error)
	Delete(name string, options *v1.DeleteOptions) error
	DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error
	Get(name string, options v1.GetOptions) (*build.Build, error)
	List(opts v1.ListOptions) (*build.BuildList, error)
	Watch(opts v1.ListOptions) (watch.Interface, error)
	Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *build.Build, err error)
	BuildResourceExpansion
}

// builds implements BuildResourceInterface
type builds struct {
	client rest.Interface
	ns     string
}

// newBuilds returns a Builds
func newBuilds(c *BuildClient, namespace string) *builds {
	return &builds{
		client: c.RESTClient(),
		ns:     namespace,
	}
}

// Create takes the representation of a buildResource and creates it.  Returns the server's representation of the buildResource, and an error, if there is any.
func (c *builds) Create(buildResource *build.Build) (result *build.Build, err error) {
	result = &build.Build{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("builds").
		Body(buildResource).
		Do().
		Into(result)
	return
}

// Update takes the representation of a buildResource and updates it. Returns the server's representation of the buildResource, and an error, if there is any.
func (c *builds) Update(buildResource *build.Build) (result *build.Build, err error) {
	result = &build.Build{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("builds").
		Name(buildResource.Name).
		Body(buildResource).
		Do().
		Into(result)
	return
}

// UpdateStatus was generated because the type contains a Status member.
// Add a +genclientstatus=false comment above the type to avoid generating UpdateStatus().

func (c *builds) UpdateStatus(buildResource *build.Build) (result *build.Build, err error) {
	result = &build.Build{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("builds").
		Name(buildResource.Name).
		SubResource("status").
		Body(buildResource).
		Do().
		Into(result)
	return
}

// Delete takes name of the buildResource and deletes it. Returns an error if one occurs.
func (c *builds) Delete(name string, options *v1.DeleteOptions) error {
	return c.client.Delete().
		Namespace(c.ns).
		Resource("builds").
		Name(name).
		Body(options).
		Do().
		Error()
}

// DeleteCollection deletes a collection of objects.
func (c *builds) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	return c.client.Delete().
		Namespace(c.ns).
		Resource("builds").
		VersionedParams(&listOptions, scheme.ParameterCodec).
		Body(options).
		Do().
		Error()
}

// Get takes name of the buildResource, and returns the corresponding buildResource object, and an error if there is any.
func (c *builds) Get(name string, options v1.GetOptions) (result *build.Build, err error) {
	result = &build.Build{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("builds").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}

// List takes label and field selectors, and returns the list of Builds that match those selectors.
func (c *builds) List(opts v1.ListOptions) (result *build.BuildList, err error) {
	result = &build.BuildList{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("builds").
		VersionedParams(&opts, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}

// Watch returns a watch.Interface that watches the requested builds.
func (c *builds) Watch(opts v1.ListOptions) (watch.Interface, error) {
	opts.Watch = true
	return c.client.Get().
		Namespace(c.ns).
		Resource("builds").
		VersionedParams(&opts, scheme.ParameterCodec).
		Watch()
}

// Patch applies the patch and returns the patched buildResource.
func (c *builds) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *build.Build, err error) {
	result = &build.Build{}
	err = c.client.Patch(pt).
		Namespace(c.ns).
		Resource("builds").
		SubResource(subresources...).
		Name(name).
		Body(data).
		Do().
		Into(result)
	return
}


text:
 .. Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.

.. _howto/operator:InfluxDBOperator:

InfluxDBOperator
=================

Use the :class:`~airflow.providers.influxdb.operators.InfluxDBOperator` to execute
SQL commands in a `InfluxDB <https://www.influxdata.com/>`__ database.

An example of running the query using the operator:

.. exampleinclude:: /../../tests/system/providers/influxdb/example_influxdb_query.py
    :language: python
    :start-after: [START howto_operator_influxdb]
    :end-before: [END howto_operator_influxdb]


text:
from jinja2 import Template
import json
from matrix_client.api import MatrixRequestError
from neb.engine import KeyValueStore, RoomContextStore
from neb.plugins import Plugin, admin_only
from Queue import PriorityQueue
from threading import Thread

import time
import logging as log

queue = PriorityQueue()

class PrometheusPlugin(Plugin):
    """Plugin for interacting with Prometheus.
    """
    name = "prometheus"

    #Webhooks:
        #    /neb/prometheus
    TYPE_TRACK = "org.matrix.neb.plugin.prometheus.projects.tracking"

    def __init__(self, *args, **kwargs):
        super(PrometheusPlugin, self).__init__(*args, **kwargs)
        self.store = KeyValueStore("prometheus.json")
        self.rooms = RoomContextStore(
            [PrometheusPlugin.TYPE_TRACK]
        )
        self.queue_counter = 1L
        self.consumer = MessageConsumer(self.matrix)
        self.consumer.daemon = True
        self.consumer.start()

    def on_event(self, event, event_type):
        self.rooms.update(event)

    def on_sync(self, sync):
        log.debug("Plugin: Prometheus sync state:")
        self.rooms.init_from_sync(sync)

    def get_webhook_key(self):
        return "prometheus"

    def on_receive_webhook(self, url, data, ip, headers):
        json_data = json.loads(data)
        log.info("recv %s", json_data)
        template = Template(self.store.get("message_template"))
        for alert in json_data.get("alert", []):
            for room_id in self.rooms.get_room_ids():
                log.debug("queued message for room " + room_id + " at " + str(self.queue_counter) + ": %s", alert)
                queue.put((self.queue_counter, room_id, template.render(alert)))
                self.queue_counter += 1

class MessageConsumer(Thread):
    """ This class consumes the produced messages
        also will try to resend the messages that
        are failed for instance when the server was down.
    """

    INITIAL_TIMEOUT_S = 5
    TIMEOUT_INCREMENT_S = 5
    MAX_TIMEOUT_S = 60 * 5

    def __init__(self, matrix):
        super(MessageConsumer, self).__init__()
        self.matrix = matrix

    def run(self):
        timeout = self.INITIAL_TIMEOUT_S

        log.debug("Starting consumer thread")
        while True:
            priority, room_id, message = queue.get()
            log.debug("Popped message for room " + room_id + " at position " + str(priority) + ": %s", message)
            try:
                self.send_message(room_id, message)
                timeout = self.INITIAL_TIMEOUT_S
            except Exception as e:
                log.debug("Failed to send message: %s", e)
                queue.put((priority, room_id, message))

                time.sleep(timeout)
                timeout += self.TIMEOUT_INCREMENT_S
                if timeout > self.MAX_TIMEOUT_S:
                    timeout = self.MAX_TIMEOUT_S

    def send_message(self, room_id, message):
        try:
            self.matrix.send_message_event(
                    room_id,
                    "m.room.message",
                    self.matrix.get_html_body(message, msgtype="m.notice"),
            )
        except KeyError:
            log.error(KeyError)
        except MatrixRequestError as e:
            if 400 <= e.code < 500:
                log.error("Matrix ignored message %s", e)
            else:
                raise


text:
package com.blackducksoftware.integration.hub.detect.detector.bitbake;

import java.util.Map;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;

import com.paypal.digraph.parser.GraphEdge;
import com.paypal.digraph.parser.GraphNode;
import com.paypal.digraph.parser.GraphParser;
import com.synopsys.integration.bdio.graph.DependencyGraph;
import com.synopsys.integration.bdio.graph.builder.LazyExternalIdDependencyGraphBuilder;
import com.synopsys.integration.bdio.model.Forge;
import com.synopsys.integration.bdio.model.dependencyid.DependencyId;
import com.synopsys.integration.bdio.model.dependencyid.NameDependencyId;
import com.synopsys.integration.bdio.model.externalid.ExternalId;

public class GraphParserTransformer {
    public DependencyGraph transform(final GraphParser graphParser, final String targetArchitecture) {
        final Map<String, GraphNode> nodes = graphParser.getNodes();
        final Map<String, GraphEdge> edges = graphParser.getEdges();
        final LazyExternalIdDependencyGraphBuilder graphBuilder = new LazyExternalIdDependencyGraphBuilder();

        for (final GraphNode graphNode : nodes.values()) {
            final String name = getNameFromNode(graphNode);
            final DependencyId dependencyId = new NameDependencyId(name);
            final Optional<String> version = getVersionFromNode(graphNode);

            if (version.isPresent()) {
                final ExternalId externalId = new ExternalId(Forge.YOCTO);
                externalId.name = name;
                externalId.version = version.get();
                externalId.architecture = targetArchitecture;
                graphBuilder.setDependencyInfo(dependencyId, name, version.get(), externalId);
            }

            graphBuilder.addChildToRoot(dependencyId);
        }

        for (final GraphEdge graphEdge : edges.values()) {
            final DependencyId node1 = new NameDependencyId(getNameFromNode(graphEdge.getNode1()));
            final DependencyId node2 = new NameDependencyId(getNameFromNode(graphEdge.getNode2()));
            graphBuilder.addParentWithChild(node1, node2);
        }

        return graphBuilder.build();
    }

    private String getNameFromNode(final GraphNode graphNode) {
        return graphNode.getId().replaceAll("\"", "");
    }

    private Optional<String> getVersionFromNode(final GraphNode graphNode) {
        final Optional<String> attribute = getLabelAttribute(graphNode);

        return attribute.map(this::getVersionFromLabel);
    }

    private Optional<String> getLabelAttribute(final GraphNode graphNode) {
        final String attribute = (String) graphNode.getAttribute("label");
        Optional<String> result = Optional.empty();

        if (StringUtils.isNotBlank(attribute)) {
            result = Optional.of(attribute);
        }

        return result;
    }

    private String getVersionFromLabel(final String label) {
        final String[] components = label.split("\\\\n:|\\\\n");
        final String version = components[1];

        return version;
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.capnproto</groupId>
	<artifactId>capnproto-java</artifactId>
	<packaging>jar</packaging>
	<version>0.1.0-SNAPSHOT</version>
	<description>Java Runtime for Cap'n Proto</description>
	<build>
		<sourceDirectory>runtime/src/main/java</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source />
					<target />
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>**/Test*.java</exclude>
					</excludes>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<executions>
					<execution>
						<id>attach-sources</id>
						<phase>package</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<executions>
					<execution>
						<id>attach-javadocs</id>
						<phase>package</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<descriptorRefs>
						<descriptorRef>project</descriptorRef>
					</descriptorRefs>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
</project>


text:
微信企业号SDK

感谢 (https://github.com/overtrue/laravel-wechat)


text:
package org.mybatis.spring.batch;

import static org.springframework.util.Assert.notNull;
import static org.springframework.util.ClassUtils.getShortName;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader;
import org.springframework.beans.factory.InitializingBean;

/**
 * @author Guillaume Darmont / guillaume@dropinocean.com
 */
public class MyBatisCursorItemReader<T> extends AbstractItemCountingItemStreamItemReader<T> implements InitializingBean {

  private String queryId;

  private SqlSessionFactory sqlSessionFactory;
  private SqlSession sqlSession;

  private Map<String, Object> parameterValues;

  private Cursor<T> cursor;
  private Iterator<T> cursorIterator;

  public MyBatisCursorItemReader() {
    setName(getShortName(MyBatisCursorItemReader.class));
  }

  @Override
  protected T doRead() throws Exception {
    T next = null;
    if (cursorIterator.hasNext()) {
      next = cursorIterator.next();
    }
    return next;
  }

  @Override
  protected void doOpen() throws Exception {
    Map<String, Object> parameters = new HashMap<String, Object>();
    if (parameterValues != null) {
      parameters.putAll(parameterValues);
    }

    sqlSession = sqlSessionFactory.openSession(ExecutorType.SIMPLE);
    cursor = sqlSession.selectCursor(queryId, parameters);
    cursorIterator = cursor.iterator();
  }

  @Override
  protected void doClose() throws Exception {
    cursor.close();
    sqlSession.close();
    cursorIterator = null;
  }

  /**
   * Check mandatory properties.
   *
   * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
   */
  public void afterPropertiesSet() throws Exception {
    notNull(sqlSessionFactory);
    notNull(queryId);
  }

  /**
   * Public setter for {@link SqlSessionFactory} for injection purposes.
   *
   * @param SqlSessionFactory sqlSessionFactory
   */
  public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    this.sqlSessionFactory = sqlSessionFactory;
  }

  /**
   * Public setter for the statement id identifying the statement in the SqlMap
   * configuration file.
   *
   * @param queryId the id for the statement
   */
  public void setQueryId(String queryId) {
    this.queryId = queryId;
  }

  /**
   * The parameter values to be used for the query execution.
   *
   * @param parameterValues the values keyed by the parameter named used in
   *                        the query string.
   */
  public void setParameterValues(Map<String, Object> parameterValues) {
    this.parameterValues = parameterValues;
  }
}