text:
package carbonserver

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil" //nolint:staticcheck
	"net/http"
	_ "net/http/pprof"
	"strings"
	"sync/atomic"
	"time"

	"go.uber.org/zap"

	"github.com/go-graphite/carbonzipper/zipper/httpHeaders"
	protov2 "github.com/go-graphite/protocol/carbonapi_v2_pb"
	protov3 "github.com/go-graphite/protocol/carbonapi_v3_pb"
	pickle "github.com/lomik/og-rek"
	"go.opentelemetry.io/otel/api/kv"
	"go.opentelemetry.io/otel/api/trace"
)

type findResponse struct {
	data        []byte
	contentType string
	files       int
}

func (listener *CarbonserverListener) findHandler(wr http.ResponseWriter, req *http.Request) {
	// URL: /metrics/find/?local=1&format=pickle&query=the.metric.path.with.glob

	t0 := time.Now()
	ctx := req.Context()
	span := trace.SpanFromContext(ctx)

	atomic.AddUint64(&listener.metrics.FindRequests, 1)

	format := req.FormValue("format")
	query := req.Form["query"]

	var response *findResponse

	logger := TraceContextToZap(ctx, listener.logger.With(
		zap.String("handler", "find"),
		zap.String("url", req.URL.RequestURI()),
		zap.String("peer", req.RemoteAddr),
	))

	accessLogger := TraceContextToZap(ctx, listener.accessLogger.With(
		zap.String("handler", "find"),
		zap.String("url", req.URL.RequestURI()),
		zap.String("peer", req.RemoteAddr),
	))

	accepts := req.Header["Accept"]
	for _, accept := range accepts {
		if accept == httpHeaders.ContentTypeCarbonAPIv3PB {
			format = "carbonapi_v3_pb"
			break
		}
	}

	if format == "" {
		format = "json"
	}

	formatCode, ok := knownFormats[format]
	if !ok {
		atomic.AddUint64(&listener.metrics.FindErrors, 1)
		accessLogger.Error("find failed",
			zap.Duration("runtime_seconds", time.Since(t0)),
			zap.String("reason", "unsupported format"),
			zap.Int("http_code", http.StatusBadRequest),
		)
		http.Error(wr, "Bad request (unsupported format)",
			http.StatusBadRequest)
		return
	}

	if formatCode == protoV3Format {
		body, err := ioutil.ReadAll(req.Body)
		if err != nil {
			accessLogger.Error("find failed",
				zap.Duration("runtime_seconds", time.Since(t0)),
				zap.String("reason", err.Error()),
				zap.Int("http_code", http.StatusBadRequest),
			)
			http.Error(wr, "Bad request (unsupported format)",
				http.StatusBadRequest)
		}

		var pv3Request protov3.MultiGlobRequest
		pv3Request.UnmarshalVT(body)
		query = pv3Request.Metrics
	}

	logger = logger.With(
		zap.Strings("query", query),
		zap.String("format", format),
	)

	accessLogger = accessLogger.With(
		zap.Strings("query", query),
		zap.String("format", format),
	)

	span.SetAttributes(
		kv.String("graphite.query", strings.Join(query, ",")),
		kv.String("graphite.format", format),
	)

	if len(query) == 0 {
		atomic.AddUint64(&listener.metrics.FindErrors, 1)
		accessLogger.Error("find failed",
			zap.Duration("runtime_seconds", time.Since(t0)),
			zap.String("reason", "empty query"),
			zap.Int("http_code", http.StatusBadRequest),
		)
		http.Error(wr, "Bad request (no query)", http.StatusBadRequest)
		return
	}

	var err error
	fromCache := false
	if listener.findCacheEnabled {
		key := strings.Join(query, ",") + "&" + format
		size := uint64(100 * 1024 * 1024)
		item := listener.findCache.getQueryItem(key, size, 300)
		res, ok := item.FetchOrLock()
		listener.prometheus.cacheRequest("find", ok)
		if !ok {
			logger.Debug("find cache miss")
			atomic.AddUint64(&listener.metrics.FindCacheMiss, 1)
			response, err = listener.findMetrics(ctx, logger, t0, formatCode, query)
			if err != nil {
				if _, ok := err.(errorNotFound); ok {
					item.StoreAndUnlock(&findResponse{})
				} else {
					item.StoreAbort()
				}
			} else {
				item.StoreAndUnlock(response)
			}
		} else if res != nil {
			logger.Debug("query cache hit")
			atomic.AddUint64(&listener.metrics.FindCacheHit, 1)
			response = res.(*findResponse)
			fromCache = true

			if response.files == 0 {
				err = errorNotFound{}
			}
		}
	} else {
		response, err = listener.findMetrics(ctx, logger, t0, formatCode, query)
	}

	if err != nil || response == nil {
		var code int
		var reason string
		if _, ok := err.(errorNotFound); ok {
			reason = "Not Found"
			code = http.StatusNotFound
		} else {
			reason = "Internal error while processing request"
			code = http.StatusInternalServerError
		}

		accessLogger.Error("find failed",
			zap.Duration("runtime_seconds", time.Since(t0)),
			zap.String("reason", reason),
			zap.Error(err),
			zap.Int("http_code", code),
		)
		http.Error(wr, fmt.Sprintf("%s (%v)", reason, err), code)

		return
	}

	wr.Header().Set("Content-Type", response.contentType)
	wr.Write(response.data)

	if response.files == 0 {
		// to get an idea how often we search for nothing
		atomic.AddUint64(&listener.metrics.FindZero, 1)
	}

	accessLogger.Info("find success",
		zap.Duration("runtime_seconds", time.Since(t0)),
		zap.Int("Files", response.files),
		zap.Bool("find_cache_enabled", listener.findCacheEnabled),
		zap.Bool("from_cache", fromCache),
		zap.Int("http_code", http.StatusOK),
	)
	span.SetAttributes(
		kv.Int("graphite.files", response.files),
		kv.Bool("graphite.from_cache", fromCache),
	)

}

type errorNotFound struct{}

// skipcq: RVV-B0013
func (err errorNotFound) Error() string {
	return "Not Found"
}

type globs struct {
	Name      string
	Files     []string
	Leafs     []bool
	TrieNodes []*trieNode
}

func (listener *CarbonserverListener) findMetrics(ctx context.Context, logger *zap.Logger, t0 time.Time, format responseFormat, names []string) (*findResponse, error) {
	var result findResponse
	metricsCount := uint64(0)
	expandedGlobs, err := listener.getExpandedGlobs(ctx, logger, t0, names)
	if expandedGlobs == nil {
		return nil, err
	}
	atomic.AddUint64(&listener.metrics.MetricsFound, metricsCount)
	switch format {
	case protoV3Format, jsonFormat:
		var err error
		multiResponse := protov3.MultiGlobResponse{}
		for _, glob := range expandedGlobs {
			result.files += len(glob.Files)
			response := protov3.GlobResponse{
				Name:    glob.Name,
				Matches: make([]*protov3.GlobMatch, 0),
			}

			for i, p := range glob.Files {
				if glob.Leafs[i] {
					metricsCount++
				}
				response.Matches = append(response.Matches, &protov3.GlobMatch{Path: p, IsLeaf: glob.Leafs[i]})
			}
			multiResponse.Metrics = append(multiResponse.Metrics, &response)
		}

		logger.Debug("will send out response",
			//skipcq: VET-V0008
			//nolint:govet
			zap.Any("response", multiResponse),
		)

		switch format {
		case jsonFormat:
			result.contentType = httpHeaders.ContentTypeJSON
			//skipcq: VET-V0008
			//nolint:govet
			result.data, err = json.Marshal(multiResponse)
		case protoV3Format:
			result.contentType = httpHeaders.ContentTypeCarbonAPIv3PB
			result.data, err = multiResponse.MarshalVT()
		}

		if err != nil {
			atomic.AddUint64(&listener.metrics.FindErrors, 1)

			logger.Error("find failed",
				zap.Duration("runtime_seconds", time.Since(t0)),
				zap.String("reason", "response encode failed"),
				zap.Error(err),
			)
			return nil, err
		}

		if len(multiResponse.Metrics) == 0 {
			return nil, errorNotFound{}
		}

		return &result, err

	case protoV2Format:
		result.contentType = httpHeaders.ContentTypeProtobuf
		var err error
		response := protov2.GlobResponse{
			Name:    names[0],
			Matches: make([]*protov2.GlobMatch, 0),
		}

		result.files += len(expandedGlobs[0].Files)
		for i, p := range expandedGlobs[0].Files {
			if expandedGlobs[0].Leafs[i] {
				metricsCount++
			}
			response.Matches = append(response.Matches, &protov2.GlobMatch{Path: p, IsLeaf: expandedGlobs[0].Leafs[i]})
		}
		result.data, err = response.MarshalVT()
		result.contentType = httpHeaders.ContentTypeProtobuf

		if err != nil {
			atomic.AddUint64(&listener.metrics.FindErrors, 1)

			logger.Error("find failed",
				zap.Duration("runtime_seconds", time.Since(t0)),
				zap.String("reason", "response encode failed"),
				zap.Error(err),
			)
			return nil, err
		}

		if len(response.Matches) == 0 {
			return nil, errorNotFound{}
		}

		return &result, err

	case pickleFormat:
		// [{'metric_path': 'metric', 'intervals': [(x,y)], 'isLeaf': True},]
		var metrics []map[string]interface{}
		var m map[string]interface{}
		files := 0

		glob := expandedGlobs[0]
		files += len(glob.Files)
		for i, p := range glob.Files {
			if glob.Leafs[i] {
				metricsCount++
			}
			m = make(map[string]interface{})
			m["metric_path"] = p
			m["isLeaf"] = glob.Leafs[i]

			metrics = append(metrics, m)
		}
		var buf bytes.Buffer
		pEnc := pickle.NewEncoder(&buf)
		pEnc.Encode(metrics)
		return &findResponse{buf.Bytes(), httpHeaders.ContentTypePickle, files}, nil
	}
	return nil, nil
}

func (listener *CarbonserverListener) getExpandedGlobs(ctx context.Context, logger *zap.Logger, t0 time.Time, names []string) ([]globs, error) {
	var expandedGlobs []globs
	var errors []error
	var err error
	expGlobResultChan := make(chan *ExpandedGlobResponse, len(names))

	for _, name := range names {
		go listener.expandGlobs(ctx, name, expGlobResultChan)
	}
	responseCount := 0
GATHER:
	for {
		select {
		case expandedResult := <-expGlobResultChan:
			responseCount++
			glob := globs{
				Name: expandedResult.Name,
			}
			glob.Files, glob.Leafs, glob.TrieNodes, err = expandedResult.Files, expandedResult.Leafs, expandedResult.TrieNodes, expandedResult.Err
			if err != nil {
				errors = append(errors, fmt.Errorf("%s: %s", expandedResult.Name, err))
			}
			expandedGlobs = append(expandedGlobs, glob)
			if responseCount == len(names) {
				break GATHER
			}

		case <-ctx.Done():
			switch ctx.Err() {
			case context.DeadlineExceeded:
				listener.prometheus.timeoutRequest()
			case context.Canceled:
				listener.prometheus.cancelledRequest()
			}
			return nil, fmt.Errorf("could not expand globs - %s", ctx.Err().Error())
		}
	}

	if len(errors) > 0 {
		atomic.AddUint64(&listener.metrics.FindErrors, uint64(len(errors)))

		if len(errors) == len(names) {
			logger.Error("find failed",
				zap.Duration("runtime_seconds", time.Since(t0)),
				zap.String("reason", "can't expand globs"),
				zap.Errors("errors", errors),
			)
			return nil, fmt.Errorf("find failed, can't expand globs: %v", errors)
		} else {
			logger.Warn("find partly failed",
				zap.Duration("runtime_seconds", time.Since(t0)),
				zap.String("reason", "can't expand globs for some metrics"),
				zap.Errors("errors", errors),
			)
		}
	}

	logger.Debug("expandGlobs result",
		zap.String("action", "expandGlobs"),
		zap.Strings("metrics", names),
		// zap.String("format", format.String()),
		zap.Any("result", expandedGlobs),
	)
	return expandedGlobs, nil
}


text:
class InvalidBarcodeData < Exception

end

redpajama_set_name: RedPajamaGithub


text:
.PHONY: all lint test test-cov install dev clean distclean

PYTHON ?= python

all: ;

lint:
	q2lint
	flake8

test: all
	py.test

test-cov: all
	py.test --cov=q2_sample_classifier

install:
	$(PYTHON) setup.py install

dev: all
	pip install -e .

clean: distclean

distclean: ;


text:
package edu.bupt.mms.util;

import edu.bupt.mms.MmsApp;
import edu.bupt.mms.R;
import com.google.android.mms.pdu.EncodedStringValue;
import com.google.android.mms.pdu.PduHeaders;
import com.google.android.mms.pdu.PduPersister;
import android.database.sqlite.SqliteWrapper;

import android.content.Context;
import android.database.Cursor;
import android.location.Country;
import android.net.Uri;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Mms.Addr;
import android.text.TextUtils;
import android.telephony.PhoneNumberUtils;
import com.android.i18n.phonenumbers.PhoneNumberUtil;

public class AddressUtils {
    private static final String TAG = "AddressUtils";
    private static PhoneNumberUtil mPhoneNumberUtil;

    private AddressUtils() {
        // Forbidden being instantiated.
    }

    public static String getFrom(Context context, Uri uri) {
        String msgId = uri.getLastPathSegment();
        Uri.Builder builder = Mms.CONTENT_URI.buildUpon();

        builder.appendPath(msgId).appendPath("addr");

        Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
                            builder.build(), new String[] {Addr.ADDRESS, Addr.CHARSET},
                            Addr.TYPE + "=" + PduHeaders.FROM, null, null);

        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    String from = cursor.getString(0);

                    if (!TextUtils.isEmpty(from)) {
                        byte[] bytes = PduPersister.getBytes(from);
                        int charset = cursor.getInt(1);
                        return new EncodedStringValue(charset, bytes)
                                .getString();
                    }
                }
            } finally {
                cursor.close();
            }
        }
        return context.getString(R.string.hidden_sender_address);
    }

    public static boolean isPossiblePhoneNumber(String query) {
        String currentCountry = MmsApp.getApplication().getCurrentCountryIso().toUpperCase();
        if (mPhoneNumberUtil == null) {
            mPhoneNumberUtil = PhoneNumberUtil.getInstance();
        }
        return mPhoneNumberUtil.isPossibleNumber(query, currentCountry);
    }

}


text:
'use strict';

/* jasmine specs for controllers go here */

describe('LocalGame', function(){
  beforeEach(module('controllers.localgame'))
  beforeEach(module('services.game'))
  var scope, ctrl, gs;

  beforeEach(inject(function($controller, gameService) {
    scope = {};
    ctrl = $controller('LocalGame', {$scope:scope});
    gs = gameService
  }));

  it('should instantiate a game board from gameService', function(gameService) {
    expect(scope.board).toEqual(gs.gameBoard());
  });

  it("should instantiate a player's record object with wins, losses and ties set to zero", function() {
    expect(scope.playerRecord.wins).toEqual(0);
    expect(scope.playerRecord.losses).toEqual(0);
    expect(scope.playerRecord.ties).toEqual(0);
  });

  it("the current player variable should be set to zero", function(gameService) {
    expect(scope.currentPlayer).toEqual("");
  });

  describe('startGame()', function() {
    it("should change the value of currentPlayer", function() {
      scope.startGame()
      expect(scope.currentPlayer === "X" || scope.currentPlayer === "O").toEqual(true)
    });
  });

  describe('swtichPlayer()', function() {
    it("should change the current Player", function() {
      var priorPlayer = scope.currentPlayer
      scope.switchPlayer()
      expect(priorPlayer !== scope.currentPlayer).toEqual(true)
    });
  });

  describe('winCheck()', function() {
    it("should save a win", function() {
      scope.currentPlayer = "X"
      scope.board[0][0].letter = scope.board[0][1].letter = scope.board[0][2].letter = "X"
      scope.winCheck(scope.board)
      expect(scope.playerRecord.wins).toEqual(1)
    });
  });

});


text:
package io.cattle.platform.core.addon;

import io.github.ibuildthecloud.gdapi.annotation.Field;
import io.github.ibuildthecloud.gdapi.annotation.Type;

@Type(list = false)
public class HealthcheckState {

    Long hostId;
    String healthState;
    Long externalTimestamp;

    public HealthcheckState() {
    }

    public HealthcheckState(Long hostId, String healthState) {
        super();
        this.hostId = hostId;
        this.healthState = healthState;
    }

    @Field(typeString="reference[host]")
    public Long getHostId() {
        return hostId;
    }

    public void setHostId(Long hostId) {
        this.hostId = hostId;
    }

    public String getHealthState() {
        return healthState;
    }

    public void setHealthState(String healthState) {
        this.healthState = healthState;
    }

    public Long getExternalTimestamp() {
        return externalTimestamp;
    }

    public void setExternalTimestamp(Long externalTimestamp) {
        this.externalTimestamp = externalTimestamp;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((externalTimestamp == null) ? 0 : externalTimestamp.hashCode());
        result = prime * result + ((healthState == null) ? 0 : healthState.hashCode());
        result = prime * result + ((hostId == null) ? 0 : hostId.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        HealthcheckState other = (HealthcheckState) obj;
        if (externalTimestamp == null) {
            if (other.externalTimestamp != null)
                return false;
        } else if (!externalTimestamp.equals(other.externalTimestamp))
            return false;
        if (healthState == null) {
            if (other.healthState != null)
                return false;
        } else if (!healthState.equals(other.healthState))
            return false;
        if (hostId == null) {
            if (other.hostId != null)
                return false;
        } else if (!hostId.equals(other.hostId))
            return false;
        return true;
    }

}


text:
// Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Unit tests for BrowserCheckerService.
 */

import { TestBed } from '@angular/core/testing';
import { BrowserCheckerService } from
  'domain/utilities/browser-checker.service';
import { WindowRef } from 'services/contextual/window-ref.service';

describe('Browser Checker Service', function() {
  let bcs: BrowserCheckerService, wrs: WindowRef;

  let mockUserAgent: (ua: string) => void;

  const mobileAgent = 'Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F' +
  ' Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko)' +
  ' Chrome/62.0.3202.84 Mobile Safari/537.36';
  beforeEach(() => {
    bcs = TestBed.get(BrowserCheckerService);
    wrs = TestBed.get(WindowRef);

    let userAgent: string;
    spyOnProperty(wrs.nativeWindow.navigator, 'userAgent')
      .and.callFake(() => userAgent);
    mockUserAgent = ua => userAgent = ua;
  });

  it('should evaluate when device is mobile checking navigator userAgent',
    () => {
      mockUserAgent(mobileAgent);
      expect(!!bcs.isMobileDevice()).toBe(true);
    });

  it('should support speech synthesis when device is desktop', () => {
    spyOnProperty(wrs.nativeWindow, 'speechSynthesis').and.returnValue({
      getVoices: () => [{ lang: 'en-US' }]
    });
    expect(bcs.supportsSpeechSynthesis()).toBe(true);
  });

  it('should support speech synthesis when device is mobile', () => {
    mockUserAgent(mobileAgent);
    spyOnProperty(window, 'speechSynthesis').and.returnValue({
      getVoices: () => [{ lang: 'en_US' }]
    });
    expect(bcs.supportsSpeechSynthesis()).toBe(true);
  });

  it('should not support speech synthesis', () => {
    spyOn(wrs.nativeWindow as Object, 'hasOwnProperty')
      .withArgs('speechSynthesis').and.returnValue(false);
    expect(bcs.supportsSpeechSynthesis()).toBe(false);
  });

  describe('.detectBrowserType', () => {
    it('should correctly detect Edge browser.', () => {
      mockUserAgent(
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' +
        '(KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246');

      expect(bcs.detectBrowserType()).toEqual('Edge');
    });

    it('should correctly detect Chrome browser.', () => {
      mockUserAgent(
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, ' +
        'like Gecko) Chrome/47.0.2526.111 Safari/537.36');

      expect(bcs.detectBrowserType()).toEqual('Chrome');
    });

    it('should correctly detect Firefox browser.', () => {
      mockUserAgent(
        'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101' +
        ' Firefox/15.0.1');

      expect(bcs.detectBrowserType()).toEqual('Firefox');
    });

    it('should correctly detect Safari browser.', () => {
      mockUserAgent(
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/' +
        '601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9');

      expect(bcs.detectBrowserType()).toEqual('Safari');
    });

    it('should return \'Others\' if no other browser type is detected.', () => {
      mockUserAgent('unknown-user-agent-value');

      expect(bcs.detectBrowserType()).toEqual('Others');
    });
  });
});


text:
import PythonQt
from PythonQt import QtCore, QtGui
import director.objectmodel as om
import director.visualization as vis
from director import affordanceitems
from director import lcmUtils
from director import callbacks
from director import cameracontrol
from director import splinewidget
from director import transformUtils
from director import teleoppanel
from director import footstepsdriverpanel
from director import applogic as app
from director import vtkAll as vtk
from director import filterUtils
from director.shallowCopy import shallowCopy
from director import segmentationpanel
from director import segmentation
from director import segmentationroutines
from director.vieweventfilter import ViewEventFilter
from director import viewbehaviors
import numpy as np
import ioUtils
import os
import re
import random
import colorsys

# todo: refactor these global variables
# several functions in this module depend on these global variables
# which are set by calling ViewBehaviors.addRobotBehaviors().
# These could be refactored to be members of a new behaviors class.
robotSystem = None
robotModel = None
handFactory = None
neckDriver = None
footstepsDriver = None
robotLinkSelector = None
lastRandomColor = 0.0

def resetCameraToRobot(view):
    t = robotModel.getLinkFrame('pelvis')
    if t is None:
        t = vtk.vtkTransform()

    focalPoint = [0.0, 0.0, 0.25]
    position = [-4.0, -2.0, 2.25]
    t.TransformPoint(focalPoint, focalPoint)
    t.TransformPoint(position, position)
    flyer = cameracontrol.Flyer(view)
    flyer.zoomTo(focalPoint, position)

def resetCameraToHeadView(view):

    head = robotModel.getLinkFrame('head')
    pelvis = robotModel.getLinkFrame('pelvis')

    viewDirection = np.array([1.0, 0.0, 0.0])
    pelvis.TransformVector(viewDirection, viewDirection)

    cameraPosition = np.array(head.GetPosition()) + 0.10 * viewDirection

    camera = view.camera()

    focalOffset = np.array(camera.GetFocalPoint()) - np.array(camera.GetPosition())
    focalOffset /= np.linalg.norm(focalOffset)

    camera.SetPosition(cameraPosition)
    camera.SetFocalPoint(cameraPosition + focalOffset*0.03)
    camera.SetViewUp([0, 0, 1])
    camera.SetViewAngle(90)
    view.render()

def getChildFrame(obj):
    if hasattr(obj, 'getChildFrame'):
        return obj.getChildFrame()

def placeHandModel(displayPoint, view, side='left'):

    obj, _ = vis.findPickedObject(displayPoint, view)
    if isinstance(obj, vis.FrameItem):
        _, handFrame = handFactory.placeHandModelWithTransform(obj.transform, view, side=side, parent=obj.parent())
        handFrame.frameSync = vis.FrameSync()
        handFrame.frameSync.addFrame(obj)
        handFrame.frameSync.addFrame(handFrame, ignoreIncoming=True)
        return

    pickedPoint, prop, _, normal = vis.pickPoint(displayPoint, view, pickType='cells', tolerance=0.0, returnNormal=True)

    obj = vis.getObjectByProp(prop)
    if not obj:
        return

    yaxis = -normal
    zaxis = [0,0,1]
    xaxis = np.cross(yaxis, zaxis)
    xaxis /= np.linalg.norm(xaxis)
    zaxis = np.cross(xaxis, yaxis)
    zaxis /= np.linalg.norm(zaxis)

    t = transformUtils.getTransformFromAxes(-zaxis, yaxis, xaxis)
    t.PostMultiply()
    t.Translate(pickedPoint)

    if side == 'right':
        t.PreMultiply()
        t.RotateY(180)

    handObj, handFrame = handFactory.placeHandModelWithTransform(t, view, side=side, parent=obj)

    syncFrame = getChildFrame(obj)
    if syncFrame:
        handFrame.frameSync = vis.FrameSync()
        handFrame.frameSync.addFrame(handFrame, ignoreIncoming=True)
        handFrame.frameSync.addFrame(syncFrame)

class RobotLinkSelector(object):

    def __init__(self):
        self.selectedLink = None
        self.setupMenuAction()

    def setupMenuAction(self):
        self.action = app.addMenuAction('Tools', 'Robot Link Selector')
        self.action.setCheckable(True)
        self.action.checked = False

    def enabled(self):
        return self.action.checked == True

    def selectLink(self, displayPoint, view):

        if not self.enabled():
            return False

        robotModel, _ = vis.findPickedObject(displayPoint, view)

        try:
            robotModel.model.getLinkNameForMesh
        except AttributeError:
            return False

        model = robotModel.model

        pickedPoint, _, polyData = vis.pickProp(displayPoint, view)

        linkName = model.getLinkNameForMesh(polyData)
        if not linkName:
            return False

        fadeValue = 1.0 if linkName == self.selectedLink else 0.05

        for name in model.getLinkNames():
            linkColor = model.getLinkColor(name)
            linkColor.setAlphaF(fadeValue)
            model.setLinkColor(name, linkColor)

        if linkName == self.selectedLink:
            self.selectedLink = None
            vis.hideCaptionWidget()
            om.removeFromObjectModel(om.findObjectByName('selected link frame'))

        else:
            self.selectedLink = linkName
            linkColor = model.getLinkColor(self.selectedLink)
            linkColor.setAlphaF(1.0)
            model.setLinkColor(self.selectedLink, linkColor)
            vis.showCaptionWidget(robotModel.getLinkFrame(self.selectedLink).GetPosition(), self.selectedLink, view=view)
            vis.updateFrame(robotModel.getLinkFrame(self.selectedLink), 'selected link frame', scale=0.2, parent=robotModel)

        return True

def newWalkingGoal(displayPoint, view):

    footFrame = footstepsDriver.getFeetMidPoint(robotModel)

    worldPt1, worldPt2 = vis.getRayFromDisplayPoint(view, displayPoint)
    groundOrigin = footFrame.GetPosition()
    groundNormal = [0.0, 0.0, 1.0]
    selectedGroundPoint = [0.0, 0.0, 0.0]

    t = vtk.mutable(0.0)
    vtk.vtkPlane.IntersectWithLine(worldPt1, worldPt2, groundNormal, groundOrigin, t, selectedGroundPoint)

    walkingTarget = transformUtils.frameFromPositionAndRPY(selectedGroundPoint, np.array(footFrame.GetOrientation()))

    footstepsdriverpanel.panel.onNewWalkingGoal(walkingTarget)

def toggleFootstepWidget(displayPoint, view, useHorizontalWidget=False):

    obj, _ = vis.findPickedObject(displayPoint, view)

    if not obj:
        return False

    name = obj.getProperty('Name')

    if name in ('footstep widget', 'footstep widget frame'):
        om.removeFromObjectModel(om.findObjectByName('footstep widget'))
        return True

    match = re.match('^step (\d+)$', name)
    if not match:
        return False

    stepIndex = int(match.group(1))

    existingWidget = om.findObjectByName('footstep widget')
    if existingWidget:
        previousStep = existingWidget.stepIndex
        om.removeFromObjectModel(existingWidget)
        if previousStep == stepIndex:
            return True

    footMesh = shallowCopy(obj.polyData)
    footFrame = transformUtils.copyFrame(obj.getChildFrame().transform)

    if useHorizontalWidget:
        rpy = [0.0, 0.0, transformUtils.rollPitchYawFromTransform(footFrame)[2]]
        footFrame = transformUtils.frameFromPositionAndRPY(footFrame.GetPosition(), np.degrees(rpy))

    footObj = vis.showPolyData(footMesh, 'footstep widget', parent='planning', alpha=0.2)
    footObj.stepIndex = stepIndex
    frameObj = vis.showFrame(footFrame, 'footstep widget frame', parent=footObj, scale=0.2)
    footObj.actor.SetUserTransform(frameObj.transform)
    footObj.setProperty('Color', obj.getProperty('Color'))
    frameObj.setProperty('Edit', True)

    rep = frameObj.widget.GetRepresentation()
    rep.SetTranslateAxisEnabled(2, False)
    rep.SetRotateAxisEnabled(0, False)
    rep.SetRotateAxisEnabled(1, False)
    frameObj.widget.HandleRotationEnabledOff()

    walkGoal = om.findObjectByName('walking goal')
    if walkGoal:
        walkGoal.setProperty('Edit', False)

    def onFootWidgetChanged(frame):
        footstepsDriver.onStepModified(stepIndex - 1, frame)

    frameObj.connectFrameModified(onFootWidgetChanged)
    return True

def reachToFrame(frameObj, side, collisionObj):
    goalFrame = teleoppanel.panel.endEffectorTeleop.newReachTeleop(frameObj.transform, side, collisionObj)
    goalFrame.frameSync = vis.FrameSync()
    goalFrame.frameSync.addFrame(goalFrame, ignoreIncoming=True)
    goalFrame.frameSync.addFrame(frameObj)

def getAsFrame(obj):
    if isinstance(obj, vis.FrameItem):
        return obj
    elif hasattr(obj, 'getChildFrame'):
        return obj.getChildFrame()

def isGraspSeed(obj):
    return hasattr(obj, 'side')

def getCollisionParent(obj):
    '''
    If obj is an affordance, return obj
    If obj is a frame or a grasp seed, return first parent.
    '''
    if isinstance(obj, vis.FrameItem):
        return obj.parent()
    if isGraspSeed(obj):
        return obj.parent()
    else:
        return obj

# The most recently cached PickedPoint - available as input to any other algorithm
lastCachedPickedPoint = np.array([0,0,0])

def getObjectAsPointCloud(obj):
    try:
        obj = obj.model.polyDataObj
    except AttributeError:
        pass

    try:
        obj.polyData
    except AttributeError:
        return None

    if obj and obj.polyData.GetNumberOfPoints():# and (obj.polyData.GetNumberOfCells() == obj.polyData.GetNumberOfVerts()):
        return obj

def getRobotActions(view, pickedObj, pickedPoint):

    reachFrame = getAsFrame(pickedObj)
    collisionParent = getCollisionParent(pickedObj)
    pointCloudObj = getObjectAsPointCloud(pickedObj)
    affordanceObj = pickedObj if isinstance(pickedObj, affordanceitems.AffordanceItem) else None

    def onReachLeft():
        reachToFrame(reachFrame, 'left', collisionParent)

    def onReachRight():
        reachToFrame(reachFrame, 'right', collisionParent)

    def flipHandSide():
        for obj in [pickedObj] + pickedObj.children():
            if not isGraspSeed(obj):
                continue
            side = 'right' if obj.side == 'left' else 'left'
            obj.side = side
            color = [1.0, 1.0, 0.0]
            if side == 'right':
                color = [0.33, 1.0, 0.0]
            obj.setProperty('Color', color)

            polyData = handFactory.getNewHandPolyData(side)
            obj.setPolyData(polyData)

            handFrame = obj.children()[0]
            t = transformUtils.copyFrame(handFrame.transform)
            t.PreMultiply()
            t.RotateY(180)
            handFrame.copyFrame(t)

            objName = obj.getProperty('Name')
            frameName = handFrame.getProperty('Name')
            if side == 'left':
                obj.setProperty('Name', objName.replace("right", "left"))
                handFrame.setProperty('Name', frameName.replace("right", "left"))
            else:
                obj.setProperty('Name', objName.replace("left", "right"))
                handFrame.setProperty('Name', frameName.replace("left", "right"))
            obj._renderAllViews()

    def flipHandThumb():
        handFrame = pickedObj.children()[0]
        t = transformUtils.copyFrame(handFrame.transform)
        t.PreMultiply()
        t.RotateY(180)
        handFrame.copyFrame(t)
        pickedObj._renderAllViews()

    def onSplineLeft():
        splinewidget.planner.newSpline(pickedObj, 'left')

    def onSplineRight():
        splinewidget.planner.newSpline(pickedObj, 'right')

    def onSegmentGround():
        groundPoints, scenePoints =  segmentation.removeGround(pointCloudObj.polyData)
        vis.showPolyData(groundPoints, 'ground points', color=[0,1,0], parent='segmentation')
        vis.showPolyData(scenePoints, 'scene points', color=[1,0,1], parent='segmentation')
        pickedObj.setProperty('Visible', False)

    def onCopyPointCloud():
        global lastRandomColor
        polyData = vtk.vtkPolyData()
        polyData.DeepCopy(pointCloudObj.polyData)

        if pointCloudObj.getChildFrame():
            polyData = segmentation.transformPolyData(polyData, pointCloudObj.getChildFrame().transform)
        polyData = segmentation.addCoordArraysToPolyData(polyData)

        # generate random color, and average with a common color to make them generally similar
        lastRandomColor = lastRandomColor + 0.1 + 0.1*random.random()
        rgb = colorsys.hls_to_rgb(lastRandomColor, 0.7, 1.0)
        obj = vis.showPolyData(polyData, pointCloudObj.getProperty('Name') + ' copy', color=rgb, parent='point clouds')

        #t = vtk.vtkTransform()
        #t.PostMultiply()
        #t.Translate(filterUtils.computeCentroid(polyData))
        #segmentation.makeMovable(obj, t)
        om.setActiveObject(obj)
        pickedObj.setProperty('Visible', False)

    def onMergeIntoPointCloud():
        allPointClouds = om.findObjectByName('point clouds')
        if allPointClouds:
            allPointClouds = [i.getProperty('Name') for i in allPointClouds.children()]
        sel =  QtGui.QInputDialog.getItem(None, "Point Cloud Merging", "Pick point cloud to merge into:", allPointClouds, current=0, editable=False)
        sel = om.findObjectByName(sel)

        # Make a copy of each in same frame
        polyDataInto = vtk.vtkPolyData()
        polyDataInto.ShallowCopy(sel.polyData)
        if sel.getChildFrame():
            polyDataInto = segmentation.transformPolyData(polyDataInto, sel.getChildFrame().transform)

        polyDataFrom = vtk.vtkPolyData()
        polyDataFrom.DeepCopy(pointCloudObj.polyData)
        if pointCloudObj.getChildFrame():
            polyDataFrom = segmentation.transformPolyData(polyDataFrom, pointCloudObj.getChildFrame().transform)

        # Actual merge
        append = filterUtils.appendPolyData([polyDataFrom, polyDataInto])
        if sel.getChildFrame():
            polyDataInto = segmentation.transformPolyData(polyDataInto, sel.getChildFrame().transform.GetInverse())

        # resample
        append = segmentationroutines.applyVoxelGrid(append, 0.01)
        append = segmentation.addCoordArraysToPolyData(append)

        # Recenter the frame
        sel.setPolyData(append)
        t = vtk.vtkTransform()
        t.PostMultiply()
        t.Translate(filterUtils.computeCentroid(append))
        segmentation.makeMovable(sel, t)

        # Hide the old one
        if pointCloudObj.getProperty('Name') in allPointClouds:
            pointCloudObj.setProperty('Visible', False)

    def onSegmentTableScene():
        data = segmentation.segmentTableScene(pointCloudObj.polyData, pickedPoint)
        vis.showClusterObjects(data.clusters, parent='segmentation')
        segmentation.showTable(data.table, parent='segmentation')

    def onSegmentDrillAlignedWithTable():
        segmentation.segmentDrillAlignedWithTable(pickedPoint, pointCloudObj.polyData)

    def onCachePickedPoint():
        ''' Cache the Picked Point for general purpose use'''
        global lastCachedPickedPoint
        lastCachedPickedPoint = pickedPoint
        #data = segmentation.segmentTableScene(pointCloudObj.polyData, pickedPoint)
        #vis.showClusterObjects(data.clusters + [data.table], parent='segmentation')

    def onLocalPlaneFit():
        planePoints, normal = segmentation.applyLocalPlaneFit(pointCloudObj.polyData, pickedPoint, searchRadius=0.1, searchRadiusEnd=0.2)
        obj = vis.showPolyData(planePoints, 'local plane fit', color=[0,1,0])
        obj.setProperty('Point Size', 7)

        fields = segmentation.makePolyDataFields(obj.polyData)

        pose = transformUtils.poseFromTransform(fields.frame)
        desc = dict(classname='BoxAffordanceItem', Name='local plane', Dimensions=list(fields.dims), pose=pose)
        box = segmentation.affordanceManager.newAffordanceFromDescription(desc)

    def onOrientToMajorPlane():
        polyData, planeFrame = segmentation.orientToMajorPlane(pointCloudObj.polyData, pickedPoint=pickedPoint)
        pointCloudObj.setPolyData(polyData)

    def onDiskGlyph():
        result = segmentation.applyDiskGlyphs(pointCloudObj.polyData)
        obj = vis.showPolyData(result, 'disks', color=[0.8,0.8,0.8])
        om.setActiveObject(obj)
        pickedObj.setProperty('Visible', False)

    def onArrowGlyph():
        result = segmentation.applyArrowGlyphs(pointCloudObj.polyData)
        obj = vis.showPolyData(result, 'arrows')

    def onSegmentationEditor():
        segmentationpanel.activateSegmentationMode(pointCloudObj.polyData)

    def addNewFrame():
        t = transformUtils.copyFrame(affordanceObj.getChildFrame().transform)
        t.PostMultiply()
        t.Translate(np.array(pickedPoint) - np.array(t.GetPosition()))
        newFrame = vis.showFrame(t, '%s frame %d' % (affordanceObj.getProperty('Name'), len(affordanceObj.children())), scale=0.2, parent=affordanceObj)
        affordanceObj.getChildFrame().getFrameSync().addFrame(newFrame, ignoreIncoming=True)

    def copyAffordance():
        desc = dict(affordanceObj.getDescription())
        del desc['uuid']
        desc['Name'] = desc['Name'] + ' copy'
        aff = robotSystem.affordanceManager.newAffordanceFromDescription(desc)
        aff.getChildFrame().setProperty('Edit', True)

    def onPromoteToAffordance():
        affObj = affordanceitems.MeshAffordanceItem.promotePolyDataItem(pickedObj)
        robotSystem.affordanceManager.registerAffordance(affObj)

    actions = []

    if affordanceObj:
        actions.extend([
            ('Copy affordance', copyAffordance),
            ('Add new frame', addNewFrame),
        ])

    elif type(pickedObj) == vis.PolyDataItem:
        actions.extend([
            ('Promote to Affordance', onPromoteToAffordance),
        ])

    if isGraspSeed(pickedObj):
        actions.extend([
            (None, None),
            ('Flip Side', flipHandSide),
            ('Flip Thumb', flipHandThumb),
        ])

    if reachFrame is not None:
        actions.extend([
            (None, None),
            ('Reach Left', onReachLeft),
            ('Reach Right', onReachRight),
            #('Spline Left', onSplineLeft),
            #('Spline Right', onSplineRight),
            ])

    if pointCloudObj:
        actions.extend([
            (None, None),
            ('Copy Pointcloud', onCopyPointCloud),
            ('Merge Pointcloud Into', onMergeIntoPointCloud),
            ('Segment Ground', onSegmentGround),
            ('Segment Table', onSegmentTableScene),
            ('Segment Drill Aligned', onSegmentDrillAlignedWithTable),
            ('Local Plane Fit', onLocalPlaneFit),
            ('Orient with Horizontal', onOrientToMajorPlane),
            ('Arrow Glyph', onArrowGlyph),
            ('Disk Glyph', onDiskGlyph),
            ('Cache Pick Point', onCachePickedPoint),
            (None, None),
            ('Open Segmentation Editor', onSegmentationEditor)
            ])

    return actions

viewbehaviors.registerContextMenuActions(getRobotActions)

class RobotViewEventFilter(ViewEventFilter):

    def onMouseWheel(self, event):
        if neckDriver:
            neckDriver.onWheelDelta(event.delta())

    def onMouseMove(self, event):

        for picker in segmentation.viewPickers:
            if not picker.enabled:
                continue

            picker.onMouseMove(vis.mapMousePosition(self.view, event), event.modifiers())
            self.consumeEvent()

    def onLeftMousePress(self, event):
        if event.modifiers() == QtCore.Qt.ControlModifier:
            displayPoint = vis.mapMousePosition(self.view, event)
            if footstepsDriver:
                newWalkingGoal(displayPoint, self.view)
                self.consumeEvent()

        for picker in segmentation.viewPickers:
            if not picker.enabled:
                continue

            picker.onMousePress(vis.mapMousePosition(self.view, event), event.modifiers())
            self.consumeEvent()

    def onLeftDoubleClick(self, event):

        displayPoint = vis.mapMousePosition(self.view, event)

        useHorizontalWidget =  (event.modifiers() == QtCore.Qt.ShiftModifier)
        if toggleFootstepWidget(displayPoint, self.view, useHorizontalWidget):
            self.consumeEvent()
            return

        if robotLinkSelector and robotLinkSelector.selectLink(displayPoint, self.view):
            self.consumeEvent()
            return

    def onKeyPress(self, event):

        consumed = False

        key = str(event.text()).lower()

        if key == 'r':
            consumed = True
            if robotModel is not None:
                resetCameraToRobot(self.view)

        elif key == 's':
            if handFactory is not None:
                side = 'left' if event.modifiers() != QtCore.Qt.ShiftModifier else 'right'
                placeHandModel(self.getCursorDisplayPosition(), self.view, side)
        elif key == 'n':
            if neckDriver:
                neckDriver.activateNeckControl()

        elif key in ['0', '1', '2', '3']:
            if neckDriver:
                neckDriver.applyNeckPitchPreset(int(key))

        if consumed:
            self.consumeEvent()

    def onKeyRelease(self, event):
        if str(event.text()).lower() == 'n':
            if neckDriver:
                neckDriver.deactivateNeckControl()

class KeyPressLogCommander(ViewEventFilter):

    def __init__(self, view):
        ViewEventFilter.__init__(self, view)
        self.commander = lcmUtils.LogPlayerCommander()

    def onKeyPressRepeat(self, event):

        key = str(event.text()).lower()
        consumed = True

        if key == 'p':
            self.commander.togglePlay()
        elif key == 'n':
            self.commander.step()
        elif key in ('+', '='):
            self.commander.faster()
        elif key in ('-', '_'):
            self.commander.slower()
        elif key == '[':
            self.commander.back()
        elif key == ']':
            self.commander.forward()
        else:
            consumed = False

        if consumed:
            self.consumeEvent()

class RobotViewBehaviors(object):

    def __init__(self, view, _robotSystem):
        self.view = view
        self.viewBehaviors = viewbehaviors.ViewBehaviors(view)
        self.logCommander = KeyPressLogCommander(view)
        self.robotViewBehaviors = RobotViewEventFilter(view)

        global robotSystem, robotModel, handFactory, footstepsDriver, neckDriver, robotLinkSelector

        robotSystem = _robotSystem
        robotModel = robotSystem.robotStateModel
        handFactory = robotSystem.handFactory
        footstepsDriver = robotSystem.footstepsDriver
        neckDriver = robotSystem.neckDriver
        if app.getMainWindow() is not None:
            robotLinkSelector = RobotLinkSelector()


text:
id: 5a23c84252665b21eecc8041
title: Sum of a series
challengeType: 5
isHidden: false
forumTopicId: 302333
---

## Description

Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
$S_n = \sum_{k=1}^n \frac{1}{k^2}$
and compute $S_{1000}$
This approximates the zeta function for S=2, whose exact value
$\zeta(2) = {\pi^2\over 6}$
is the solution of the Basel problem.

## Instructions

Write a function that take $a$ and $b$ as parameters and returns the sum of $a^{th}$ to $b^{th}$ members of the sequence.

## Tests

```yml
tests:
  - text: <code>sum</code> should be a function.
    testString: assert(typeof sum == 'function');
  - text: <code>sum(1, 100)</code> should return a number.
    testString: assert(typeof sum(1, 100) == 'number');
  - text: <code>sum(1, 100)</code> should return <code>1.6349839001848923</code>.
    testString: assert.equal(sum(1, 100), 1.6349839001848923);
  - text: <code>sum(33, 46)</code> should return <code>0.009262256361481223</code>.
    testString: assert.equal(sum(33, 46), 0.009262256361481223);
  - text: <code>sum(21, 213)</code> should return <code>0.044086990748706555</code>.
    testString: assert.equal(sum(21, 213), 0.044086990748706555);
  - text: <code>sum(11, 111)</code> should return <code>0.08619778593108679</code>.
    testString: assert.equal(sum(11, 111), 0.08619778593108679);
  - text: <code>sum(1, 10)</code> should return <code>1.5497677311665408</code>.
    testString: assert.equal(sum(1, 10), 1.5497677311665408);
```

## Challenge Seed

```js
function sum(a, b) {
  // Good luck!
}
```

## Solution

```js
function sum(a, b) {
  function fn(x) {
    return 1 / (x * x);
  }
  var s = 0;
  for (; a <= b; a++) s += fn(a);
  return s;
}
```


text:
package com.commonsware.android.rotation.async;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

public class RotationAsync extends Activity {
  private ProgressBar bar=null;
  private RotationAwareTask task=null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    bar=(ProgressBar)findViewById(R.id.progress);

    task=(RotationAwareTask)getLastNonConfigurationInstance();

    if (task==null) {
      task=new RotationAwareTask(this);
      task.execute();
    }
    else {
      task.attach(this);
      updateProgress(task.getProgress());

      if (task.getProgress()>=100) {
        markAsDone();
      }
    }
  }

  @Override
  public Object onRetainNonConfigurationInstance() {
    task.detach();

    return(task);
  }

  void updateProgress(int progress) {
    bar.setProgress(progress);
  }

  void markAsDone() {
    findViewById(R.id.completed).setVisibility(View.VISIBLE);
  }

  static class RotationAwareTask extends AsyncTask<Void, Void, Void> {
    RotationAsync activity=null;
    int progress=0;

    RotationAwareTask(RotationAsync activity) {
      attach(activity);
    }

    @Override
    protected Void doInBackground(Void... unused) {
      for (int i=0;i<20;i++) {
        SystemClock.sleep(500);
        publishProgress();
      }

      return(null);
    }

    @Override
    protected void onProgressUpdate(Void... unused) {
      if (activity==null) {
        Log.w("RotationAsync", "onProgressUpdate() skipped -- no activity");
      }
      else {
        progress+=5;
        activity.updateProgress(progress);
      }
    }

    @Override
    protected void onPostExecute(Void unused) {
      if (activity==null) {
        Log.w("RotationAsync", "onPostExecute() skipped -- no activity");
      }
      else {
        activity.markAsDone();
      }
    }

    void detach() {
      activity=null;
    }

    void attach(RotationAsync activity) {
      this.activity=activity;
    }

    int getProgress() {
      return(progress);
    }
  }
}


text:
import { Change } from './actions'

const initState = ''

export default (state = initState, action) => {
  switch (action.constructor) {
    case Change:
      return action.value
    default:
      return state
  }
}


text:
package com.adv.manager.mapper;

import com.adv.manager.po.Account;

public interface AccountMapper {
    int deleteByPrimaryKey(String username);

    int insert(Account record);

    int insertSelective(Account record);

    Account selectByPrimaryKey(String username);

    int updateByPrimaryKeySelective(Account record);

    int updateByPrimaryKey(Account record);
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="../stylesheets/default.css">
  <link rel="stylesheet" type="text/css" href="../stylesheets/blog.css">
  <link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css'>
  <link href='http://fonts.googleapis.com/css?family=Raleway:400,500' rel='stylesheet' type='text/css'>
  <title>Nathan Vanderlaan</title>

<canvas id="topStripe"></canvas>

Nathan Vanderlaan

Contact Info

Blog

About Me

Past Blog Posts

Helpful Resources

Ruby Docs

Stack Overflow

Sublime Shortcuts

Ruby Monk

Thought Matters

Hello, World!

March 23, 2015

        This is my very first post, but this journey began over a year ago. Join me as I explore the world through code! Stay tuned for updates on where I was, where I am, and where (I think) I'm headed.

        8 weeks til Dev Bootcamp's Phase 0 begins...here goes everything!

  <canvas id="blogbottomShadow"></canvas>

Copyright - 2015


text:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:configure="fr.rjoakim.android.navbro.widget.NavBroWidgetConfigurationActivity"
    android:initialLayout="@layout/main_widget"
    android:minHeight="40dp"
    android:minWidth="40dp"
    android:updatePeriodMillis="0"
    android:widgetCategory="home_screen|keyguard" />


text:
package org.apache.rave.provider.w3c.web.renderer;

import org.apache.rave.exception.NotSupportedException;
import org.apache.rave.model.*;
import org.apache.rave.portal.service.UserService;
import org.apache.rave.portal.service.WidgetProviderService;
import org.apache.rave.portal.web.renderer.RegionWidgetWrapperRenderer;
import org.apache.rave.portal.web.renderer.RenderScope;
import org.apache.rave.portal.web.renderer.ScriptLocation;
import org.apache.rave.portal.web.renderer.ScriptManager;
import org.apache.rave.portal.web.renderer.model.RegionWidgetWrapper;
import org.apache.rave.portal.web.renderer.model.RenderContext;
import org.apache.rave.provider.w3c.service.impl.W3CWidget;
import org.apache.rave.util.JsonUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import static org.apache.rave.provider.w3c.Constants.WIDGET_TYPE;

/**
 * Creates the appropriate markup to represent a W3C widget
 */
@Component
public class W3cWidgetWrapperRenderer implements RegionWidgetWrapperRenderer {
    private static Logger logger = LoggerFactory.getLogger(W3cWidgetWrapperRenderer.class);

    private static final String REGISTER_WIDGET_KEY = "wookieRegisterWidget";

    private final WidgetProviderService widgetService;
    private final UserService userService;
    private ScriptManager scriptManager;

    @Autowired
    public W3cWidgetWrapperRenderer(@Qualifier("wookieWidgetService") WidgetProviderService widgetService,
                                    UserService userService, ScriptManager scriptManager) {
        this.widgetService = widgetService;
        this.userService = userService;
        this.scriptManager = scriptManager;
    }

    /**
     * The script block template
     */
    private static final String SCRIPT_BLOCK =
        "<script>require(['rave'], function(rave){rave.registerWidget('%1$s', {type: '%2$s'," +
        " regionWidgetId: %3$s," +
        " widgetUrl: '%4$s', " +
        " height: '%5$s', " +
        " width: '%6$s', " +
        " collapsed: %7$s, " +
        " widgetId: %8$s, " +
        " locked: %9$s, " +
        " hideChrome: %10$s, " +
        " subPage: {id: %11$s, name: '%12$s', isDefault: %13$s}," +
        " properties: %14$s" +
        "})});</script>";
    private static final String MARKUP = "<!-- RegionWidget %1$s placeholder -->";

    @Override
    public String getSupportedContext() {
        return WIDGET_TYPE;
    }

    /**
     * Renders a {@link org.apache.rave.model.RegionWidget} as HTML markup
     *
     * @param wrapper RegionWidgetImpl to render
     * @param context
     * @return valid HTML markup
     */
    @Override
    public String render(RegionWidgetWrapper wrapper, RenderContext context) {
        Widget widget = wrapper.getWidget();
        RegionWidget item = wrapper.getRegionWidget();
        if(!WIDGET_TYPE.equals(widget.getType())) {
            throw new NotSupportedException("Invalid widget type passed to renderer: " + widget.getType());
        }

        String widgetScript = getWidgetScript(item, widget);
        // the key is based off the RegionWidget.id to ensure uniqueness
        String key = REGISTER_WIDGET_KEY + "-" + item.getId();
        scriptManager.registerScriptBlock(key, widgetScript, ScriptLocation.AFTER_RAVE, RenderScope.CURRENT_REQUEST, context);
        logger.debug("Gadget Script Data: " + widgetScript);

        return String.format(MARKUP, item.getId());
    }

    @Override
    public RegionWidgetWrapper prepareForRender(RegionWidgetWrapper item) {
        throw new UnsupportedOperationException();
    }

    /**
     * Create a widget script block
     *
     * @param item the RegionWidget to create a script block for
     * @param widget
     * @return the script block
     */
    private String getWidgetScript(RegionWidget item, Widget widget) {
        User user = userService.getAuthenticatedUser();

        //
        // For the shared data key we use the RegionWidget entity ID.
        //
        String sharedDataKey = String.valueOf(item.getId());

        //
        // Get the Rave Widget for this regionWidget instance
        //
        W3CWidget contextualizedWidget = (W3CWidget) widgetService.getWidget(user, sharedDataKey, widget);

        //
        // TODO make this do something useful; currently these preferences aren't
        // actually available in the Widget Instance as prefs are managed separately in Wookie
        //
        JSONObject userPrefs = new JSONObject();
        if (item.getPreferences() != null) {
            for (RegionWidgetPreference regionWidgetPreference : item.getPreferences()) {
                try {
                    userPrefs.put(regionWidgetPreference.getName(), regionWidgetPreference.getValue());
                } catch (JSONException e) {
                    logger.error("Exception caught adding preference to JSONObject: " + regionWidgetPreference, e);
                }
            }
        }

        //
        // Use width and height attributes if available, otherwise set to "100%"
        //
        String width = "100%";
        String height = "100%";
        if (contextualizedWidget.getWidth() > 0)
           width = String.valueOf(contextualizedWidget.getWidth()) + "px";
        if (contextualizedWidget.getHeight() > 0)
        	height = String.valueOf(contextualizedWidget.getHeight()) + "px";

        // get attributes about the sub page this regionWidget is on.  This is needed to assist the client in
        // determining which gadgets are on visible tabs/sub pages initially to make widget rendering more efficient
        String pageId = null;
        String pageName = "";
        boolean isDefault = false;
        Page page =  item.getRegion().getPage();
        if (PageType.SUB_PAGE.equals(page.getPageType())) {
            pageId = page.getId();
            pageName = page.getName();
            // check to see if this regionWidget is on the first sub page, which will be the default
            // subpage rendered if the user doesn't specify which subpage via the URL hash
            isDefault = isDefaultSubPage(page);
        }

        //
        // Construct and return script block
        //
        return String.format(SCRIPT_BLOCK,
                item.getRegion().getId(),
                WIDGET_TYPE,
                item.getId(),
                contextualizedWidget.getUrl(),
                height,
                width,
                item.isCollapsed(),
                item.getWidgetId(),
                item.isLocked(),
                item.isHideChrome(),
                pageId,
                pageName,
                isDefault,
                JsonUtils.stringify(widget.getProperties()));
    }

    private boolean isDefaultSubPage(Page subPage) {
        return subPage.getParentPage().getSubPages().get(0).getId().equals(subPage.getId());
    }
}


text:
from __future__ import unicode_literals

import logging
import pprint

from .credentials import Credentials
from .node import Node

class Controller(Node):
    """
    Base class for an NFV/VIM or SDN Contoller
    """
    def __init__(self, **kwargs):
        logging.debug('core.Controller.__init__: {}'.format(pprint.PrettyPrinter().pformat(kwargs)))

        Node.__init__(self, **kwargs)

        # Save off site SSH credentials.  Should be useful for most all controller types
        # TODO: Do we want to support per-VIM/SDN sets of credentials?
        # TODO: How about global SSH user/passwords to try as well?

        self._ssh_credentials = None
        config = kwargs.get('config')
        while config is not None:
            if config.type.lower() == 'site':
                self._ssh_credentials = Credentials(config.ssh_username_and_passwords)
                break
            config = config.config_parent

    @staticmethod
    def create(parent, **kwargs):
        from openstack.controller import Controller as OpenStackController
        from onos.controller import Controller as ONOSController

        _supported_vims = {
            'openstack': OpenStackController.create,
            'onos': ONOSController.create
        }
        logging.debug('core.Controller.create: {}'.format(pprint.PrettyPrinter().pformat(kwargs)))

        config = kwargs.get('config')
        create_method = _supported_vims.get(config.type.lower())

        if create_method is None:
            raise NotImplemented("Controller type '{}' is not supported".format(config.type))

        kwargs['parent'] = parent

        return create_method(**kwargs)

    @property
    def ssh_credentials(self):
        return self._ssh_credentials


text:
#pragma once

#include <chrono>

#include "boost/algorithm/string/case_conv.hpp"
#include "boost/algorithm/string/find.hpp"
#include "boost/algorithm/string/trim.hpp"
#include "boost/lexical_cast.hpp"
#include "boost/msm/front/state_machine_def.hpp"

#include "mediafire_sdk/http/detail/http_request_events.hpp"
#include "mediafire_sdk/http/detail/race_preventer.hpp"
#include "mediafire_sdk/http/detail/types.hpp"
#include "mediafire_sdk/http/error.hpp"

namespace mf {
namespace http {
namespace detail {

char const * const header_terminator = "\r\n\r\n";

class ReadHeadersData
{
public:
    ReadHeadersData() :
        cancelled(false)
    {}

    bool cancelled;
};
using ReadHeadersDataPointer = std::shared_ptr<ReadHeadersData>;

template <typename FSM>
void HandleHeaderRead(
        FSM & fsm,
        ReadHeadersDataPointer state_data,
        SharedStreamBuf read_buffer,
        RacePreventer race_preventer,
        const TimePoint start_time,
        const std::size_t bytes_transferred,
        const boost::system::error_code& err
    )
{
    using mf::http::http_error;

    // Stop processing if actions cancelled.
    if (state_data->cancelled == true)
        return;

    // Skip if cancelled due to timeout.
    if ( ! race_preventer.IsFirst() ) return;

    fsm.ClearAsyncTimeout();  // Must stop timeout timer.

    if (fsm.get_bw_analyser())
    {
        fsm.get_bw_analyser()->RecordIncomingBytes(
            read_buffer->size(), start_time, sclock::now() );
    }

    HeadersReadEvent evt;
    {
        // Copy headers.

        asio::streambuf::const_buffers_type bufs = read_buffer->data();

        evt.raw_headers = std::string(
                asio::buffers_begin(bufs),
                (asio::buffers_begin(bufs) + bytes_transferred));
    }

    // Instead of checking for error, which is sometimes masked by SSL errors,
    // check for header termination.
    const bool headers_received = evt.raw_headers.find(header_terminator)
                                  != std::string::npos;

    if (headers_received)
    {
        // Pass the buffer incase it contains any unread data.
        evt.read_buffer = read_buffer;

        std::istream response_stream(read_buffer.get());
        response_stream >> evt.http_version;
        response_stream >> evt.status_code;
        std::getline(response_stream, evt.status_message);

        if ( ! response_stream
                || evt.http_version.substr(0, 5) != "HTTP/")
        {
            std::stringstream ss;
            ss << "Protocol error while parsing headers("
                << fsm.get_url() << ").";
            fsm.ProcessEvent(
                ErrorEvent{
                    make_error_code(
                        http_error::UnparsableHeaders ),
                    ss.str()
                });
            return;
        }

        std::string line;
        std::string last_header_name;
        while (std::getline(response_stream, line) && line != "\r")
        {
            boost::trim_right(line);

            if ( line.empty() ) continue;

            // HTTP headers can be split up inbetween lines.
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2
            if ( line[0] == ' ' || line[0] == '\t' )
            {
                if ( last_header_name.empty() )
                {
                    std::stringstream ss;
                    ss << "Failure while reading headers url("
                        << fsm.get_url() << ").";
                    ss << " Badly formatted headers.";
                    fsm.ProcessEvent(
                        ErrorEvent{
                            make_error_code(
                                http_error::UnparsableHeaders ),
                            ss.str()
                        });
                    return;
                }

                // This is a continuation of previous line.
                auto it = evt.headers.find(last_header_name);
                it->second += " ";
                boost::trim(line);
                it->second += line;

                continue;
            }

            boost::iterator_range<std::string::iterator> result =
                boost::find_first(line, ":");

            if ( ! result.empty() )
            {
                std::string header_name = std::string(
                        line.begin(), result.begin());

                std::string header_value = std::string(
                        result.end(), line.end());

                boost::trim(header_name);
                boost::to_lower(header_name);

                boost::trim(header_value);

                evt.headers.emplace(header_name, header_value);

                // Record the last header name in case the next line is
                // extended.
                last_header_name.swap(header_name);
            }
        }

        {
            auto it = evt.headers.find("content-length");
            if ( it != evt.headers.end() )
            {
                try {
                    evt.content_length = boost::lexical_cast<uint64_t>(
                            it->second);
                } catch(boost::bad_lexical_cast &) {
                    std::stringstream ss;
                    ss << "Failure while parsing headers url("
                        << fsm.get_url() << ").";
                    ss << " Invalid Content-Length: " << it->second;
                    fsm.ProcessEvent(
                        ErrorEvent{
                            make_error_code(
                                http_error::UnparsableHeaders ),
                            ss.str()
                        });
                    return;
                }
            }
        }

        fsm.ProcessEvent(evt);  // Send HeadersReadEvent
    }
    else if (!err)
    {
        std::stringstream ss;
        ss << "Failure while reading headers url(" << fsm.get_url() << ").";
        ss << " Header termination not in response.";
        ss << " Received: \"" << evt.raw_headers << "\"";
        fsm.ProcessEvent(
                ErrorEvent{make_error_code(http_error::ReadFailure), ss.str()});
    }
    else
    {
        std::stringstream ss;
        ss << "Failure while reading headers url(" << fsm.get_url() << ").";
        ss << " Error: (" << err.message() << ")";
        ss << " Received: \"" << evt.raw_headers << "\"";
        fsm.ProcessEvent(
                ErrorEvent{make_error_code(http_error::ReadFailure), ss.str()});
    }
}

class ReadHeaders : public boost::msm::front::state<>
{
public:
    template <typename Event, typename FSM>
    void on_entry(Event const &, FSM & fsm)
    {
        auto state_data = std::make_shared<ReadHeadersData>();
        state_data_ = state_data;

        // Must prime timeout for async actions.
        auto race_preventer = fsm.SetAsyncTimeout("read response header",
            fsm.get_timeout_seconds());
        auto fsmp = fsm.AsFrontShared();
        auto start_time = sclock::now();

        auto read_buffer = std::make_shared<boost::asio::streambuf>();

        asio::async_read_until(
                *fsm.get_socket_wrapper(), *read_buffer, header_terminator,
                [fsmp, state_data, read_buffer, race_preventer, start_time](
                        const boost::system::error_code & ec,
                        std::size_t bytes_transferred)
                {
                    HandleHeaderRead(*fsmp, state_data, read_buffer,
                                     race_preventer, start_time,
                                     bytes_transferred, ec);
                });
    }

    template <typename Event, typename FSM>
    void on_exit(Event const&, FSM &)
    {
        state_data_->cancelled = true;
        state_data_.reset();
    }

private:
    ReadHeadersDataPointer state_data_;
};

}  // namespace detail
}  // namespace http
}  // namespace mf


text:
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/golang/glog"
	"google.golang.org/grpc"

	"github.com/google/certificate-transparency-go/client"
	"github.com/google/certificate-transparency-go/jsonclient"
	"github.com/google/certificate-transparency-go/trillian/migrillian/configpb"
	"github.com/google/certificate-transparency-go/trillian/migrillian/core"
	"github.com/google/trillian"
	"github.com/google/trillian/monitoring"
	"github.com/google/trillian/monitoring/prometheus"
	"github.com/google/trillian/util"
	"github.com/google/trillian/util/election2"
	etcdelect "github.com/google/trillian/util/election2/etcd"
	"github.com/google/trillian/util/etcd"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
	cfgPath = flag.String("config", "", "Path to migration config file")

	forceMaster   = flag.Bool("force_master", false, "If true, assume master for all logs")
	etcdServers   = flag.String("etcd_servers", "", "A comma-separated list of etcd servers; no etcd registration if empty")
	lockDir       = flag.String("lock_file_path", "/migrillian/master", "etcd lock file directory path")
	electionDelay = flag.Duration("election_delay", 0, "Max random pause before participating in master election")

	metricsEndpoint = flag.String("metrics_endpoint", "localhost:8099", "Endpoint for serving metrics")

	maxIdleConnsPerHost = flag.Int("max_idle_conns_per_host", 10, "Max idle HTTP connections per host (0 = DefaultMaxIdleConnsPerHost)")
	maxIdleConns        = flag.Int("max_idle_conns", 100, "Max number of idle HTTP connections across all hosts (0 = unlimited)")
)

func main() {
	flag.Parse()
	glog.CopyStandardLogTo("WARNING")
	defer glog.Flush()

	cfg, err := getConfig()
	if err != nil {
		glog.Exitf("Failed to load MigrillianConfig: %v", err)
	}
	backendMap, err := core.ValidateConfig(cfg)
	if err != nil {
		glog.Exitf("Failed to validate MigrillianConfig: %v", err)
	}

	// Dial all log backends.
	// TODO(pavelkalinnikov): Commonize backend connection code with CTFE.
	connMap := make(map[string]*grpc.ClientConn)
	dialOpts := []grpc.DialOption{grpc.WithInsecure()}
	if len(backendMap) == 1 {
		// If there's only one backend we can't serve anything until connected.
		dialOpts = append(dialOpts, grpc.WithBlock())
	}
	for _, be := range backendMap {
		glog.Infof("Dialling Trillian backend: %v", be)
		conn, err := grpc.Dial(be.BackendSpec, dialOpts...)
		if err != nil {
			glog.Exitf("Could not dial Trillian server: %v: %v", be, err)
		}
		defer conn.Close()
		connMap[be.Name] = conn
	}

	httpClient := getHTTPClient()
	mf := prometheus.MetricFactory{}
	ef, closeFn := getElectionFactory()
	defer closeFn()

	ctx := context.Background()
	var ctrls []*core.Controller
	for _, mc := range cfg.MigrationConfigs.Config {
		conn := connMap[mc.LogBackendName] // Not nil (config is verified).
		ctrl, err := getController(ctx, mc, httpClient, mf, ef, conn)
		if err != nil {
			glog.Exitf("Failed to create Controller for %q: %v", mc.SourceUri, err)
		}
		ctrls = append(ctrls, ctrl)
	}

	// Handle metrics on the DefaultServeMux.
	http.Handle("/metrics", promhttp.Handler())
	go func() {
		err := http.ListenAndServe(*metricsEndpoint, nil)
		glog.Fatalf("http.ListenAndServe(): %v", err)
	}()

	cctx, cancel := context.WithCancel(ctx)
	defer cancel()
	go util.AwaitSignal(cctx, cancel)

	core.RunMigration(cctx, ctrls)
}

// getController creates a single log migration Controller.
func getController(
	ctx context.Context,
	cfg *configpb.MigrationConfig,
	httpClient *http.Client,
	mf monitoring.MetricFactory,
	ef election2.Factory,
	conn *grpc.ClientConn,
) (*core.Controller, error) {
	ctOpts := jsonclient.Options{PublicKeyDER: cfg.PublicKey.Der, UserAgent: "ct-go-migrillian/1.0"}
	ctClient, err := client.New(cfg.SourceUri, httpClient, ctOpts)
	if err != nil {
		return nil, fmt.Errorf("failed to create CT client: %v", err)
	}
	plClient, err := newPreorderedLogClient(ctx, conn, cfg)
	if err != nil {
		return nil, fmt.Errorf("failed to create PreorderedLogClient: %v", err)
	}

	opts := core.OptionsFromConfig(cfg)
	opts.StartDelay = *electionDelay
	return core.NewController(opts, ctClient, plClient, ef, mf), nil
}

// getConfig returns MigrillianConfig loaded from the file specified in flags.
func getConfig() (*configpb.MigrillianConfig, error) {
	if len(*cfgPath) == 0 {
		return nil, errors.New("config file not specified")
	}
	cfg, err := core.LoadConfigFromFile(*cfgPath)
	if err != nil {
		return nil, err
	}
	return cfg, nil
}

// getHTTPClient returns an HTTP client created from flags.
func getHTTPClient() *http.Client {
	transport := &http.Transport{
		TLSHandshakeTimeout:   30 * time.Second,
		DisableKeepAlives:     false,
		MaxIdleConns:          *maxIdleConns,
		MaxIdleConnsPerHost:   *maxIdleConnsPerHost,
		IdleConnTimeout:       90 * time.Second,
		ResponseHeaderTimeout: 30 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
	}
	// TODO(pavelkalinnikov): Make the timeout tunable.
	return &http.Client{
		Timeout:   10 * time.Second,
		Transport: transport,
	}
}

// newPreorderedLogClient creates a PreorderedLogClient for the specified tree.
func newPreorderedLogClient(
	ctx context.Context,
	conn *grpc.ClientConn,
	cfg *configpb.MigrationConfig,
) (*core.PreorderedLogClient, error) {
	admin := trillian.NewTrillianAdminClient(conn)
	gt := trillian.GetTreeRequest{TreeId: cfg.LogId}
	tree, err := admin.GetTree(ctx, &gt)
	if err != nil {
		return nil, err
	}
	log := trillian.NewTrillianLogClient(conn)
	pref := fmt.Sprintf("%d", cfg.LogId)
	return core.NewPreorderedLogClient(log, tree, cfg.IdentityFunction, pref)
}

// getElectionFactory returns an election factory based on flags, and a
// function which releases the resources associated with the factory.
func getElectionFactory() (election2.Factory, func()) {
	if *forceMaster {
		glog.Warning("Acting as master for all logs")
		return election2.NoopFactory{}, func() {}
	}
	if len(*etcdServers) == 0 {
		glog.Exit("Either --force_master or --etcd_servers must be supplied")
	}

	cli, err := etcd.NewClient(strings.Split(*etcdServers, ","), 5*time.Second)
	if err != nil || cli == nil {
		glog.Exitf("Failed to create etcd client: %v", err)
	}
	closeFn := func() {
		if err := cli.Close(); err != nil {
			glog.Warningf("etcd client Close(): %v", err)
		}
	}

	hostname, _ := os.Hostname()
	instanceID := fmt.Sprintf("%s.%d", hostname, os.Getpid())
	factory := etcdelect.NewFactory(instanceID, cli, *lockDir)

	return factory, closeFn
}


text:
namespace bluez {

const char BluetoothProfileManagerClient::kNoResponseError[] =
    "org.chromium.Error.NoResponse";

BluetoothProfileManagerClient::Options::Options() = default;

BluetoothProfileManagerClient::Options::~Options() = default;

// The BluetoothProfileManagerClient implementation used in production.
class BluetoothProfileManagerClientImpl : public BluetoothProfileManagerClient {
 public:
  BluetoothProfileManagerClientImpl() {}

  ~BluetoothProfileManagerClientImpl() override = default;

  // BluetoothProfileManagerClient override.
  void RegisterProfile(const dbus::ObjectPath& profile_path,
                       const std::string& uuid,
                       const Options& options,
                       const base::Closure& callback,
                       const ErrorCallback& error_callback) override {
    dbus::MethodCall method_call(
        bluetooth_profile_manager::kBluetoothProfileManagerInterface,
        bluetooth_profile_manager::kRegisterProfile);

    dbus::MessageWriter writer(&method_call);
    writer.AppendObjectPath(profile_path);
    writer.AppendString(uuid);

    dbus::MessageWriter array_writer(NULL);
    writer.OpenArray("{sv}", &array_writer);

    dbus::MessageWriter dict_writer(NULL);

    // Send Name if provided.
    if (options.name.get() != NULL) {
      array_writer.OpenDictEntry(&dict_writer);
      dict_writer.AppendString(bluetooth_profile_manager::kNameOption);
      dict_writer.AppendVariantOfString(*(options.name));
      array_writer.CloseContainer(&dict_writer);
    }

    // Send Service if provided.
    if (options.service.get() != NULL) {
      dbus::MessageWriter dict_writer(NULL);
      array_writer.OpenDictEntry(&dict_writer);
      dict_writer.AppendString(bluetooth_profile_manager::kServiceOption);
      dict_writer.AppendVariantOfString(*(options.service));
      array_writer.CloseContainer(&dict_writer);
    }

    // Send Role if not the default value.
    if (options.role != SYMMETRIC) {
      dbus::MessageWriter dict_writer(NULL);
      array_writer.OpenDictEntry(&dict_writer);
      dict_writer.AppendString(bluetooth_profile_manager::kRoleOption);
      if (options.role == CLIENT)
        dict_writer.AppendVariantOfString(
            bluetooth_profile_manager::kClientRoleOption);
      else if (options.role == SERVER)
        dict_writer.AppendVariantOfString(
            bluetooth_profile_manager::kServerRoleOption);
      else
        dict_writer.AppendVariantOfString("");
      array_writer.CloseContainer(&dict_writer);
    }

    // Send Channel if provided.
    if (options.channel.get() != NULL) {
      dbus::MessageWriter dict_writer(NULL);
      array_writer.OpenDictEntry(&dict_writer);
      dict_writer.AppendString(bluetooth_profile_manager::kChannelOption);
      dict_writer.AppendVariantOfUint16(*(options.channel));
      array_writer.CloseContainer(&dict_writer);
    }

    // Send PSM if provided.
    if (options.psm.get() != NULL) {
      dbus::MessageWriter dict_writer(NULL);
      array_writer.OpenDictEntry(&dict_writer);
      dict_writer.AppendString(bluetooth_profile_manager::kPSMOption);
      dict_writer.AppendVariantOfUint16(*(options.psm));
      array_writer.CloseContainer(&dict_writer);
    }

    // Send RequireAuthentication if provided.
    if (options.require_authentication.get() != NULL) {
      array_writer.OpenDictEntry(&dict_writer);
      dict_writer.AppendString(
          bluetooth_profile_manager::kRequireAuthenticationOption);
      dict_writer.AppendVariantOfBool(*(options.require_authentication));
      array_writer.CloseContainer(&dict_writer);
    }

    // Send RequireAuthorization if provided.
    if (options.require_authorization.get() != NULL) {
      array_writer.OpenDictEntry(&dict_writer);
      dict_writer.AppendString(
          bluetooth_profile_manager::kRequireAuthorizationOption);
      dict_writer.AppendVariantOfBool(*(options.require_authorization));
      array_writer.CloseContainer(&dict_writer);
    }

    // Send AutoConnect if provided.
    if (options.auto_connect.get() != NULL) {
      array_writer.OpenDictEntry(&dict_writer);
      dict_writer.AppendString(bluetooth_profile_manager::kAutoConnectOption);
      dict_writer.AppendVariantOfBool(*(options.auto_connect));
      array_writer.CloseContainer(&dict_writer);
    }

    // Send ServiceRecord if provided.
    if (options.service_record.get() != NULL) {
      dbus::MessageWriter dict_writer(NULL);
      array_writer.OpenDictEntry(&dict_writer);
      dict_writer.AppendString(bluetooth_profile_manager::kServiceRecordOption);
      dict_writer.AppendVariantOfString(*(options.service_record));
      array_writer.CloseContainer(&dict_writer);
    }

    // Send Version if provided.
    if (options.version.get() != NULL) {
      dbus::MessageWriter dict_writer(NULL);
      array_writer.OpenDictEntry(&dict_writer);
      dict_writer.AppendString(bluetooth_profile_manager::kVersionOption);
      dict_writer.AppendVariantOfUint16(*(options.version));
      array_writer.CloseContainer(&dict_writer);
    }

    // Send Features if provided.
    if (options.features.get() != NULL) {
      dbus::MessageWriter dict_writer(NULL);
      array_writer.OpenDictEntry(&dict_writer);
      dict_writer.AppendString(bluetooth_profile_manager::kFeaturesOption);
      dict_writer.AppendVariantOfUint16(*(options.features));
      array_writer.CloseContainer(&dict_writer);
    }

    writer.CloseContainer(&array_writer);

    object_proxy_->CallMethodWithErrorCallback(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&BluetoothProfileManagerClientImpl::OnSuccess,
                       weak_ptr_factory_.GetWeakPtr(), callback),
        base::BindOnce(&BluetoothProfileManagerClientImpl::OnError,
                       weak_ptr_factory_.GetWeakPtr(), error_callback));
  }

  // BluetoothProfileManagerClient override.
  void UnregisterProfile(const dbus::ObjectPath& profile_path,
                         const base::Closure& callback,
                         const ErrorCallback& error_callback) override {
    dbus::MethodCall method_call(
        bluetooth_profile_manager::kBluetoothProfileManagerInterface,
        bluetooth_profile_manager::kUnregisterProfile);

    dbus::MessageWriter writer(&method_call);
    writer.AppendObjectPath(profile_path);

    object_proxy_->CallMethodWithErrorCallback(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&BluetoothProfileManagerClientImpl::OnSuccess,
                       weak_ptr_factory_.GetWeakPtr(), callback),
        base::BindOnce(&BluetoothProfileManagerClientImpl::OnError,
                       weak_ptr_factory_.GetWeakPtr(), error_callback));
  }

 protected:
  void Init(dbus::Bus* bus,
            const std::string& bluetooth_service_name) override {
    DCHECK(bus);
    object_proxy_ = bus->GetObjectProxy(
        bluetooth_service_name,
        dbus::ObjectPath(
            bluetooth_profile_manager::kBluetoothProfileManagerServicePath));
  }

 private:
  // Called when a response for successful method call is received.
  void OnSuccess(const base::Closure& callback, dbus::Response* response) {
    DCHECK(response);
    callback.Run();
  }

  // Called when a response for a failed method call is received.
  void OnError(const ErrorCallback& error_callback,
               dbus::ErrorResponse* response) {
    // Error response has optional error message argument.
    std::string error_name;
    std::string error_message;
    if (response) {
      dbus::MessageReader reader(response);
      error_name = response->GetErrorName();
      reader.PopString(&error_message);
    } else {
      error_name = kNoResponseError;
      error_message = "";
    }
    error_callback.Run(error_name, error_message);
  }

  dbus::ObjectProxy* object_proxy_;

  // Weak pointer factory for generating 'this' pointers that might live longer
  // than we do.
  // Note: This should remain the last member so it'll be destroyed and
  // invalidate its weak pointers before any other members are destroyed.
  base::WeakPtrFactory<BluetoothProfileManagerClientImpl> weak_ptr_factory_{
      this};

  DISALLOW_COPY_AND_ASSIGN(BluetoothProfileManagerClientImpl);
};

BluetoothProfileManagerClient::BluetoothProfileManagerClient() = default;

BluetoothProfileManagerClient::~BluetoothProfileManagerClient() = default;

BluetoothProfileManagerClient* BluetoothProfileManagerClient::Create() {
  return new BluetoothProfileManagerClientImpl();
}

}  // namespace bluez


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<TITLE>CLHS: Issue PACKAGE-FUNCTION-CONSISTENCY Writeup</TITLE>
<META HTTP-EQUIV="Author" CONTENT="Kent M. Pitman">
<META HTTP-EQUIV="Organization" CONTENT="The Harlequin Group Limited">
<LINK REL=TOP HREF="../FrontMatter/index.html">
<LINK REL=COPYRIGHT HREF="../FrontMatter/About-HyperSpec.html#Legal">
<LINK REL=DISCLAIMER HREF="../FrontMatter/About-HyperSpec.html#Disclaimer">
<LINK REL=PREV HREF="../Issues/iss253-writeup.html">
<LINK REL=UP HREF="../Issues/iss254.html">
<LINK REL=NEXT HREF="../Issues/iss255-writeup.html">

Issue PACKAGE-FUNCTION-CONSISTENCY Writeup

Issue:        PACKAGE-FUNCTION-CONSISTENCY

References:   11.7 Package System Functions and Variables (pp182-188)

Category:     CLARIFICATION/CHANGE

Edit history: 21-Oct-88, Version 1 by Pitman

		12-Jan-89, Version 2 by Masinter (add MORE-PERMISSIVE option)

		17-Mar-89, Version 3, by Masinter, MORE-PERMISSIVE as

			amended & adopted at Jan 89 X3j13

		17-Mar-89, Version 4, by Moon, correct amended wording

Problem Description:

  CLtL is vague about whether either or both of package or package name

  are permissible in some cases.

Proposal (PACKAGE-FUNCTION-CONSISTENCY:MORE-PERMISSIVE):

  Clarify that it is permissible to pass either a package object

  or a package name (symbol or string) in the following situations:

    - the :USE argument to MAKE-PACKAGE or IN-PACKAGE

    - the first argument to IN-PACKAGE, FIND-PACKAGE, RENAME-PACKAGE

			or DELETE-PACKAGE

    - the second argument to INTERN, FIND-SYMBOL, UNINTERN

    - the second argument to EXPORT, UNEXPORT, IMPORT,

      SHADOWING-IMPORT, and SHADOW

    - the first argument (or a member of the list which is the first

      argument) to USE-PACKAGE or UNUSE-PACKAGE.

    - all package-name arguments in DEFPACKAGE except for the name and

      nicknames of the package being defined.

    - the first argument to PACKAGE-NAME, PACKAGE-NICKNAMES,

      PACKAGE-USE-LIST, or PACKAGE-USED-BY-LIST

    - the PACKAGE argument to DO-SYMBOLS.

    - the PACKAGE argument to DO-EXTERNAL-SYMBOLS.

    - the PACKAGE argument to DO-ALL-SYMBOLS.

  If FIND-PACKAGE is given a package object as an argument, it simply

  returns it.

  Clarify that the function MAKE-PACKAGE permits only a package name

  as an argument since it does not make sense to create an existing

  package.

  Clarify that package nicknames must always be expressed as package

  names (symbols or strings) and may never be actual package objects.

  In the list above, IN-PACKAGE may be changed to SELECT-PACKAGE

  if IN-PACKAGE-FUNCTIONALITY:NEW-MACRO passes.

Examples:

  (INTERN "FOO" "KEYWORD") => :FOO

  (DEFVAR *FOO-PACKAGE* (MAKE-PACKAGE "FOO"))

  (RENAME-PACKAGE "FOO" "FOO0")

  (PACKAGE-NAME *FOO-PACKAGE*) => "FOO0"

  (PACKAGE-NAME "SYS") might return "SYSTEM".

Rationale:

   This makes things more consistent.

   It also adds a generally useful capability.

Current Practice:

  Symbolics Genera & Lucid permit strings as package names.

  Symbolics Cloe does not permit strings as package names.

  In Lucid FIND-PACKAGE and IN-PACKAGE require names.

Cost to Implementors:

  Small.

Cost to Users:

  None. This change is upward compatible.

Cost of Non-Adoption:

  Implementations would continue to vary gratuitously, leaving a potential

  for portability problems.

Benefits:

  The cost of non-adoption is avoided.

Aesthetics:

  This makes things more regular, and so presumably more aesthetic.

Discussion:

  Pitman ran across this problem while trying to port Macsyma to various

  implementations. Discussion with other maintainers of portable programs

  shows this is a common source of aggravation in portable code.

  It would be possible to say that MAKE-PACKAGE took package objects as

  arguments and just returned that package. That might have limited

  usefulness on rare occasions, but mostly seemed too far out in left

  field to bother suggesting it.

Copyright 1996, The Harlequin Group Limited.  All Rights Reserved.


text:
/**
 *
 */
package com.aravind.md5.generator.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

import com.aravind.md5.generator.MD5Genaral;

/**
 * @author aravind
 *
 */
public class MD5Genarator {
	private static final Logger LOG = Logger.getLogger(MD5Genarator.class);
	public static enum MESSAGE_DIGEST_ALGORITHM_TYPE {
		MD5, SHA160 , SHA256
	}

	public static String generateMD5HashString(String message, MESSAGE_DIGEST_ALGORITHM_TYPE TYPE){
		StringBuffer hashString = null;
		String algorithm = TYPE.name();
		LOG.info("-----algorithm type---"+algorithm);
		if(!message.isEmpty() && !message.equals(null) && !algorithm.isEmpty() && !algorithm.equals(null)){
			try {
				MessageDigest msgDigest = MessageDigest.getInstance(algorithm);
				byte[] messageInByte = message.getBytes();
				msgDigest.update(messageInByte);
				byte[] messageHashInByte = msgDigest.digest();
				hashString = new StringBuffer();
				for(int i=0; i<messageHashInByte.length; i++){
					hashString.append(Integer.toString((messageHashInByte[i] & 0xff) + 0x100, 16).substring(1));
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		}
		LOG.info("-----------hashed value==="+hashString);
		return hashString.toString();
	}
	/**
	 * To get SHA-256 hashed values
	 * @param message
	 * @param TYPE
	 * @return {@link String}
	 */
	public static String generateSHA256HashString(String message, MESSAGE_DIGEST_ALGORITHM_TYPE TYPE) {
		StringBuffer shaHasedString = new StringBuffer();
		try {
	        MessageDigest md;
	        String algorithem = "SHA-256";
			md = MessageDigest.getInstance(algorithem);
			md.update(message.getBytes());
		    byte byteData[] = md.digest();
	        for (int i = 0; i < byteData.length; i++) {
	        	shaHasedString.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
	        }
	        LOG.info("----sha-256-"+shaHasedString.toString());
		} catch (NoSuchAlgorithmException e) {
			LOG.error(e);
		}
		return shaHasedString.toString();
	}

}


text:
import nltk

class ConsecutiveNPChunkTagger(nltk.TaggerI):

    def __init__(self, train_sents):
        train_set = []
        for tagged_sent in train_sents:
            untagged_sent = nltk.tag.untag(tagged_sent)
            history = []
            for i, (word, tag) in enumerate(tagged_sent):
                featureset = npchunk_features(untagged_sent, i, history)
                train_set.append( (featureset, tag) )
                history.append(tag)
        self.classifier = nltk.MaxentClassifier.train(
            train_set, algorithm='megam', trace=0)

    def tag(self, sentence):
        history = []
        for i, word in enumerate(sentence):
            featureset = npchunk_features(sentence, i, history)
            tag = self.classifier.classify(featureset)
            history.append(tag)
        return zip(sentence, history)

class ConsecutiveNPChunker(nltk.ChunkParserI):
    def __init__(self, train_sents):
        tagged_sents = [[((w,t),c) for (w,t,c) in
                         nltk.chunk.tree2conlltags(sent)]
                        for sent in train_sents]
        self.tagger = ConsecutiveNPChunkTagger(tagged_sents)

    def parse(self, sentence):
        tagged_sents = self.tagger.tag(sentence)
        conlltags = [(w,t,c) for ((w,t),c) in tagged_sents]
        return nltk.chunk.conlltags2tree(conlltags)


text:
package org.uberfire.ext.wires.bpmn.client.commands.impl;

import java.util.Stack;

import javax.enterprise.context.ApplicationScoped;

import org.kie.soup.commons.validation.PortablePreconditions;
import org.uberfire.ext.wires.bpmn.client.commands.Command;
import org.uberfire.ext.wires.bpmn.client.commands.CommandManager;
import org.uberfire.ext.wires.bpmn.client.commands.ResultType;
import org.uberfire.ext.wires.bpmn.client.commands.Results;
import org.uberfire.ext.wires.bpmn.client.rules.RuleManager;

/**
 * Default implementation of CommandManager
 */
@ApplicationScoped
public class DefaultCommandManagerImpl implements CommandManager {

    private Stack<Command> commands = new Stack<Command>();

    @Override
    public Results execute(final RuleManager ruleManager,
                           final Command command) {
        PortablePreconditions.checkNotNull("command",
                                           command);
        final Results results = command.apply(ruleManager);
        if (!results.contains(ResultType.ERROR)) {
            commands.push(command);
        }
        return results;
    }

    @Override
    public Results undo(final RuleManager ruleManager) {
        if (commands.isEmpty()) {
            throw new IllegalStateException("No commands to undo");
        }
        return commands.pop().undo(ruleManager);
    }
}