text:
package com.modeln.build.ctrl.command.patch;

import com.modeln.build.common.data.account.CMnAccount;
import com.modeln.build.common.data.product.CMnPatch;
import com.modeln.build.common.data.product.CMnPatchOwner;
import com.modeln.build.common.enums.CMnServicePatch;
import com.modeln.build.common.database.CMnCustomerTable;
import com.modeln.build.ctrl.database.CMnPatchTable;
import com.modeln.build.ctrl.forms.CMnPatchOwnerForm;
import com.modeln.build.ctrl.forms.IMnPatchForm;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import com.modeln.build.common.data.account.UserData;
import com.modeln.build.common.database.LoginTable;
import com.modeln.build.web.errors.ApplicationError;
import com.modeln.build.web.errors.ApplicationException;
import com.modeln.build.web.application.CommandResult;
import com.modeln.build.web.application.ProtectedCommand;
import com.modeln.build.web.application.WebApplication;
import com.modeln.build.web.database.RepositoryConnection;
import com.modeln.build.web.errors.ErrorMap;
import com.modeln.build.web.util.SessionUtility;

/**
 * This command creates and updates patch assignment information.
 *
 * @author             Shawn Stafford
 */
public class CMnPatchAssignment extends ProtectedCommand {

    /**
     * This is the primary method which will be used to perform the command
     * actions.  The application will use this method to service incoming
     * requests.  You must pass a reference to the calling application into
     * the service method to allow callback method calls to be performed.
     *
     * @param   app     Application which called the command
     * @param   req     HttpServletRequest object
     * @param   res     HttpServletResponse object
     */
    public CommandResult execute(WebApplication app, HttpServletRequest req, HttpServletResponse res)
        throws ApplicationException
    {
        // Execute the generic actions for all commands
        CommandResult result = super.execute(app, req, res);

        // Execute the actions for the command
        if (!result.containsError()) {
            // Get the login information from the session
            UserData user = SessionUtility.getLogin(req.getSession());

            ApplicationException exApp = null;
            ApplicationError error = null;
            RepositoryConnection rc = null;
            RepositoryConnection ac = null;
            try {
                rc = app.getRepositoryConnection();
                ac = app.getAccountConnection();
                CMnPatchTable patchTable = CMnPatchTable.getInstance();
                CMnCustomerTable custTable = CMnCustomerTable.getInstance();

                // Fall back to the request attributes in case the data was set by another command
                String patchId = (String) req.getParameter(IMnPatchForm.PATCH_ID_LABEL);
                if (patchId == null) {
                    patchId = (String) req.getAttribute(IMnPatchForm.PATCH_ID_LABEL);
                }

                if ((patchId != null) && (patchId.length() > 0)) {
                    CMnPatch patch = patchTable.getRequest(rc.getConnection(), patchId, true);
                    if (patch != null) {
                        req.setAttribute(IMnPatchForm.PATCH_DATA, patch);
                    } else {
                        throw new ApplicationException(ErrorMap.APPLICATION_DISPLAY_FAILURE, "Failed to obtain patch data for patch ID " + patchId);
                    }

                    // Obtain the patch owner information from the database
                    CMnPatchOwner owner = patchTable.getPatchOwner(rc.getConnection(), patchId);
                    if (owner != null) {
                        req.setAttribute(CMnPatchOwnerForm.OWNER_DATA, owner);
                    }

                    // Obtain the patch owner information from the database
                    Vector<UserData> users = LoginTable.getInstance().getUsers(ac.getConnection());
                    if (users != null) {
                        Hashtable userhash = new Hashtable(users.size());
                        Enumeration userlist = users.elements();
                        while (userlist.hasMoreElements()) {
                            UserData currentUser = (UserData) userlist.nextElement();
                            if (currentUser.isAdmin()) {
                                String uid = currentUser.getUid();
                                StringBuffer name = new StringBuffer();
                                if (currentUser.getFirstName() != null) {
                                    name.append(currentUser.getFirstName());
                                }
                                if (currentUser.getMiddleName() != null) {
                                    name.append(" " + currentUser.getMiddleName());
                                }
                                if (currentUser.getLastName() != null) {
                                    name.append(" " + currentUser.getLastName());
                                }
                                userhash.put(uid, name.toString());
                            }
                        }
                        req.setAttribute(CMnPatchOwnerForm.USER_LIST, userhash);
                    }

                } // has patchId

                result.setDestination("patch/patch_assignment.jsp");

            } catch (ApplicationException aex) {
                exApp = aex;
            } catch (Exception ex) {
                exApp = new ApplicationException(
                    ErrorMap.APPLICATION_DISPLAY_FAILURE,
                    "Failed to process command.");
                exApp.setStackTrace(ex);
            } finally {
                app.releaseRepositoryConnection(rc);
                app.releaseRepositoryConnection(ac);

                // Throw any exceptions once the database connections have been cleaned up
                if (exApp != null) {
                    throw exApp;
                }
            }
        }

        return result;
    }

}


text:
package csvutil

import (
	"encoding/csv"
	"encoding/json"
	"io"
	"os"

	"github.com/grokify/gotilla/type/stringsutil"
)

var DebugReadCSV = false // should not need to edit

/*

For UTF-8 BOM, csv.Reader.Read() will return error = "line 1, column 1: bare \" in non-quoted-field"

If you encounter this close the file and call again with stripBom = true

*/

// NewReader will create a csv.Reader and optionally strip off the
// byte order mark (BOM) if requested. Close file reader with
// `defer f.Close()`.
func NewReader(path string, comma rune, stripBom bool) (*csv.Reader, *os.File, error) {
	var csvReader *csv.Reader
	var file *os.File
	file, err := os.Open(path)
	if err != nil {
		return csvReader, file, err
	}
	if stripBom {
		b3 := make([]byte, 3)
		_, err := file.Read(b3)
		if err != nil {
			return csvReader, file, err
		}
	}
	csvReader = csv.NewReader(file)
	csvReader.Comma = comma
	return csvReader, file, nil
}

// Writer is a struct for a CSV/TSV writer.
type Writer struct {
	Separator        string
	StripRepeatedSep bool
	ReplaceSeparator bool
	SeparatorAlt     string
	File             *os.File
}

// NewWriter returns a Writer with the separator params set.
func NewWriter(filepath, sep string, replaceSeparator bool, alt string) (Writer, error) {
	w := Writer{
		Separator:        sep,
		StripRepeatedSep: false,
		ReplaceSeparator: replaceSeparator,
		SeparatorAlt:     alt}
	return w, w.open(filepath)
}

// Open opens a filepath.
func (w *Writer) open(filepath string) error {
	f, err := os.Create(filepath)
	if err != nil {
		return err
	}
	w.File = f
	return nil
}

// AddLine adds an []interface{} to the file.
func (w *Writer) AddLine(cells []interface{}) error {
	_, err := w.File.WriteString(
		stringsutil.JoinInterface(
			cells, w.Separator, false, w.ReplaceSeparator, w.SeparatorAlt) + "\n")
	if err != nil {
		return err
	}
	return w.File.Sync()
}

// Close closes the file.
func (w *Writer) Close() error {
	return w.File.Close()
}

func NewWriterFile(filename string) (*csv.Writer, *os.File, error) {
	file, err := os.Create(filename)
	if err != nil {
		return nil, file, err
	}
	//defer file.Close()

	writer := csv.NewWriter(file)
	//defer writer.Flush()
	return writer, file, nil
}

type CSVHeader struct {
	Columns []string
}

func (ch *CSVHeader) Index(want string) int {
	for i, try := range ch.Columns {
		if want == try {
			return i
		}
	}
	return -1
}

func (ch *CSVHeader) RecordMatch(row []string, andFilter map[string]stringsutil.MatchInfo) (bool, error) {
	for colName, matchInfo := range andFilter {
		idx := ch.Index(colName)
		if idx >= len(row) {
			return false, nil
		}
		match, err := stringsutil.Match(row[idx], matchInfo)
		if err != nil {
			return false, err
		}
		if !match {
			return false, nil
		}
	}
	return true, nil
}

func (ch *CSVHeader) RecordToMSS(row []string) map[string]string {
	mss := map[string]string{}
	l := len(row)
	for i, key := range ch.Columns {
		if i < l {
			mss[key] = row[i]
		}
	}
	return mss
}

func FilterCSVFile(inPath, outPath string, inComma rune, inStripBom bool, andFilter map[string]stringsutil.MatchInfo) error {
	reader, inFile, err := NewReader(inPath, inComma, inStripBom)
	if err != nil {
		return err
	}
	defer inFile.Close()
	writer, outFile, err := NewWriterFile(outPath)
	if err != nil {
		return err
	}
	defer writer.Flush()
	defer outFile.Close()
	return WriteCSVFiltered(reader, writer, andFilter, true)
}

// MergeFilterCSVFiles can merge and filter multiple CSV files. It expects row definitions to be the same
// across all input files.
func MergeFilterCSVFiles(inPaths []string, outPath string, inComma rune, inStripBom bool, andFilter map[string]stringsutil.MatchInfo) error {
	writer, outFile, err := NewWriterFile(outPath)
	if err != nil {
		return err
	}
	defer writer.Flush()
	defer outFile.Close()

	for i, inPath := range inPaths {
		reader, inFile, err := NewReader(inPath, inComma, inStripBom)
		if err != nil {
			return err
		}
		defer inFile.Close()

		writeHeader := false
		if i == 0 {
			writeHeader = true
		}
		err = WriteCSVFiltered(reader, writer, andFilter, writeHeader)
		if err != nil {
			return err
		}
	}
	return nil
}

/*
type JsonRecordsInfo struct {
	Meta    JsonRecordsInfoMeta `json:"meta"`
	Records []map[string]string `json:"records"`
}

type JsonRecordsInfoMeta struct {
	Count int `json:"count"`
}*/
/*
func ReadMergeFilterCSVFiles(inPaths []string, outPath string, inComma rune, inStripBom bool, andFilter map[string]stringsutil.MatchInfo) (table.DocumentsSet, error) {
	//data := JsonRecordsInfo{Records: []map[string]string{}}
	data := table.NewDocumentsSet()

	for _, inPath := range inPaths {
		reader, inFile, err := NewReader(inPath, inComma, inStripBom)
		if err != nil {
			return data, err
		}

		csvHeader := CSVHeader{}
		j := -1

		for {
			line, err := reader.Read()
			if err == io.EOF {
				break
			} else if err != nil {
				return data, err
			}
			j += 1

			if j == 0 {
				csvHeader.Columns = line
				continue
			}
			match, err := csvHeader.RecordMatch(line, andFilter)
			if err != nil {
				return data, err
			}
			if !match {
				continue
			}

			mss := csvHeader.RecordToMSS(line)
			data.Documents = append(data.Documents, mss)
		}
		err = inFile.Close()
		if err != nil {
			return data, err
		}
	}
	data.Inflate()
	return data, nil
}
*/
/*
func MergeFilterCSVFilesToJSON(inPaths []string, outPath string, inComma rune, inStripBom bool, perm os.FileMode, andFilter map[string]stringsutil.MatchInfo) error {
	data, err := ReadMergeFilterCSVFiles(inPaths, outPath, inComma, inStripBom, andFilter)
	if err != nil {
		return err
	}
	bytes, err := jsonutil.MarshalSimple(data, "", "  ")
	if err != nil {
		return err
	}
	return ioutil.WriteFile(outPath, bytes, perm)
}
*/
func MergeFilterCSVFilesToJSONL(inPaths []string, outPath string, inComma rune, inStripBom bool, andFilter map[string]stringsutil.MatchInfo) error {
	outFh, err := os.Create(outPath)
	if err != nil {
		return err
	}

	for _, inPath := range inPaths {
		reader, inFile, err := NewReader(inPath, inComma, inStripBom)
		if err != nil {
			return err
		}

		csvHeader := CSVHeader{}
		j := -1

		for {
			line, err := reader.Read()
			if err == io.EOF {
				break
			} else if err != nil {
				return err
			}
			j += 1

			if j == 0 {
				csvHeader.Columns = line
				continue
			}
			match, err := csvHeader.RecordMatch(line, andFilter)
			if err != nil {
				return err
			}
			if !match {
				continue
			}

			mss := csvHeader.RecordToMSS(line)

			bytes, err := json.Marshal(mss)
			if err != nil {
				return err
			}
			_, err = outFh.Write(bytes)
			if err != nil {
				return err
			}
			_, err = outFh.Write([]byte("\n"))
			if err != nil {
				return err
			}
			outFh.Sync()
		}
		err = inFile.Close()
		if err != nil {
			return err
		}
	}
	return outFh.Close()
}

// WriteCSVFiltered filters an existing CSV and writes the matching lines
// to a *csv.Writer.
func WriteCSVFiltered(reader *csv.Reader, writer *csv.Writer, andFilter map[string]stringsutil.MatchInfo, writeHeader bool) error {
	csvHeader := CSVHeader{}
	i := -1
	for {
		line, err := reader.Read()
		if err == io.EOF {
			break
		} else if err != nil {
			return err
		}
		i += 1
		if i == 0 {
			csvHeader.Columns = line
			if writeHeader {
				err := writer.Write(line)
				if err != nil {
					return err
				}
			}
			continue
		}
		match, err := csvHeader.RecordMatch(line, andFilter)
		if err != nil {
			return err
		}
		if match {
			err := writer.Write(line)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

/*
func NewTableDataFilesSimple(filenames []string, sep string, hasHeader, trimSpace bool) (table.TableData, error) {
	tbl := table.NewTableData()
	for i, filename := range filenames {
		filename = strings.TrimSpace(filename)
		if len(filename) == 0 {
			continue
		}
		tblx, err := NewTableDataFileSimple(filename, sep, hasHeader, trimSpace)
		if err != nil {
			return tbl, err
		}
		if len(tbl.Columns) == 0 {
			tbl.Columns = tblx.Columns
		} else {
			curCols := strings.Join(tbl.Columns, ",")
			nowCols := strings.Join(tblx.Columns, ",")
			if curCols != nowCols {
				if i == 0 {
					// if len(tbl.Columns) > 0, i has to be > 0
					panic("E_BAD_FILE_COUNTER_TABLE_COLUMNS")
				}
				return tbl, fmt.Errorf("CSV table definition mismatch [%s] AND [%s] for FILES [%s]",
					curCols, nowCols,
					filenames[i-1]+","+filename)
			}
		}
		if len(tblx.Records) > 0 {
			tbl.Records = append(tbl.Records, tblx.Records...)
		}
	}
	return tbl, nil
}

func NewTableDataFileSimple(path string, sep string, hasHeader, trimSpace bool) (table.TableData, error) {
	tbl := table.NewTableData()
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return tbl, err
	}
	lines := strings.Split(string(data), "\n")
	for i, line := range lines {
		if trimSpace {
			line = strings.TrimSpace(line)
		}
		parts := strings.Split(line, sep)
		parts = stringsutil.SliceTrimSpace(parts, false)
		if hasHeader && i == 0 {
			tbl.Columns = parts
		} else {
			tbl.Records = append(tbl.Records, parts)
		}
	}
	return tbl, nil
}

// NewTableDataFileCSV reads in a CSV file and returns a TableData struct.
func NewTableDataFileCSV(path string, comma rune, stripBom bool) (table.TableData, error) {
	tbl := table.NewTableData()
	csvReader, f, err := NewReader(path, comma, stripBom)
	if err != nil {
		return tbl, err
	}
	defer f.Close()
	if DebugReadCSV {
		i := -1
		for {
			line, err := csvReader.Read()
			if err == io.EOF {
				break
			} else if err != nil {
				return tbl, err
			}
			i += 1
			if i == 0 {
				tbl.Columns = line
				continue
			}
			tbl.Records = append(tbl.Records, line)
			if i > 2500 {
				fmt.Printf("[%v] %v\n", i, strings.Join(line, ","))
			}
		}

	} else {
		lines, err := csvReader.ReadAll()
		if err != nil {
			return tbl, err
		}
		tbl.LoadMergedRows(lines)
	}
	return tbl, nil
}
*/

redpajama_set_name: RedPajamaGithub


text:
date: 2018-11-18 09:36:32
title: Reimagining Rockwell
tags:
    - art
    - photography
---

> Mr. Thomas and the photographer Emily Shur rented a home in Los Angeles for a weekend in May. There, they shot several images that harked back to Mr. Rockwell's "Freedom From Want," one in a series of four paintings inspired by Franklin D. Roosevelt's 1941 speech to Congress celebrating America's freedom and democratic values.
>
> "The image haunted me because of the world we live in," the artist said, referring to today's divisive political climate. "I wanted to imagine what it would look like today."

-- [The New York Times](https://www.nytimes.com/2018/11/08/arts/norman-rockwell-freedom.html)

![](/misc/f/freedom_from_want_3.jpg)

Some recreations

![](/misc/f/freedom_from_want_2.jpg)
![](/misc/f/freedom_from_want_1.jpg)

<small class="credit">-- Hank Willis Thomas and Emily Shur</small>

A lot of parodies of the painting [here as well](http://www.ifitshipitshere.com/37-best-parodies-rockwells-freedom-want-aka-thanksgiving-dinner).


text:
package cs.ucla.edu.bwaspark.datatype

class MemAlnType {
  var pos: Long = 0          // forward strand 5'-end mapping position
  var rid: Int = 0           // reference sequence index in bntseq_t; <0 for unmapped
  var flag: Int = 0          // extra flag
  var isRev: Byte = 0        // is_rev: whether on the reverse strand
  var mapq: Short = 0        // mapq: mapping quality
  var NM: Int = 0            // NM: edit distance
  var nCigar: Int = 0        // number of CIGAR operations
  var cigar: CigarType = _   // CIGAR in the BAM encoding: opLen<<4|op; op to integer mapping: MIDSH=>01234
  var score: Int = 0
  var sub: Int = 0

  /**
    *  Make a copy of the current object
    */
  def copy(): MemAlnType = {
    var aln = new MemAlnType
    aln.pos = pos
    aln.rid = rid
    aln.flag = flag
    aln.isRev = isRev
    aln.mapq = mapq
    aln.NM = NM
    aln.nCigar = nCigar
    if(nCigar > 0)
      aln.cigar = cigar.copy
    aln.score = score
    aln.sub = sub
    aln
  }
}


text:
package org.nikkii.embedhttp.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * A basic Http Cookie implementation
 *
 * @author Nikki
 *
 */
public class HttpCookie {

	/**
	 * The RFC1123 date pattern
	 */
	private final static String RFC1123_PATTERN =
	        "EEE, dd MMM yyyy HH:mm:ss z";

	/**
	 * GMT Timezone
	 */
	private final static TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT");

	/**
	 * The RFC1123 Date Formatter
	 */
	private static DateFormat RFC_DATEFORMAT = new SimpleDateFormat(RFC1123_PATTERN, Locale.US);

	static {
		RFC_DATEFORMAT.setTimeZone(GMT_ZONE);
	}

	/**
	 * The cookie name
	 */
	private String name;

	/**
	 * The cookie value
	 */
	private String value;

	/**
	 * The cookie's expire time
	 */
	private long expireTime = -1;

	/**
	 * The cookie's path
	 */
	private String path;

	/**
	 * The cookie's domain
	 */
	private String domain;

	/**
	 * Whether or not the cookie is only available on secure connections
	 */
	private boolean secure;

	/**
	 * Constructs a new basic cookie
	 * @param name
	 * 			The cookie name
	 * @param value
	 * 			The cookie value
	 */
	public HttpCookie(String name, String value) {
		this.name = name;
		this.value = value;
	}

	/**
	 * Gets the cookie's name
	 * @return
	 * 		The cookie name
	 */
	public String getName() {
		return name;
	}

	/**
	 * Gets the cookie's value
	 * @return
	 * 		The cookie value
	 */
	public String getValue() {
		return value;
	}

	/**
	 * Gets the cookie's expire time in milliseconds from epoch
	 * @return
	 * 		The expire time
	 */
	public long getExpireTime() {
		return expireTime;
	}

	/**
	 * Returns whether or not the cookie has expired
	 * @return
	 * 		True if expireTime > currentTime
	 */
	public boolean hasExpired() {
		return expireTime > System.currentTimeMillis();
	}

	/**
	 * Gets the cookie's path
	 * @return
	 * 		The cookie's path
	 */
	public String getPath() {
		return path;
	}

	/**
	 * Gets the cookie's domain
	 * @return
	 * 		The cookie's domain
	 */
	public String getDomain() {
		return domain;
	}

	/**
	 * Gets whether the cookie is available only on secure connections
	 * @return
	 * 		The cookie's secure setting
	 */
	public boolean isSecure() {
		return secure;
	}

	/**
	 * Transforms this cookie into a Set-Cookie header field
	 * @return
	 * 			The header
	 */
	public String toHeader() {
		StringBuilder header = new StringBuilder();
		header.append(name).append('=').append(value);
		if(domain != null) {
			header.append("; ").append("Domain=").append(domain);
		}
		if(path != null) {
			header.append("; ").append("Path=").append(path);
		}
		if(expireTime > -1) {
			header.append("; ").append("Expires=").append(RFC_DATEFORMAT.format(new Date(expireTime)));
		}
		if(secure) {
			header.append("; ").append("Secure");
		}
		return header.toString();
	}

	@Override
	public String toString() {
		return name + '=' + value;
	}

}


text:
![Djanban](resources/images/logos/logo.png)

A kanban application with statistics and charts, including Trello integration.

# IMPORTANT NOTICE: [CONTRIBUTORS WANTED](#contributing)

**This project is stagnated**.

I need your help. Want to collaborate?

I'm listening to all kind of help (bug-fixing, new features, proposing features...).

# What's this?

Djanban is a web site that allows you to connect to your Trello user and fetch data from your boards.

The fetched data is processed and you are presented with several stats for each project that help you take
strategic decisions like:

- Is the maximum *work in progress* for each state/list being followed?
- Is there some tasks that are going back to earlier states too much?
- How many hours are your team working and in what projects?
- What's the lead and cycle time of each project tasks?
- Is the project on time according to its percentage of completion?

# Test site

Sign up in this [test site](https://djanban-test.intelligenia.com/) and share your ideas, suggestion or bug reports.

IMPORTANT NOTE: **this site deletes all your data each day**, so don't use it for your projects. Use it for testing this web app.
If you need help some help when installing this project in your servers, contact me and I will help you.

# Want to see it running in your computer?

Run this commands in your terminal:

```sh
sudo apt-get update
sudo apt-get -y install git python python-dev virtualenv build-essential\
    libssl-dev libffi-dev libmysqlclient-dev libxml2-dev libxslt1-dev
git clone https://github.com/diegojromerolopez/djanban
cd djanban
./start_local_server.sh
```

And open your web browser in the address http://localhost:8000

# How does it work?

First you have to sign up with your Trello API credentials. Initialize your boards and customize the type of each board list.

Once you have your boards ready, fetch the data.

You can also give other board members access to the dashboard. Each member will be able to access to his/her own boards, so it is perfect for a multi-project team.

![How it works](resources/images/diagrams/how-it-works.png)

# Requirements

## Plus for Trello

If you have chose the Sign up with Trello integration, you'll have to provide the spent and estimated times for each task.

That's what [Plus for Trello](https://chrome.google.com/webstore/detail/plus-for-trello-time-trac/gjjpophepkbhejnglcmkdnncmaanojkf?hl=en) is.
Use Plus for Trello in your boards to allow this application to get card spent and estimated times.

Configure Plus for Trello to use **time storage in comments**. Otherwise, Djanban will be unable to track spend and estimated time.

Don't use the feature of assigning times to other members of the team because it is not implemented yet.

## Py-Trello

[This library](https://github.com/sarumont/py-trello) is free software and I've collaborated with Py-Trello team to include all features required for Djanban.

## System packages

Run this command to install all the needed packages for this project in Ubuntu/Debian.

```sh
sudo apt-get -y install git python python-dev virtualenv build-essential libssl-dev libffi-dev\
   libmysqlclient-dev libxml2-dev libxslt1-dev
```

## Other packages

Django, python-mysql and more packages specified in **requirements.txt**.

## External requirements (optional)

### cloc

[cloc](https://github.com/AlDanial/cloc) is a tool to count lines of code.

It is used to compute the errors per LOC when assessing code quality.

### PHPMD

[PHP Mess Detector](https://phpmd.org/) is needed in you want to assess PHP code.

Install it by typing in Linux:

```sh
sudo apt-get install phpmd
```

Or in MacOS (using brew):

```sh
brew install homebrew/php/phpmd
```

# Configuration

## Local settings

Copy this code and create a settings_local.py file in your server in **src**.

Write your database credentials and your domain. Switch off debug messages.

I've used MySQL as the DBMS but you can use whatever you want.

```python
# -*- coding: utf-8 -*-

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<whatever string you want>'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# Set your email to be notified when a 500 error happens
ADMINS = (
    ("Your name", "youremail@example.com"),
)

DOMAIN = "<your domain>"
ALLOWED_HOSTS = [DOMAIN]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.<dbms>',
        'NAME': '<database name>',
        'USER': '<user>',
        'PASSWORD': '<password>',
        'HOST': '',
        'PORT': ''
    }
}

LANGUAGE_CODE = '<language code>'
TIME_ZONE = "<TIME ZONE>"

EMAIL_USE_TLS = <USE TLS?>
EMAIL_HOST = '<email host>'
EMAIL_PORT = <email host portr>
EMAIL_HOST_USER = '<email host user>'
EMAIL_HOST_PASSWORD = '<email host user password>'
DEFAULT_FROM_EMAIL = '<email host user from email>'
SERVER_EMAIL = '<email host user from email>'

# Date format that will be used in templates, by default is Y-m-d. Optional.
DATE_FORMAT = "<LOCAL DATE FORMAT IN TEMPLATES>"

# Datetime format that will be used in templates, by default is Y-m-d H:i. Optional.
DATETIME_FORMAT = "<LOCAL DATETIME FORMAT IN TEMPLATES>"

```

## Sign up

![Sign up](resources/images/screencaptures/auth-signup.png)

## Sign up with your Trello credentials

First you need to sign up with the api key, token and token secret.

This action will create a new user in the system.

User your email to log in the application.

![Sign up](resources/images/screencaptures/auth-signup-trello.png)

## Standard sign up

Don't have Trello account? Or don't want Trello synchronization? Register as a new user fulfilling the form.

NOTE: Trello synchronization can't be added later for the moment, so please choose wisely

## Initialize boards and lists

Later, you need to initialize the boards.

Use this command:

```python
python src/manage.py init <trello_username>
```

This initialization is only done for boards that are not initialized.

So, if you create a new board, execute the command again without fear of losing data.

## Set up boards

Setting up which lists of the board are the "development" and "done" lists.

Thus, the rest of the lists must be positioned before or after the development lists.

![View board lists](resources/images/screencaptures/board-lists.png)

## Fetch cards

And of course, you have to fetch the cards.

```python
python src/manage.py fetch <trello_username>
```

You'll need to set this action in a cron action and call it each hour or half-hour.

This process takes several seconds for each board (only three requests are needed per board).
In my tests, for 4 boards, the process takes 1 minute.

If you want to call this action, there is a button that allows you to fetch all the board data:

![Fetch board data](resources/images/screencaptures/board-fetch.png)

And that's all, then you have several interfaces with data about members, labels, cards and daily spent times

# Assess repository code (optional)

Run this command once a day to assess the code quality of your GitLab repositories.

```python
python src/manage.py assess_code_quality
```

# Test

Want to test this web application?

Run this commands in your terminal:

```sh
sudo apt-get -y install git python python-dev virtualenv build-essential\
    libssl-dev libffi-dev libmysqlclient-dev libxml2-dev libxslt1-dev
git clone https://github.com/diegojromerolopez/djanban
cd djanban
./start_local_server.sh
```

And open your favorite web browser in the address https://localhost:8000

# Board interfaces

## Board header

![Board header](resources/images/screencaptures/board-header.png)

## Board view

![Board index](resources/images/screencaptures/board-index.png)

## Board public view

A subset of board view, this view allows sharing stats with stakeholders that are not members of each Trello board.

## Board cards

![Board cards](resources/images/screencaptures/board-cards.png)

## Card reviews

To mark a card as reviewed, write **Reviewed by ** followed by the prefixed-by-@-usernames of the board members that reviewed this card.

For example: **Reviewed by @anastasious45 @petra99** means that both members (anastasious45 and petra99 have contributed to this card review.)

![Card review](resources/images/screencaptures/board-card-reviews.png)

## Board blocked cards

To block a card, make a comment in the blocked card with the following text:
**Blocked by CARD_URL** where CARD_URL is the URL of the blocking card in this board.

![Board blocked cards](resources/images/screencaptures/board-blocked-cards.png)

## Board requirements

To associate a card to a requirement make a comment in that card with the following text:
**Task of requirement REQUIREMENT_CODE** where REQUIREMENT_CODE is the unique requirement code
of this requirement.

![Board blocked cards](resources/images/screencaptures/board-requirements.png)

## Board labels

![Board labels](resources/images/screencaptures/board-labels.png)

## Board members

![Board members](resources/images/screencaptures/board-members.png)

## Board spent times

![Board spent times](resources/images/screencaptures/board-spent-times.png)

# Member interfaces

## What members have access to at least one board

![Members](resources/images/screencaptures/members.png)

# Permissions

There is no use of django permissions yet.

Only board creators have especial permissions with the board they created.

# Reports

## Daily report

Send a daily report with the spent times to each administrator user:

```python
python src/manage.py reporter daily_report [date of the report, by default today]
```

## Daily development report

Send a daily report with the spent times of each developer.

```python
python src/manage.py reporter daily_development_report [date of the report, by default today]
```

## Weekly report

Send a weekly report with the spent times to each administrator user:

```python
python src/manage.py reporter weekly_report [date whose week we want to get the report, by default current week]
```

## Monthly report

Send a monthly report with the spent times to each administrator user:

```python
python src/manage.py reporter monthly_report [date whose month we want to get the report, by default current month]
```

## Workflows

Workflows are a feature that will allow you to define what lists have to be
considered to measure spent, estimated and card living times.

Workflow stats are partially completed. Only the average time in each list and the standard deviation time on each list is shown for each workflow.

# Contributing

If you want to implement some feature, or fix some bug, please contact me.

I would gladly accept feature requests, pull requests and suggestions.

# Acknowledgements

* [intelligenia](http://www.intelligenia.com/), the place where I worked while developing this project in my own free time. intelligenia also supported some of the development of this project.
* [Trello](http://trello.com), for making the best web kanban board and providing the developers with an API.
* My former development team in intelligenia: [Brian Holsters](https://github.com/brian-holsters) & [Francisco Morales](https://github.com/moralesgea) for testing the app and suggesting new features.

# Legal notice

This project is not affiliated, endorsed or supported in any way by [Trello Inc.](http://trello.com)

Trello is a registered trademark in USA and other countries.

This project uses [Trello API](https://developers.trello.com/) to help users of Trello to get some useful charts, lists and stats.

This project was started by Diego J. Romero-López.

The license of this project is [MIT](LICENSE).

Project logos have been created with [Mark Maker](http://emblemmatic.org/markmaker).

# Questions? Suggestions? Need some help?

Don't hesitate to contact me, write me to diegojREMOVETHISromeroREMOVETHISlopez@REMOVETHISgmail.REMOVETHIScom.

(remove REMOVETHIS to see the real email address)


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bc;

import be.Cuentatipo;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author argos
 */
@Stateless
public class CuentatipoFacade extends AbstractFacade<Cuentatipo> implements CuentatipoFacadeLocal {
    @PersistenceContext(unitName = "sinergia-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public CuentatipoFacade() {
        super(Cuentatipo.class);
    }

}


text:
#pragma once

#include <kitBase/robotModel/robotParts/button.h>

namespace trik {
namespace robotModel {
namespace parts {

/// "Magic button" of android gamepad.
class TrikGamepadButton : public kitBase::robotModel::robotParts::Button
{
	Q_OBJECT
	Q_CLASSINFO("name", "gamepadButton")
	Q_CLASSINFO("friendlyName", tr("Android Gamepad Button"))

public:
	/// Constructor.
	/// @param info - device info for that device.
	/// @param port - port on which this device is configured.
	TrikGamepadButton(const kitBase::robotModel::DeviceInfo &info
			, const kitBase::robotModel::PortInfo &port);
};

}
}
}


text:
package com.litierses.Paginas;                                          //Package
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import java.io.Serializable;

import com.example.android.xyztouristattractions.R;                     //nombreproyecto.R
import com.litierses.Controladores.DietaManager;
import com.litierses.Entidades.Dieta;                                   //Parametro del Page (tipo)   Sin collection
//Para colections
import java.util.ArrayList;

public class DietaList_Activity extends AppCompatActivity {             //nombre del Page + _activity

    private static final String EXTRA_OBJECT = "DietaList_object";                           // nombre Page

    public static void launch(Activity activity, ArrayList<Dieta> dietas) {           //Parametro del Page (nombre + tipo)
        Intent intent = getLaunchIntent(activity, dietas);                 //Parametro del Page (nombre + tipo)
        activity.startActivity(intent);
    }

    public static Intent getLaunchIntent(Context context, ArrayList<Dieta>  dietas) {    //Parametro del Page (nombre + tipo)
        Intent intent = new Intent(context, DietaList_Activity.class);      //nombre del Page + _activity
        intent.putExtra(EXTRA_OBJECT, (Serializable) dietas);              //Parametro del Page (nombre )
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dietalist_activity);                                 //nombre del Page + _activity (minuscula)
        ArrayList<Dieta> dietas = (ArrayList<Dieta>) getIntent().getSerializableExtra(EXTRA_OBJECT);       //Parametro del Page (nombre + tipo)

        //SI ES LA ACTIVIDAD INICIAL
        if (dietas == null) {    DietaManager.listAll(this);    }

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, DietaList_Fragment.createInstance(dietas))    //nombre del Page + _Fragment //Parametro del Page (nombre )
                    .commit();
        }
    }

    /********************* Menu de la actividad inicial ******************************************************************/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case R.id.test_notification:
                //UtilityService.triggerWearTest(this, false);
                //showDebugDialog(R.string.action_test_notification,
                  //      R.string.action_test_notification_dialog);
                return true;
            case R.id.test_microapp:
                //U/tilityService.triggerWearTest(this, true);
                //showDebugDialog(R.string.action_test_microapp,
                 //       R.string.action_test_microapp_dialog);
                return true;
            case R.id.test_toggle_geofence:
                //boolean geofenceEnabled = Utils.getGeofenceEnabled(this);
                //Utils.storeGeofenceEnabled(this, !geofenceEnabled);
                Toast.makeText(this,
                        "Debug: Geofencing trigger disabled" , Toast.LENGTH_SHORT).show();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    /********************* Menu de la actividad inicial ******************************************************************/
}


text:
CKEDITOR.plugins.setLang( 'slideshow', 'pt', {
	toolbar	: 'SlideShow',
	dialogTitle : 'propriedades do SlideShow',
	fakeObject : 'SlideShow',
	imgList : 'Imagem',
	imgAdd : 'Adicione uma Imagem',
	imgTitle : 'Título',
	imgDelete : 'Deletar',
	imgEdit : 'Editar',
    validModif : 'salve as alteracoes',
	previewMode : 'Preview',
	imgDesc : 'Descrição curta',
	editSlideShow : 'Editar SlideShow',
	picturesList : "Lista de imagens :",
    insertSlideShow : 'Inserir Galeria',
	showThumbs : 'Mostrar thumbnails',
	showTitle : 'Mostrar título',
	showControls : "Mostrar Início / Fim",
	labelStart : "Início",
	labelStop : "Fim",
	arrowUp : "\u2191",
	arrowDown : "\u2193",
    displayTime : 'Aparecer por(Seg)',
    transitionTime : 'Transição (mSeg)',
	autoStart : 'AutoStart',
	pictHeight : 'Altura (px)',
	openOnClick : 'Abrir ao clicar',
	transition : 'Tipo de Transição',
	tr1 : 'Nenhum',
	tr2 : 'Redimensionar',
	tr3 : 'Slide Vertical',
	tr4 : 'Slide Horizontal',
	tr5 : 'Desaparecer'
});


text:
using System;

namespace GLSLSyntaxAST.Preprocessor
{
	//
	// The behaviors from the GLSL "#extension extension_name : behavior"
	//
	[Flags]
	public enum ExtensionBehavior : int
	{
		// use as initial state of an extension that is only partially implemented
		Missing = 0,
		Require,
		Enable,
		Warn,
		Disable,
		DisablePartial
	}
}


text:
interface GeneralActionType {
  type: ActionType;
  payload?: any;
}

type SetAction = {type: "set", payload: {x: number, y: number, value: boolean}};
type SizeAction = {type: "size", payload: number};
export type ActionType =
    "clear" /* reinit game of life cell*/
        | "next" /* calculate and render next generation*/
        | "initRandom" /* init cell with random life */
        | "initRegular" /* init cell with regular pattern */
        | "initPentomino" /* init cell wit pentominos for long lasting generations */
        | "set"
        | "size";
/* set life on position maxX,maxY to value (true or false) */

export type Action = GeneralActionType | SetAction | SizeAction;


text:
/* needed for theme editor subwidget menu pop up */
@import url("Menu.css");

.maqHidden {
	display: none;
}

.maqShown {
	visibility: visible !important;
}

.maqFocus {
	z-index: 900;
}

.flowDragOuter {
	opacity:.5;
	z-index:2000000;
	position:absolute;
	border:2px solid #6a94dc;
	pointer-events:none;
}
.flowDragInner {
	border:4px solid #d3e1ee;
	pointer-events:none;
}

.areaSelectDiv {
	position:absolute;
	border:1px dashed black;
	z-index:1000000;
}

.selectToolDragDiv {
	position:absolute;
	z-index:2000000;
	background-color: rgba(200,100,100,0.8);
}
.selectToolDragMove {
	cursor:move;
}
.selectToolDragCopy {
	cursor:copy;
}
.editFeedback {
	background-color: #AAA;
}

.editSubwidgetFocusFrame{
	border-style: dotted;
	border-color: red;
	border-width: 3px;
	z-index: 1000002;

}
.disableWidgetFocusFrame{
	z-index: 1002;
	opacity:0.75;
	background-color: white;

}

.enableWidgetFocusFrame{
	z-index: 1001;

}

.themeSubwidgetMenu{
	z-index: 1115;
	font-family:Verdana,Arial,Helvetica,sans-serif;
	font-style:normal;
	color:#131313;
	background-color: #fff;
	background-image:none;
}

.editCursor {
	display: block;
	position:absolute;
	border: 1px solid black;
	z-index:1000001;	/* Above focus, which is at z-index:100000 */
}

.editCursorBlink {
	visibility: hidden;
}

.editContextContainer FORM,
.editContextContainer .dijitContentPane,
.editContextContainer .dojoxScrollWindow {
	outline: 1px dotted #AAA;
}
.editContextContainer .dijitTabContainer .dijitContentPane {
	outline: 0px none #FFFFFF;
}

/* HTML widgets */
.stickyNote DIV.HtmlWidget,
.stickyNote FORM.HtmlWidget,
.stickyNote SPAN.HtmlWidget,
.stickyNote A.HtmlWidget,
.stickyNote TABLE.HtmlWidget,
.stickyNote TD.HtmlWidget,
.stickyNote TH.HtmlWidget,
.stickyNote AUDIO.HtmlWidget,
.stickyNote EMBED.HtmlWidget,
.stickyNote VIDEO.HtmlWidget,
.stickyNote IMG.HtmlWidget,
.richText DIV.HtmlWidget,
.richText FORM.HtmlWidget,
.richText SPAN.HtmlWidget,
.richText A.HtmlWidget,
.richText TABLE.HtmlWidget,
.richText TD.HtmlWidget,
.richText TH.HtmlWidget,
.richText AUDIO.HtmlWidget,
.richText EMBED.HtmlWidget,
.richText VIDEO.HtmlWidget,
.richText IMG.HtmlWidget
{
	outline:none;
}

DIV.HtmlWidget {
	min-width:1em;
	min-height:1em;
	outline: 1px dotted #AAA;
	outline-color:rgba(128,128,128,0.5);
}
FORM.HtmlWidget {
	min-width:1em;
	min-height:1em;
	outline: 1px dotted #AAA;
	outline-color:rgba(128,128,128,0.5);
}
SPAN.HtmlWidget {
	min-width:1em;
	min-height:1em;
	display:inline-block;
	outline: 1px dotted #AAA;
	outline-color:rgba(128,128,128,0.5);
}
A.HtmlWidget {
	min-width:1em;
	min-height:1em;
	display:inline-block;
	outline: 1px dotted #AAA;
	outline-color:rgba(128,128,128,0.5);
}
TABLE.HtmlWidget {
	outline: 1px dotted #AAA;
	outline-color:rgba(128,128,128,0.4);
}
TD.HtmlWidget {
	outline: 1px dotted #AAA;
	outline-color:rgba(128,128,128,0.4);
}
TH.HtmlWidget {
	outline: 1px dotted #AAA;
	outline-color:rgba(128,128,128,0.4);
}
AUDIO.HtmlWidget {
	min-width:1em;
	min-height:1em;
	outline: 1px dotted #AAA;
	outline-color:rgba(128,128,128,0.5);
}
EMBED.HtmlWidget {
	min-width:1em;
	min-height:1em;
	outline: 1px dotted #AAA;
	outline-color:rgba(128,128,128,0.5);
}
VIDEO.HtmlWidget {
	min-width:1em;
	min-height:1em;
	outline: 1px dotted #AAA;
	outline-color:rgba(128,128,128,0.5);
}
IMG.HtmlWidget {
	min-width:1em;
	min-height:1em;
	outline: 1px dotted #AAA;
	outline-color:rgba(128,128,128,0.5);
}

/* dojox.mobile widgets */

div.mblView,
div.mblContentPane,
div.mblPane,
div.mblContainer,
div.mblScrollablePane {
    min-width:1em;
    min-height:1em;
    outline: 1px dotted #AAA;
    outline-color:rgba(128,128,128,0.5);
    background-clip:content-box;
}
::-webkit-scrollbar {
	width: 0.6em;
	height: 0.8em;
}

::-webkit-scrollbar-thumb {
	background: slategray;
}

 ::-webkit-scrollbar-track {
	background: #b8c0c8;
}
body {
	border:1px solid black;
	margin: 0;
	-webkit-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	-o-user-select: none;
	user-select: none;
}

.dijitDialogUnderlayWrapper {
	display: none !important;
}
/* Overcome Firefox outline issue (#2295) */
.dijitButton .dijitOffScreen {
	display:none;
}


text:
c64::InstrInternalAbsoluteIndexed::InstrInternalAbsoluteIndexed(
    Instr instr, MachineInstruction machineInstr, Reg cpuReg)
  : InstrInternal(instr, machineInstr), cpuReg_{cpuReg}
{
}

void c64::InstrInternalAbsoluteIndexed::execFinalInterleaved()
{
  executeInstruction();
}

void c64::InstrInternalAbsoluteIndexed::doExecSingle()
{
  switch (cycles_)
  {
    case 0:
      // Fetch op-code
      return;
    case 1:
      // Fetch effective address (LSB)
      effectiveAddrLSB_ = cpu_->memory().peek(cpu_->pc());
      cpu_->incrementPC();
      return;
    case 2:
      // Fetch effective address (MSB)
      effectiveAddrMSB_ = cpu_->memory().peek(cpu_->pc());
      cpu_->incrementPC();
      return;
    case 3: {
      cpu_->clc();
      c64_size_t balPlusIndex{static_cast<c64_size_t>(effectiveAddrLSB_ + cpu_->getReg(cpuReg_))};
      effectiveAddrLSB_ += cpu_->getReg(cpuReg_);
      if (balPlusIndex > 0xff)
      {
        // page boundary crossed
        cpu_->sec();
      }
      else
      {
        byte data{cpu_->memory().peek(
            static_cast<c64_size_t>((effectiveAddrMSB_ << 0x08) + effectiveAddrLSB_))};
        cpu_->memory().setImmediate(data);
        end_ = true;  // skip T4 (page boundary not crossed)
      }
      return;
    }
    case 4:
      bool carry = (cpu_->sr() & CPUFlags::carry) != 0;
      effectiveAddrMSB_ += (carry ? 1 : 0);

      // overwrite result from T3
      byte data{cpu_->memory().peek(
          static_cast<c64_size_t>((effectiveAddrMSB_ << 0x08) + effectiveAddrLSB_))};
      cpu_->memory().setImmediate(data);
      end_ = true;
      return;
  }
}

void c64::InstrInternalAbsoluteIndexed::executeInstruction()
{
  ((*cpu_).*machineInstr_)(memmap::immediateAddr);
}

void c64::InstrInternalAbsoluteIndexed::doReset()
{
  effectiveAddrLSB_ = {};
  effectiveAddrMSB_ = {};
}

unsigned short c64::InstrInternalAbsoluteIndexed::length() const noexcept
{
  return 3;
}
// ################################### Tests #################################

#include <doctest.h>

TEST_CASE("InstrInternalAbsoluteIndexed")
{
  c64::Memory memory;
  c64::CPU cpu{memory};
  c64::InstrInternalAbsoluteIndexed instr{c64::Instr::LDA, &c64::CPU::lda, c64::Reg::x};
  instr.reset(&cpu);

  DOCTEST_SUBCASE("Construction")
  {
    REQUIRE(instr.cycles() == 0);
    REQUIRE(!instr.end());
  }

  DOCTEST_SUBCASE("page_boundary_not_crossed")
  {
    memory.poke(0xc000, 0xbd);
    memory.poke(0xc001, 0x02);
    memory.poke(0xc002, 0xe0);
    cpu.a(0xaa);
    cpu.x(0x03);
    memory.poke(0xe005, 0xee);
    cpu.pc(0xc001);

    instr.execSingle();
    instr.execSingle();
    instr.execSingle();
    REQUIRE(!instr.end());
    instr.execSingle();
    REQUIRE(instr.end());

    instr.execFinalInterleaved();
    REQUIRE(cpu.pc() == 0xc003);
    REQUIRE(instr.cycles() == 4);
    REQUIRE(cpu.a() == 0xee);
    REQUIRE((cpu.sr() & c64::CPUFlags::carry) == 0);
  }

  DOCTEST_SUBCASE("pageBoundaryCrossed")
  {
    memory.poke(0xc000, 0xbd);
    memory.poke(0xc001, 0xff);
    memory.poke(0xc002, 0xe0);
    cpu.a(0xaa);
    cpu.x(0x03);
    memory.poke(0xe102, 0xee);
    cpu.pc(0xc001);

    instr.execSingle();
    instr.execSingle();
    instr.execSingle();
    instr.execSingle();
    REQUIRE(!instr.end());
    instr.execSingle();
    REQUIRE(instr.end());

    instr.execFinalInterleaved();
    REQUIRE(cpu.pc() == 0xc003);
    REQUIRE(instr.cycles() == 5);
    REQUIRE(cpu.a() == 0xee);
    REQUIRE((cpu.sr() & c64::CPUFlags::carry) == 1);
  }
}


text:
#pragma once
#include <aws/chime/Chime_EXPORTS.h>
#include <aws/chime/ChimeRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Chime
{
namespace Model
{

  /**
   */
  class AWS_CHIME_API DescribeAppInstanceUserRequest : public ChimeRequest
  {
  public:
    DescribeAppInstanceUserRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DescribeAppInstanceUser"; }

    Aws::String SerializePayload() const override;

    /**
     *
The ARN of the AppInstanceUser.

     */
    inline const Aws::String& GetAppInstanceUserArn() const{ return m_appInstanceUserArn; }

    /**
     *
The ARN of the AppInstanceUser.

     */
    inline bool AppInstanceUserArnHasBeenSet() const { return m_appInstanceUserArnHasBeenSet; }

    /**
     *
The ARN of the AppInstanceUser.

     */
    inline void SetAppInstanceUserArn(const Aws::String& value) { m_appInstanceUserArnHasBeenSet = true; m_appInstanceUserArn = value; }

    /**
     *
The ARN of the AppInstanceUser.

     */
    inline void SetAppInstanceUserArn(Aws::String&& value) { m_appInstanceUserArnHasBeenSet = true; m_appInstanceUserArn = std::move(value); }

    /**
     *
The ARN of the AppInstanceUser.

     */
    inline void SetAppInstanceUserArn(const char* value) { m_appInstanceUserArnHasBeenSet = true; m_appInstanceUserArn.assign(value); }

    /**
     *
The ARN of the AppInstanceUser.

     */
    inline DescribeAppInstanceUserRequest& WithAppInstanceUserArn(const Aws::String& value) { SetAppInstanceUserArn(value); return *this;}

    /**
     *
The ARN of the AppInstanceUser.

     */
    inline DescribeAppInstanceUserRequest& WithAppInstanceUserArn(Aws::String&& value) { SetAppInstanceUserArn(std::move(value)); return *this;}

    /**
     *
The ARN of the AppInstanceUser.

     */
    inline DescribeAppInstanceUserRequest& WithAppInstanceUserArn(const char* value) { SetAppInstanceUserArn(value); return *this;}

  private:

    Aws::String m_appInstanceUserArn;
    bool m_appInstanceUserArnHasBeenSet = false;
  };

} // namespace Model
} // namespace Chime
} // namespace Aws


text:
'''
 The MIT License(MIT)

 Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
'''

import json
from abc import ABC

class Export:
    def get_completion_webhook(self):
        '''
            Scan id to export.
        '''
        return self.completionWebhook

    def set_completion_webhook(self, value):
        '''
            Scan id to export.

            Parameters:
                value: String (uri).
        '''

        assert value

        self.completionWebhook = value

    def get_max_retries(self):
        '''
            How many retries to send before giving up.
            Using high value (12) may lead to a longer time until the completionWebhook being executed.
            A low value (1) may lead to errors while your service is temporary having problems.
        '''
        return self.maxRetries

    def set_max_retries(self, value):
        '''
            How many retries to send before giving up.
            Using high value (12) may lead to a longer time until the completionWebhook being executed.
            A low value (1) may lead to errors while your service is temporary having problems.

            Parameters:
                value: String (uri).
        '''

        assert value and value >= 1 and value <= 12

        self.maxRetries = value

    def get_developer_payload(self):
        '''
            Add a custom developer payload that will then be provided on the Export-Completed webhook.
        '''
        return self.developerPayload

    def set_developer_payload(self, value):
        '''
            Add a custom developer payload that will then be provided on the Export-Completed webhook.

            Parameters:
                value: String (uri).
        '''

        assert value and len(value) <= 512

        self.developerPayload = value

    def get_results(self):
        '''
            An list of results to be exported.
        '''
        return self.results

    def set_results(self, value):
        '''
            An list of results to be exported.

            Parameters:
                value: `ExportResult` list.
        '''

        assert value

        self.results = value

    def get_pdf_report(self):
        '''
            Download the PDF report. Allowed only when `properties.pdf.create` was set to true on the scan submittion.
        '''
        return self.pdfReport

    def set_pdf_report(self, value):
        '''
            Download the PDF report. Allowed only when `properties.pdf.create` was set to true on the scan submittion.

            Parameters:
                value: `ExportPdf`.
        '''

        assert value

        self.pdfReport = value

    def get_crawled_version(self):
        '''
            Download the crawled version of the submitted text.
        '''
        return self.crawledVersion

    def set_crawled_version(self, value):
        '''
            Download the crawled version of the submitted text.

            Parameters:
                value: `ExportCrawledVersion`.
        '''

        assert value

        self.crawledVersion = value

    def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__,
                          sort_keys=True, indent=4)

class ExportItem(ABC):
    def get_endpoint(self):
        '''
            The HTTP url to upload the data.
        '''
        return self.endpoint

    def set_endpoint(self, value):
        '''
            The HTTP url to upload the data.

            Parameters:
                value: String.
        '''

        assert value

        self.endpoint = value

    def get_verb(self):
        '''
            The HTTP verb (also called "HTTP Methods") to upload the data to your specified endpoint.
        '''
        return self.verb

    def set_verb(self, value):
        '''
            The HTTP verb (also called "HTTP Methods") to upload the data to your specified endpoint.

            Parameters:
                value: String.
        '''

        assert value

        self.verb = value

    def get_headers(self):
        '''
            List of headers to be submitted with the upload request. You may use this field to provide additional request headers, such as "Authorization" header.
        '''
        return self.headers

    def set_headers(self, value):
        '''
            List of headers to be submitted with the upload request. You may use this field to provide additional request headers, such as "Authorization" header.

            Parameters:
                value: List of list of strings.

            Example:
                [["header-key1", "header-value1"], ["header-key2", "header-value2"]]
        '''

        assert value

        self.headers = value

class ExportResult(ExportItem):
    def get_id(self):
        '''
            Result identification to be downloaded. You get these identifications from the completed webhook.
        '''
        return self.id

    def set_id(self, value):
        '''
            Result identification to be downloaded. You get these identifications from the completed webhook.

            Parameters:
                value: String.
        '''

        assert value

        self.id = value

class ExportPdf(ExportItem):
    def __init__(self):
        pass

class ExportCrawledVersion(ExportItem):
    def __init__(self):
        pass


text:
package falgout.utils.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;

/**
 * This class provides methods for finding a method or constructor in a given
 * class. You can either provide the actual arguments or the classes of the
 * actual arguments when using the methods in this class, but make sure to
 * provide the classes of the actual arguments in a {@code Class<?>[]} instead
 * of a {@code Object[]} or else the wrong overloaded method will be called.

 *

 * The methods in this class may throw one of two exceptions:
 *

 *
{@link AmbiguousDeclarationException}

 *

 *
If more than one method is equally specific for the given name and
 * arguments.

 *

 *
{@link NoSuchMethodException}

 *

 *
If there is no method for the given name and arguments

 *

 *

 *
 * You can avoid the first by using a pluralized version of the method. I.E.
 * {@link #getMethods(Class, String, Object...) getMethods} instead of
 * {@link #getMethod(Class, String, Object...) getMethod}.
 *
 * @author jeffrey
 *
 */
public abstract class MethodLocator {
    public Method getMethod(Class<?> clazz, String name, Object... args) throws AmbiguousDeclarationException,
            NoSuchMethodException {
        return getMethod(clazz, name, ReflectionUtilities.getClasses(args));
    }

    public Method getMethod(Class<?> clazz, String name, Class<?>... args) throws AmbiguousDeclarationException,
            NoSuchMethodException {
        return getMethod(Arrays.asList(clazz.getMethods()), clazz, name, args);
    }

    public Set<Method> getMethods(Class<?> clazz, String name, Object... args) throws NoSuchMethodException {
        return getMethods(clazz, name, ReflectionUtilities.getClasses(args));
    }

    public Set<Method> getMethods(Class<?> clazz, String name, Class<?>... args) throws NoSuchMethodException {
        return getMethods(Arrays.asList(clazz.getMethods()), clazz, name, args);
    }

    public Method getDeclaredMethod(Class<?> clazz, String name, Object... args) throws AmbiguousDeclarationException,
            NoSuchMethodException {
        return getDeclaredMethod(clazz, name, ReflectionUtilities.getClasses(args));
    }

    public Method getDeclaredMethod(Class<?> clazz, String name, Class<?>... args)
            throws AmbiguousDeclarationException, NoSuchMethodException {
        return getMethod(Arrays.asList(clazz.getDeclaredMethods()), clazz, name, args);
    }

    public Set<Method> getDeclaredMethods(Class<?> clazz, String name, Object... args) throws NoSuchMethodException {
        return getDeclaredMethods(clazz, name, ReflectionUtilities.getClasses(args));
    }

    public Set<Method> getDeclaredMethods(Class<?> clazz, String name, Class<?>... args) throws NoSuchMethodException {
        return getMethods(Arrays.asList(clazz.getDeclaredMethods()), clazz, name, args);
    }

    protected abstract Method getMethod(Collection<? extends Method> methods, Class<?> clazz, String name,
            Class<?>... args) throws AmbiguousDeclarationException, NoSuchMethodException;

    protected abstract Set<Method> getMethods(Collection<? extends Method> methods, Class<?> clazz, String name,
            Class<?>... args) throws NoSuchMethodException;

    public <T> Constructor<T> getConstructor(Class<T> clazz, Object... args) throws AmbiguousDeclarationException,
            NoSuchMethodException {
        return getConstructor(clazz, ReflectionUtilities.getClasses(args));
    }

    public <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>... args) throws AmbiguousDeclarationException,
            NoSuchMethodException {
        return getConstructor(ReflectionUtilities.getConstructors(clazz), clazz, args);
    }

    public <T> Set<Constructor<T>> getConstructors(Class<T> clazz, Object... args) throws NoSuchMethodException {
        return getConstructors(clazz, ReflectionUtilities.getClasses(args));
    }

    public <T> Set<Constructor<T>> getConstructors(Class<T> clazz, Class<?>... args) throws NoSuchMethodException {
        return getConstructors(ReflectionUtilities.getConstructors(clazz), clazz, args);
    }

    public <T> Constructor<T> getDeclaredConstructor(Class<T> clazz, Object... args)
            throws AmbiguousDeclarationException, NoSuchMethodException {
        return getDeclaredConstructor(clazz, ReflectionUtilities.getClasses(args));
    }

    public <T> Constructor<T> getDeclaredConstructor(Class<T> clazz, Class<?>... args)
            throws AmbiguousDeclarationException, NoSuchMethodException {
        return getConstructor(ReflectionUtilities.getDeclaredConstructors(clazz), clazz, args);
    }

    public <T> Set<Constructor<T>> getDeclaredConstructors(Class<T> clazz, Object... args) throws NoSuchMethodException {
        return getDeclaredConstructors(clazz, ReflectionUtilities.getClasses(args));
    }

    public <T> Set<Constructor<T>> getDeclaredConstructors(Class<T> clazz, Class<?>... args)
            throws NoSuchMethodException {
        return getConstructors(ReflectionUtilities.getDeclaredConstructors(clazz), clazz, args);
    }

    protected abstract <T> Constructor<T> getConstructor(Collection<? extends Constructor<T>> constructors,
            Class<T> clazz, Class<?>... args) throws AmbiguousDeclarationException, NoSuchMethodException;

    protected abstract <T> Set<Constructor<T>> getConstructors(Collection<? extends Constructor<T>> constructors,
            Class<T> clazz, Class<?>... args) throws NoSuchMethodException;
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using TableDependency.SqlClient.Base.Enums;
using TableDependency.SqlClient.Base.EventArgs;

namespace TableDependency.SqlClient.Test
{
    [TestClass]
    public class MultiDmlOperationsOrderTest : Base.SqlTableDependencyBaseTest
    {
        private class MultiDmlOperationsOrderTestModel
        {
            public int Id { get; set; }
            public DateTime When { get; set; }
            public string Letter { get; set; }

            [NotMapped]
            public ChangeType ChangeType { get; set; }
        }

        private static readonly string TableName = typeof(MultiDmlOperationsOrderTestModel).Name;
        private static IList<MultiDmlOperationsOrderTestModel> _checkValues;

        [ClassInitialize]
        public static void ClassInitialize(TestContext testContext)
        {
            using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
            {
                sqlConnection.Open();
                using (var sqlCommand = sqlConnection.CreateCommand())
                {
                    sqlCommand.CommandText = $"IF OBJECT_ID('{TableName}', 'U') IS NOT NULL DROP TABLE [{TableName}];";
                    sqlCommand.ExecuteNonQuery();

                    sqlCommand.CommandText = $"CREATE TABLE [{TableName}]([Id] [int] NULL, [Letter] NVARCHAR(50), [When] DATETIME NOT NULL)";
                    sqlCommand.ExecuteNonQuery();
                }
            }
        }

        [TestInitialize]
        public void TestInitialize()
        {
            _checkValues =  new List<MultiDmlOperationsOrderTestModel>();

            using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
            {
                sqlConnection.Open();
                using (var sqlCommand = sqlConnection.CreateCommand())
                {
                    sqlCommand.CommandText = $"DELETE FROM [{TableName}]";
                    sqlCommand.ExecuteNonQuery();
                }
            }
        }

        [ClassCleanup]
        public static void ClassCleanup()
        {
            using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
            {
                sqlConnection.Open();
                using (var sqlCommand = sqlConnection.CreateCommand())
                {
                    sqlCommand.CommandText = $"IF OBJECT_ID('{TableName}', 'U') IS NOT NULL DROP TABLE [{TableName}];";
                    sqlCommand.ExecuteNonQuery();
                }
            }
        }

        [TestCategory("SqlServer")]
        [TestMethod]
        public void MultiInsertTest1()
        {
            SqlTableDependency<MultiDmlOperationsOrderTestModel> tableDependency = null;

            try
            {
                tableDependency = new SqlTableDependency<MultiDmlOperationsOrderTestModel>(ConnectionStringForTestUser, tableName: TableName);
                tableDependency.OnChanged += this.TableDependency_Changed;
                tableDependency.OnError += this.TableDependency_OnError;
                tableDependency.Start();

                var t = new Task(MultiInsertOperation1);
                t.Start();
                Thread.Sleep(1000 * 15 * 1);
            }
            finally
            {
                tableDependency?.Dispose();
            }

            Assert.AreEqual(3, _checkValues.Count);
            Assert.IsTrue(_checkValues[0].Id == 100);
            Assert.IsTrue(_checkValues[1].Id == 200);
            Assert.IsTrue(_checkValues[2].Id == 300);
        }

        [TestCategory("SqlServer")]
        [TestMethod]
        public void MultiInsertTest2()
        {
            SqlTableDependency<MultiDmlOperationsOrderTestModel> tableDependency = null;

            try
            {
                tableDependency = new SqlTableDependency<MultiDmlOperationsOrderTestModel>(ConnectionStringForTestUser, tableName: TableName);
                tableDependency.OnChanged += this.TableDependency_Changed;
                tableDependency.OnError += this.TableDependency_OnError;
                tableDependency.Start();

                var t = new Task(MultiInsertOperation2);
                t.Start();
                Thread.Sleep(1000 * 15 * 1);
            }
            finally
            {
                tableDependency?.Dispose();
            }

            Assert.AreEqual(3, _checkValues.Count);
            Assert.IsTrue(_checkValues[0].Letter == "a");
            Assert.IsTrue(_checkValues[1].Letter == "b");
            Assert.IsTrue(_checkValues[2].Letter == "c");
        }

        private void TableDependency_OnError(object sender, ErrorEventArgs e)
        {
            throw e.Error;
        }

        private void TableDependency_Changed(object sender, RecordChangedEventArgs<MultiDmlOperationsOrderTestModel> e)
        {
            switch (e.ChangeType)
            {
                case ChangeType.Insert:
                    _checkValues.Add(new MultiDmlOperationsOrderTestModel { Id = e.Entity.Id, When = e.Entity.When, Letter = e.Entity.Letter });
                    break;

                case ChangeType.Update:
                    throw new Exception("Update non expected");

                case ChangeType.Delete:
                    throw new Exception("Delete non expected");
            }
        }

        private static void MultiInsertOperation1()
        {
            using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
            {
                var sql = $"INSERT INTO [{TableName}] ([Id], [When]) VALUES" +
                          "(100, GETDATE())," +
                          "(200, GETDATE())," +
                          "(300, GETDATE())";

                sqlConnection.Open();
                using (var sqlCommand = sqlConnection.CreateCommand())
                {
                    sqlCommand.CommandText = sql;
                    sqlCommand.ExecuteNonQuery();
                }
            }

            Thread.Sleep(500);
        }

        private static void MultiInsertOperation2()
        {
            using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
            {
                var sql = $"INSERT INTO [{TableName}] ([When], [Letter]) VALUES" +
                          "(GETDATE(), 'a')," +
                          "(GETDATE(), 'b')," +
                          "(GETDATE(), 'c')";

                sqlConnection.Open();
                using (var sqlCommand = sqlConnection.CreateCommand())
                {
                    sqlCommand.CommandText = sql;
                    sqlCommand.ExecuteNonQuery();
                }
            }

            Thread.Sleep(500);
        }
    }
}


text:
name 		    'joindomain'
maintainer       'Daniel Washko'
maintainer_email 'dwashko@gmti.gannett.com'
license          'Apache License'
description      'joins server to domain'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.1.0'

supports 'centos'
supports 'redhat'


text:
'use strict';

const _ = require('lodash');

angular.module('27th.acmi.filter', [
        'ngTagsInput',
        '27th.acmi.services.acmi',
        '27th.common.services.pilot',
        '27th.acmi.services.tag',
        '27th.common.services.theater'
    ])
    .controller('AcmiFilterController', class {
        constructor($rootScope, $q, acmiService, pilotService, tagService, theaterService) {
            this.$rootScope = $rootScope;
            this.pilotService = pilotService;
            this.tagService = tagService;
            this.title = '';
            this.tags = [];
            this.pilots = [];
            this.popularTags = [];
            this.hasVideo = false;
            this.theater = null;
            this.theaters = [
                {
                    name: '<Any Theater>',
                    value: null
                }
            ];
            this.missionType = null;
            this.missionTypes = [
                {
                    name: '<Any Type>',
                    value: null
                }]
                .concat(acmiService.getMissionTypes());

            const debouncedApply = () => {
                this.$rootScope.$emit('acmi.filterChanged', {
                    title: this.title,
                    theater: this.theater,
                    missionType: this.missionType,
                    tags: _.map(this.tags, t => t.text),
                    pilots: _.map(this.pilots, p => p.text),
                    hasVideo: this.hasVideo
                });
            };
            this.applyFilters = _.debounce(debouncedApply, 500);

            $q.all([
                    tagService.get(null, 10),
                    theaterService.get()
                ])
                .then(data => {
                    this.popularTags = data[0];
                    this.theaters = this.theaters.concat(
                        _.map(data[1], t => {
                            return {
                                name: t.name,
                                value: t.name
                            };
                        }));
                });
        }

        loadPilots(query) {
            return this.pilotService.get(query);
        }

        loadTags(query) {
            return this.tagService.get(query);
        }
    });


text:
package com.fionapet.business.consumer;

import com.alibaba.fastjson.JSON;
import com.fionapet.business.entity.ItemSingleDetail;
import com.fionapet.business.service.ItemSingleDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
* Created by tom on 2016-07-25 09:32:32.
 */
public class ItemSingleDetailDemoAction {
    private static final Logger LOGGER = LoggerFactory.getLogger(ItemSingleDetailDemoAction.class);
    private ItemSingleDetailService itemSingleDetailService;

    public ItemSingleDetailService getItemSingleDetailService() {
        return itemSingleDetailService;
    }

    public void setItemSingleDetailService(ItemSingleDetailService itemSingleDetailService) {
        this.itemSingleDetailService = itemSingleDetailService;
    }

    public void start() throws Exception {
        List<ItemSingleDetail> itemSingleDetails = itemSingleDetailService.listAll();
        assert(itemSingleDetails != null);
        assert(itemSingleDetails.size() == 1);

        LOGGER.info("list all:{}", JSON.toJSON(itemSingleDetails));
    }
}


text:
package processing.pokemon.creation;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.simpleframework.xml.*;
import org.simpleframework.xml.core.Persister;

import logger.Logger;
import processing.pokemon.moves.Learnset;
import processing.pokemon.moves.Move;
import processing.pokemon.moves.MoveType;
import utils.DirectoryUtils;

@Root
public class PokemonObject {

	private static long lastUUID = -1;
	private static Serializer serializer = new Persister();

	@Attribute
	private long pokemonUUID;

	@Attribute
	private int pokemonID;

	@ElementMap(entry="date", key="name", attribute=true, inline=false, required = false)
	private Map<String, Long> trainerList = new HashMap<String, Long>();

	@Element
	private int XP;

	@Element
	private int HP;

	@ElementArray
	private int[] EVs;

	@ElementArray
	private int[] IVs;

	@Element
	private int ability;

	@Element
	private int moveID[];

	@Element
	private int movePP[];

	@Element
	private int movePPUps[];

	@Element(required=false)
	private String Nickname = "";

	@Element
	private boolean isFemale;

	public synchronized MoveType[] getTypes() { return BaseValues.getBaseValues(pokemonID).types; }

	public synchronized boolean hasType(MoveType moveType) {

		for (MoveType type : BaseValues.getBaseValues(pokemonID).types) {
			if (moveType == type) { return true; }
		}
		return false;

	}

	public void useMove(int moveIndex) {
		moveIndex = Math.min(Math.max(0, moveIndex), 3);
		movePP[moveIndex]--;
		savePokemon(this);
	}

	public int getLevel() { return Math.max((int) Math.pow(this.XP, (1.0f/3.0f)), 1); }
	public long getID() { return pokemonUUID; }

	public int getBaseHP() {
		int baseHP = (2 * BaseValues.getBaseValues(pokemonID).baseStats[0]) + this.IVs[0] + (this.EVs[0] / 4);
		baseHP = (baseHP * this.getLevel()) / 100;
		return baseHP + this.getLevel() + 10;
	}

	public void modifyHP(int modify) {
		this.HP = Math.max(0, Math.min(this.getBaseHP(), this.HP + modify));
		savePokemon(this);
	}

	public int[] getMoves() { return moveID; }
	public int[] getMovesPP() { return movePP; }
	public String getName() { return BaseValues.getBaseValues(this.pokemonID).name(); }
	public String getNickname() {	return this.Nickname;}
	public int getHP() { 	return this.HP;}
	public int getAtk() { 	return this.getStat(1);}
	public int getDef() { 	return this.getStat(2);}
	public int getSPAtk() { return this.getStat(3);}
	public int getSPDef() { return this.getStat(4);}
	public int getSpd() { 	return this.getStat(5);}
	private int getStat(int statValue) {

		int stat = (2 * BaseValues.getBaseValues(pokemonID).baseStats[statValue]) + this.IVs[statValue] + (this.EVs[statValue] / 4);
		stat = (stat * this.getLevel()) / 100;
		return stat + 5;
	}
 	public static synchronized PokemonObject getPokemon(long UUID) {
		System.out.println(UUID);
		File pokefile = getFile(UUID);

		try {
			PokemonObject p = pokefile.exists() ? serializer.read(PokemonObject.class, pokefile) : null;
			System.out.println(p.pokemonID);
			return p;
		} catch (Exception e1) {
			Logger.STACK("Error retrieving pokemon - " + UUID, e1);
		}

		return null;

	}
	private static synchronized File getFile(long UUID) {

		DirectoryUtils.createDirectories("pokemon/pokemon");

		String filename = "pokemon/pokemon/" + UUID + ".xml";
		return new File(filename);

	}
	private static synchronized void savePokemon(PokemonObject p) {

		File pokefile = getFile(p.pokemonUUID);
		try {
			serializer.write(p, pokefile);
		} catch (Exception e) {
			Logger.STACK("Error writing pokemon - " + p.pokemonUUID, e);
		}

	}
	public PokemonObject() {}
	private PokemonObject(int ID, int XP) {
		this.pokemonUUID = getUUID();
		this.pokemonID = ID;
		this.XP = XP;

		this.IVs = new int[6];
		this.EVs = new int[6];
		this.HP = this.getBaseHP();
		this.ability = (int) (Math.random() * 2);

		//POPULATE MOVEIDS MOVEPPS AND PPUPS
		this.moveID = new int[]{0,0,0,0};
		this.movePP = new int[]{0,0,0,0};
		this.movePPUps = new int[]{0,0,0,0};

		Map<Move, Integer> moveset = Learnset.getLearnset(BaseValues.getBaseValues(ID));

		Iterator<Map.Entry<Move, Integer>> iter = moveset.entrySet().iterator();
		while (iter.hasNext()) {
		    Map.Entry<Move, Integer> entry = iter.next();
		    if (entry.getValue() > this.getLevel()) iter.remove();
		}

		List<Move> movelist = new ArrayList<Move>(moveset.keySet());
		for (int i = 0; i < 4 && i < movelist.size(); i++) {
			moveID[i] = movelist.get(movelist.size() - (i + 1)).ID;
			movePP[i] = movelist.get(movelist.size() - (i + 1)).basePP;
		}
		for (int i = 0; i < 6; i++) {
			this.IVs[i] = (int) (Math.random() * 32);
			this.EVs[i] = 0;
		}

		this.isFemale = Math.random() * 100 > BaseValues.getBaseValues(ID).percentageMale;

	}

	private long getUUID() {
		long currentUUID = System.currentTimeMillis();
		if (lastUUID == currentUUID) {
			currentUUID++;
		}
		lastUUID = currentUUID;
		return currentUUID;
	}

	public static synchronized PokemonObject generatePokemon(int generatorID, int pokemonID) {
		PokemonObject poke = null;
		if (generatorID == 47) {
			poke = new PokemonObject(1,(int) (Math.random() * 10000));
		} else if (generatorID == 1) {
			poke = new PokemonObject(pokemonID, 0);
		}
		PokemonObject.savePokemon(poke);
		return poke;
	}

	@Override
	public String toString() {
		return BaseValues.getBaseValues(this.pokemonID).name() + " (Level " + this.getLevel() + ")";
	}

}


text:
using Xamarin.Forms;
using System;

using Esri.ArcGISRuntime.Mapping;

namespace sample
{
    public partial class samplePage : ContentPage
    {

        // ArcGIS Online のアイテム URL
        private string _mapstyler1Url = "https://www.arcgis.com/home/item.html?id=53198d7dc1ac458086a7da43f409260f";
        private string _mapstyler2Url = "https://www.arcgis.com/home/item.html?id=4f8e8d131bbd488b822d258a8218cfae";
        private string _mapstyler3Url = "https://www.arcgis.com/home/item.html?id=1d7cb019befc43ed86f6c7631d9315dd";
        private string _mapstyler4Url = "https://www.arcgis.com/home/item.html?id=02224acbcbfc4e238fdb11b4f1a6924e";

        private string _vectorTiledLayerUrl;
        private ArcGISVectorTiledLayer _vectorTiledLayer;

        // ベクター タイルの選択肢を格納する配列
        private string[] _vectorLayerNames = new string[]
        {
            "VectorTiledLayer 1",
            "VectorTiledLayer 2",
            "VectorTiledLayer 3",
            "VectorTiledLayer 4"
        };

        public samplePage()
        {
            InitializeComponent();

            Initialize();
        }

        private void Initialize()
        {

            // URL を指定して新しい ArcGISVectorTiledLayer のインスタンスを作成
            _vectorTiledLayer = new ArcGISVectorTiledLayer(new Uri(_mapstyler1Url));

            // ベクター タイルを使用して新しいベースマップを作成
            Map myMap = new Map(new Basemap(_vectorTiledLayer));

            // 作成したマップを MapView に割り当て
            MyMapView.Map = myMap;

        }

        private async void OnChangeLayerButtonClicked(object sender, EventArgs e)
        {
            // ベクター タイルの選択画面を表示し、選択画面から任意のベクター タイルを選択
            var selectedLayer =
                await DisplayActionSheet("Select basemap", "Cancel", null, _vectorLayerNames);

            // キャンセルを選択した場合は何もしない
            if (selectedLayer == "Cancel") return;

            switch (selectedLayer)
            {
                case "VectorTiledLayer 1":
                    _vectorTiledLayerUrl = _mapstyler1Url;
                    break;

                case "VectorTiledLayer 2":
                    _vectorTiledLayerUrl = _mapstyler2Url;
                    break;

                case "VectorTiledLayer 3":
                    _vectorTiledLayerUrl = _mapstyler3Url;
                    break;

                case "VectorTiledLayer 4":
                    _vectorTiledLayerUrl = _mapstyler4Url;
                    break;

                default:
                    break;
            }

            // ユーザーが選択した URL で新しい ArcGISVectorTiledLayer のインスタンスを作成
            _vectorTiledLayer = new ArcGISVectorTiledLayer(new Uri(_vectorTiledLayerUrl));

            // 新しいベクター タイルを使用してベースマップを作成し、Mapview に割り当て
            MyMapView.Map.Basemap = new Basemap(_vectorTiledLayer);

        }

    }
}


text:
{% extends 'base.html' %}

{% load staticfiles %}

{% block content %}

    {% include "users/useraddress.html" with object_list=tweet_list %}

{% endblock %}


text:
#region MIT license
//
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#endregion
using System.Data;

#if MONO_STRICT
using System.Data.Linq;
#else
using DbLinq.Data.Linq;
#endif

namespace DbLinq.Oracle
{
#if !MONO_STRICT
    public
#endif
    class OracleDataContext : DataContext
    {
#if ORACLE_IS_REFERENCED
        public OracleDataContext(string connStr)
            : base(
#if ODP
            new Oracle.DataAccess.Client.OracleConnection(connStr)
#else
            new System.Data.OracleClient.OracleConnection(connStr)
#endif
            ,new OracleVendor())
        {
        }
#endif

        public OracleDataContext(IDbConnection conn)
#if MONO_STRICT
            : base(conn)
#else
            : base(conn, new OracleVendor())
#endif
        {
        }

    }
}


text:
package org.apache.ignite.internal.processors.cache;

import java.util.HashMap;
import java.util.Map;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.lang.IgnitePredicate;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;

import static org.apache.ignite.cache.CacheMode.REPLICATED;
import static org.apache.ignite.cache.CacheRebalanceMode.SYNC;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;

/**
 *
 */
public class IgniteDynamicCacheFilterTest extends GridCommonAbstractTest {
    /** */
    private static final String ATTR_NAME = "cacheAttr";

    /** */
    private String attrVal;

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);

        ccfg.setWriteSynchronizationMode(FULL_SYNC);
        ccfg.setCacheMode(REPLICATED);
        ccfg.setRebalanceMode(SYNC);

        ccfg.setNodeFilter(new TestNodeFilter("A"));
        ccfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);

        if (attrVal != null) {
            Map<String, Object> attrs = new HashMap<>();

            attrs.put(ATTR_NAME, attrVal);

            cfg.setUserAttributes(attrs);
        }

        cfg.setCacheConfiguration(ccfg);

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        super.afterTest();

        stopAllGrids();
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testCofiguredCacheFilter() throws Exception {
        attrVal = "A";

        Ignite ignite0 = startGrid(0);

        IgniteCache<Integer, Integer> cache0 = ignite0.cache(DEFAULT_CACHE_NAME);

        assertNotNull(cache0);

        cache0.put(1, 1);

        attrVal = null;

        Ignite ignite1 = startGrid(1);

        IgniteCache<Integer, Integer> cache1 = ignite1.cache(DEFAULT_CACHE_NAME);

        assertNotNull(cache1);

        attrVal = "B";

        Ignite ignite2 = startGrid(2);

        IgniteCache<Integer, Integer> cache2 = ignite2.cache(DEFAULT_CACHE_NAME);

        assertNotNull(cache2);

        attrVal = "A";

        Ignite ignite3 = startGrid(3);

        IgniteCache<Integer, Integer> cache3 = ignite3.cache(DEFAULT_CACHE_NAME);

        assertNotNull(cache3);

        assertNotNull(cache0.localPeek(1));
        assertNotNull(cache3.localPeek(1));

        assertNull(cache1.localPeek(1));
        assertNull(cache2.localPeek(1));
    }

    /**
     *
     */
    private static class TestNodeFilter implements IgnitePredicate<ClusterNode> {
        /** */
        private String val;

        /**
         * @param val Attribute value.
         */
        public TestNodeFilter(String val) {
            assert val != null;

            this.val = val;
        }

        /** {@inheritDoc} */
        @Override public boolean apply(ClusterNode node) {
            return val.equals(node.attribute(ATTR_NAME));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEngine;

namespace UnityTest
{
	public class MemberResolver
	{
		private object callingObjectRef;
		private MemberInfo[] callstack;
		private GameObject gameObject;
		private string path;

		public MemberResolver (GameObject gameObject, string path)
		{
			path = path.Trim ();
			ValidatePath (path);

			this.gameObject = gameObject;
			this.path = path.Trim ();
		}

		public object GetValue (bool useCache)
		{
			if (useCache && callingObjectRef!=null)
			{
				object val = callingObjectRef;
				for (int i = 0; i < callstack.Length;i++)
					val = GetValueFromMember (val, callstack[i]);
				return val;
			}

			object result = GetBaseObject ();
			var fullCallStack = GetCallstack ();

			callingObjectRef = result;
			var tempCallstack = new List<MemberInfo> ();
			for (int i = 0; i < fullCallStack.Length; i++ )
			{
				var member = fullCallStack[i];
				result = GetValueFromMember (result, member);
				tempCallstack.Add (member);
				if(result==null) return null;
				if (!IsValueType (result.GetType ()))
				{
					tempCallstack.Clear ();
					callingObjectRef = result;
				}
			}
			callstack = tempCallstack.ToArray ();
			return result;
		}

		public Type GetMemberType ()
		{
			var callstack = GetCallstack ();
			if (callstack.Length == 0) return GetBaseObject().GetType();

			var member = callstack[callstack.Length - 1];
			if (member is FieldInfo)
				return (member as FieldInfo).FieldType;
			if (member is MethodInfo)
				return (member as MethodInfo).ReturnType;
			return null;
		}

		#region Static wrappers
		public static bool TryGetMemberType ( GameObject gameObject, string path, out Type value )
		{
			try
			{
				var mr = new MemberResolver (gameObject, path);
				value = mr.GetMemberType ();
				return true;
			}
			catch (InvalidPathException)
			{
				value = null;
				return false;
			}
		}

		public static bool TryGetValue ( GameObject gameObject, string path, out object value )
		{
			try
			{
				var mr = new MemberResolver (gameObject, path);
				value = mr.GetValue (false);
				return true;
			}
			catch (InvalidPathException)
			{
				value = null;
				return false;
			}
		}
		#endregion

		private object GetValueFromMember (object obj, MemberInfo memberInfo)
		{
			if (memberInfo is FieldInfo)
				return (memberInfo as FieldInfo).GetValue (obj);
			if (memberInfo is MethodInfo)
				return (memberInfo as MethodInfo).Invoke (obj, null);
			throw new InvalidPathException (memberInfo.Name);
		}

		private object GetBaseObject ()
		{
			if (string.IsNullOrEmpty (path)) return gameObject;
			var firstElement = path.Split ('.')[0];
			var comp = gameObject.GetComponent (firstElement);
			if (comp != null)
				return comp;
			else
				return gameObject;
		}

		private MemberInfo[] GetCallstack ()
		{
			if (path == "") return new MemberInfo[0];
			var propsQueue = new Queue<string> (path.Split ('.'));

			Type type = GetBaseObject ().GetType ();
			if (type != typeof(GameObject))
				propsQueue.Dequeue ();

			PropertyInfo propertyTemp = null;
			FieldInfo fieldTemp = null;
			var list = new List<MemberInfo> ();
			while (propsQueue.Count != 0)
			{
				var nameToFind = propsQueue.Dequeue ();
				fieldTemp = GetField(type,nameToFind);
				if (fieldTemp != null)
				{
					type = fieldTemp.FieldType;
					list.Add (fieldTemp);
					continue;
				}
				propertyTemp = GetProperty(type,nameToFind);
				if (propertyTemp != null)
				{
					type = propertyTemp.PropertyType;
					var getMethod = GetGetMethod(propertyTemp);
					list.Add (getMethod);
					continue;
				}
				throw new InvalidPathException (nameToFind);
			}
			return list.ToArray ();
		}

		private Type GetTypeFromMember ( MemberInfo memberInfo )
		{
			if (memberInfo is FieldInfo)
				return (memberInfo as FieldInfo).FieldType;
			if (memberInfo is MethodInfo)
				return (memberInfo as MethodInfo).ReturnType;
			throw new InvalidPathException (memberInfo.Name);
		}

		private void ValidatePath (string path)
		{
			bool invalid = false;
			if (path.StartsWith (".") || path.EndsWith ("."))
				invalid = true;
			if (path.IndexOf ("..") >= 0)
				invalid = true;
			if (Regex.IsMatch (path, @"\s"))
				invalid = true;

			if (invalid)
				throw new InvalidPathException (path);
		}

		private static bool IsValueType(Type type)
		{
			#if !UNITY_METRO
			return type.IsValueType;
			#else
			return false;
			#endif
		}

		private static FieldInfo GetField (Type type, string fieldName)
		{
			#if !UNITY_METRO
			return type.GetField (fieldName);
			#else
			return null;
			#endif
		}

		private static PropertyInfo GetProperty (Type type, string propertyName)
		{
			#if !UNITY_METRO
			return type.GetProperty (propertyName);
			#else
			return null;
			#endif
		}

		private static MethodInfo GetGetMethod (PropertyInfo propertyInfo)
		{
			#if !UNITY_METRO
			return propertyInfo.GetGetMethod ();
			#else
			return null;
			#endif
		}

	}

}


text:
<?php

namespace spec\Judopay;

use Judopay\Configuration;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class ConfigurationSpec extends ObjectBehavior
{
    public function it_is_initializable()
    {
        $this->shouldHaveType('Judopay\Configuration');
    }

    public function it_sets_the_correct_endpoint_url()
    {
        $this->beConstructedWith(array('useProduction' => true));

        /** @var Configuration|ConfigurationSpec $this */
        $this->get('endpointUrl')->shouldBe('https://gw1.judopay.com/');
    }

    public function it_should_allow_a_custom_api_version_to_be_set()
    {
        $this->beConstructedWith(array('apiVersion' => '4.0.1'));

        /** @var Configuration|ConfigurationSpec $this */
        $this->get('apiVersion')->shouldBe('4.0.1');
    }
}


text:
"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
from sklearn.learning_curve import  validation_curve
from sklearn.datasets import load_digits
from sklearn.svm import SVC
import matplotlib.pyplot as plt
import numpy as np

digits = load_digits()
X = digits.data
y = digits.target
param_range = np.logspace(-6, -2.3, 5)
train_loss, test_loss = validation_curve(
        SVC(), X, y, param_name='gamma', param_range=param_range, cv=10,
        scoring='mean_squared_error')
train_loss_mean = -np.mean(train_loss, axis=1)
test_loss_mean = -np.mean(test_loss, axis=1)

plt.plot(param_range, train_loss_mean, 'o-', color="r",
             label="Training")
plt.plot(param_range, test_loss_mean, 'o-', color="g",
             label="Cross-validation")

plt.xlabel("gamma")
plt.ylabel("Loss")
plt.legend(loc="best")
plt.show()


text:
require "rails"

# Supply generator for Rails 3.0.x or if asset pipeline is not enabled
if ::Rails.version < "3.1" || !::Rails.application.config.assets.enabled
  module Keymaster
    module Generators
      class InstallGenerator < ::Rails::Generators::Base
        desc "This generator installs keymaster #{Keymaster::Rails::KEYMASTERJS_VERSION}"
        source_root File.expand_path("../../../../../vendor/assets", __FILE__)

        def copy_javascript
          say_status("copying", "Keymaster JS", :green)
          copy_file "javascripts/keymaster.js", "public/javascripts/keymaster.js"
        end
      end
    end
  end
else
  module Keymaster
    module Generators
      class InstallGenerator < ::Rails::Generators::Base
        desc "Just show instructions so people will know what to do when mistakenly using generator for Rails 3.1 apps"

        def do_nothing
          say_status("deprecated", "You are using Rails 3.1 with the asset pipeline enabled, so this generator is not needed.")
          say_status("", "The necessary files are already in your asset pipeline.")
          say_status("", "Just add `//= require keymaster` to your app/assets/javascripts/application.js")
          say_status("", "If you upgraded your app from Rails 3.0 and still have keymaster.js in your public assets folders, be sure to remove them.")
          say_status("", "If you do not want the asset pipeline enabled, you may turn it off in application.rb and re-run this generator.")
          # ok, nothing
        end
      end
    end
  end
end


text:
var Model = function() {};

Model.prototype.albums = [];

module.exports = Model;


text:
function require(moduleName) {
  var whereToStart = moduleName.lastIndexOf('/'), name;

  if (whereToStart === -1){
    throw new Error('Module "' + moduleName + '" not found');
  }
  name = moduleName.substr(whereToStart + 1);

  return require.modules[name] || (require.modules[name] = {});
};

require.modules = {};

window.di = require('./ng-di');