<commit_before>/*
   Copyright 2014 Hariharan Srinath

   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.
*/

/*
GoAniGiffy is a utility for converting a set of alphabetically sorted images such as video frames
grabbed from VLC or MPlayer into an animated GIF with options to Crop, Resize, Rotate & Flip the
images prior to creating the GIF

GoAniGiffy performs image operations in the order of cropping, scaling, rotating & flipping
before converting the images into an Animated GIF. Image manipulation is done using
Grigory Dryapak's imaging package. We use the Lanczos filter in Resizing and the default
Floyd-Steinberg dithering used by Go Language's image/gif package to ensure video quality.
Arbitrary angle rotations are not supported.

The -delay parameter must be an integer specifying delay between frames in hundredths of
a second. A value of 3 would give approximately 33 fps theoritically

Usage of goanigiffy:
  -cropheight=-1: height of cropped image, -1 specified full height
  -cropleft=0: left co-ordinate for crop to start
  -croptop=0: top co-ordinate for crop to start
  -cropwidth=-1: width of cropped image, -1 specifies full width
  -delay=3: delay time between frame in hundredths of a second
  -dest="movie.gif": a destination filename for the animated gif
  -flip="none": valid falues are none, horizontal, vertical
  -rotate=0: valid values are 0, 90, 180, 270
  -scale=1: scaling factor to apply if any
  -src="*.jpg": a glob pattern for source images. defaults to *.jpg
  -verbose=false: show in-process messages

Sources: https://github.com/srinathh/goanigiffy
*/
package main

import (
	"bytes"
	"flag"
	"image"
	"image/gif"
	_ "image/jpeg"
	_ "image/png"
	"log"
	"os"
	"path/filepath"
	"runtime"
	"sort"

	"github.com/disintegration/imaging"
)

func CropImage(cropleft, croptop, cropwidth, cropheight int, img image.Image, verbose bool) image.Image {
	//Crop operation. Ignore if there is no crop operation specified
	if !(cropwidth == -1 && cropheight == -1 && cropleft == 0 && croptop == 0) {
		if cropwidth == -1 {
			cropwidth = img.Bounds().Dx()
		}
		if cropheight == -1 {
			cropheight = img.Bounds().Dy()
		}
		if verbose {
			log.Printf("Cropping original image at (%d,%d)->(%d,%d)", cropleft, croptop, cropleft+cropwidth-1, croptop+cropheight-1)
		}
		img = imaging.Crop(img, image.Rect(cropleft, croptop, cropleft+cropwidth-1, croptop+cropheight-1))
	}
	return img
}

func ScaleImage(scale float64, img image.Image, verbose bool) image.Image {
	//Scale operation. Ignore if scale is 1.0
	if scale != 1.0 {
		newwidth := int(float64(img.Bounds().Dx()) * scale)
		newheight := int(float64(img.Bounds().Dy()) * scale)

		if verbose {
			log.Printf("Scaling image from (%d, %d) -> (%d, %d)", img.Bounds().Dx(), img.Bounds().Dy(), newwidth, newheight)
		}
		img = imaging.Resize(img, newwidth, newheight, imaging.Lanczos)
	}
	return img

}

func RotateImage(rotate int, img image.Image, verbose bool) image.Image {
	//Rotate operation. Ignore if rotate is 0
	if rotate != 0 && verbose {
		log.Printf("Rotating by %d", rotate)
	}
	switch rotate {
	case 90:
		img = imaging.Rotate90(img)
	case 180:
		img = imaging.Rotate180(img)
	case 270:
		img = imaging.Rotate270(img)
	}
	return img
}

//FlipImage takes a string
func FlipImage(flip string, img image.Image, verbose bool) image.Image {
	//Flip operation
	if flip != "none" && verbose {
		log.Printf("Flipping %s", flip)
	}

	switch flip {
	case "horizontal":
		img = imaging.FlipH(img)
	case "vertical":
		img = imaging.FlipV(img)
	}
	return img
}

func main() {

	runtime.GOMAXPROCS(runtime.NumCPU())

	srcglob := flag.String("src", "*.jpg", "a glob pattern for source images. defaults to *.jpg")
	destname := flag.String("dest", "movie.gif", "a destination filename for the animated gif")
	cropleft := flag.Int("cropleft", 0, "left co-ordinate for crop to start")
	croptop := flag.Int("croptop", 0, "top co-ordinate for crop to start")
	cropwidth := flag.Int("cropwidth", -1, "width of cropped image, -1 specifies full width")
	cropheight := flag.Int("cropheight", -1, "height of cropped image, -1 specified full height")
	delay := flag.Int("delay", 3, "delay time between frame in hundredths of a second")
	verbose := flag.Bool("verbose", false, "show in-process messages")
	scale := flag.Float64("scale", 1.0, "scaling factor to apply if any")
	rotate := flag.Int("rotate", 0, "valid values are 0, 90, 180, 270")
	flip := flag.String("flip", "none", "valid falues are none, horizontal, vertical")

	flag.Parse()

	if !(*rotate == 0 || *rotate == 90 || *rotate == 180 || *rotate == 270) {
		log.Printf("rotate flag must be one of 0, 90, 180 or 270")
		flag.PrintDefaults()
		os.Exit(1)
	}

	if !(*flip == "none" || *flip == "horizontal" || *flip == "vertical") {
		log.Printf("flip flag must be one of none, horizontal or vertical")
		flag.PrintDefaults()
		os.Exit(1)
	}

	srcfilenames, err := filepath.Glob(*srcglob)
	if err != nil {
		log.Fatalf("Error in globbing source file pattern %s : %s", *srcglob, err)
	}

	if len(srcfilenames) == 0 {
		log.Fatalf("No source images found via pattern %s", *srcglob)
	}

	if *verbose {
		log.Printf("Found %d images to parse", len(srcfilenames))
	}

	sort.Strings(srcfilenames)

	var frames []*image.Paletted

	for ctr, filename := range srcfilenames {
		img, err := imaging.Open(filename)
		if err != nil {
			log.Printf("Skipping file %s due to error reading it :%s", filename, err)
			continue
		}

		if *verbose {
			log.Printf("Parsing image %d of %d : %s", ctr, len(srcfilenames), filename)
		}

		img = CropImage(*cropleft, *croptop, *cropwidth, *cropheight, img, *verbose)
		img = ScaleImage(*scale, img, *verbose)
		img = RotateImage(*rotate, img, *verbose)
		img = FlipImage(*flip, img, *verbose)

		buf := bytes.Buffer{}
		if err := gif.Encode(&buf, img, nil); err != nil {
			log.Printf("Skipping file %s due to error in gif encoding:%s", filename, err)
			continue
		}

		tmpimg, err := gif.Decode(&buf)
		if err != nil {
			log.Printf("Skipping file %s due to weird error reading the temporary gif :%s", filename, err)
			continue
		}
		frames = append(frames, tmpimg.(*image.Paletted))
	}

	if *verbose {
		log.Printf("Parsed all images.. now attemting to create animated GIF %s", *destname)
	}

	delays := make([]int, len(frames))
	for j, _ := range delays {
		delays[j] = *delay
	}

	opfile, err := os.Create(*destname)
	if err != nil {
		log.Fatalf("Error creating the destination file %s : %s", *destname, err)
	}

	if err := gif.EncodeAll(opfile, &gif.GIF{frames, delays, 0}); err != nil {
		log.Printf("Error encoding output into animated gif :%s", err)
	}
	opfile.Close()
}
<commit_msg>Fixed git.GIF initialization<commit_after>/*
   Copyright 2014 Hariharan Srinath

   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.
*/

/*
GoAniGiffy is a utility for converting a set of alphabetically sorted images such as video frames
grabbed from VLC or MPlayer into an animated GIF with options to Crop, Resize, Rotate & Flip the
images prior to creating the GIF

GoAniGiffy performs image operations in the order of cropping, scaling, rotating & flipping
before converting the images into an Animated GIF. Image manipulation is done using
Grigory Dryapak's imaging package. We use the Lanczos filter in Resizing and the default
Floyd-Steinberg dithering used by Go Language's image/gif package to ensure video quality.
Arbitrary angle rotations are not supported.

The -delay parameter must be an integer specifying delay between frames in hundredths of
a second. A value of 3 would give approximately 33 fps theoritically

Usage of goanigiffy:
  -cropheight=-1: height of cropped image, -1 specified full height
  -cropleft=0: left co-ordinate for crop to start
  -croptop=0: top co-ordinate for crop to start
  -cropwidth=-1: width of cropped image, -1 specifies full width
  -delay=3: delay time between frame in hundredths of a second
  -dest="movie.gif": a destination filename for the animated gif
  -flip="none": valid falues are none, horizontal, vertical
  -rotate=0: valid values are 0, 90, 180, 270
  -scale=1: scaling factor to apply if any
  -src="*.jpg": a glob pattern for source images. defaults to *.jpg
  -verbose=false: show in-process messages

Sources: https://github.com/srinathh/goanigiffy
*/
package main

import (
	"bytes"
	"flag"
	"image"
	"image/gif"
	_ "image/jpeg"
	_ "image/png"
	"log"
	"os"
	"path/filepath"
	"runtime"
	"sort"

	"github.com/disintegration/imaging"
)

func CropImage(cropleft, croptop, cropwidth, cropheight int, img image.Image, verbose bool) image.Image {
	//Crop operation. Ignore if there is no crop operation specified
	if !(cropwidth == -1 && cropheight == -1 && cropleft == 0 && croptop == 0) {
		if cropwidth == -1 {
			cropwidth = img.Bounds().Dx()
		}
		if cropheight == -1 {
			cropheight = img.Bounds().Dy()
		}
		if verbose {
			log.Printf("Cropping original image at (%d,%d)->(%d,%d)", cropleft, croptop, cropleft+cropwidth-1, croptop+cropheight-1)
		}
		img = imaging.Crop(img, image.Rect(cropleft, croptop, cropleft+cropwidth-1, croptop+cropheight-1))
	}
	return img
}

func ScaleImage(scale float64, img image.Image, verbose bool) image.Image {
	//Scale operation. Ignore if scale is 1.0
	if scale != 1.0 {
		newwidth := int(float64(img.Bounds().Dx()) * scale)
		newheight := int(float64(img.Bounds().Dy()) * scale)

		if verbose {
			log.Printf("Scaling image from (%d, %d) -> (%d, %d)", img.Bounds().Dx(), img.Bounds().Dy(), newwidth, newheight)
		}
		img = imaging.Resize(img, newwidth, newheight, imaging.Lanczos)
	}
	return img

}

func RotateImage(rotate int, img image.Image, verbose bool) image.Image {
	//Rotate operation. Ignore if rotate is 0
	if rotate != 0 && verbose {
		log.Printf("Rotating by %d", rotate)
	}
	switch rotate {
	case 90:
		img = imaging.Rotate90(img)
	case 180:
		img = imaging.Rotate180(img)
	case 270:
		img = imaging.Rotate270(img)
	}
	return img
}

//FlipImage takes a string
func FlipImage(flip string, img image.Image, verbose bool) image.Image {
	//Flip operation
	if flip != "none" && verbose {
		log.Printf("Flipping %s", flip)
	}

	switch flip {
	case "horizontal":
		img = imaging.FlipH(img)
	case "vertical":
		img = imaging.FlipV(img)
	}
	return img
}

func main() {

	runtime.GOMAXPROCS(runtime.NumCPU())

	srcglob := flag.String("src", "*.jpg", "a glob pattern for source images. defaults to *.jpg")
	destname := flag.String("dest", "movie.gif", "a destination filename for the animated gif")
	cropleft := flag.Int("cropleft", 0, "left co-ordinate for crop to start")
	croptop := flag.Int("croptop", 0, "top co-ordinate for crop to start")
	cropwidth := flag.Int("cropwidth", -1, "width of cropped image, -1 specifies full width")
	cropheight := flag.Int("cropheight", -1, "height of cropped image, -1 specified full height")
	delay := flag.Int("delay", 3, "delay time between frame in hundredths of a second")
	verbose := flag.Bool("verbose", false, "show in-process messages")
	scale := flag.Float64("scale", 1.0, "scaling factor to apply if any")
	rotate := flag.Int("rotate", 0, "valid values are 0, 90, 180, 270")
	flip := flag.String("flip", "none", "valid falues are none, horizontal, vertical")

	flag.Parse()

	if !(*rotate == 0 || *rotate == 90 || *rotate == 180 || *rotate == 270) {
		log.Printf("rotate flag must be one of 0, 90, 180 or 270")
		flag.PrintDefaults()
		os.Exit(1)
	}

	if !(*flip == "none" || *flip == "horizontal" || *flip == "vertical") {
		log.Printf("flip flag must be one of none, horizontal or vertical")
		flag.PrintDefaults()
		os.Exit(1)
	}

	srcfilenames, err := filepath.Glob(*srcglob)
	if err != nil {
		log.Fatalf("Error in globbing source file pattern %s : %s", *srcglob, err)
	}

	if len(srcfilenames) == 0 {
		log.Fatalf("No source images found via pattern %s", *srcglob)
	}

	if *verbose {
		log.Printf("Found %d images to parse", len(srcfilenames))
	}

	sort.Strings(srcfilenames)

	var frames []*image.Paletted

	for ctr, filename := range srcfilenames {
		img, err := imaging.Open(filename)
		if err != nil {
			log.Printf("Skipping file %s due to error reading it :%s", filename, err)
			continue
		}

		if *verbose {
			log.Printf("Parsing image %d of %d : %s", ctr, len(srcfilenames), filename)
		}

		img = CropImage(*cropleft, *croptop, *cropwidth, *cropheight, img, *verbose)
		img = ScaleImage(*scale, img, *verbose)
		img = RotateImage(*rotate, img, *verbose)
		img = FlipImage(*flip, img, *verbose)

		buf := bytes.Buffer{}
		if err := gif.Encode(&buf, img, nil); err != nil {
			log.Printf("Skipping file %s due to error in gif encoding:%s", filename, err)
			continue
		}

		tmpimg, err := gif.Decode(&buf)
		if err != nil {
			log.Printf("Skipping file %s due to weird error reading the temporary gif :%s", filename, err)
			continue
		}
		frames = append(frames, tmpimg.(*image.Paletted))
	}

	if *verbose {
		log.Printf("Parsed all images.. now attemting to create animated GIF %s", *destname)
	}

	delays := make([]int, len(frames))
	for j, _ := range delays {
		delays[j] = *delay
	}

	opfile, err := os.Create(*destname)
	if err != nil {
		log.Fatalf("Error creating the destination file %s : %s", *destname, err)
	}

	if err := gif.EncodeAll(opfile, &gif.GIF{Image: frames, Delay: delays, LoopCount: 0}); err != nil {
		log.Printf("Error encoding output into animated gif :%s", err)
	}
	opfile.Close()
}
<|endoftext|>


<commit_before>package router

import (
	"net/http"
	"strconv"
	"time"

	"github.com/NyaaPantsu/nyaa/model"
	"github.com/NyaaPantsu/nyaa/service/captcha"
	"github.com/NyaaPantsu/nyaa/service/notifier"
	"github.com/NyaaPantsu/nyaa/service/user"
	"github.com/NyaaPantsu/nyaa/service/user/form"
	"github.com/NyaaPantsu/nyaa/service/user/permission"
	"github.com/NyaaPantsu/nyaa/util/crypto"
	"github.com/NyaaPantsu/nyaa/util/publicSettings"
	msg "github.com/NyaaPantsu/nyaa/util/messages"
	"github.com/NyaaPantsu/nyaa/util/modelHelper"
	"github.com/gorilla/mux"
)

// UserRegisterFormHandler : Getting View User Registration
func UserRegisterFormHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	_, errorUser := userService.CurrentUser(r)
	// User is already connected, redirect to home
	if errorUser == nil {
		HomeHandler(w, r)
		return
	}
	messages := msg.GetMessages(r)
	registrationForm := form.RegistrationForm{}
	modelHelper.BindValueForm(&registrationForm, r)
	registrationForm.CaptchaID = captcha.GetID()
	urtv := formTemplateVariables{
		commonTemplateVariables: newCommonVariables(r),
		Form:       registrationForm,
		FormErrors: messages.GetAllErrors(),
	}
	err := viewRegisterTemplate.ExecuteTemplate(w, "index.html", urtv)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

// UserLoginFormHandler : Getting View User Login
func UserLoginFormHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	_, errorUser := userService.CurrentUser(r)
	// User is already connected, redirect to home
	if errorUser == nil {
		HomeHandler(w, r)
		return
	}

	loginForm := form.LoginForm{}
	modelHelper.BindValueForm(&loginForm, r)
	messages := msg.GetMessages(r)
	ulfv := formTemplateVariables{
		commonTemplateVariables: newCommonVariables(r),
		Form:       loginForm,
		FormErrors: messages.GetAllErrors(),
	}

	err := viewLoginTemplate.ExecuteTemplate(w, "index.html", ulfv)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

// UserProfileHandler :  Getting User Profile
func UserProfileHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	vars := mux.Vars(r)
	id := vars["id"]
	Ts, _ := publicSettings.GetTfuncAndLanguageFromRequest(r)
	messages := msg.GetMessages(r)

	userProfile, _, errorUser := userService.RetrieveUserForAdmin(id)
	if errorUser == nil {
		currentUser := getUser(r)
		follow := r.URL.Query()["followed"]
		unfollow := r.URL.Query()["unfollowed"]
		deleteVar := r.URL.Query()["delete"]

		if (deleteVar != nil) && (userPermission.CurrentOrAdmin(currentUser, userProfile.ID)) {
			_, errUser := userService.DeleteUser(w, currentUser, id)
			if errUser != nil {
				messages.ImportFromError("errors", errUser)
			}
			htv := userVerifyTemplateVariables{newCommonVariables(r), messages.GetAllErrors()}
			errorTmpl := viewUserDeleteTemplate.ExecuteTemplate(w, "index.html", htv)
			if errorTmpl != nil {
				http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
			}
		} else {
			if follow != nil {
				messages.AddInfof("infos", Ts("user_followed_msg"), userProfile.Username)
			}
			if unfollow != nil {
				messages.AddInfof("infos", Ts("user_unfollowed_msg"), userProfile.Username)
			}
			userProfile.ParseSettings()
			htv := userProfileVariables{newCommonVariables(r), &userProfile, messages.GetAllInfos()}

			err := viewProfileTemplate.ExecuteTemplate(w, "index.html", htv)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
		}
	} else {
		NotFoundHandler(w, r)
	}
}

// UserDetailsHandler : Getting User Profile Details View
func UserDetailsHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	vars := mux.Vars(r)
	id := vars["id"]
	currentUser := getUser(r)
	messages := msg.GetMessages(r)

	userProfile, _, errorUser := userService.RetrieveUserForAdmin(id)
	if errorUser == nil && userPermission.CurrentOrAdmin(currentUser, userProfile.ID) {
		if userPermission.CurrentOrAdmin(currentUser, userProfile.ID) {
			b := form.UserForm{}
			modelHelper.BindValueForm(&b, r)
			availableLanguages := publicSettings.GetAvailableLanguages()
			userProfile.ParseSettings()
			htv := userProfileEditVariables{newCommonVariables(r), &userProfile, b, messages.GetAllErrors(), messages.GetAllInfos(), availableLanguages}
			err := viewProfileEditTemplate.ExecuteTemplate(w, "index.html", htv)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
		}
	} else {
		NotFoundHandler(w, r)
	}
}

// UserProfileFormHandler : Getting View User Profile Update
func UserProfileFormHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	vars := mux.Vars(r)
	id := vars["id"]
	currentUser := getUser(r)
	userProfile, _, errorUser := userService.RetrieveUserForAdmin(id)
	if errorUser != nil || !userPermission.CurrentOrAdmin(currentUser, userProfile.ID) || userProfile.ID == 0 {
		NotFoundHandler(w, r)
		return
	}
	userProfile.ParseSettings()
	messages := msg.GetMessages(r)
	userForm := form.UserForm{}
	userSettingsForm := form.UserSettingsForm{}

	Ts, _ := publicSettings.GetTfuncAndLanguageFromRequest(r)

	if len(r.PostFormValue("email")) > 0 {
		form.EmailValidation(r.PostFormValue("email"), messages)
	}
	if len(r.PostFormValue("username")) > 0 {
		form.ValidateUsername(r.PostFormValue("username"), messages)
	}

	if !messages.HasErrors() {
		modelHelper.BindValueForm(&userForm, r)
		modelHelper.BindValueForm(&userSettingsForm, r)
		if !userPermission.HasAdmin(currentUser) {
			userForm.Username = userProfile.Username
			userForm.Status = userProfile.Status
		} else {
			if userProfile.Status != userForm.Status && userForm.Status == 2 {
				messages.AddError("errors", "Elevating status to moderator is prohibited")
			}
		}
		modelHelper.ValidateForm(&userForm, messages)
		if !messages.HasErrors() {
			if userForm.Email != userProfile.Email {
				userService.SendVerificationToUser(*currentUser, userForm.Email)
				messages.AddInfof("infos", Ts("email_changed"), userForm.Email)
				userForm.Email = userProfile.Email // reset, it will be set when user clicks verification
			}
			userProfile, _, errorUser = userService.UpdateUser(w, &userForm, &userSettingsForm, currentUser, id)
			if errorUser != nil {
				messages.ImportFromError("errors", errorUser)
			} else {
				messages.AddInfo("infos", Ts("profile_updated"))
			}
		}
	}
	availableLanguages := publicSettings.GetAvailableLanguages()
	upev := userProfileEditVariables{
		commonTemplateVariables: newCommonVariables(r),
		UserProfile:             &userProfile,
		UserForm:                userForm,
		FormErrors:              messages.GetAllErrors(),
		FormInfos:               messages.GetAllInfos(),
		Languages:               availableLanguages,
	}
	errorTmpl := viewProfileEditTemplate.ExecuteTemplate(w, "index.html", upev)
	if errorTmpl != nil {
		http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
	}
}

// UserRegisterPostHandler : Post Registration controller, we do some check on the form here, the rest on user service
func UserRegisterPostHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	b := form.RegistrationForm{}
	messages := msg.GetMessages(r)

	if !captcha.Authenticate(captcha.Extract(r)) {
		messages.AddError("errors", "Wrong captcha!")
	}
	if !messages.HasErrors() {
		if len(r.PostFormValue("email")) > 0 {
			form.EmailValidation(r.PostFormValue("email"), messages)
		}
		form.ValidateUsername(r.PostFormValue("username"), messages)
		if !messages.HasErrors() {
			modelHelper.BindValueForm(&b, r)
			modelHelper.ValidateForm(&b, messages)
			if !messages.HasErrors() {
				_, errorUser := userService.CreateUser(w, r)
				if errorUser != nil {
					messages.ImportFromError("errors", errorUser)
				}
				if !messages.HasErrors() {
					common := newCommonVariables(r)
					common.User = &model.User{
						Email: r.PostFormValue("email"), // indicate whether user had email set
					}
					htv := formTemplateVariables{common, b, messages.GetAllErrors(), messages.GetAllInfos()}
					errorTmpl := viewRegisterSuccessTemplate.ExecuteTemplate(w, "index.html", htv)
					if errorTmpl != nil {
						http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
					}
				}
			}
		}
	}
	if messages.HasErrors() {
		UserRegisterFormHandler(w, r)
	}
}

// UserVerifyEmailHandler : Controller when verifying email, needs a token
func UserVerifyEmailHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	vars := mux.Vars(r)
	token := vars["token"]
	messages := msg.GetMessages(r)

	_, errEmail := userService.EmailVerification(token, w)
	if errEmail != nil {
		messages.ImportFromError("errors", errEmail)
	}
	htv := userVerifyTemplateVariables{newCommonVariables(r), messages.GetAllErrors()}
	errorTmpl := viewVerifySuccessTemplate.ExecuteTemplate(w, "index.html", htv)
	if errorTmpl != nil {
		http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
	}
}

// UserLoginPostHandler : Post Login controller
func UserLoginPostHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	b := form.LoginForm{}
	modelHelper.BindValueForm(&b, r)
	messages := msg.GetMessages(r)

	modelHelper.ValidateForm(&b, messages)
	if !messages.HasErrors() {
		_, errorUser := userService.CreateUserAuthentication(w, r)
		if errorUser != nil {
			messages.ImportFromError("errors", errorUser)
			htv := formTemplateVariables{newCommonVariables(r), b, messages.GetAllErrors(), messages.GetAllInfos()}
			errorTmpl := viewLoginTemplate.ExecuteTemplate(w, "index.html", htv)
			if errorTmpl != nil {
				http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
			}
			return
		}
		url, _ := Router.Get("home").URL()
		http.Redirect(w, r, url.String(), http.StatusSeeOther)
	}
	if messages.HasErrors() {
		UserLoginFormHandler(w, r)
	}
}

// UserLogoutHandler : Controller to logout users
func UserLogoutHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	_, _ = userService.ClearCookie(w)
	url, _ := Router.Get("home").URL()
	http.Redirect(w, r, url.String(), http.StatusSeeOther)
}

// UserFollowHandler : Controller to follow/unfollow users, need user id to follow
func UserFollowHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	var followAction string
	vars := mux.Vars(r)
	id := vars["id"]
	currentUser := getUser(r)
	user, _, errorUser := userService.RetrieveUserForAdmin(id)
	if errorUser == nil && user.ID > 0 {
		if !userPermission.IsFollower(&user, currentUser) {
			followAction = "followed"
			userService.SetFollow(&user, currentUser)
		} else {
			followAction = "unfollowed"
			userService.RemoveFollow(&user, currentUser)
		}
	}
	url, _ := Router.Get("user_profile").URL("id", strconv.Itoa(int(user.ID)), "username", user.Username)
	http.Redirect(w, r, url.String()+"?"+followAction, http.StatusSeeOther)
}

// UserNotificationsHandler : Controller to show user notifications
func UserNotificationsHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	currentUser := getUser(r)
	if currentUser.ID > 0 {
		messages := msg.GetMessages(r)
		Ts, _ := publicSettings.GetTfuncAndLanguageFromRequest(r)
		if r.URL.Query()["clear"] != nil {
			notifierService.DeleteAllNotifications(currentUser.ID)
			messages.AddInfo("infos", Ts("notifications_cleared"))
			currentUser.Notifications = []model.Notification{}
		}
		htv := userProfileVariables{newCommonVariables(r), currentUser, messages.GetAllInfos()}
		err := viewProfileNotifTemplate.ExecuteTemplate(w, "index.html", htv)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	} else {
		NotFoundHandler(w, r)
	}
}

// UserAPIKeyResetHandler : Controller to reset user api key
func UserAPIKeyResetHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	vars := mux.Vars(r)
	id := vars["id"]
	currentUser := getUser(r)

	Ts, _ := publicSettings.GetTfuncAndLanguageFromRequest(r)
	messages := msg.GetMessages(r)
	userProfile, _, errorUser := userService.RetrieveUserForAdmin(id)
	if errorUser != nil || !userPermission.CurrentOrAdmin(currentUser, userProfile.ID) || userProfile.ID == 0 {
		NotFoundHandler(w, r)
		return
	}
	userProfile.APIToken, _ = crypto.GenerateRandomToken32()
	userProfile.APITokenExpiry = time.Unix(0, 0)
	_, errorUser = userService.UpdateRawUser(&userProfile)
	if errorUser != nil {
		messages.ImportFromError("errors", errorUser)
	} else {
		messages.AddInfo("infos", Ts("profile_updated"))
	}
	UserProfileHandler(w, r)
}
<commit_msg>Hopefully patch exploit that allows anyone to log users out<commit_after>package router

import (
	"net/http"
	"strconv"
	"time"

	"github.com/NyaaPantsu/nyaa/model"
	"github.com/NyaaPantsu/nyaa/service/captcha"
	"github.com/NyaaPantsu/nyaa/service/notifier"
	"github.com/NyaaPantsu/nyaa/service/user"
	"github.com/NyaaPantsu/nyaa/service/user/form"
	"github.com/NyaaPantsu/nyaa/service/user/permission"
	"github.com/NyaaPantsu/nyaa/util/crypto"
	msg "github.com/NyaaPantsu/nyaa/util/messages"
	"github.com/NyaaPantsu/nyaa/util/modelHelper"
	"github.com/NyaaPantsu/nyaa/util/publicSettings"
	"github.com/gorilla/mux"
)

// UserRegisterFormHandler : Getting View User Registration
func UserRegisterFormHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	_, errorUser := userService.CurrentUser(r)
	// User is already connected, redirect to home
	if errorUser == nil {
		HomeHandler(w, r)
		return
	}
	messages := msg.GetMessages(r)
	registrationForm := form.RegistrationForm{}
	modelHelper.BindValueForm(&registrationForm, r)
	registrationForm.CaptchaID = captcha.GetID()
	urtv := formTemplateVariables{
		commonTemplateVariables: newCommonVariables(r),
		Form:       registrationForm,
		FormErrors: messages.GetAllErrors(),
	}
	err := viewRegisterTemplate.ExecuteTemplate(w, "index.html", urtv)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

// UserLoginFormHandler : Getting View User Login
func UserLoginFormHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	_, errorUser := userService.CurrentUser(r)
	// User is already connected, redirect to home
	if errorUser == nil {
		HomeHandler(w, r)
		return
	}

	loginForm := form.LoginForm{}
	modelHelper.BindValueForm(&loginForm, r)
	messages := msg.GetMessages(r)
	ulfv := formTemplateVariables{
		commonTemplateVariables: newCommonVariables(r),
		Form:       loginForm,
		FormErrors: messages.GetAllErrors(),
	}

	err := viewLoginTemplate.ExecuteTemplate(w, "index.html", ulfv)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

// UserProfileHandler :  Getting User Profile
func UserProfileHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	vars := mux.Vars(r)
	id := vars["id"]
	Ts, _ := publicSettings.GetTfuncAndLanguageFromRequest(r)
	messages := msg.GetMessages(r)

	userProfile, _, errorUser := userService.RetrieveUserForAdmin(id)
	if errorUser == nil {
		currentUser := getUser(r)
		follow := r.URL.Query()["followed"]
		unfollow := r.URL.Query()["unfollowed"]
		deleteVar := r.URL.Query()["delete"]

		if (deleteVar != nil) && (userPermission.CurrentOrAdmin(currentUser, userProfile.ID)) {
			_, errUser := userService.DeleteUser(w, currentUser, id)
			if errUser != nil {
				messages.ImportFromError("errors", errUser)
			}
			htv := userVerifyTemplateVariables{newCommonVariables(r), messages.GetAllErrors()}
			errorTmpl := viewUserDeleteTemplate.ExecuteTemplate(w, "index.html", htv)
			if errorTmpl != nil {
				http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
			}
		} else {
			if follow != nil {
				messages.AddInfof("infos", Ts("user_followed_msg"), userProfile.Username)
			}
			if unfollow != nil {
				messages.AddInfof("infos", Ts("user_unfollowed_msg"), userProfile.Username)
			}
			userProfile.ParseSettings()
			htv := userProfileVariables{newCommonVariables(r), &userProfile, messages.GetAllInfos()}

			err := viewProfileTemplate.ExecuteTemplate(w, "index.html", htv)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
		}
	} else {
		NotFoundHandler(w, r)
	}
}

// UserDetailsHandler : Getting User Profile Details View
func UserDetailsHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	vars := mux.Vars(r)
	id := vars["id"]
	currentUser := getUser(r)
	messages := msg.GetMessages(r)

	userProfile, _, errorUser := userService.RetrieveUserForAdmin(id)
	if errorUser == nil && userPermission.CurrentOrAdmin(currentUser, userProfile.ID) {
		if userPermission.CurrentOrAdmin(currentUser, userProfile.ID) {
			b := form.UserForm{}
			modelHelper.BindValueForm(&b, r)
			availableLanguages := publicSettings.GetAvailableLanguages()
			userProfile.ParseSettings()
			htv := userProfileEditVariables{newCommonVariables(r), &userProfile, b, messages.GetAllErrors(), messages.GetAllInfos(), availableLanguages}
			err := viewProfileEditTemplate.ExecuteTemplate(w, "index.html", htv)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
		}
	} else {
		NotFoundHandler(w, r)
	}
}

// UserProfileFormHandler : Getting View User Profile Update
func UserProfileFormHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	vars := mux.Vars(r)
	id := vars["id"]
	currentUser := getUser(r)
	userProfile, _, errorUser := userService.RetrieveUserForAdmin(id)
	if errorUser != nil || !userPermission.CurrentOrAdmin(currentUser, userProfile.ID) || userProfile.ID == 0 {
		NotFoundHandler(w, r)
		return
	}
	userProfile.ParseSettings()
	messages := msg.GetMessages(r)
	userForm := form.UserForm{}
	userSettingsForm := form.UserSettingsForm{}

	Ts, _ := publicSettings.GetTfuncAndLanguageFromRequest(r)

	if len(r.PostFormValue("email")) > 0 {
		form.EmailValidation(r.PostFormValue("email"), messages)
	}
	if len(r.PostFormValue("username")) > 0 {
		form.ValidateUsername(r.PostFormValue("username"), messages)
	}

	if !messages.HasErrors() {
		modelHelper.BindValueForm(&userForm, r)
		modelHelper.BindValueForm(&userSettingsForm, r)
		if !userPermission.HasAdmin(currentUser) {
			userForm.Username = userProfile.Username
			userForm.Status = userProfile.Status
		} else {
			if userProfile.Status != userForm.Status && userForm.Status == 2 {
				messages.AddError("errors", "Elevating status to moderator is prohibited")
			}
		}
		modelHelper.ValidateForm(&userForm, messages)
		if !messages.HasErrors() {
			if userForm.Email != userProfile.Email {
				userService.SendVerificationToUser(*currentUser, userForm.Email)
				messages.AddInfof("infos", Ts("email_changed"), userForm.Email)
				userForm.Email = userProfile.Email // reset, it will be set when user clicks verification
			}
			userProfile, _, errorUser = userService.UpdateUser(w, &userForm, &userSettingsForm, currentUser, id)
			if errorUser != nil {
				messages.ImportFromError("errors", errorUser)
			} else {
				messages.AddInfo("infos", Ts("profile_updated"))
			}
		}
	}
	availableLanguages := publicSettings.GetAvailableLanguages()
	upev := userProfileEditVariables{
		commonTemplateVariables: newCommonVariables(r),
		UserProfile:             &userProfile,
		UserForm:                userForm,
		FormErrors:              messages.GetAllErrors(),
		FormInfos:               messages.GetAllInfos(),
		Languages:               availableLanguages,
	}
	errorTmpl := viewProfileEditTemplate.ExecuteTemplate(w, "index.html", upev)
	if errorTmpl != nil {
		http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
	}
}

// UserRegisterPostHandler : Post Registration controller, we do some check on the form here, the rest on user service
func UserRegisterPostHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	b := form.RegistrationForm{}
	messages := msg.GetMessages(r)

	if !captcha.Authenticate(captcha.Extract(r)) {
		messages.AddError("errors", "Wrong captcha!")
	}
	if !messages.HasErrors() {
		if len(r.PostFormValue("email")) > 0 {
			form.EmailValidation(r.PostFormValue("email"), messages)
		}
		form.ValidateUsername(r.PostFormValue("username"), messages)
		if !messages.HasErrors() {
			modelHelper.BindValueForm(&b, r)
			modelHelper.ValidateForm(&b, messages)
			if !messages.HasErrors() {
				_, errorUser := userService.CreateUser(w, r)
				if errorUser != nil {
					messages.ImportFromError("errors", errorUser)
				}
				if !messages.HasErrors() {
					common := newCommonVariables(r)
					common.User = &model.User{
						Email: r.PostFormValue("email"), // indicate whether user had email set
					}
					htv := formTemplateVariables{common, b, messages.GetAllErrors(), messages.GetAllInfos()}
					errorTmpl := viewRegisterSuccessTemplate.ExecuteTemplate(w, "index.html", htv)
					if errorTmpl != nil {
						http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
					}
				}
			}
		}
	}
	if messages.HasErrors() {
		UserRegisterFormHandler(w, r)
	}
}

// UserVerifyEmailHandler : Controller when verifying email, needs a token
func UserVerifyEmailHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	vars := mux.Vars(r)
	token := vars["token"]
	messages := msg.GetMessages(r)

	_, errEmail := userService.EmailVerification(token, w)
	if errEmail != nil {
		messages.ImportFromError("errors", errEmail)
	}
	htv := userVerifyTemplateVariables{newCommonVariables(r), messages.GetAllErrors()}
	errorTmpl := viewVerifySuccessTemplate.ExecuteTemplate(w, "index.html", htv)
	if errorTmpl != nil {
		http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
	}
}

// UserLoginPostHandler : Post Login controller
func UserLoginPostHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	b := form.LoginForm{}
	modelHelper.BindValueForm(&b, r)
	messages := msg.GetMessages(r)

	modelHelper.ValidateForm(&b, messages)
	if !messages.HasErrors() {
		_, errorUser := userService.CreateUserAuthentication(w, r)
		if errorUser != nil {
			messages.ImportFromError("errors", errorUser)
			htv := formTemplateVariables{newCommonVariables(r), b, messages.GetAllErrors(), messages.GetAllInfos()}
			errorTmpl := viewLoginTemplate.ExecuteTemplate(w, "index.html", htv)
			if errorTmpl != nil {
				http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
			}
			return
		}
		url, _ := Router.Get("home").URL()
		http.Redirect(w, r, url.String(), http.StatusSeeOther)
	}
	if messages.HasErrors() {
		UserLoginFormHandler(w, r)
	}
}

// UserLogoutHandler : Controller to logout users
func UserLogoutHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	vars := mux.Vars(r)
	id := vars["id"]
	currentUser := getUser(r)
	messages := msg.GetMessages(r)
	userProfile, _, errorUser := userService.RetrieveUserForAdmin(id)
	if userPermission.CurrentOrAdmin(currentUser, userProfile.ID) {
		_, _ = userService.ClearCookie(w)
		url, _ := Router.Get("home").URL()
		http.Redirect(w, r, url.String(), http.StatusSeeOther)
	}
	messages.ImportFromError("errors", errorUser)
}

// UserFollowHandler : Controller to follow/unfollow users, need user id to follow
func UserFollowHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	var followAction string
	vars := mux.Vars(r)
	id := vars["id"]
	currentUser := getUser(r)
	user, _, errorUser := userService.RetrieveUserForAdmin(id)
	if errorUser == nil && user.ID > 0 {
		if !userPermission.IsFollower(&user, currentUser) {
			followAction = "followed"
			userService.SetFollow(&user, currentUser)
		} else {
			followAction = "unfollowed"
			userService.RemoveFollow(&user, currentUser)
		}
	}
	url, _ := Router.Get("user_profile").URL("id", strconv.Itoa(int(user.ID)), "username", user.Username)
	http.Redirect(w, r, url.String()+"?"+followAction, http.StatusSeeOther)
}

// UserNotificationsHandler : Controller to show user notifications
func UserNotificationsHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	currentUser := getUser(r)
	if currentUser.ID > 0 {
		messages := msg.GetMessages(r)
		Ts, _ := publicSettings.GetTfuncAndLanguageFromRequest(r)
		if r.URL.Query()["clear"] != nil {
			notifierService.DeleteAllNotifications(currentUser.ID)
			messages.AddInfo("infos", Ts("notifications_cleared"))
			currentUser.Notifications = []model.Notification{}
		}
		htv := userProfileVariables{newCommonVariables(r), currentUser, messages.GetAllInfos()}
		err := viewProfileNotifTemplate.ExecuteTemplate(w, "index.html", htv)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	} else {
		NotFoundHandler(w, r)
	}
}

// UserAPIKeyResetHandler : Controller to reset user api key
func UserAPIKeyResetHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	vars := mux.Vars(r)
	id := vars["id"]
	currentUser := getUser(r)

	Ts, _ := publicSettings.GetTfuncAndLanguageFromRequest(r)
	messages := msg.GetMessages(r)
	userProfile, _, errorUser := userService.RetrieveUserForAdmin(id)
	if errorUser != nil || !userPermission.CurrentOrAdmin(currentUser, userProfile.ID) || userProfile.ID == 0 {
		NotFoundHandler(w, r)
		return
	}
	userProfile.APIToken, _ = crypto.GenerateRandomToken32()
	userProfile.APITokenExpiry = time.Unix(0, 0)
	_, errorUser = userService.UpdateRawUser(&userProfile)
	if errorUser != nil {
		messages.ImportFromError("errors", errorUser)
	} else {
		messages.AddInfo("infos", Ts("profile_updated"))
	}
	UserProfileHandler(w, r)
}
<|endoftext|>


<commit_before>package cask

import (
	"bytes"
	"fmt"
)

// Errors represents a group of errors and its context.
type Errors struct {
	// context specifies the errors context.
	context string

	// errors specify a group of errors represented as an array.
	errors []error
}

// An unexpectedTokenError represents the error that occurs when an the expected
// tokens doesn't match the actual ones.
type unexpectedTokenError struct {
	// expectedTokens specify a group of expected token types.
	expectedTokens []TokenType

	// actualToken specifies the actual token type.
	actualToken TokenType
}

// NewErrors creates a new Errors instance and returns its pointer. Requires
// both Errors.context and Errors.errors to be passed as arguments.
func NewErrors(context string, errors ...error) *Errors {
	return &Errors{context, errors}
}

// Error returns all error messages represented as a single string. All errors
// include trailing newlines and prepended context.
func (e *Errors) Error() string {
	var buffer bytes.Buffer

	fmt.Fprintf(&buffer, "%s:\n", e.context)
	for _, err := range e.errors {
		fmt.Fprintf(&buffer, "%s\n", err.Error())
	}

	return buffer.String()
}

// Error returns a string representation of the unexpectedTokenError.
func (u *unexpectedTokenError) Error() string {
	return fmt.Sprintf(
		"expected next token to be of type %v, got %s instead",
		u.expectedTokens,
		u.actualToken,
	)
}
<commit_msg>Use String() for u.actualToken in unexpectedTokenError.Error()<commit_after>package cask

import (
	"bytes"
	"fmt"
)

// Errors represents a group of errors and its context.
type Errors struct {
	// context specifies the errors context.
	context string

	// errors specify a group of errors represented as an array.
	errors []error
}

// An unexpectedTokenError represents the error that occurs when an the expected
// tokens doesn't match the actual ones.
type unexpectedTokenError struct {
	// expectedTokens specify a group of expected token types.
	expectedTokens []TokenType

	// actualToken specifies the actual token type.
	actualToken TokenType
}

// NewErrors creates a new Errors instance and returns its pointer. Requires
// both Errors.context and Errors.errors to be passed as arguments.
func NewErrors(context string, errors ...error) *Errors {
	return &Errors{context, errors}
}

// Error returns all error messages represented as a single string. All errors
// include trailing newlines and prepended context.
func (e *Errors) Error() string {
	var buffer bytes.Buffer

	fmt.Fprintf(&buffer, "%s:\n", e.context)
	for _, err := range e.errors {
		fmt.Fprintf(&buffer, "%s\n", err.Error())
	}

	return buffer.String()
}

// Error returns a string representation of the unexpectedTokenError.
func (u *unexpectedTokenError) Error() string {
	return fmt.Sprintf(
		"expected next token to be of type %v, got %s instead",
		u.expectedTokens,
		u.actualToken.String(),
	)
}
<|endoftext|>


<commit_before>package godoauth

import (
	"fmt"
	"net/http"
)

type HTTPAuthError struct {
	err string
	Code  int
}

// Predefined internal error
var ErrUnauthorized *HTTPAuthError = NewHTTPError("Unauthorized Access", http.StatusUnauthorized)
var ErrForbidden *HTTPAuthError = NewHTTPError("Forbiden Access", http.StatusForbidden)
var ErrInternal *HTTPAuthError = NewHTTPError("Internal server error", http.StatusInternalServerError)

// HTTPBadRequest returns *HTTPError with supplied informative string and error code 400.
func HTTPBadRequest(s string) (err *HTTPAuthError) {
	return NewHTTPError(s, http.StatusBadRequest)
}

// NewHTTPError creates new HTTPError with supplied error message and code.
// The message is displayed to the end user, so please be careful.
func NewHTTPError(s string, code int) (err *HTTPAuthError) {
	return &HTTPAuthError{s, code}
}

func (e HTTPAuthError) Error() string {
	return fmt.Sprintf("%d: %v", e.Code, e.err)
}

// Respond sends the error code and message to the supplied ResponseWriter
func (e *HTTPAuthError) Respond(w http.ResponseWriter) {
	http.Error(w, e.err, e.Code)
}
<commit_msg>Refactor error definition into a block.<commit_after>package godoauth

import (
	"fmt"
	"net/http"
)

type HTTPAuthError struct {
	err  string
	Code int
}

// Predefined internal error
var (
	ErrUnauthorized *HTTPAuthError = NewHTTPError("Unauthorized Access", http.StatusUnauthorized)
	ErrForbidden                   = NewHTTPError("Forbiden Access", http.StatusForbidden)
	ErrInternal                    = NewHTTPError("Internal server error", http.StatusInternalServerError)
)

// HTTPBadRequest returns *HTTPError with supplied informative string and error code 400.
func HTTPBadRequest(s string) (err *HTTPAuthError) {
	return NewHTTPError(s, http.StatusBadRequest)
}

// NewHTTPError creates new HTTPError with supplied error message and code.
// The message is displayed to the end user, so please be careful.
func NewHTTPError(s string, code int) (err *HTTPAuthError) {
	return &HTTPAuthError{s, code}
}

func (e HTTPAuthError) Error() string {
	return fmt.Sprintf("%d: %v", e.Code, e.err)
}

// Respond sends the error code and message to the supplied ResponseWriter
func (e *HTTPAuthError) Respond(w http.ResponseWriter) {
	http.Error(w, e.err, e.Code)
}
<|endoftext|>


<commit_before>package sqldb

import "database/sql"

func ErrOnNoRows(err, newErr error) error {
	if err == sql.ErrNoRows {
		return newErr
	}
	return err
}

func ErrAllowNoRows(err error) error {
	return ErrOnNoRows(err, nil)
}

func ErrOnNoAffects(n int64, err, newErr error) error {
	if n == 0 && err == nil {
		return newErr
	}
	return err
}

func ErrOnNoAffectsResult(res sql.Result, err, newErr error) error {
	var n int64
	if err == nil {
		n, err = res.RowsAffected()
	}
	return ErrOnNoAffects(n, err, newErr)
}
<commit_msg>clean code.<commit_after>package sqldb

import "database/sql"

func ErrOnNoRows(err, newErr error) error {
	if err == sql.ErrNoRows {
		return newErr
	}
	return err
}

func ErrAllowNoRows(err error) error {
	return ErrOnNoRows(err, nil)
}

func ErrOnNoAffects(n int64, err, newErr error) error {
	if n == 0 && err == nil {
		return newErr
	}
	return err
}

func ErrOnNoAffectsResult(res sql.Result, err, newErr error) error {
	n, err := ResultRowsAffected(res, err)
	return ErrOnNoAffects(n, err, newErr)
}
<|endoftext|>


<commit_before>package entry

import (
	"bytes"
	"fmt"
	urlparse "net/url"
	"regexp"
	"strings"

	libm "bitbucket.org/ikeikeikeike/antenna/lib/models"
	gq "github.com/PuerkitoBio/goquery"
	behavior "github.com/ikeikeikeike/gopkg/net/http"
	"github.com/ikeikeikeike/gopkg/str"

	"golang.org/x/net/html"

	"bitbucket.org/ikeikeikeike/antenna/models"
)

var (
	defaultUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.3.18 (KHTML, like Gecko) Version/7.1.3 Safari/537.85.12"

	embedUrls = []string{
		`flashservice.xvideos.com/embedframe`,
		`video.fc2.com/content`,
		`video.fc2.com/a/content`,
		`video.fc2.com/ja/a/content`,
		`www.tokyo-tube.com/embedcode`,
		`xhamster.com/xembed.php`,
		`www.pornhost.com/embed`,
		`www.tube8.com/embed/asian`,
		`www.pipii.tv/player`,
		`jp.pornhub.com/embed`,
		`www.pornhub.com/embed`,
		`japan-whores.com/embed`,
		`www.tokyo-porn-tube.com/embedcode`,
	}

	// TODO: will be support future below.

	//

	// <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" wmode="transparent" width="448" height="284" id="flv2" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="http://video.fc2.com/flv2.swf?i=20150206aZzPs9Mg&d=3063&movie_stop=off&no_progressive=1&otag=1&sj=28000&rel=1" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><param name="allowFullScreen" value="true" /><embed src="http://video.fc2.com/flv2.swf?i=20150206aZzPs9Mg&d=3063&movie_stop=off&no_progressive=1&otag=1&sj=28000&rel=1" quality="high" bgcolor="#ffffff" wmode="transparent" width="448" height="284" name="flv2" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" allowFullScreen="true" /></object>
<a href="http://video.fc2.com/content/20150206aZzPs9Mg/" title="対応" rel="nofollow" 【、可愛いが好き

	videoHrefs = []string{
		`www.xvideos.com/video`,
		`jp.xvideos.com/video`,
		`video.fc2.com/content`,
		`video.fc2.com/a/content`,
		`video.fc2.com/ja/a/content`,
		`www.tokyo-tube.com/video`,
		`ero-video.net/movie`,
		`jp.xhamster.com/movies`,
		`www.xhamster.com/movies`,
		`asg.to/contentsPage.html`,
		`www.pornhost.com`,
		`jp.pornhost.com`,
		`www.tube8.com`,
		`www.redtube.com`,
		`www.pornhub.com/view_video.php`,
		`jp.pornhub.com/view_video.php`,
		`japan-whores.com/videos`,
		`www.tokyo-porn-tube.com/video`,
		`www.flashx.tv`,
		// `www.thisav.com/video`,  // unko
	}
)

type Extractor struct {
	*behavior.UserBehavior

	entry *models.Entry
	doc   *gq.Document
}

func NewExtractor() *Extractor {
	return &Extractor{
		UserBehavior: behavior.NewUserBehavior(),
	}
}

func (e *Extractor) Doc(urlStr string) (*gq.Document, error) {
	resp, err := e.Behave(urlStr)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	return gq.NewDocumentFromResponse(resp)
}

/*
	Do parsing document
*/
func (e *Extractor) Do(entry *models.Entry) error {
	doc, err := e.Doc(entry.Url)
	if err != nil {
		return err
	}

	e.doc = doc
	e.entry = entry
	return nil
}

/*
	Extracting ExternalURLs
*/
func (e *Extractor) Urls() (urls []string) {
	var re = regexp.MustCompile(strings.Join(videoHrefs, `|`))

	e.doc.Find("a").Each(func(i int, s *gq.Selection) {
		h, ok := s.Attr("href")
		if !ok {
			return
		}
		u, err := urlparse.Parse(h)
		if err != nil || u.Host == "" {
			return
		}

		if re.MatchString(h) {
			urls = append(urls, h)
		}
	})

	return
}

// iframe or script or object
// srcとurlでcontains ableなもの
func (e *Extractor) Codes() (codes []string) {

	var render = func(selectors ...*gq.Selection) {
		var raw string
		for _, sel := range selectors {
			var buf bytes.Buffer
			sel.Each(func(i int, s *gq.Selection) {
				html.Render(&buf, s.Nodes[0])
				raw += str.Clean(buf.String())
			})
		}
		codes = append(codes, raw)
	}

	// sel := e.doc.Find("iframe,script,embed,object").FilterFunction(func(i int, s *gq.Selection) bool {
	var re = regexp.MustCompile(strings.Join(embedUrls, `|`))
	e.doc.Find("iframe,script").Each(func(i int, s *gq.Selection) {
		src, ok := s.Attr("src")
		if ok && re.MatchString(src) {
			render(s)
		}
		url, ok := s.Attr("url")
		if ok && re.MatchString(url) {
			render(s)
		}
		if strings.Contains(src, "ero-video.net/js/embed_evplayer") {
			render(s, s.Next())
		}
		if strings.Contains(src, "asg.to/js/past_uraui") {
			render(s, s.Next())
		}
	})

	if len(codes) <= 0 {
		e.doc.Find("object").Each(func(i int, s *gq.Selection) {
			data, ok := s.Attr("data")
			if ok && strings.Contains(data, "embed.redtube.com/player") {
				render(s)
			}
		})
	}

	return
}

/*
	Extracting by string array in Title, Content

	.. note:: 3 chars less word will not extract in function.
*/
func (e *Extractor) ByNames(names []string) (choices []string) {
	for _, name := range names {
		if len([]rune(name)) > 2 && !libm.ReHK3.MatchString(name) {
			if strings.Contains(e.entry.Title, name) {
				choices = append(choices, name)
			} else if strings.Contains(e.entry.Content, name) {
				choices = append(choices, name)
			} else {
				for _, t := range e.entry.Tags {
					if strings.Contains(t.Name, name) {
						choices = append(choices, name)
					}
				}
			}
		}
	}
	return
}

func (e *Extractor) Duration() {}

type Img struct {
	Src string
	Alt string
}

/*
	Extracting img tag
*/
func (e *Extractor) Imgs() (imgs []*Img) {
	u, err := urlparse.Parse(strings.TrimSpace(e.entry.Url))
	if err != nil || u.Host == "" {
		return
	}

	var src string
	domain := strings.Split(u.Host, ":")[0]

	if strings.Contains(domain, "livedoor.jp") {
		src = strings.Split(u.Path, "/")[1]
	} else if strings.Contains(domain, "fc2.com") {
		src = strings.Split(domain, ".")[0]
	} else {
		parts := strings.Split(domain, ".")
		src = parts[len(parts)-2]
	}

	selector := fmt.Sprintf(`img[src*='%s']`, src)
	e.doc.Find(selector).Each(func(i int, s *gq.Selection) {
		src, ok := s.Attr("src")
		if !ok {
			return
		}
		alt, _ := s.Attr("alt")
		if alt == "" {
			alt, _ = s.Attr("title")
		}
		imgs = append(imgs, &Img{Src: src, Alt: alt})
	})

	return
}
<commit_msg>support wordpress images in summarized picture<commit_after>package entry

import (
	"bytes"
	"fmt"
	urlparse "net/url"
	"regexp"
	"strings"

	libm "bitbucket.org/ikeikeikeike/antenna/lib/models"
	gq "github.com/PuerkitoBio/goquery"
	behavior "github.com/ikeikeikeike/gopkg/net/http"
	"github.com/ikeikeikeike/gopkg/str"

	"golang.org/x/net/html"

	"bitbucket.org/ikeikeikeike/antenna/models"
)

var (
	defaultUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.3.18 (KHTML, like Gecko) Version/7.1.3 Safari/537.85.12"

	embedUrls = []string{
		`flashservice.xvideos.com/embedframe`,
		`video.fc2.com/content`,
		`video.fc2.com/a/content`,
		`video.fc2.com/ja/a/content`,
		`www.tokyo-tube.com/embedcode`,
		`xhamster.com/xembed.php`,
		`www.pornhost.com/embed`,
		`www.tube8.com/embed/asian`,
		`www.pipii.tv/player`,
		`jp.pornhub.com/embed`,
		`www.pornhub.com/embed`,
		`japan-whores.com/embed`,
		`www.tokyo-porn-tube.com/embedcode`,
	}

	// TODO: will be support future below.

	//

	// <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" wmode="transparent" width="448" height="284" id="flv2" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="http://video.fc2.com/flv2.swf?i=20150206aZzPs9Mg&d=3063&movie_stop=off&no_progressive=1&otag=1&sj=28000&rel=1" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><param name="allowFullScreen" value="true" /><embed src="http://video.fc2.com/flv2.swf?i=20150206aZzPs9Mg&d=3063&movie_stop=off&no_progressive=1&otag=1&sj=28000&rel=1" quality="high" bgcolor="#ffffff" wmode="transparent" width="448" height="284" name="flv2" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" allowFullScreen="true" /></object>
<a href="http://video.fc2.com/content/20150206aZzPs9Mg/" title="対応" rel="nofollow" 【、可愛いが好き

	videoHrefs = []string{
		`www.xvideos.com/video`,
		`jp.xvideos.com/video`,
		`video.fc2.com/content`,
		`video.fc2.com/a/content`,
		`video.fc2.com/ja/a/content`,
		`www.tokyo-tube.com/video`,
		`ero-video.net/movie`,
		`jp.xhamster.com/movies`,
		`www.xhamster.com/movies`,
		`asg.to/contentsPage.html`,
		`www.pornhost.com`,
		`jp.pornhost.com`,
		`www.tube8.com`,
		`www.redtube.com`,
		`www.pornhub.com/view_video.php`,
		`jp.pornhub.com/view_video.php`,
		`japan-whores.com/videos`,
		`www.tokyo-porn-tube.com/video`,
		`www.flashx.tv`,
		// `www.thisav.com/video`,  // unko
	}
)

type Extractor struct {
	*behavior.UserBehavior

	entry *models.Entry
	doc   *gq.Document
}

func NewExtractor() *Extractor {
	return &Extractor{
		UserBehavior: behavior.NewUserBehavior(),
	}
}

func (e *Extractor) Doc(urlStr string) (*gq.Document, error) {
	resp, err := e.Behave(urlStr)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	return gq.NewDocumentFromResponse(resp)
}

/*
	Do parsing document
*/
func (e *Extractor) Do(entry *models.Entry) error {
	doc, err := e.Doc(entry.Url)
	if err != nil {
		return err
	}

	e.doc = doc
	e.entry = entry
	return nil
}

/*
	Extracting ExternalURLs
*/
func (e *Extractor) Urls() (urls []string) {
	var re = regexp.MustCompile(strings.Join(videoHrefs, `|`))

	e.doc.Find("a").Each(func(i int, s *gq.Selection) {
		h, ok := s.Attr("href")
		if !ok {
			return
		}
		u, err := urlparse.Parse(h)
		if err != nil || u.Host == "" {
			return
		}

		if re.MatchString(h) {
			urls = append(urls, h)
		}
	})

	return
}

// iframe or script or object
// srcとurlでcontains ableなもの
func (e *Extractor) Codes() (codes []string) {

	var render = func(selectors ...*gq.Selection) {
		var raw string
		for _, sel := range selectors {
			var buf bytes.Buffer
			sel.Each(func(i int, s *gq.Selection) {
				html.Render(&buf, s.Nodes[0])
				raw += str.Clean(buf.String())
			})
		}
		codes = append(codes, raw)
	}

	// sel := e.doc.Find("iframe,script,embed,object").FilterFunction(func(i int, s *gq.Selection) bool {
	var re = regexp.MustCompile(strings.Join(embedUrls, `|`))
	e.doc.Find("iframe,script").Each(func(i int, s *gq.Selection) {
		src, ok := s.Attr("src")
		if ok && re.MatchString(src) {
			render(s)
		}
		url, ok := s.Attr("url")
		if ok && re.MatchString(url) {
			render(s)
		}
		if strings.Contains(src, "ero-video.net/js/embed_evplayer") {
			render(s, s.Next())
		}
		if strings.Contains(src, "asg.to/js/past_uraui") {
			render(s, s.Next())
		}
	})

	if len(codes) <= 0 {
		e.doc.Find("object").Each(func(i int, s *gq.Selection) {
			data, ok := s.Attr("data")
			if ok && strings.Contains(data, "embed.redtube.com/player") {
				render(s)
			}
		})
	}

	return
}

/*
	Extracting by string array in Title, Content

	.. note:: 3 chars less word will not extract in function.
*/
func (e *Extractor) ByNames(names []string) (choices []string) {
	for _, name := range names {
		if len([]rune(name)) > 2 && !libm.ReHK3.MatchString(name) {
			if strings.Contains(e.entry.Title, name) {
				choices = append(choices, name)
			} else if strings.Contains(e.entry.Content, name) {
				choices = append(choices, name)
			} else {
				for _, t := range e.entry.Tags {
					if strings.Contains(t.Name, name) {
						choices = append(choices, name)
					}
				}
			}
		}
	}
	return
}

func (e *Extractor) Duration() {}

type Img struct {
	Src string
	Alt string
}

/*
	Extracting img tag
*/
func (e *Extractor) Imgs() (imgs []*Img) {
	u, err := urlparse.Parse(strings.TrimSpace(e.entry.Url))
	if err != nil || u.Host == "" {
		return
	}

	var appendImg = func(src string) {
		selector := fmt.Sprintf(`img[src*='%s']`, src)
		e.doc.Find(selector).Each(func(i int, s *gq.Selection) {
			src, ok := s.Attr("src")
			if !ok {
				return
			}
			alt, _ := s.Attr("alt")
			if alt == "" {
				alt, _ = s.Attr("title")
			}
			imgs = append(imgs, &Img{Src: src, Alt: alt})
		})
	}

	domain := strings.Split(u.Host, ":")[0]

	if strings.Contains(domain, "livedoor.jp") {
		src = strings.Split(u.Path, "/")[1]
		appendImg(src)
	} else if strings.Contains(domain, "fc2.com") {
		src = strings.Split(domain, ".")[0]
		appendImg(src)
	} else {
		parts := strings.Split(domain, ".")
		src = parts[len(parts)-2]
		appendImg(src)

		if len(imgs) <= 0 {
			appendImg("/wp-content/uploads/") // for wordpress
		}
	}

	return
}
<|endoftext|>


<commit_before>package cl11

import (
	"fmt"
	"unsafe"

	clw "github.com/rdwilliamson/clw11"
)

//
type Event struct {
	id           clw.Event
	Context      *Context
	CommandType  CommandType
	CommandQueue *CommandQueue

	Queued int64 // Profiling information.
	Submit int64 // Profiling information.
	Start  int64 // Profiling information.
	End    int64 // Profiling information.
}

type CommandType int

const (
	CommandNDRangeKernel        = CommandType(clw.CommandNdrangeKernel)
	CommandTask                 = CommandType(clw.CommandTask)
	CommandNativeKernel         = CommandType(clw.CommandNativeKernel)
	CommandReadBuffer           = CommandType(clw.CommandReadBuffer)
	CommandWriteBuffer          = CommandType(clw.CommandWriteBuffer)
	CommandCopyBuffer           = CommandType(clw.CommandCopyBuffer)
	CommandReadImage            = CommandType(clw.CommandReadImage)
	CommandWriteImage           = CommandType(clw.CommandWriteImage)
	CommandCopyImage            = CommandType(clw.CommandCopyImage)
	CommandCopyImageToBuffer    = CommandType(clw.CommandCopyImageToBuffer)
	CommandCopyBufferToImage    = CommandType(clw.CommandCopyBufferToImage)
	CommandMapBuffer            = CommandType(clw.CommandMapBuffer)
	CommandMapImage             = CommandType(clw.CommandMapImage)
	CommandUnmapMemoryObject    = CommandType(clw.CommandUnmapMemoryObject)
	CommandMarker               = CommandType(clw.CommandMarker)
	CommandAcquireGlObjects     = CommandType(clw.CommandAcquireGlObjects)
	CommandReleaseGlObjects     = CommandType(clw.CommandReleaseGlObjects)
	CommandReadBufferRectangle  = CommandType(clw.CommandReadBufferRectangle)
	CommandWriteBufferRectangle = CommandType(clw.CommandWriteBufferRectangle)
	CommandCopyBufferRectangle  = CommandType(clw.CommandCopyBufferRectangle)
	CommandUser                 = CommandType(clw.CommandUser)
)

var commandTypeMap = map[CommandType]string{
	CommandNDRangeKernel:        "ND range kernel",
	CommandTask:                 "task",
	CommandNativeKernel:         "native kernel",
	CommandReadBuffer:           "read buffer",
	CommandWriteBuffer:          "write buffer",
	CommandCopyBuffer:           "copy buffer",
	CommandReadImage:            "read image",
	CommandWriteImage:           "write image",
	CommandCopyImage:            "copy image",
	CommandCopyImageToBuffer:    "copy image to buffer",
	CommandCopyBufferToImage:    "copy buffer to image",
	CommandMapBuffer:            "map buffer",
	CommandMapImage:             "map image",
	CommandUnmapMemoryObject:    "unmap memory object",
	CommandMarker:               "marker",
	CommandAcquireGlObjects:     "acquire GL objects",
	CommandReleaseGlObjects:     "release GL objects",
	CommandReadBufferRectangle:  "read buffer rectangle",
	CommandWriteBufferRectangle: "write buffer rectangle",
	CommandCopyBufferRectangle:  "copy buffer rectangle",
	CommandUser:                 "user",
}

func (ct CommandType) String() string {
	return commandTypeMap[ct]
}

type CommandExecutionStatus int

const (
	Complete  = CommandExecutionStatus(clw.Complete)
	Running   = CommandExecutionStatus(clw.Running)
	Submitted = CommandExecutionStatus(clw.Submitted)
	Queued    = CommandExecutionStatus(clw.Queued)
)

func (ces CommandExecutionStatus) String() string {
	switch ces {
	case Complete:
		return "complete"
	case Running:
		return "running"
	case Submitted:
		return "submitted"
	case Queued:
		return "queued"
	}
	return ""
}

// Creates a user event object.
//
// User events allow applications to enqueue commands that wait on a user event
// to finish before the command is executed by the device. The execution status
// of the user event object created is set to Submitted.
func (c *Context) CreateUserEvent() (*Event, error) {

	event, err := clw.CreateUserEvent(c.id)
	if err != nil {
		return nil, err
	}

	return &Event{id: event, Context: c, CommandType: CommandUser}, nil
}

// Return the execution status of the command identified by event.
//
// Statuses are: Queued (command has been enqueued in the command-queue),
// Submitted (enqueued command has been submitted by the host to the device
// associated with the command-queue), Running (device is currently executing
// this command), Complete (the command has completed).
//
// An eventErr is an error that cause the event to abnormally terminate. A
// getStatusErr is an error that occurred while trying to retrieve the event's
// status.
func (e *Event) Status() (ces CommandExecutionStatus, eventErr, getStatusErr error) {

	err := clw.GetEventInfo(e.id, clw.EventCommandExecutionStatus, clw.Size(unsafe.Sizeof(ces)),
		unsafe.Pointer(&ces), nil)
	if err != nil {
		return 0, nil, err
	}

	if ces < 0 {
		return 0, fmt.Errorf("event abnormally terminated: %s", clw.CodeToError(clw.Int(ces)).Error()), nil
	}

	return CommandExecutionStatus(ces), nil, nil
}

// Gets profiling information for the command associated with event if profiling
// is enabled.
func (e *Event) GetProfilingInfo() error {

	var value clw.Ulong
	err := clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandQueued, clw.Size(unsafe.Sizeof(value)),
		unsafe.Pointer(&value), nil)
	if err != nil {
		return err
	}
	e.Queued = int64(value)

	err = clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandSubmit, clw.Size(unsafe.Sizeof(value)),
		unsafe.Pointer(&value), nil)
	if err != nil {
		return err
	}
	e.Submit = int64(value)

	err = clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandStart, clw.Size(unsafe.Sizeof(value)),
		unsafe.Pointer(&value), nil)
	if err != nil {
		return err
	}
	e.Start = int64(value)

	err = clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandEnd, clw.Size(unsafe.Sizeof(value)),
		unsafe.Pointer(&value), nil)
	if err != nil {
		return err
	}
	e.End = int64(value)

	return nil
}

func (e *Event) SetCallback(callback func(e *Event, userData interface{}), userData interface{}) error {

	return clw.SetEventCallback(e.id, clw.Complete,
		func(event clw.Event, ces clw.CommandExecutionStatus, _userData interface{}) {
			callback(e, _userData)
		},
		userData)
}

func (e *Event) Wait() error {
	return clw.WaitForEvents([]clw.Event{e.id})
}

func WaitForEvents(events ...*Event) error {
	waitList := make([]clw.Event, len(events))
	for i := range events {
		waitList[i] = events[i].id
	}
	return clw.WaitForEvents(waitList)
}
<commit_msg>Added documentation.<commit_after>package cl11

import (
	"fmt"
	"unsafe"

	clw "github.com/rdwilliamson/clw11"
)

// Event objects can be used to refer to a kernel execution command, read,
// write, map and copy commands on memory objects, EnqueueMarker, or user
// events.
//
// An event object can be used to track the execution status of a command. The
// API calls that enqueue commands to a command-queue create a new event object
// that is returned in the event argument.
type Event struct {
	id           clw.Event
	Context      *Context
	CommandType  CommandType
	CommandQueue *CommandQueue

	Queued int64 // Profiling information.
	Submit int64 // Profiling information.
	Start  int64 // Profiling information.
	End    int64 // Profiling information.
}

type CommandType int

const (
	CommandNDRangeKernel        = CommandType(clw.CommandNdrangeKernel)
	CommandTask                 = CommandType(clw.CommandTask)
	CommandNativeKernel         = CommandType(clw.CommandNativeKernel)
	CommandReadBuffer           = CommandType(clw.CommandReadBuffer)
	CommandWriteBuffer          = CommandType(clw.CommandWriteBuffer)
	CommandCopyBuffer           = CommandType(clw.CommandCopyBuffer)
	CommandReadImage            = CommandType(clw.CommandReadImage)
	CommandWriteImage           = CommandType(clw.CommandWriteImage)
	CommandCopyImage            = CommandType(clw.CommandCopyImage)
	CommandCopyImageToBuffer    = CommandType(clw.CommandCopyImageToBuffer)
	CommandCopyBufferToImage    = CommandType(clw.CommandCopyBufferToImage)
	CommandMapBuffer            = CommandType(clw.CommandMapBuffer)
	CommandMapImage             = CommandType(clw.CommandMapImage)
	CommandUnmapMemoryObject    = CommandType(clw.CommandUnmapMemoryObject)
	CommandMarker               = CommandType(clw.CommandMarker)
	CommandAcquireGlObjects     = CommandType(clw.CommandAcquireGlObjects)
	CommandReleaseGlObjects     = CommandType(clw.CommandReleaseGlObjects)
	CommandReadBufferRectangle  = CommandType(clw.CommandReadBufferRectangle)
	CommandWriteBufferRectangle = CommandType(clw.CommandWriteBufferRectangle)
	CommandCopyBufferRectangle  = CommandType(clw.CommandCopyBufferRectangle)
	CommandUser                 = CommandType(clw.CommandUser)
)

var commandTypeMap = map[CommandType]string{
	CommandNDRangeKernel:        "ND range kernel",
	CommandTask:                 "task",
	CommandNativeKernel:         "native kernel",
	CommandReadBuffer:           "read buffer",
	CommandWriteBuffer:          "write buffer",
	CommandCopyBuffer:           "copy buffer",
	CommandReadImage:            "read image",
	CommandWriteImage:           "write image",
	CommandCopyImage:            "copy image",
	CommandCopyImageToBuffer:    "copy image to buffer",
	CommandCopyBufferToImage:    "copy buffer to image",
	CommandMapBuffer:            "map buffer",
	CommandMapImage:             "map image",
	CommandUnmapMemoryObject:    "unmap memory object",
	CommandMarker:               "marker",
	CommandAcquireGlObjects:     "acquire GL objects",
	CommandReleaseGlObjects:     "release GL objects",
	CommandReadBufferRectangle:  "read buffer rectangle",
	CommandWriteBufferRectangle: "write buffer rectangle",
	CommandCopyBufferRectangle:  "copy buffer rectangle",
	CommandUser:                 "user",
}

func (ct CommandType) String() string {
	return commandTypeMap[ct]
}

type CommandExecutionStatus int

const (
	Queued    = CommandExecutionStatus(clw.Queued)
	Submitted = CommandExecutionStatus(clw.Submitted)
	Running   = CommandExecutionStatus(clw.Running)
	Complete  = CommandExecutionStatus(clw.Complete)
)

func (ces CommandExecutionStatus) String() string {
	switch ces {
	case Complete:
		return "complete"
	case Running:
		return "running"
	case Submitted:
		return "submitted"
	case Queued:
		return "queued"
	}
	return ""
}

// Creates a user event object.
//
// User events allow applications to enqueue commands that wait on a user event
// to finish before the command is executed by the device. The execution status
// of the user event object created is set to Submitted.
func (c *Context) CreateUserEvent() (*Event, error) {

	event, err := clw.CreateUserEvent(c.id)
	if err != nil {
		return nil, err
	}

	return &Event{id: event, Context: c, CommandType: CommandUser}, nil
}

// Return the execution status of the command identified by event.
//
// Statuses are: Queued (command has been enqueued in the command-queue),
// Submitted (enqueued command has been submitted by the host to the device
// associated with the command-queue), Running (device is currently executing
// this command), Complete (the command has completed).
//
// An eventErr is an error that cause the event to abnormally terminate. A
// getStatusErr is an error that occurred while trying to retrieve the event's
// status.
func (e *Event) Status() (ces CommandExecutionStatus, eventErr, getStatusErr error) {

	err := clw.GetEventInfo(e.id, clw.EventCommandExecutionStatus, clw.Size(unsafe.Sizeof(ces)),
		unsafe.Pointer(&ces), nil)
	if err != nil {
		return 0, nil, err
	}

	if ces < 0 {
		return 0, fmt.Errorf("event abnormally terminated: %s", clw.CodeToError(clw.Int(ces)).Error()), nil
	}

	return CommandExecutionStatus(ces), nil, nil
}

// Gets profiling information for the command associated with event if profiling
// is enabled.
//
// The 64-bit values can be used to measure the time in nano-seconds consumed by
// OpenCL commands.
//
// OpenCL devices are required to correctly track time across changes in device
// frequency and power states. The Device.ProfilingTimerResolution specifies the
// resolution of the timer i.e. the number of nanoseconds elapsed before the
// timer is incremented.
//
// Event objects can be used to capture profiling information that measure
// execution time of a command. Profiling of OpenCL commands can be enabled
// either by using a command-queue created with QueueProfilingEnable flag set in
// properties argument to CreateCommandQueue.
func (e *Event) GetProfilingInfo() error {

	var value clw.Ulong
	err := clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandQueued, clw.Size(unsafe.Sizeof(value)),
		unsafe.Pointer(&value), nil)
	if err != nil {
		return err
	}
	e.Queued = int64(value)

	err = clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandSubmit, clw.Size(unsafe.Sizeof(value)),
		unsafe.Pointer(&value), nil)
	if err != nil {
		return err
	}
	e.Submit = int64(value)

	err = clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandStart, clw.Size(unsafe.Sizeof(value)),
		unsafe.Pointer(&value), nil)
	if err != nil {
		return err
	}
	e.Start = int64(value)

	err = clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandEnd, clw.Size(unsafe.Sizeof(value)),
		unsafe.Pointer(&value), nil)
	if err != nil {
		return err
	}
	e.End = int64(value)

	return nil
}

// Registers a user callback function for a specific command execution status.
//
// The registered callback function will be called when the execution status of
// command associated with event changes to Complete.
//
// Each call to SetCallback registers the specified user callback
// function on a callback stack associated with event. The order in which the
// registered user callback functions are called is undefined.
//
// All callbacks registered for an event object must be called. All enqueued
// callbacks shall be called before the event object is destroyed. Callbacks
// must return promptly. The behavior of calling expensive system routines,
// OpenCL API calls to create contexts or command-queues, or blocking OpenCL
// operations, in a callback is undefined.
func (e *Event) SetCallback(callback func(e *Event, userData interface{}), userData interface{}) error {

	return clw.SetEventCallback(e.id, clw.Complete,
		func(event clw.Event, ces clw.CommandExecutionStatus, _userData interface{}) {
			callback(e, _userData)
		},
		userData)
}

// Waits on the host thread for the event to complete. See WaitForEvents for
// more info.
func (e *Event) Wait() error {
	return clw.WaitForEvents([]clw.Event{e.id})
}

// Waits on the host thread for commands identified by event objects to
// complete.
//
// Waits on the host thread for commands identified by event objects in
// event_list to complete. A command is considered complete if its execution
// status is "complete" or abnormally terminated (an error occured).
//
// If the cl_khr_gl_event extension is enabled, event objects can also be used
// to reflect the status of an OpenGL sync object. The sync object in turn
// refers to a fence command executing in an OpenGL command stream. This
// provides another method of coordinating sharing of buffers and images between
// OpenGL and OpenCL.
func WaitForEvents(events ...*Event) error {
	waitList := make([]clw.Event, len(events))
	for i := range events {
		waitList[i] = events[i].id
	}
	return clw.WaitForEvents(waitList)
}
<|endoftext|>


<commit_before>//
//Application:bridge
//EventName:CHANNEL_HANGUP
//EventName:CHANNEL_EXECUTE_COMPLETE
//Application:bridge
//Variable_bridge_hangup_cause:NORMAL_CLEARING
//Variable_dialstatus:DONTCALL
//Channel-Call-State:HELD
//Variable_originate_disposition:CALL_REJECTED
//Hangup-Cause:CALL_REJECTED
package glivo

import (
	"net/textproto"
	"fmt"
	"strings"
)

//Representa un evento de Freeswitch
//Las claves estan Camelised
type Event struct {
	call *Call
	Content map[string]string
}

//Permite llamar procedimiento cuando se cumpla el filro
//o bien cuando el evento cumpla las condiciones esperadas.
type HandlerEvent interface {
	//Delimita el handler a que eventos trabajar
	//retorna +true+ si es evento esperado
	Filter(Event) bool

	//Recibe evento y reacciona a este
	Handle(Event)

}

//Crea evento apartir de el MIME leido
func EventFromMIME(call *Call, mime textproto.MIMEHeader) Event{
	return Event{ call, mimeToMap(mime)}
}

func eventDispatch(call *Call, event Event) {

	if event.Content["Unique-Id"] != call.uuid {
		return
	}

	for _, handler := range call.handlers {
		if handler == nil {
			continue
		}
		if handler.Filter(event) {
			go handler.Handle(event)
		}
	}

	for k, handler := range call.handlerOnce {
		if handler == nil {
			continue
		}
		if handler.Filter(event) {
			handler.Handle(event)
			call.DoneActionHandle(k)
		}
	}

}

//Este permite esperar un evento determinado
//y bloquear la gorutina atraves del chan *wait*
//@todo como manejar un timeout por demora??
type WaitEventHandle struct {
	wait chan interface{}
	filter map[string]string
}

func NewWaitEventHandle(wait chan interface{}, filter map[string]string) WaitEventHandle {
	return WaitEventHandle{wait, filter}
}

func (we WaitEventHandle) Filter(ev Event) bool {
	for fk,fv := range we.filter {
		if ev.Content[fk] != fv {
			return false
		}
	}
	return true
}

func (we WaitEventHandle) Handle(ev Event) {
	we.wait <- ev
}

//Este permite esperar un evento determinado
//y bloquear la gorutina atraves del chan *wait*
//@todo como manejar un timeout por demora??
type WaitAnyEventHandle struct {
	wait chan interface{}
	filter []map[string]string
}

func NewWaitAnyEventHandle(wait chan interface{}, filter []map[string]string) WaitAnyEventHandle {
	return WaitAnyEventHandle{wait, filter}
}

func (we WaitAnyEventHandle) Filter(ev Event) bool {
	valid_and := true
	for _, filter := range we.filter {
		valid_and = true
		for fk,fv := range filter {
			if  ev.Content[fk] != fv {
				valid_and = false
				break
			}
		}
		if valid_and { break }
	}
	return valid_and
}

func (we WaitAnyEventHandle) Handle(ev Event) {
	we.wait <- ev
}

//Recolecta marcacion
type CollectDTMFEventHandle struct {
	wait chan string

	//Caracter con que se termina deteccion
	terminator uint8

	//los digitos que se esperan recibir
	validDigits string

	//la cantidad que se espera recibir
	numDigits int

	//donde se recopilan lo que van escribiendo
	collection *string
}

func NewCollectDTMFEventHandle(wait chan string, numDigits int, validDigits string, terminator uint8) CollectDTMFEventHandle {
	return CollectDTMFEventHandle{wait,terminator, validDigits, numDigits, new(string)}
}

func (cl CollectDTMFEventHandle) Filter(ev Event) bool {
	if ev.Content["Event-Name"] == "DTMF" {
		return true
	}

	return false
}

func (cl CollectDTMFEventHandle) Handle(ev Event) {
	switch(ev.Content["Dtmf-Digit"]) {
	case fmt.Sprintf("%c",cl.terminator):
		cl.wait <- *cl.collection
		*cl.collection = ""
	default:
		if strings.ContainsAny(ev.Content["Dtmf-Digit"], cl.validDigits) {
			*cl.collection += ev.Content["Dtmf-Digit"]
		}else{
			*cl.collection = ""
		}
	}

	if len(*cl.collection) == cl.numDigits {
		cl.wait <- *cl.collection
		*cl.collection = ""
	}
}
<commit_msg>se fuerza a collection de dtmf, deternse cuando se detiene play_and_get_digits<commit_after>//
//Application:bridge
//EventName:CHANNEL_HANGUP
//EventName:CHANNEL_EXECUTE_COMPLETE
//Application:bridge
//Variable_bridge_hangup_cause:NORMAL_CLEARING
//Variable_dialstatus:DONTCALL
//Channel-Call-State:HELD
//Variable_originate_disposition:CALL_REJECTED
//Hangup-Cause:CALL_REJECTED
package glivo

import (
	"net/textproto"
	"fmt"
	"strings"
)

//Representa un evento de Freeswitch
//Las claves estan Camelised
type Event struct {
	call *Call
	Content map[string]string
}

//Permite llamar procedimiento cuando se cumpla el filro
//o bien cuando el evento cumpla las condiciones esperadas.
type HandlerEvent interface {
	//Delimita el handler a que eventos trabajar
	//retorna +true+ si es evento esperado
	Filter(Event) bool

	//Recibe evento y reacciona a este
	Handle(Event)

}

//Crea evento apartir de el MIME leido
func EventFromMIME(call *Call, mime textproto.MIMEHeader) Event{
	return Event{ call, mimeToMap(mime)}
}

func eventDispatch(call *Call, event Event) {

	if event.Content["Unique-Id"] != call.uuid {
		return
	}

	for _, handler := range call.handlers {
		if handler == nil {
			continue
		}
		if handler.Filter(event) {
			go handler.Handle(event)
		}
	}

	for k, handler := range call.handlerOnce {
		if handler == nil {
			continue
		}
		if handler.Filter(event) {
			handler.Handle(event)
			call.DoneActionHandle(k)
		}
	}

}

//Este permite esperar un evento determinado
//y bloquear la gorutina atraves del chan *wait*
//@todo como manejar un timeout por demora??
type WaitEventHandle struct {
	wait chan interface{}
	filter map[string]string
}

func NewWaitEventHandle(wait chan interface{}, filter map[string]string) WaitEventHandle {
	return WaitEventHandle{wait, filter}
}

func (we WaitEventHandle) Filter(ev Event) bool {
	for fk,fv := range we.filter {
		if ev.Content[fk] != fv {
			return false
		}
	}
	return true
}

func (we WaitEventHandle) Handle(ev Event) {
	we.wait <- ev
}

//Este permite esperar un evento determinado
//y bloquear la gorutina atraves del chan *wait*
//@todo como manejar un timeout por demora??
type WaitAnyEventHandle struct {
	wait chan interface{}
	filter []map[string]string
}

func NewWaitAnyEventHandle(wait chan interface{}, filter []map[string]string) WaitAnyEventHandle {
	return WaitAnyEventHandle{wait, filter}
}

func (we WaitAnyEventHandle) Filter(ev Event) bool {
	valid_and := true
	for _, filter := range we.filter {
		valid_and = true
		for fk,fv := range filter {
			if  ev.Content[fk] != fv {
				valid_and = false
				break
			}
		}
		if valid_and { break }
	}
	return valid_and
}

func (we WaitAnyEventHandle) Handle(ev Event) {
	we.wait <- ev
}

//Recolecta marcacion
type CollectDTMFEventHandle struct {
	wait chan string

	//Caracter con que se termina deteccion
	terminator uint8

	//los digitos que se esperan recibir
	validDigits string

	//la cantidad que se espera recibir
	numDigits int

	//donde se recopilan lo que van escribiendo
	collection *string
}

func NewCollectDTMFEventHandle(wait chan string, numDigits int, validDigits string, terminator uint8) CollectDTMFEventHandle {
	return CollectDTMFEventHandle{wait,terminator, validDigits, numDigits, new(string)}
}

func (cl CollectDTMFEventHandle) Filter(ev Event) bool {
	if ev.Content["Event-Name"] == "DTMF" {
		return true
	}

	if ev.Content["Event-Name"] == "CHANNEL_EXECUTE_COMPLETE" && ev.Content["Variable_current_application"] == "play_and_get_digits" {
		cl.wait <- *cl.collection
		*cl.collection = ""
	}

	return false
}

func (cl CollectDTMFEventHandle) Handle(ev Event) {
	switch(ev.Content["Dtmf-Digit"]) {
	case fmt.Sprintf("%c",cl.terminator):
		cl.wait <- *cl.collection
		*cl.collection = ""
	default:
		if strings.ContainsAny(ev.Content["Dtmf-Digit"], cl.validDigits) {
			*cl.collection += ev.Content["Dtmf-Digit"]
		}else{
			*cl.collection = ""
		}
	}

	if len(*cl.collection) == cl.numDigits {
		cl.wait <- *cl.collection
		*cl.collection = ""
	}
}
<|endoftext|>


<commit_before>package app

// ChangeEvent represents the data passed in a change event.
type ChangeEvent struct {
	Value string
}

// MouseEvent represents data fired when interacting with a pointing device
// (such as a mouse).
type MouseEvent struct {
	ClientX  float64
	ClientY  float64
	PageX    float64
	PageY    float64
	ScreenX  float64
	ScreenY  float64
	Button   int
	Detail   int
	AltKey   bool
	CtrlKey  bool
	MetaKey  bool
	ShiftKey bool
}

// WheelEvent represents data fired when a wheel button of a pointing device
// (usually a mouse) is rotated.
type WheelEvent struct {
	DeltaX    float64
	DeltaY    float64
	DeltaZ    float64
	DeltaMode DeltaMode
	Target    DOMElement
}

// DeltaMode is an indication of the units of measurement for a delta value.
type DeltaMode uint64

// KeyboardEvent represents data fired when the keyboard is used.
type KeyboardEvent struct {
	CharCode rune
	KeyCode  KeyCode
	Location KeyLocation
	AltKey   bool
	CtrlKey  bool
	MetaKey  bool
	ShiftKey bool
}
<commit_msg>fix build<commit_after>package app

// ChangeEvent represents the data passed in a change event.
type ChangeEvent struct {
	Value string
}

// MouseEvent represents data fired when interacting with a pointing device
// (such as a mouse).
type MouseEvent struct {
	ClientX  float64
	ClientY  float64
	PageX    float64
	PageY    float64
	ScreenX  float64
	ScreenY  float64
	Button   int
	Detail   int
	AltKey   bool
	CtrlKey  bool
	MetaKey  bool
	ShiftKey bool
}

// WheelEvent represents data fired when a wheel button of a pointing device
// (usually a mouse) is rotated.
type WheelEvent struct {
	DeltaX    float64
	DeltaY    float64
	DeltaZ    float64
	DeltaMode DeltaMode
}

// DeltaMode is an indication of the units of measurement for a delta value.
type DeltaMode uint64

// KeyboardEvent represents data fired when the keyboard is used.
type KeyboardEvent struct {
	CharCode rune
	KeyCode  KeyCode
	Location KeyLocation
	AltKey   bool
	CtrlKey  bool
	MetaKey  bool
	ShiftKey bool
}
<|endoftext|>


<commit_before>// Copyright (c) 2014 Stefan Schroeder, NY, 2014-03-10
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file

package gocal_test

import (
	"gocal"
	"os"
	"testing"
)

func Test_Example01(t *testing.T) {
  g := gocal.New(1,12,2010)
  g.CreateCalendar("test-example01.pdf")
}

func Test_Example02(t *testing.T) {
  g := gocal.New(1,1,2011)
  g.SetNocolor()
  g.CreateCalendar("test-example02.pdf")
}

func Test_Example03(t *testing.T) {
  g := gocal.New(1,1,2015)
  g.SetOrientation("P")
  g.SetLocale("fr_FR")
  g.SetFont("sans")
  g.CreateCalendar("test-example03.pdf")
}

func Test_Example04(t *testing.T) {
  g := gocal.New(1,1,2015)
  g.SetOrientation("P")
  g.SetPhotos("gocalendar" + string(os.PathSeparator) + "pics")
  g.CreateCalendar("test-example04.pdf")
}

    /*
$E -o example01.pdf -p P -photos pics 1 2014
$E -o example04.pdf -lang de_DE -font mono 2 2014
$E -o example05.pdf -lang nl_NL -plain 3 2014
$E -o example06.pdf -font c:/windows/Fonts/cabalett.ttf -lang en_US 4 2014
$E -o example07.pdf -p P -lang fr_FR -photo pics/taxi.JPG  4 2014
$E -o example09.pdf -lang fi_FI -font serif -p L  4 2014
$E -o example10.pdf -lang fi_FI -font mono -p L 12 2013
$E -o example11.pdf -lang de_DE -font sans -p L 6 2014
$E -o example13.pdf -font sans -noother 7 2014
$E -o example14.pdf -small 2 2014
     */
<commit_msg>more tests<commit_after>// Copyright (c) 2014 Stefan Schroeder, NY, 2014-03-10
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file

package gocal_test

import (
	"gocal"
	"os"
	"testing"
)

func Test_Example01(t *testing.T) {
  g := gocal.New(1,12,2010)
  g.CreateCalendar("test-example01.pdf")
}

func Test_Example02(t *testing.T) {
  g := gocal.New(1,1,2011)
  g.SetNocolor()
  g.CreateCalendar("test-example02.pdf")
}

func Test_Example03(t *testing.T) {
  g := gocal.New(1,1,2015)
  g.SetOrientation("P")
  g.SetLocale("fr_FR")
  g.SetFont("sans")
  g.CreateCalendar("test-example03.pdf")
}

func Test_Example04(t *testing.T) {
  g := gocal.New(1,1,2015)
  g.SetOrientation("P")
  g.SetPhotos("gocalendar" + string(os.PathSeparator) + "pics")
  g.CreateCalendar("test-example04.pdf")
}

func Test_Example05(t *testing.T) {
  g := gocal.New(3,4,2013)
  g.SetOrientation("P")
  g.SetFont("mono")
  g.SetLocale("de_DE")
  g.CreateCalendar("test-example05.pdf")
}

func Test_Example06(t *testing.T) {
  g := gocal.New(3,4,2013)
  g.SetOrientation("P")
  g.SetPlain()
  g.SetLocale("nl_NL")
  g.CreateCalendar("test-example06.pdf")
}

// This test will fail on non-Windows platforms.
func Test_Example07(t *testing.T) {
  g := gocal.New(3,4,2013)
  g.SetFont("c:\\windows\\Fonts\\cabalett.ttf")
  g.CreateCalendar("test-example07.pdf")
}

func Test_Example08(t *testing.T) {
  g := gocal.New(3,4,2013)
  g.SetPhoto("gocalendar" + string(os.PathSeparator) + "pics" + string(os.PathSeparator) + "taxi.JPG")
  g.CreateCalendar("test-example08.pdf")
}

func Test_Example09(t *testing.T) {
  g := gocal.New(3,4,2013)
  g.SetLocale("fi_FI")
  g.CreateCalendar("test-example09.pdf")
}

func Test_Example10(t *testing.T) {
  g := gocal.New(3,4,2013)
  g.SetFontScale(0.5)
  g.CreateCalendar("test-example10.pdf")
}

func Test_Example11(t *testing.T) {
  g := gocal.New(3,4,2013)
  g.SetSmall()
  g.CreateCalendar("test-example11.pdf")
}

func Test_Example12(t *testing.T) {
  g := gocal.New(3,4,2013)
  g.SetHideOtherMonth()
  g.CreateCalendar("test-example12.pdf")
}

func Test_Example13(t *testing.T) {
  g := gocal.New(3,4,2013)
  g.SetHideWeek()
  g.SetHideMoon()
  g.CreateCalendar("test-example13.pdf")
}
func Test_Example14(t *testing.T) {
  g := gocal.New(1,12,2013)
  g.SetConfig("test-gocal.xml")
  g.CreateCalendar("test-example14.pdf")
}

<|endoftext|>


<commit_before>package gomon

import (
	"testing"
)

const resource string = `pokemon`
const resource_id string = `1`
const resource_url string = `http://pokeapi.co/api/v1/pokemon/1/`

func TestRequestUrl(t *testing.T) {
	if u := requestUrl(resource, resource_id); u != resource_url {
		t.Errorf("\nrequestUrl(`%v`, `%v`) returned (%v).\n\tExpected (%v).", resource, resource_id, u, resource_url)
	}
}
<commit_msg>Fix type in test<commit_after>package gomon

import (
	"testing"
)

const resource string = `pokemon`
const resource_id int = 1
const resource_url string = `http://pokeapi.co/api/v1/pokemon/1/`

func TestRequestUrl(t *testing.T) {
	if u := requestUrl(resource, resource_id); u != resource_url {
		t.Errorf("\nrequestUrl(`%v`, `%v`) returned (%v).\n\tExpected (%v).", resource, resource_id, u, resource_url)
	}
}
<|endoftext|>


<commit_before>package main

import (
    "encoding/binary"
    "xcl"
)

func main() {
    // Allocate a 'world' for interacting with kernels
    world := xcl.NewWorld()
    defer world.Release()

    // Import the kernel.
    // Right now these two identifiers are hard coded as an output from the build process
    krnl := world.Import("kernel_test").GetKernel("reconfigure_io_sdaccel_builder_stub_0_1")
    defer krnl.Release()

    // Create/get data and pass arguments to the kernel as required. These could be small pieces of data,
    // pointers to memory, data lengths so the Kernel knows what to expect. This all depends on your project.
    // We have passed three arguments here, you can pass more as neccessary

    // make an array to send to the kernel for processing
    input := make([]uint32, 10)

	  // seed it with incrementing values
  	for i, _ := range input {
  		input[i] = uint32(i)
  	}

    fmt.Println("Here is our example array:")

    for _, val := range input {
      print(val)
    }

    // Create space in shared memory for our array input
  	buff := world.Malloc(xcl.ReadOnly, uint(binary.Size(input)))
  	defer buff.Free()

    // Create a variable to hold the output from the FPGA
  	var output [10]uint32

  	// Create space in the shared memory for the output from the FPGA
  	outputBuff := world.Malloc(xcl.ReadWrite, uint(binary.Size(output)))
  	defer outputBuff.Free()

  	// write our input to the shared memory at the location we specified previously
  	binary.Write(buff.Writer(), binary.LittleEndian, &input)

  	// zero out output space
  	binary.Write(outputBuff.Writer(), binary.LittleEndian, &output)

    // Send the location of the input array as the first argument
    krnl.SetMemoryArg(0, buff)
    // Send the location the FPGA should put the result as the second argument
    krnl.SetMemoryArg(1, outputBuff)
    // Send the length of the input array, so the kernel knows what to expect, as the third argument
    krnl.SetArg(2, uint32(len(input)))

    // Run the kernel with the supplied arguments. This is the same for all projects.
    // The arguments ``(1, 1, 1)`` relate to x, y, z co-ordinates and correspond to our current
    // underlying technology.
    krnl.Run(1, 1, 1)

    // Display/use the results returned from the FPGA as required!

    binary.Read(outputBuff.Reader(), binary.LittleEndian, &output);

    fmt.Println("...and here is our array with each integer multiplied by 2.")

    for _, val := range output {
      print(val)
    }

}
<commit_msg>include library<commit_after>package main

import (
    "encoding/binary"
    "xcl"
    "fmt"
)

func main() {
    // Allocate a 'world' for interacting with kernels
    world := xcl.NewWorld()
    defer world.Release()

    // Import the kernel.
    // Right now these two identifiers are hard coded as an output from the build process
    krnl := world.Import("kernel_test").GetKernel("reconfigure_io_sdaccel_builder_stub_0_1")
    defer krnl.Release()

    // Create/get data and pass arguments to the kernel as required. These could be small pieces of data,
    // pointers to memory, data lengths so the Kernel knows what to expect. This all depends on your project.
    // We have passed three arguments here, you can pass more as neccessary

    // make an array to send to the kernel for processing
    input := make([]uint32, 10)

	  // seed it with incrementing values
  	for i, _ := range input {
  		input[i] = uint32(i)
  	}

    fmt.Println("Here is our example array:")

    for _, val := range input {
      print(val)
    }

    // Create space in shared memory for our array input
  	buff := world.Malloc(xcl.ReadOnly, uint(binary.Size(input)))
  	defer buff.Free()

    // Create a variable to hold the output from the FPGA
  	var output [10]uint32

  	// Create space in the shared memory for the output from the FPGA
  	outputBuff := world.Malloc(xcl.ReadWrite, uint(binary.Size(output)))
  	defer outputBuff.Free()

  	// write our input to the shared memory at the location we specified previously
  	binary.Write(buff.Writer(), binary.LittleEndian, &input)

  	// zero out output space
  	binary.Write(outputBuff.Writer(), binary.LittleEndian, &output)

    // Send the location of the input array as the first argument
    krnl.SetMemoryArg(0, buff)
    // Send the location the FPGA should put the result as the second argument
    krnl.SetMemoryArg(1, outputBuff)
    // Send the length of the input array, so the kernel knows what to expect, as the third argument
    krnl.SetArg(2, uint32(len(input)))

    // Run the kernel with the supplied arguments. This is the same for all projects.
    // The arguments ``(1, 1, 1)`` relate to x, y, z co-ordinates and correspond to our current
    // underlying technology.
    krnl.Run(1, 1, 1)

    // Display/use the results returned from the FPGA as required!

    binary.Read(outputBuff.Reader(), binary.LittleEndian, &output);

    fmt.Println("...and here is our array with each integer multiplied by 2.")

    for _, val := range output {
      print(val)
    }

}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 ZionSoft. All rights reserved.
 * Use of this source code is governed by a BSD-style license
 * that can be found in the LICENSE file.
 */

package account

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"

	"appengine"
	"appengine/datastore"

	"src/core"
)

func registerDeviceAccountHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		panic(&core.Error{http.StatusMethodNotAllowed, ""})
	}

	var da deviceAccount
	if err := da.unmarshalHTTPRequest(r); err != nil {
		panic(&core.Error{http.StatusBadRequest, ""})
	}

	c := appengine.NewContext(r)
	err := datastore.RunInTransaction(c, func(c appengine.Context) error {
		if da.AccountID == 0 {
			// it might be a new device, or the request is fired by old clients
			if existing, ok := daCache.Get(da.PushNotificationID); ok {
				// hit in-memory cache, so it's a known device with old client
				da.AccountID = existing.(deviceAccount).AccountID
				da.Created = existing.(deviceAccount).Created
			} else {
				// missed in-memory cache, should fall back to datastore
				q := datastore.NewQuery("DeviceAccount").
					Ancestor(createDeviceAccountAncestorKey(c)).
					Filter("PushNotificationID =", da.PushNotificationID)
				count, err := q.Count(c)
				if err != nil {
					return err
				}

				if count == 0 {
					// from an unknown device, should create a new account
					key, err := datastore.Put(c, createIncompleteDeviceAccountKey(c), &da)
					if err != nil {
						return err
					}
					da.AccountID = key.IntID()
					daCache.Set(da.PushNotificationID, da)
					return nil
				} else {
					var existing []*deviceAccount
					keys, err := q.GetAll(c, &existing)
					if err != nil {
						return err
					}
					da.AccountID = keys[0].IntID()
					da.Created = existing[0].Created
				}
			}

			_, err := datastore.Put(c, createDeviceAccountKey(c, da.AccountID), &da)
			daCache.Set(da.PushNotificationID, da)
			return err
		} else {
			// update existing account (for request fired by new clients)
			key := strconv.FormatInt(da.AccountID, 10)
			if existing, ok := daCache.Get(key); ok {
				// hit in-memory cache
				da.Created = existing.(deviceAccount).Created
			} else {
				// missed in-memory cache, falls back to datastore
				var existing deviceAccount
				if err := datastore.Get(c, createDeviceAccountKey(c, da.AccountID), &existing); err != nil {
					return err
				}
				da.Created = existing.Created
			}

			if _, err := datastore.Put(c, createDeviceAccountKey(c, da.AccountID), &da); err != nil {
				return err
			}
			daCache.Set(key, da)
		}

		return nil
	}, nil)
	if err != nil {
		panic(&core.Error{http.StatusInternalServerError, err.Error()})
	}

	// writes the response
	w.WriteHeader(http.StatusCreated)

	var resp struct {
		AccountID int64 `json:"accountId"`
	}
	resp.AccountID = da.AccountID
	b, _ := json.Marshal(resp)
	fmt.Fprintf(w, string(b))
}
<commit_msg>Removed one unnecessary query.<commit_after>/*
 * Copyright (c) 2015 ZionSoft. All rights reserved.
 * Use of this source code is governed by a BSD-style license
 * that can be found in the LICENSE file.
 */

package account

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"

	"appengine"
	"appengine/datastore"

	"src/core"
)

func registerDeviceAccountHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		panic(&core.Error{http.StatusMethodNotAllowed, ""})
	}

	var da deviceAccount
	if err := da.unmarshalHTTPRequest(r); err != nil {
		panic(&core.Error{http.StatusBadRequest, ""})
	}

	c := appengine.NewContext(r)
	err := datastore.RunInTransaction(c, func(c appengine.Context) error {
		if da.AccountID == 0 {
			// it might be a new device, or the request is fired by old clients
			if existing, ok := daCache.Get(da.PushNotificationID); ok {
				// hit in-memory cache, so it's a known device with old client
				da.AccountID = existing.(deviceAccount).AccountID
				da.Created = existing.(deviceAccount).Created
			} else {
				// missed in-memory cache, should fall back to datastore
				q := datastore.NewQuery("DeviceAccount").
					Ancestor(createDeviceAccountAncestorKey(c)).
					Filter("PushNotificationID =", da.PushNotificationID)
				var existing []*deviceAccount
				keys, err := q.GetAll(c, &existing)
				if err != nil {
					return err
				}

				if len(keys) == 0 {
					// from an unknown device, should create a new account
					key, err := datastore.Put(c, createIncompleteDeviceAccountKey(c), &da)
					if err != nil {
						return err
					}
					da.AccountID = key.IntID()
					daCache.Set(da.PushNotificationID, da)
					return nil
				} else {
					// a known device with old client
					da.AccountID = keys[0].IntID()
					da.Created = existing[0].Created
				}
			}

			_, err := datastore.Put(c, createDeviceAccountKey(c, da.AccountID), &da)
			daCache.Set(da.PushNotificationID, da)
			return err
		} else {
			// update existing account (for request fired by new clients)
			key := strconv.FormatInt(da.AccountID, 10)
			if existing, ok := daCache.Get(key); ok {
				// hit in-memory cache
				da.Created = existing.(deviceAccount).Created
			} else {
				// missed in-memory cache, falls back to datastore
				var existing deviceAccount
				if err := datastore.Get(c, createDeviceAccountKey(c, da.AccountID), &existing); err != nil {
					return err
				}
				da.Created = existing.Created
			}

			if _, err := datastore.Put(c, createDeviceAccountKey(c, da.AccountID), &da); err != nil {
				return err
			}
			daCache.Set(key, da)
		}

		return nil
	}, nil)
	if err != nil {
		panic(&core.Error{http.StatusInternalServerError, err.Error()})
	}

	// writes the response
	w.WriteHeader(http.StatusCreated)

	var resp struct {
		AccountID int64 `json:"accountId"`
	}
	resp.AccountID = da.AccountID
	b, _ := json.Marshal(resp)
	fmt.Fprintf(w, string(b))
}
<|endoftext|>


<commit_before><commit_msg>moving host port up in visibility<commit_after><|endoftext|>