text:
#ifndef __DC_CDROM_H
#define __DC_CDROM_H

#include <sys/cdefs.h>
__BEGIN_DECLS

#include <arch/types.h>

/** \file   dc/cdrom.h
    \brief  CD access to the GD-ROM drive.

    This file contains the interface to the Dreamcast's GD-ROM drive. It is
    simply called cdrom.h and cdrom.c because, by design, you cannot directly
    use this code to read the high-density area of GD-ROMs. This is the way it
    always has been, and always will be.

    The way things are set up, as long as you're using fs_iso9660 to access the
    CD, it will automatically detect and react to disc changes for you.

    This file only facilitates reading raw sectors and doing other fairly low-
    level things with CDs. If you're looking for higher-level stuff, like
    normal file reading, consult with the stuff for the fs and for fs_iso9660.

    \author Dan Potter
    \see    kos/fs.h
    \see    dc/fs_iso9660.h
*/

/** \defgroup cd_cmd_codes          CD-ROM syscall command codes

    These are the syscall command codes used to actually do stuff with the
    GD-ROM drive. These were originally provided by maiwe.

    @{
*/
#define CMD_PIOREAD 16  /**< \brief Read via PIO */
#define CMD_DMAREAD 17  /**< \brief Read via DMA */
#define CMD_GETTOC  18  /**< \brief Read TOC */
#define CMD_GETTOC2 19  /**< \brief Read TOC */
#define CMD_PLAY    20  /**< \brief Play track */
#define CMD_PLAY2   21  /**< \brief Play sectors */
#define CMD_PAUSE   22  /**< \brief Pause playback */
#define CMD_RELEASE 23  /**< \brief Resume from pause */
#define CMD_INIT    24  /**< \brief Initialize the drive */
#define CMD_SEEK    27  /**< \brief Seek to a new position */
#define CMD_READ    28  /**< \brief Read raw sectors */
#define CMD_STOP    33  /**< \brief Stop the disc from spinning */
#define CMD_GETSCD  34  /**< \brief Get subcode data */
#define CMD_GETSES  35  /**< \brief Get session */
/** @} */

/** \defgroup cd_cmd_response       CD-ROM command responses

    These are the values that the various functions can return as error codes.
    @{
*/
#define ERR_OK          0   /**< \brief No error */
#define ERR_NO_DISC     1   /**< \brief No disc in drive */
#define ERR_DISC_CHG    2   /**< \brief Disc changed, but not reinitted yet */
#define ERR_SYS         3   /**< \brief System error */
#define ERR_ABORTED     4   /**< \brief Command aborted */
#define ERR_NO_ACTIVE   5   /**< \brief System inactive? */
/** @} */

/** \defgroup cd_cmd_status         CD-ROM Command Status responses

    These are the raw values the status syscall returns.
    @{
*/
#define FAILED      -1  /**< \brief Command failed */
#define NO_ACTIVE   0   /**< \brief System inactive? */
#define PROCESSING  1   /**< \brief Processing command */
#define COMPLETED   2   /**< \brief Command completed successfully */
#define ABORTED     3   /**< \brief Command aborted before completion */
/** @} */

/** \defgroup cdda_read_modes       CDDA read modes

    Valid values to pass to the cdrom_cdda_play() function for the mode
    parameter.
    @{
*/
#define CDDA_TRACKS     1   /**< \brief Play by track number */
#define CDDA_SECTORS    2   /**< \brief Play by sector number */
/** @} */

/** \defgroup cd_read_sector_part    CD-ROM Read Sector Part

    Parts of the a CD-ROM sector to read. These are possible values for the
    third parameter word sent with the change data type syscall.
    @{
*/
#define CDROM_READ_WHOLE_SECTOR 0x1000    /**< \brief Read the whole sector */
#define CDROM_READ_DATA_AREA    0x2000    /**< \brief Read the data area */
/** @} */

/** \defgroup cd_read_subcode_type    CD-ROM Read Subcode Type

    Types of data available to read from the sector subcode. These are
    possible values for the first parameter sent to the GETSCD syscall.
    @{
*/
#define CD_SUB_Q_CHANNEL        0    /**< \brief Read Q Channel Subcode Data */
#define CD_SUB_CURRENT_POSITION 1    /**< \brief Read all Subcode Data for
                                                 most recent sector */
#define CD_SUB_MEDIA_CATALOG    2    /**< \brief Read the Media Catalog
                                                 Subcode Data */
#define CD_SUB_TRACK_ISRC       3    /**< \brief Read the ISRC Subcode Data */
/** @} */

/** \defgroup cd_read_sector_mode    CD-ROM Read Sector Mode

    How to read the sectors of a CD, via PIO or DMA. 4th parameter of
    cdrom_read_sectors_ex.
    @{
*/
#define CDROM_READ_PIO 0    /**< \brief Read sector(s) in PIO mode */
#define CDROM_READ_DMA 1    /**< \brief Read sector(s) in DMA mode */
/** @} */

/** \defgroup cd_status_values      CD-ROM status values

    These are the values that can be returned as the status parameter from the
    cdrom_get_status() function.
    @{
*/
#define CD_STATUS_BUSY      0   /**< \brief Drive is busy */
#define CD_STATUS_PAUSED    1   /**< \brief Disc is paused */
#define CD_STATUS_STANDBY   2   /**< \brief Drive is in standby */
#define CD_STATUS_PLAYING   3   /**< \brief Drive is currently playing */
#define CD_STATUS_SEEKING   4   /**< \brief Drive is currently seeking */
#define CD_STATUS_SCANNING  5   /**< \brief Drive is scanning */
#define CD_STATUS_OPEN      6   /**< \brief Disc tray is open */
#define CD_STATUS_NO_DISC   7   /**< \brief No disc inserted */
/** @} */

/** \defgroup cd_disc_types         CD-ROM drive disc types

    These are the values that can be returned as the disc_type parameter from
    the cdrom_get_status() function.
    @{
*/
#define CD_CDDA     0       /**< \brief Audio CD (Red book) */
#define CD_CDROM    0x10    /**< \brief CD-ROM or CD-R (Yellow book) */
#define CD_CDROM_XA 0x20    /**< \brief CD-ROM XA (Yellow book extension) */
#define CD_CDI      0x30    /**< \brief CD-i (Green book) */
#define CD_GDROM    0x80    /**< \brief GD-ROM */
/** @} */

/** \brief  TOC structure returned by the BIOS.

    This is the structure that the CMD_GETTOC2 syscall command will return for
    the TOC. Note the data is in FAD, not LBA/LSN.

    \headerfile dc/cdrom.h
*/
typedef struct {
    uint32  entry[99];          /**< \brief TOC space for 99 tracks */
    uint32  first;              /**< \brief Point A0 information (1st track) */
    uint32  last;               /**< \brief Point A1 information (last track) */
    uint32  leadout_sector;     /**< \brief Point A2 information (leadout) */
} CDROM_TOC;

/** \defgroup cd_toc_access         CD-ROM TOC access macros
    @{
*/
/** \brief  Get the FAD address of a TOC entry.
    \param  n               The actual entry from the TOC to look at.
    \return                 The FAD of the entry.
*/
#define TOC_LBA(n) ((n) & 0x00ffffff)

/** \brief  Get the address of a TOC entry.
    \param  n               The entry from the TOC to look at.
    \return                 The entry's address.
*/
#define TOC_ADR(n) ( ((n) & 0x0f000000) >> 24 )

/** \brief  Get the control data of a TOC entry.
    \param  n               The entry from the TOC to look at.
    \return                 The entry's control value.
*/
#define TOC_CTRL(n) ( ((n) & 0xf0000000) >> 28 )

/** \brief  Get the track number of a TOC entry.
    \param  n               The entry from the TOC to look at.
    \return                 The entry's track.
*/
#define TOC_TRACK(n) ( ((n) & 0x00ff0000) >> 16 )
/** @} */

/** \brief  Set the sector size for read sectors.

    This function sets the sector size that the cdrom_read_sectors() function
    will return. Be sure to set this to the correct value for the type of
    sectors you're trying to read. Common values are 2048 (for reading CD-ROM
    sectors) or 2352 (for reading raw sectors).

    \param  size            The size of the sector data.

    \return                 \ref cd_cmd_response
*/
int cdrom_set_sector_size(int size);

/** \brief  Execute a CD-ROM command.

    This function executes the specified command using the BIOS syscall for
    executing GD-ROM commands. This is now thread-safe to be called by users.

    \param  cmd             The command number to execute.
    \param  param           Data to pass to the syscall.

    \return                 \ref cd_cmd_response
*/
int cdrom_exec_cmd(int cmd, void *param);

/** \brief  Get the status of the GD-ROM drive.

    \param  status          Space to return the drive's status.
    \param  disc_type       Space to return the type of disc in the drive.

    \return                 \ref cd_cmd_response
    \see    cd_status_values
    \see    cd_disc_types
*/
int cdrom_get_status(int *status, int *disc_type);

/** \brief    Change the datatype of disc.

    This function will take in all parameters to pass to the change_datatype
    syscall. This allows these parameters to be modified without a reinit.
    Each parameter allows -1 as a default, which is tied to the former static
    values provided by cdrom_reinit and cdrom_set_sector_size.

    \param sector_part      How much of each sector to return.
    \param cdxa             What CDXA mode to read as (if applicable).
    \param sector_size      What sector size to read (eg. - 2048, 2532).

    \return                 \ref cd_cmd_response
    \see    cd_read_sector_part
*/
int cdrom_change_dataype(int sector_part, int cdxa, int sector_size);

/** \brief  Re-initialize the GD-ROM drive.

    This function is for reinitializing the GD-ROM drive after a disc change to
    its default settings. Calls cdrom_reinit(-1,-1,-1)

    \return                 \ref cd_cmd_response
    \see    cdrom_reinit_ex
*/
int cdrom_reinit();

/** \brief    Re-initialize the GD-ROM drive with custom parameters.

    At the end of each cdrom_reinit(), cdrom_change_datatype is called.
    This passes in the requested values to that function after
    reinitialization, as opposed to defaults.

    \param sector_part      How much of each sector to return.
    \param cdxa             What CDXA mode to read as (if applicable).
    \param sector_size      What sector size to read (eg. - 2048, 2532).

    \return                 \ref cd_cmd_response
    \see    cd_read_sector_part
    \see    cdrom_change_datatype
*/
int cdrom_reinit_ex(int sector_part, int cdxa, int sector_size);

/** \brief  Read the table of contents from the disc.

    This function reads the TOC from the specified session of the disc.

    \param  toc_buffer      Space to store the returned TOC in.
    \param  session         The session of the disc to read.
    \return                 \ref cd_cmd_response
*/
int cdrom_read_toc(CDROM_TOC *toc_buffer, int session);

/** \brief  Read one or more sector from a CD-ROM.

    This function reads the specified number of sectors from the disc, starting
    where requested. This will respect the size of the sectors set with
    cdrom_change_dataype(). The buffer must have enough space to store the
    specified number of sectors.

    \param  buffer          Space to store the read sectors.
    \param  sector          The sector to start reading from.
    \param  cnt             The number of sectors to read.
    \param  mode            DMA or PIO
    \return                 \ref cd_cmd_response
    \see    cd_read_sector_mode
*/
int cdrom_read_sectors_ex(void *buffer, int sector, int cnt, int mode);

/** \brief  Read one or more sector from a CD-ROM in PIO mode.

    Default version of cdrom_read_sectors_ex, which forces PIO mode.

    \param  buffer          Space to store the read sectors.
    \param  sector          The sector to start reading from.
    \param  cnt             The number of sectors to read.
    \return                 \ref cd_cmd_response
    \see    cdrom_read_sectors_ex
*/
int cdrom_read_sectors(void *buffer, int sector, int cnt);

/** \brief    Read subcode data from the most recently read sectors.

    After reading sectors, this can pull subcode data regarding the sectors
    read. If reading all subcode data with CD_SUB_CURRENT_POSITION, this needs
    to be performed one sector at a time.

    \param  buffer          Space to store the read subcode data.
    \param  buflen          Amount of data to be read.
    \param  which           Which subcode type do you wish to get.

    \return                 \ref cd_cmd_response
    \see    cd_read_subcode_type
*/
int cdrom_get_subcode(void *buffer, int buflen, int which);

/** \brief  Locate the sector of the data track.

    This function will search the toc for the last entry that has a CTRL value
    of 4, and return its FAD address.

    \param  toc             The TOC to search through.
    \return                 The FAD of the track, or 0 if none is found.
*/
uint32 cdrom_locate_data_track(CDROM_TOC *toc);

/** \brief  Play CDDA audio tracks or sectors.

    This function starts playback of CDDA audio.

    \param  start           The track or sector to start playback from.
    \param  end             The track or sector to end playback at.
    \param  loops           The number of times to repeat (max of 15).
    \param  mode            The mode to play (see \ref cdda_read_modes).
    \return                 \ref cd_cmd_response
*/
int cdrom_cdda_play(uint32 start, uint32 end, uint32 loops, int mode);

/** \brief  Pause CDDA audio playback.

    \return                 \ref cd_cmd_response
*/
int cdrom_cdda_pause();

/** \brief  Resume CDDA audio playback after a pause.

    \return                 \ref cd_cmd_response
*/
int cdrom_cdda_resume();

/** \brief  Spin down the CD.

    This stops the disc in the drive from spinning until it is accessed again.

    \return                 \ref cd_cmd_response
*/
int cdrom_spin_down();

/** \brief  Initialize the GD-ROM for reading CDs.

    This initializes the CD-ROM reading system, reactivating the drive and
    handling initial setup of the disc.

    \retval 0               On success.
    \retval -1              Already initted, shutdown before initting again.
*/
int cdrom_init();

/** \brief  Shutdown the CD reading system. */
void cdrom_shutdown();

__END_DECLS

#endif  /* __DC_CDROM_H */


text:
filename=$(basename "%%arc_input_file%%")
# append warc file name to the filename-filepath mapping file
echo "${filename}\t%%arc_input_file%%" >> %%wayback_pathindex_file%%

# append cdx file to wayback directory
cat %%arc_cdx_file%% >> %%wayback_cdx_index%%

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Autism Exposome Project</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Autism Exposome Project

                        About us

                        Project

                                Overview

                                Approaches

                        Resources

                                Publications

                                Data

                                Tools

                                Important Links

                        News

                        FAQ

Resources

                Publications
                • Autism
                • Autism  & Environmental factors
                • Exposome
                • Metabolomics

                Data
                Tools
                Important Links

Tools

The tools listed here have been developed by:  Clinical Metabolomics.

apLCMS, LC-MS metabolomics feature extraction

The apLCMS is used for preprocessing LC-MS data. The major improvements include the following aspects: the adaptive tolerance level searching, to apply non-parametric methods of fine-tune intensity grouping, to better preserve weak signals and the estimation method on peak intensities for absolute quantification. The algorithms are implemented in an R package apLCMS.

More about the tool: Yu, T., Park, Y., Johnson, J. M., and Jones, D. P. (2009). apLCMS—adaptive processing of high-resolution LC/MS data. Bioinformatics, 25(15), 1930-1936.

xMSanalyzer

xMSanalyzer is an automated pipeline for processing of metabolomics data which integrates with packages apLCMS and XCMS, but it could be also used to improve the data extraction steps performed by other software.  It includes the following functions: data extraction, quality control assessment, detection of overlapping and unique metabolites in multiple datasets as well as batch annotation of metabolites.

 Fig 1. xMSanalyzer workflow (Taken from Uppal et al. 2013)

More about the tool: Uppal, K., Soltow, Q. A., Strobel, F. H., Pittard, W. S., Gernert, K. M., Yu, T., &emp Jones, D. P. (2013). xMSanalyzer: automated pipeline for improved feature detection and downstream analysis of large-scale, non-targeted metabolomics data. BMC bioinformatics, 14(1), 15.

Mummichog

Mummichog is a method to post-process high-throughput metabolomics data, namely, metabolite identification . This software features a biological activity prediction method which is directly from mass spectrometry data without priori identification of metabolites. Both gene expression and metabolite identification confirmed the predicted results.

 Fig 2. Workflow comparison between conventional methods VS Mummichog (Taken from Li et al. 2013)

More about the tool: Li, S., Park, Y., Duraisingham, S., Strobel, F. H., Khan, N., Soltow, Q. A., ... &emp Pulendran, B. (2013). Predicting network activity from high throughput metabolomics. PLoS computational biology, 9(7), e1003123.

Copyright © Boston Children's Hospital 2015

Follow us: Follow @AutismExposome


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
#if ! __ANDROID__
using System.Drawing;
#else
using Android.Graphics;
#endif
namespace Duality.Cloning.Surrogates
{
	public class BitmapSurrogate : Surrogate<Bitmap>
	{
#if ! __ANDROID__
		public override Bitmap CreateTargetObject(CloneProvider provider)
		{
			return new Bitmap(this.RealObject.Width, this.RealObject.Height);
		}
		public override void CopyDataTo(Bitmap targetObj, CloneProvider provider)
		{
			Bitmap target = targetObj as Bitmap;
			target.SetPixelDataIntArgb(this.RealObject.GetPixelDataIntArgb());
		}
#endif

#if __ANDROID__
		public override void CopyDataTo(Bitmap targetObj, CloneProvider provider)
		{
			throw new NotImplementedException();
		}
#endif
	}
}


text:
//
//  Term.m
//  Homework_3
//
//  Created by YunhanXu on 15/11/1.
//  Copyright © 2015年 YunhanXu. All rights reserved.
//

#import "Term.h"

@implementation Term

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

+(instancetype)addWithDict:(NSDictionary *)add
{
    return [[self alloc] init:add];
}

-(instancetype)init:(NSDictionary *)dict
{
    if (self=[super init])
    {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

-(NSMutableDictionary *)getDictionary
{
    NSMutableDictionary *dict=[NSMutableDictionary dictionary];
    [dict setObject:self.inputString forKey:@"inputString"];
    return dict;
}

@end


text:
package filter

import (
	"fmt"
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/docker/swarm/cluster"
	"github.com/docker/swarm/scheduler/node"
)

// AffinityFilter selects only nodes based on other containers on the node.
type AffinityFilter struct {
}

// Name returns the name of the filter
func (f *AffinityFilter) Name() string {
	return "affinity"
}

// Filter is exported
func (f *AffinityFilter) Filter(config *cluster.ContainerConfig, nodes []*node.Node) ([]*node.Node, error) {
	affinities, err := parseExprs(config.Affinities())
	if err != nil {
		return nil, err
	}

	for _, affinity := range affinities {
		log.Debugf("matching affinity: %s%s%s", affinity.key, OPERATORS[affinity.operator], affinity.value)

		candidates := []*node.Node{}
		for _, node := range nodes {
			switch affinity.key {
			case "container":
				containers := []string{}
				for _, container := range node.Containers {
					containers = append(containers, container.Id, strings.TrimPrefix(container.Names[0], "/"))
				}
				if affinity.Match(containers...) {
					candidates = append(candidates, node)
				}
			case "image":
				images := []string{}
				for _, image := range node.Images {
					images = append(images, image.Id)
					images = append(images, image.RepoTags...)
					for _, tag := range image.RepoTags {
						images = append(images, strings.Split(tag, ":")[0])
					}
				}
				if affinity.Match(images...) {
					candidates = append(candidates, node)
				}
			default:
				labels := []string{}
				for _, container := range node.Containers {
					labels = append(labels, container.Labels[affinity.key])
				}
				if affinity.Match(labels...) {
					candidates = append(candidates, node)
				}

			}
		}
		if len(candidates) == 0 {
			if affinity.isSoft {
				continue
			}
			return nil, fmt.Errorf("unable to find a node that satisfies %s%s%s", affinity.key, OPERATORS[affinity.operator], affinity.value)
		}
		nodes = candidates
	}
	return nodes, nil
}


text:
require 'test/unit'
require_relative './utils/driver'

include Test::Unit::Assertions
include ::Driver

step 'Sign up as <name> with email <email> and <password>' do |name,email,password|
  driver.find_element(:link_text, 'Sign up').click

  form = driver.find_element(:id, 'new_user')

  form.find_element(:name,"user[username]").send_keys(name);
  form.find_element(:name,"user[email]").send_keys(email);
  form.find_element(:name,"user[password]").send_keys(password);
  form.find_element(:name,"user[password_confirmation]").send_keys(password);
  form.find_element(:name,"commit").click;
end

step 'See items available for purchase.' do
    products = driver.find_elements(:class_name, 'product')
    assert_true products.count > 0
end


text:
<?php
/**
 * Created by PhpStorm.
 * User: hak2c
 * Date: 1/5/16
 * Time: 17:50
 */

namespace App\Controller;

use Slim\Container;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

final class ProductController extends BaseController
{
    public function productAction(Request $request ,Response $response,$args){
        $messages = $this->flash->getMessage('info');

        $page = (isset($args['page'])) ? $args['page']: 1;
//        var_dump($page);die;
        $limit = 12;
        $offset = ($page - 1) * $limit;

        try {
            //$products = $this->em->getRepository('App\Model\Products')->findAll();
            $products = $this->em->getRepository('App\Model\Products')->findBy([],['id' => 'ASC'],$limit,$offset);
            //select * from products  order by id ASC , limit = 100  offset = 1
            $all = $this->em->getRepository('App\Model\Products')->findBy([]);
        } catch (\Exception $e) {
            echo $e->getMessage();
            die;
        }

        $count = count($all);
        $totalPage = ceil($count/$limit);
        //var_dump($count, $totalPage); die;

        $this->view->render($response, 'product/products.html', [
            'products' => $products,
            'cat' => '',
            'totalPage' => $totalPage,
            'currentPage' => $page
        ]);
        return $response;
    }

    public function productDetailAction(Request $request, Response $response, $args)
    {

        try {

            $product_detail = $this->em->getRepository('App\Model\Products')->findOneBy(['slug' => $args['slug']]);

        } catch (\Exception $e) {
            echo $e->getMessage();
            die;
        }

        $this->view->render($response, 'product/product_detail.html',[
            'p'=>$product_detail
        ]);
        return $response;
    }

    public function productCategoryAction(Request $request, Response $response, $args)
    {
        try {

            $page = (isset($args['page'])) ? $args['page']: 1;
            $limit = 6;
            $offset = ($page - 1) * $limit;

            $cat = $this->em->getRepository('App\Model\Categories')->findOneBy(['slug'=>$args['slug']]);
            if($cat->getIsParent() == false){
                //select * from products where                                    cagtegory=... order by id desc limit 23 offset 0;
                $category = $this->em->getRepository('App\Model\Products')->findBy(['category'=> $cat->getId()],['id'=>'ASC'],$limit,$offset);
                $all = $this->em->getRepository('App\Model\Categories')->findBy([]);
            }else{

                $cats = $this->em->getRepository('App\Model\Categories')->findBy(['parent'=> $cat->getId()]);
                $cid=[];
                foreach($cats as $c){
                    $cid[] =  $c->getId();
//                    array_push($cid, $c->getId());
                }

                $arr = implode(',',$cid);
                //select * from products where category in (3,4,5,6,7,8,9,10,11,12,13,14)
                $category = $this->em->createQuery("SELECT p FROM App\Model\Products AS p WHERE p.category IN ($arr)")
                    ->setMaxResults($limit)
                    ->setFirstResult($offset)
                    ->getResult();
                $all = $this->em->getRepository('App\Model\Products')->findBy([]);

            }

        } catch (\Exception $e) {
            echo $e->getMessage();
            die;
        }
        $count = count($all);
        $totalPage = ceil($count/$limit);

        $this->view->render($response, 'product/products.html',[
            'products' => $category,
            //'cat'=> $cat->getTitle()
            'cat'=>$cat,
            'totalPage' => $totalPage,
            'currentPage' => $page

        ]);
        return $response;
    }

}


text:
{%- if obj.display %}
{% if sphinx_version >= (2, 1) %}
.. py:method:: {{ obj.short_name }}({{ obj.args }}){% if obj.return_annotation is not none %} -> {{ obj.return_annotation }}{% endif %}

{% for (args, return_annotation) in obj.overloads %}
            {{ obj.short_name }}({{ args }}){% if return_annotation is not none %} -> {{ return_annotation }}{% endif %}

{% endfor %}
   {% if obj.properties %}
   {% for property in obj.properties %}
   :{{ property }}:
   {% endfor %}

   {% else %}

   {% endif %}
{% else %}
.. py:{{ obj.method_type }}:: {{ obj.short_name }}({{ obj.args }})
{% for (args, return_annotation) in obj.overloads %}
   {{ " " * (obj.method_type | length) }}   {{ obj.short_name }}({{ args }})
{% endfor %}

{% endif %}
   {% if obj.docstring %}
   {{ obj.docstring|indent(3) }}
   {% endif %}
{% endif %}


text:
obj-m := defunct.o
all :
	$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
	$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean


text:
/*****************************************************************************/
/**
*
* @file xiic_options.c
* @addtogroup iic_v3_1
* @{
*
* Contains options functions for the XIic component. This file is not required
* unless the functions in this file are called.
*
*

* MODIFICATION HISTORY:
*
* Ver   Who  Date     Changes
* ----- --- ------- -----------------------------------------------
* 1.01b jhl 3/26/02 repartioned the driver
* 1.01c ecm 12/05/02 new rev
* 1.13a wgr 03/22/07 Converted to new coding style.
* 2.00a ktn 10/22/09 Converted all register accesses to 32 bit access.
*		     Updated to use the HAL APIs/macros.
*

*
****************************************************************************/

/***************************** Include Files *******************************/

#include "xiic.h"
#include "xiic_i.h"

/************************** Constant Definitions ***************************/

/**************************** Type Definitions *****************************/

/***************** Macros (Inline Functions) Definitions *******************/

/************************** Function Prototypes ****************************/

/************************** Variable Definitions **************************/

/*****************************************************************************/
/**
*
* This function sets the options for the IIC device driver. The options control
* how the device behaves relative to the IIC bus. If an option applies to
* how messages are sent or received on the IIC bus, it must be set prior to
* calling functions which send or receive data.
*
* To set multiple options, the values must be ORed together. To not change
* existing options, read/modify/write with the current options using
* XIic_GetOptions().
*
* USAGE EXAMPLE:
*
* Read/modify/write to enable repeated start:
*

*   u8 Options;
*   Options = XIic_GetOptions(&Iic);
*   XIic_SetOptions(&Iic, Options | XII_REPEATED_START_OPTION);
*

*
* Disabling General Call:
*

*   Options = XIic_GetOptions(&Iic);
*   XIic_SetOptions(&Iic, Options &= ~XII_GENERAL_CALL_OPTION);
*

*
* @param	InstancePtr is a pointer to the XIic instance to be worked on.
* @param	NewOptions are the options to be set.  See xiic.h for a list of
*		the available options.
*
* @return	None.
*
* @note
*
* Sending or receiving messages with repeated start enabled, and then
* disabling repeated start, will not take effect until another master
* transaction is completed. i.e. After using repeated start, the bus will
* continue to be throttled after repeated start is disabled until a master
* transaction occurs allowing the IIC to release the bus.
*

* Options enabled will have a 1 in its appropriate bit position.
*
****************************************************************************/
void XIic_SetOptions(XIic *InstancePtr, u32 NewOptions)
{
	u32 CntlReg;

	Xil_AssertVoid(InstancePtr != NULL);

	XIic_IntrGlobalDisable(InstancePtr->BaseAddress);

	/*
	 * Update the options in the instance and get the contents of the
	 * control register such that the general call option can be modified.
	 */
	InstancePtr->Options = NewOptions;
	CntlReg = XIic_ReadReg(InstancePtr->BaseAddress, XIIC_CR_REG_OFFSET);

	/*
	 * The general call option is the only option that maps directly to
	 * a hardware register feature.
	 */
	if (NewOptions & XII_GENERAL_CALL_OPTION) {
		CntlReg |= XIIC_CR_GENERAL_CALL_MASK;
	} else {
		CntlReg &= ~XIIC_CR_GENERAL_CALL_MASK;
	}

	/*
	 * Write the new control register value to the register.
	 */
	XIic_WriteReg(InstancePtr->BaseAddress, XIIC_CR_REG_OFFSET, CntlReg);

	XIic_IntrGlobalEnable(InstancePtr->BaseAddress);
}

/*****************************************************************************/
/**
*
* This function gets the current options for the IIC device. Options control
* the how the device behaves on the IIC bus. See SetOptions for more information
* on options.
*
* @param	InstancePtr is a pointer to the XIic instance to be worked on.
*
* @return	The options of the IIC device. See xiic.h for a list of
*		available options.
*
* @note
*
* Options enabled will have a 1 in its appropriate bit position.
*
****************************************************************************/
u32 XIic_GetOptions(XIic *InstancePtr)
{
	Xil_AssertNonvoid(InstancePtr != NULL);

	return InstancePtr->Options;
}
/** @} */


text:
@class circleCollectionView;

@protocol circleCollectionViewDelegate <NSObject>

-(void) collectionView:(circleCollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
-(void) collectionView:(circleCollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath;

@optional
-(void) addItem:(circleCollectionView *)collectionView;
-(void) showDestructiveAlertVC;
//-(void) collectionView:(circleCollectionView *)collectionView didLongPressItemAtIndexPath:(NSIndexPath *)indexPath;
@end

@interface circleCollectionView : UICollectionView <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

+(circleCollectionView *) newCircleCollectionViewEmbeddedIn:(UIView *)viewContainer includedData:(NSArray * )data withOptionalAddButtonImage:(UIImage *)addButtonImage delegatedBy:(id)delegate isAllowingMultiSelection:(BOOL) isAllowingMultiSelection;
-(void)addItemWithName:(NSString *)name picture:(UIImage *)picture color:(UIColor *)color;
-(void) deleteSelectedItem;
-(void) longPressOnItem:(UILongPressGestureRecognizer *)sender;

-(UIImage *) selectedImageIcon;
-(NSArray *) selectedItems;

@property (weak, nonatomic) id <circleCollectionViewDelegate> delegateCircleCollectionView;
@property (strong, nonatomic) NSMutableArray *items;
@end


text:
"""Classes and functions to represents gladiators."""

from random import randint

class Gladiator(object):
    """Represents a gladiator."""

    def __init__(self, name, gladiator_class='fighter', gladiator_species='human'):
        self.name = name
        self.gladiator_class = gladiatorClass(gladiator_class)
        self.gladiator_species = gladiatorSpecies(gladiator_species)
        self.gold_coins = randint(2, 10) # should this be determined by gladiatorClass?

    def attack(self, target):
        return '{0} is attacking {1}'.format(self.name, target)

    def saving_throw(self, type):
        pass

    # Gold coins
    # Inventory: weapons, armor
    # Hit points
    # Armor class
    # Damage modifiers
    # gladiator class
    # gladiator species

class GladiatorClass(object):
    """Represents a gladiator class."""

    def __init__(self, gladiator_class):
        self.gladiator_class = gladiator_class

    def __repr__(self):
        return self.gladiator_class

class GladiatorSpecies(object):
    """Represents a gladiator species."""

    def __init__(self, gladiator_species):
        self.gladiator_species = gladiator_species

    def __repr__(self):
        return self.gladiator_species


text:
<?php

class Google_Service_AnalyticsReporting_Segment extends Google_Model
{
  protected $dynamicSegmentType = 'Google_Service_AnalyticsReporting_DynamicSegment';
  protected $dynamicSegmentDataType = '';
  public $segmentId;

  /**
   * @param Google_Service_AnalyticsReporting_DynamicSegment
   */
  public function setDynamicSegment(Google_Service_AnalyticsReporting_DynamicSegment $dynamicSegment)
  {
    $this->dynamicSegment = $dynamicSegment;
  }
  /**
   * @return Google_Service_AnalyticsReporting_DynamicSegment
   */
  public function getDynamicSegment()
  {
    return $this->dynamicSegment;
  }
  public function setSegmentId($segmentId)
  {
    $this->segmentId = $segmentId;
  }
  public function getSegmentId()
  {
    return $this->segmentId;
  }
}


text:
<?php

namespace App\Models;

use App\Facades\Helpers;
use App\Models\Extensions\ConfigsHas;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\QueryException;

/**
 * App\Configs.
 *
 * @property int         $id
 * @property string      $key
 * @property string|null $value
 * @property string      $cat
 * @property string      $type_range
 * @property int         $confidentiality
 * @property string      $description
 *
 * @method static Builder|Configs admin()
 * @method static Builder|Configs info()
 * @method static Builder|Configs newModelQuery()
 * @method static Builder|Configs newQuery()
 * @method static Builder|Configs public ()
 * @method static Builder|Configs query()
 * @method static Builder|Configs whereCat($value)
 * @method static Builder|Configs whereConfidentiality($value)
 * @method static Builder|Configs whereId($value)
 * @method static Builder|Configs whereKey($value)
 * @method static Builder|Configs whereValue($value)
 * @mixin Eloquent
 */
class Configs extends Model
{
	use ConfigsHas;

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = ['key', 'value', 'cat', 'type_range', 'confidentiality', 'description'];

	/**
	 *  this is a parameter for Laravel to indicate that there is no created_at, updated_at columns.
	 */
	public $timestamps = false;

	/** We define this as a singleton */
	private static $cache = null;

	/**
	 * Sanity check.
	 *
	 * @param $value
	 *
	 * @return string
	 */
	public function sanity($value)
	{
		if (!defined('INT')) {
			define('INT', 'int');
			define('STRING', 'string');
			define('STRING_REQ', 'string_required');
			define('BOOL', '0|1');
			define('TERNARY', '0|1|2');
			define('DISABLED', '');
			define('LICENSE', 'license');
		}

		$message = '';
		$val_range = [BOOL => explode('|', BOOL), TERNARY => explode('|', TERNARY)];

		switch ($this->type_range) {
			case STRING:
			case DISABLED:
				break;
			case STRING_REQ:
				if ($value == '') {
					$message = 'Error: ' . $this->key . ' empty or not set in database';
				}
				break;
			case INT:
				// we make sure that we only have digits in the chosen value.
				if (!ctype_digit(strval($value))) {
					$message = 'Error: Wrong property for ' . $this->key . ' in database, expected positive integer.';
				}
				break;
			case BOOL:
			case TERNARY:
				if (!in_array($value, $val_range[$this->type_range])) { // BOOL or TERNARY
					$message = 'Error: Wrong property for ' . $this->key
						. ' in database, expected ' . implode(
							' or ',
							$val_range[$this->type_range]
						) . ', got ' . ($value ? $value : 'NULL');
				}
				break;
			case LICENSE:
				if (!in_array($value, Helpers::get_all_licenses())) {
					$message = 'Error: Wrong property for ' . $this->key
						. ' in database, expected a valide license, got ' . ($value ? $value : 'NULL');
				}
				break;
			default:
				$values = explode('|', $this->type_range);
				if (!in_array($value, $values)) {
					$message = 'Error: Wrong property for ' . $this->key
						. ' in database, expected ' . implode(' or ', $values)
						. ', got ' . ($value ? $value : 'NULL');
				}
				break;
		}

		return $message;
	}

	/**
	 * Cache and return the current settings of this Lychee installation.
	 *
	 * @return array
	 */
	public static function get()
	{
		if (self::$cache) {
			return self::$cache;
		}

		try {
			$query = Configs::select([
				'key',
				'value',
			]);
			$return = $query->pluck('value', 'key')->all();

			$return['sorting_Photos'] = 'ORDER BY ' . $return['sorting_Photos_col'] . ' ' . $return['sorting_Photos_order'];
			$return['sorting_Albums'] = 'ORDER BY ' . $return['sorting_Albums_col'] . ' ' . $return['sorting_Albums_order'];

			self::$cache = $return;
		} catch (Exception $e) {
			self::$cache = null;

			return null;
		}

		return $return;
	}

	/**
	 * The best way to request a value from the config...
	 *
	 * @param string $key
	 * @param mixed  $default
	 *
	 * @return int|bool|string
	 */
	public static function get_value(string $key, $default = null)
	{
		if (!self::$cache) {
			/*
			 * try is here because when composer does the package discovery it
			 * looks at AppServiceProvider which register a singleton with:
			 * $compressionQuality = Configs::get_value('compression_quality', 90);
			 *
			 * this will fail for sure as the config table does not exist yet
			 */
			try {
				self::get();
			} catch (QueryException $e) {
				return $default;
			}
		}

		if (!isset(self::$cache[$key])) {
			/*
			 * For some reason the $default is not returned above...
			 */
			try {
				Logs::notice(__METHOD__, __LINE__, $key . ' does not exist in config (local) !');
			} catch (Exception $e) {
				// yeah we do nothing because we cannot do anything in that case ...  :p
			}

			return $default;
		}

		return self::$cache[$key];
	}

	/**
	 * Update Lychee configuration
	 * Note that we must invalidate the cache now.
	 *
	 * @param string $key
	 * @param $value
	 *
	 * @return bool returns true when successful
	 */
	public static function set(string $key, $value)
	{
		$config = Configs::where('key', '=', $key)->first();

		// first() may return null, fixup 'Creating default object from empty value' error
		// we also log a warning
		if ($config == null) {
			Logs::warning(__METHOD__, __LINE__, 'key ' . $key . ' not found!');

			return true;
		}

		/**
		 * Sanity check. :).
		 */
		$message = $config->sanity($value);
		if ($message != '') {
			Logs::error(__METHOD__, __LINE__, $message);

			return false;
		}

		$config->value = $value;

		try {
			$config->save();
		} catch (Exception $e) {
			Logs::error(__METHOD__, __LINE__, $e->getMessage());

			return false;
		}

		// invalidate cache.
		self::$cache = null;

		return true;
	}

	/**
	 * Define scopes.
	 */

	/**
	 * @param $query
	 *
	 * @return mixed
	 */
	public function scopePublic(Builder $query)
	{
		return $query->where('confidentiality', '=', 0);
	}

	/**
	 * Logged user can see.
	 *
	 * @param $query
	 *
	 * @return mixed
	 */
	public function scopeInfo(Builder $query)
	{
		return $query->where('confidentiality', '<=', 2);
	}

	/**
	 * Only admin can see.
	 *
	 * @param $query
	 *
	 * @return mixed
	 */
	public function scopeAdmin(Builder $query)
	{
		return $query->where('confidentiality', '<=', 3);
	}
}


text:
package com.b2international.snowowl.snomed.datastore.request;

import static com.b2international.snowowl.snomed.datastore.index.entry.SnomedConceptDocument.Expressions.mapTargetComponentTypes;
import static com.b2international.snowowl.snomed.datastore.index.entry.SnomedConceptDocument.Expressions.refSetTypes;
import static com.b2international.snowowl.snomed.datastore.index.entry.SnomedConceptDocument.Expressions.referencedComponentTypes;

import com.b2international.index.Hits;
import com.b2international.index.query.Expression;
import com.b2international.index.query.Expressions;
import com.b2international.index.query.Expressions.ExpressionBuilder;
import com.b2international.snowowl.core.domain.BranchContext;
import com.b2international.snowowl.core.repository.RevisionDocument;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedRefSetType;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSets;
import com.b2international.snowowl.snomed.datastore.converter.SnomedReferenceSetConverter;
import com.b2international.snowowl.snomed.datastore.index.entry.SnomedConceptDocument;
import com.b2international.snowowl.snomed.datastore.index.entry.SnomedDocument;

/**
 * @since 4.5
 */
final class SnomedRefSetSearchRequest extends SnomedSearchRequest<SnomedReferenceSets, SnomedConceptDocument> {

	enum OptionKey {
		/**
		 * A collection of {@link SnomedRefSetType reference set types} to use
		 */
		TYPE,

		/**
		 * A collection of referenced component types to use
		 */
		REFERENCED_COMPONENT_TYPE,

		/**
		 * A collection of map target component types, only applicable for maps
		 */
		MAP_TARGET_COMPONENT_TYPE
	};

	@Override
	protected Class<SnomedConceptDocument> getDocumentType() {
		return SnomedConceptDocument.class;
	}

	@Override
	protected Expression prepareQuery(BranchContext context) {
		final ExpressionBuilder queryBuilder = Expressions.builder();

		addActiveClause(queryBuilder);
		addReleasedClause(queryBuilder);
		addIdFilter(queryBuilder, RevisionDocument.Expressions::ids);
		addEclFilter(context, queryBuilder, SnomedSearchRequest.OptionKey.MODULE, SnomedDocument.Expressions::modules);
		addEffectiveTimeClause(queryBuilder);

		if (containsKey(OptionKey.TYPE)) {
			queryBuilder.filter(refSetTypes(getCollection(OptionKey.TYPE, SnomedRefSetType.class)));
		} else {
			// always add type filter, so only concept docs with refset props will be returned
			queryBuilder.filter(Expressions.exists(SnomedConceptDocument.Fields.REFSET_TYPE));
		}

		if (containsKey(OptionKey.REFERENCED_COMPONENT_TYPE)) {
			queryBuilder.filter(referencedComponentTypes(getCollection(OptionKey.REFERENCED_COMPONENT_TYPE, String.class)));
		}

		if (containsKey(OptionKey.MAP_TARGET_COMPONENT_TYPE)) {
			queryBuilder.filter(mapTargetComponentTypes(getCollection(OptionKey.MAP_TARGET_COMPONENT_TYPE, String.class)));
		}

		return queryBuilder.build();
	}

	@Override
	protected SnomedReferenceSets toCollectionResource(BranchContext context, Hits<SnomedConceptDocument> hits) {
		if (limit() < 1 || hits.getTotal() < 1) {
			return new SnomedReferenceSets(limit(), hits.getTotal());
		} else {
			return new SnomedReferenceSetConverter(context, expand(), locales()).convert(hits);
		}
	}

	@Override
	protected SnomedReferenceSets createEmptyResult(int limit) {
		return new SnomedReferenceSets(limit, 0);
	}

}


text:
Invert Image Using Binary Not Operation
=======================================

.. index::
   single: BinaryNotImageFilter
   pair: binary; not
   single: invert

Synopsis
--------

Invert an image using the Binary Not operation.

Results
-------
.. figure:: Input.png
  :scale: 70%

  input.png

.. figure:: output.png
  :scale: 70%

  output.png

Code
----

C++
...

.. literalinclude:: Code.cxx
   :lines: 18-

Classes demonstrated
--------------------

.. breathelink:: itk::BinaryNotImageFilter


text:
package com.github.olivergondza.dumpling.cli;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;

import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
import org.kohsuke.args4j.OptionHandlerRegistry;
import org.kohsuke.args4j.spi.OptionHandler;
import org.kohsuke.args4j.spi.Parameters;
import org.kohsuke.args4j.spi.Setter;
import org.reflections.Reflections;

import com.github.olivergondza.dumpling.model.ProcessRuntime;

/**
 * Cli entry point.
 *
 * @author ogondza
 */
public class Main {

    // TODO metaVar is not extracted from handler in: Argument "COMMAND" is required
    @Argument(required = true, metaVar = "COMMAND")
    private CliCommand handler;

    public static void main(@Nonnull String[] args) {
        int exitCode = new Main().run(args, ProcessStream.system());
        System.exit(exitCode);
    }

    /*package*/ int run(@Nonnull String[] args, @Nonnull final ProcessStream system) {
        OptionHandlerRegistry.getRegistry().registerHandler(CliCommand.class, CliCommandOptionHandler.class);
        OptionHandlerRegistry.getRegistry().registerHandler(ProcessRuntime.class, new OptionHandlerRegistry.OptionHandlerFactory() {
            public OptionHandler<?> getHandler(CmdLineParser parser, OptionDef o, Setter setter) {
                return new ProcessRuntimeOptionHandler(parser, o, setter, system);
            }
        });

        CmdLineParser parser = new CmdLineParser(this);

        try {
            parser.parseArgument(args);

            return handler.run(system);
        } catch (CmdLineException ex) {

            system.err().println(ex.getMessage());
            HelpCommand.printUsage(handler, system.err(), ex);
        } catch (CommandFailedException ex) {

            system.err().println(ex.getMessage());
        } catch (RuntimeException ex) {

            ex.printStackTrace(system.err());
        }

        return -1;
    }

    public static class ProcessRuntimeOptionHandler extends OptionHandler<ProcessRuntime<?, ?, ?>> {

        private final @Nonnull ProcessStream streams;

        public ProcessRuntimeOptionHandler(CmdLineParser parser, OptionDef option, Setter<? super ProcessRuntime<?, ?, ?>> setter, ProcessStream streams) {
            super(parser, option, setter);
            this.streams = streams;
        }

        @Override
        public int parseArguments(Parameters params) throws CmdLineException {

            String scheme = namedParameter("KIND", params, 0);

            String locator = null;
            int delim = scheme.indexOf(':');
            if (delim == -1) { // No scheme provided - guess
                try {
                    Integer.parseInt(scheme);
                    locator = scheme;
                    scheme = "process";
                } catch (NumberFormatException ex) {
                    File file = new File(scheme);
                    if (file.exists() && !file.isDirectory()) {
                        locator = scheme;
                        scheme = "threaddump";
                    }
                }

                // Inference failed
                if (locator == null) {
                    if (getFactory(scheme) != null) {
                        throw new UnknownRuntimeKind(owner, "Source format mismatch. Expected " + scheme + ":LOCATOR");
                    }
                    throw new UnknownRuntimeKind(owner, "Unable to infer source from: " + scheme);
                }
            } else {
                locator = scheme.substring(delim + 1);
                scheme = scheme.substring(0, delim);
            }

            CliRuntimeFactory<?> factory = getFactory(scheme);
            if (factory == null) throw new UnknownRuntimeKind(owner, "Unknown runtime source kind: " + scheme);

            if (locator.isEmpty()) throw new UnknownRuntimeKind(owner, "No locator provided for scheme: " + scheme);

            ProcessRuntime<?, ?, ?> runtime = factory.createRuntime(locator, streams);
            if (runtime == null) throw new AssertionError(factory.getClass() + " failed to create runtime");

            setter.addValue(runtime);

            return 1;
        }

        private @Nonnull String namedParameter(String name, Parameters params, int index) throws CmdLineException {
            try {
                return params.getParameter(index);
            } catch (CmdLineException ex) {
                throw new CmdLineException(owner, ex.getMessage() + " " + name);
            }
        }

        @Override
        public String getDefaultMetaVariable() {
            return "KIND:LOCATOR";
        }

        /*package*/ static @Nonnull List<CliRuntimeFactory<?>> getFactories() {
            List<CliRuntimeFactory<?>> factories = new ArrayList<CliRuntimeFactory<?>>();
            for (Class<? extends CliRuntimeFactory<?>> type: factoryTypes()) {
                factories.add(instantiateFactory(type));
            }
            return factories;
        }

        public static @CheckForNull CliRuntimeFactory<?> getFactory(String name) {
            for (Class<? extends CliRuntimeFactory<?>> type: factoryTypes()) {
                CliRuntimeFactory<?> factory = instantiateFactory(type);
                if (name.equals(factory.getKind())) return factory;
            }

            return null;
        }

        @SuppressWarnings({"rawtypes", "unchecked"})
        private static Set<Class<? extends CliRuntimeFactory<?>>> factoryTypes() {
            return (Set) new Reflections("com.github.olivergondza.dumpling").getSubTypesOf(CliRuntimeFactory.class);
        }

        private static CliRuntimeFactory<?> instantiateFactory(Class<? extends CliRuntimeFactory<?>> type) {
            try {

                return type.newInstance();
            } catch (InstantiationException ex) {

                AssertionError e = new AssertionError("Cli handler " + type.getName() + " does not declare default constructor");
                e.initCause(ex);
                throw e;
            } catch (IllegalAccessException ex) {

                AssertionError e = new AssertionError("Cli handler " + type.getName() + " does not declare default constructor");
                e.initCause(ex);
                throw e;
            }
        }

        /*package*/ static final class UnknownRuntimeKind extends CmdLineException {

            public UnknownRuntimeKind(CmdLineParser owner, String message) {
                super(owner, message);
            }
        }
    }
}


text:
We have three deploy environment: test, staging, production

### test
for local test, we can acess from our local computer, and every one can deploy a new version. this env run on our test machine

### staging
for pre-release test, this is an 'tiny production environment'.

### production
the production environment, only ops can access to this.


text:
// <copyright file="ApdexSnapshot.cs" company="App Metrics Contributors">
// Copyright (c) App Metrics Contributors. All rights reserved.
// </copyright>

using System.Collections.Generic;
using System.Linq;

namespace App.Metrics.Apdex
{
    public struct ApdexSnapshot
    {
        private static readonly double ApdexTimeUnitFactor = TimeUnit.Seconds.ScalingFactorFor(TimeUnit.Nanoseconds);

        public ApdexSnapshot(IEnumerable<long> samples, double apdexTSeconds)
        {
            var sampleSet = samples as long[] ?? samples.ToArray();
            var apdexTNanoseconds = apdexTSeconds * ApdexTimeUnitFactor;

            FrustratingSize = sampleSet.Count(t => t > 4.0 * apdexTNanoseconds);
            SatisfiedSize = sampleSet.Count(t => t <= apdexTNanoseconds);
            ToleratingSize = sampleSet.Count(t => t > apdexTNanoseconds && t <= 4.0 * apdexTNanoseconds);
        }

        public int FrustratingSize { get; }

        public int SatisfiedSize { get; }

        public int ToleratingSize { get; }

        public static bool operator ==(ApdexSnapshot left, ApdexSnapshot right) { return left.Equals(right); }

        public static bool operator !=(ApdexSnapshot left, ApdexSnapshot right) { return !left.Equals(right); }

        /// <inheritdoc />
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }

            return obj is ApdexSnapshot && Equals((ApdexSnapshot)obj);
        }

        /// <inheritdoc />
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = FrustratingSize;
                hashCode = (hashCode * 397) ^ SatisfiedSize;
                hashCode = (hashCode * 397) ^ ToleratingSize;
                return hashCode;
            }
        }

        // ReSharper disable MemberCanBePrivate.Global
        public bool Equals(ApdexSnapshot other)
        {
            return FrustratingSize == other.FrustratingSize && SatisfiedSize == other.SatisfiedSize && ToleratingSize == other.ToleratingSize;
        }

        // ReSharper restore MemberCanBePrivate.Global
    }
}


text:
interface IConfig {
    port: string | number;
    mongoUri: string;
    tvdbApi: string;
}


text:
"""A class for parsing a resource projection expression."""

import re

from googlecloudsdk.core.resource import resource_exceptions
from googlecloudsdk.core.resource import resource_lex
from googlecloudsdk.core.resource import resource_projection_spec
from googlecloudsdk.core.resource import resource_transform
from googlecloudsdk.third_party.py27 import py27_copy as copy

class Parser(object):
  """Resource projection expression parser.

  A projection is an expression string that contains a list of resource keys
  with optional attributes. This class parses a projection expression into
  resource key attributes and a tree data structure that is used by a projector.

  A projector is a method that takes a JSON-serializable object and a
  projection as input and produces a new JSON-serializable object containing
  only the values corresponding to the keys in the projection. Optional
  projection key attributes may transform the values in the resulting
  JSON-serializable object.

  In the Cloud SDK projection attributes are used for output formatting.

  A default or empty projection expression still produces a projector that
  converts a resource to a JSON-serializable object.

  Attributes:
    __key_attributes_only: Parse projection key list for attributes only.
    _projection: The resource_projection_spec.ProjectionSpec to parse into.
    _root: The projection _Tree tree root node.
    _snake_headings: Dict used to disambiguate key attribute labels.
    _snake_re: Compiled re for converting key names to angry snake case.
  """

  _BOOLEAN_ATTRIBUTES = ['reverse']

  def __init__(self, defaults=None, symbols=None, compiler=None):
    """Constructor.

    Args:
      defaults: resource_projection_spec.ProjectionSpec defaults.
      symbols: Transform function symbol table dict indexed by function name.
      compiler: The projection compiler method for nested projections.
    """
    self.__key_attributes_only = False
    self._projection = resource_projection_spec.ProjectionSpec(
        defaults=defaults, symbols=symbols, compiler=compiler)
    self._snake_headings = {}
    self._snake_re = None
    self._builtin_transforms = resource_transform

  class _Tree(object):
    """Defines a Projection tree node.

    Attributes:
      tree: Projection _Tree node indexed by key path.
      attribute: Key _Attribute.
    """

    def __init__(self, attribute):
      self.tree = {}
      self.attribute = attribute

  class _Attribute(object):
    """Defines a projection key attribute.

    Attribute semantics, except transform, are caller defined.  e.g., the table
    formatter uses the label attribute for the column heading for the key.

    Attributes:
      flag: The projection algorithm flag, one of DEFAULT, INNER, PROJECT.
      order: The column sort order, None if not ordered. Lower values have
        higher sort precedence.
      label: A string associated with each projection key.
      reverse: Reverse column sort if True.
      align: The column alignment name: left, center, or right.
      transform: obj = func(obj,...) function applied during projection.
      subformat: Sub-format string.
    """

    def __init__(self, flag):
      self.flag = flag
      self.order = None
      self.label = None
      self.reverse = None
      self.align = resource_projection_spec.ALIGN_DEFAULT
      self.transform = []
      self.subformat = None

    def __str__(self):
      return (
          '({flag}, {order}, {label}, {align}, {active},'
          ' {transform})'.format(
              flag=self.flag,
              order=('UNORDERED' if self.order is None else str(self.order)),
              label=repr(self.label),
              align=self.align,
              active=self.transform[0].active if self.transform else None,
              transform='[{0}]'.format('.'.join(map(str, self.transform)))))

  class _Transform(object):
    """A key transform function with actual args.

    Attributes:
      name: The transform function name.
      func: The transform function.
      active: The parent projection active level. A transform is active if
        transform.active is None or equal to the current projection.active.
      map_transform: If r is a list then apply the transform to each list item.
      args: List of function call actual arg strings.
      kwargs: List of function call actual keyword arg strings.
    """

    def __init__(self, name, func, active, map_transform, args, kwargs):
      self.name = name
      self.func = func
      self.active = active
      self.map_transform = map_transform
      self.args = args
      self.kwargs = kwargs

    def __str__(self):
      return '{0}{1}({2})'.format('map().' if self.map_transform else '',
                                  self.name, ','.join(self.args))

  def _AngrySnakeCase(self, key):
    """Returns an ANGRY_SNAKE_CASE string representation of a parsed key.

    Args:
        key: A parsed resource key.

    Returns:
      The ANGRY_SNAKE_CASE string representation of key, adding components
        from right to left to disambiguate from previous ANGRY_SNAKE_CASE
        strings.
    """
    if self._snake_re is None:
      self._snake_re = re.compile('((?<=[a-z0-9])[A-Z]+|(?!^)[A-Z](?=[a-z]))')
    label = ''
    for index in reversed(key):
      if isinstance(index, basestring):
        key_snake = self._snake_re.sub(r'_\1', index).upper()
        if label:
          label = key_snake + '_' + label
        else:
          label = key_snake
        if label not in self._snake_headings:
          self._snake_headings[label] = 1
          break
    return label

  def _AddKey(self, key, attribute_add):
    """Propagates default attribute values and adds key to the projection.

    Args:
      key: The parsed key to add.
      attribute_add: Parsed _Attribute to add.
    """
    projection = self._root

    # Add or update the inner nodes.
    for name in key[:-1]:
      tree = projection.tree
      if name in tree:
        attribute = tree[name].attribute
        if attribute.flag != self._projection.PROJECT:
          attribute.flag = self._projection.INNER
      else:
        tree[name] = self._Tree(self._Attribute(self._projection.INNER))
      projection = tree[name]

    # Add or update the terminal node.
    tree = projection.tree
    # self.key == [] => . or a function on the entire object.
    name = key[-1] if key else ''
    name_in_tree = name in tree
    if name_in_tree:
      # Already added.
      if (not self.__key_attributes_only and
          any([col for col in self._projection.Columns() if col.key == key])):
        # A duplicate column. A projection can only have one attribute object
        # per key. The first <key, attribute> pair added to the current set of
        # columns remains in the projection. Projection columns may have
        # duplicate keys (e.g., table columns with the same key but different
        # transforms). The attribute copy, with attribute_add merged in, is
        # added to the projection columns but not the projection tree.
        attribute = copy.copy(tree[name].attribute)
      else:
        attribute = tree[name].attribute
    elif isinstance(name, (int, long)) and None in tree:
      # New projection for explicit name using slice defaults.
      tree[name] = copy.deepcopy(tree[None])
      attribute = tree[name].attribute
    else:
      # New projection.
      attribute = attribute_add
      if key or attribute.transform:
        tree[name] = self._Tree(attribute)

    # Propagate non-default values from attribute_add to attribute.
    if attribute_add.order is not None:
      attribute.order = attribute_add.order
    if attribute_add.label is not None:
      attribute.label = attribute_add.label
    elif attribute.label is None:
      attribute.label = self._AngrySnakeCase(key)
    if attribute_add.align != resource_projection_spec.ALIGN_DEFAULT:
      attribute.align = attribute_add.align
    if attribute_add.reverse is not None:
      attribute.reverse = attribute_add.reverse
    elif attribute.reverse is None:
      attribute.reverse = False
    if attribute_add.transform:
      attribute.transform = attribute_add.transform
    if attribute_add.subformat:
      attribute.subformat = attribute_add.subformat
    self._projection.AddAlias(attribute.label, key)

    if not self.__key_attributes_only:
      # This key is in the projection.
      attribute.flag = self._projection.PROJECT
      self._projection.AddKey(key, attribute)
    elif not name_in_tree:
      # This is a new attributes only key.
      attribute.flag = self._projection.DEFAULT

  def _ParseTransform(self, func_name, active, map_transform):
    """Parses a transform function call.

    Args:
      func_name: The transform function name.
      active: The transform active level or None if always active.
      map_transform: Apply the transform to each resource list item.

    Returns:
      A _Transform call item. The caller appends these to a list that is used
      to apply the transform functions.

    Raises:
      ExpressionSyntaxError: The expression has a syntax error.
    """
    here = self._lex.GetPosition()
    if (not self._projection.symbols or
        func_name not in self._projection.symbols):
      raise resource_exceptions.ExpressionSyntaxError(
          'Unknown transform function {0} [{1}].'.format(
              func_name, self._lex.Annotate(here)))
    func = self._projection.symbols[func_name]
    args = []
    kwargs = {}
    doc = func.func_doc
    if doc and resource_projection_spec.PROJECTION_ARG_DOC in doc:
      # The second transform arg is the parent ProjectionSpec.
      args.append(self._projection)
    if func.func_defaults:
      # Separate the args from the kwargs.
      for arg in self._lex.Args():
        name, sep, val = arg.partition('=')
        if sep:
          kwargs[name] = val
        else:
          args.append(arg)
    else:
      # No kwargs.
      args += self._lex.Args()
    return self._Transform(func_name, func, active, map_transform, args, kwargs)

  def _ParseKeyAttributes(self, key, attribute):
    """Parses one or more key attributes and adds them to attribute.

    The initial ':' has been consumed by the caller.

    Args:
      key: The parsed key name of the attributes.
      attribute: Add the parsed transform to this resource_projector._Attribute.

    Raises:
      ExpressionSyntaxError: The expression has a syntax error.
    """
    while True:
      name = self._lex.Token('=:,)', space=False)
      here = self._lex.GetPosition()
      if self._lex.IsCharacter('=', eoi_ok=True):
        boolean_value = False
        value = self._lex.Token(':,)', space=False, convert=True)
      else:
        boolean_value = True
        if name.startswith('no-'):
          name = name[3:]
          value = False
        else:
          value = True
      if name in self._BOOLEAN_ATTRIBUTES:
        if not boolean_value:
          # A Boolean attribute with a non-Boolean value.
          raise resource_exceptions.ExpressionSyntaxError(
              'value not expected [{0}].'.format(self._lex.Annotate(here)))
      elif boolean_value:
        # A non-Boolean attribute without a value or a no- prefix.
        raise resource_exceptions.ExpressionSyntaxError(
            'value expected [{0}].'.format(self._lex.Annotate(here)))
      if name == 'alias':
        if not value:
          raise resource_exceptions.ExpressionSyntaxError(
              'Cannot unset alias [{0}].'.format(self._lex.Annotate(here)))
        self._projection.AddAlias(value, key)
      elif name == 'align':
        if value not in resource_projection_spec.ALIGNMENTS:
          raise resource_exceptions.ExpressionSyntaxError(
              'Unknown alignment [{0}].'.format(self._lex.Annotate(here)))
        attribute.align = value
      elif name == 'format':
        attribute.subformat = value or ''
      elif name == 'label':
        attribute.label = value or ''
      elif name == 'reverse':
        attribute.reverse = value
      elif name == 'sort':
        attribute.order = value
      else:
        raise resource_exceptions.ExpressionSyntaxError(
            'Unknown key attribute [{0}].'.format(self._lex.Annotate(here)))
      if not self._lex.IsCharacter(':'):
        break

  def _ParseKey(self):
    """Parses a key and optional attributes from the expression.

    Transform functions and key attributes are also handled here.

    Raises:
      ExpressionSyntaxError: The expression has a syntax error.

    Returns:
      The parsed key.
    """
    key = self._lex.Key()
    here = self._lex.GetPosition()
    attribute = self._Attribute(self._projection.PROJECT)
    if self._lex.IsCharacter('(', eoi_ok=True):
      func_name = key.pop()
      active = self._projection.active
      map_transform = False
      while True:
        transform = self._ParseTransform(func_name, active, map_transform)
        if transform.func == self._builtin_transforms.TransformAlways:
          active = None  # Always active.
          func_name = None
        elif transform.func == self._builtin_transforms.TransformMap:
          map_transform = True
          func_name = None
        else:
          # always() applies to all transforms for key.
          # map() applies to the next transform.
          map_transform = False
          attribute.transform.append(transform)
        if not self._lex.IsCharacter('.', eoi_ok=True):
          break
        call = self._lex.Key()
        here = self._lex.GetPosition()
        if not self._lex.IsCharacter('('):
          raise resource_exceptions.ExpressionSyntaxError(
              'Transform function expected [{0}].'.format(
                  self._lex.Annotate(here)))
        if len(call) != 1:
          raise resource_exceptions.ExpressionSyntaxError(
              'Unknown transform function {0} [{1}].'.format(
                  '.'.join(call), self._lex.Annotate(here)))
        func_name = call.pop()
    else:
      func_name = None
    self._lex.SkipSpace()
    if self._lex.IsCharacter(':'):
      self._ParseKeyAttributes(key, attribute)
    if func_name and attribute.label is None and not key:
      attribute.label = self._AngrySnakeCase([func_name])
    self._AddKey(key, attribute)

  def _ParseKeys(self):
    """Parses a comma separated list of keys.

    The initial '(' has already been consumed by the caller.

    Raises:
      ExpressionSyntaxError: The expression has a syntax error.
    """
    if self._lex.IsCharacter(')'):
      # An empty projection is OK.
      return
    while True:
      self._ParseKey()
      self._lex.SkipSpace()
      if self._lex.IsCharacter(')'):
        break
      if not self._lex.IsCharacter(','):
        raise resource_exceptions.ExpressionSyntaxError(
            'Expected ) in projection expression [{0}].'.format(
                self._lex.Annotate()))

  def _ParseAttributes(self):
    """Parses a comma separated [no-]name[=value] projection attribute list.

    The initial '[' has already been consumed by the caller.

    Raises:
      ExpressionSyntaxError: The expression has a syntax error.
    """
    while True:
      name = self._lex.Token('=,])', space=False)
      if name:
        if self._lex.IsCharacter('='):
          value = self._lex.Token(',])', space=False, convert=True)
        else:
          value = 1
        self._projection.AddAttribute(name, value)
        if name.startswith('no-'):
          self._projection.DelAttribute(name[3:])
        else:
          self._projection.DelAttribute('no-' + name)
      if self._lex.IsCharacter(']'):
        break
      if not self._lex.IsCharacter(','):
        raise resource_exceptions.ExpressionSyntaxError(
            'Expected ] in attribute list [{0}].'.format(self._lex.Annotate()))

  def Parse(self, expression=None):
    """Parse a projection expression.

    An empty projection is OK.

    Args:
      expression: The resource projection expression string.

    Raises:
      ExpressionSyntaxError: The expression has a syntax error.

    Returns:
      A ProjectionSpec for the expression.
    """
    self._root = self._projection.GetRoot()
    if not self._root:
      self._root = self._Tree(self._Attribute(self._projection.DEFAULT))
      self._projection.SetRoot(self._root)
    self._projection.SetEmpty(
        self._Tree(self._Attribute(self._projection.PROJECT)))
    if expression:
      self._lex = resource_lex.Lexer(expression,
                                     aliases=self._projection.aliases)
      defaults = False
      self.__key_attributes_only = False
      while self._lex.SkipSpace():
        if self._lex.IsCharacter('('):
          if not self.__key_attributes_only:
            defaults = False
            self._projection.Defaults()
          self._ParseKeys()
        elif self._lex.IsCharacter('['):
          self._ParseAttributes()
        elif self._lex.IsCharacter(':'):
          self.__key_attributes_only = True
        else:
          self.__key_attributes_only = False
          here = self._lex.GetPosition()
          name = self._lex.Token(':([')
          if not name.isalpha():
            raise resource_exceptions.ExpressionSyntaxError(
                'Name expected [{0}].'.format(self._lex.Annotate(here)))
          self._projection.SetName(name)
          defaults = True
      self._lex = None
      if defaults:
        self._projection.Defaults()
    return self._projection

def Parse(expression, defaults=None, symbols=None, compiler=None):
  """Parses a resource projector expression.

  Args:
    expression: The resource projection expression string.
    defaults: resource_projection_spec.ProjectionSpec defaults.
    symbols: Transform function symbol table dict indexed by function name.
    compiler: The projection compiler method for nested projections.

  Returns:
    A ProjectionSpec for the expression.
  """
  return Parser(
      defaults=defaults, symbols=symbols, compiler=compiler).Parse(expression)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="launcher_view_columns">4</integer>
</resources>


text:
function activarEstrella(magnitud){
	$('.estrella').each(function(){
		if($(this).attr('data-magnitud') <= magnitud){
			$(this).addClass('estrella-activa');
		}else{
			$(this).removeClass('estrella-activa');
		}
	});
	var fecha = new Date($("#fecha-siento-actual").val());
	var attr = $("#attr-siento-actual").val();

	guardarSientoBase(fecha, attr, magnitud);
	leerDatosGrafica(fecha.getMonth(), fecha.getFullYear(), attr);
}

function cargarSientoActual(fecha, attr){
	$("#fecha-siento-actual").val(fecha);
	$("#attr-siento-actual").val(attr);
	consultarSientoBase(fecha, attr);
	leerDatosGrafica(fecha.getMonth(), fecha.getFullYear(), attr);
}

function consultarSientoBase(fecha, attr){
	fechaFormato = fechaJSaDB(fecha);
	db.transaction(function(tx){
		//tx.executeSql("DROP TABLE sentimientos");
		tx.executeSql('SELECT * FROM sentimientos WHERE fecha = "' + fechaFormato + '" AND atributo = "' + attr + '"', [],
					function(tx, results){
						var magnitudActual = 0;
						var comentarioActual = '';
						if(results.rows.length == 0){
							magnitudActual = 1;
						}else{
							magnitudActual = results.rows.item(0).magnitud;
							comentarioActual = results.rows.item(0).comentarios;
						}
						activarEstrella(magnitudActual);
						cargarComentarioSiento(comentarioActual);
					}, errorCargarSiento);
	}, errorCargarSiento);

}

function guardarSientoBase(fecha, attr, magnitud){
	fechaFormato = fechaJSaDB(fecha);
	db.transaction(function(tx){
			tx.executeSql('SELECT * FROM sentimientos WHERE fecha = "' + fechaFormato + '" AND atributo = "' + attr + '"', [],
					function(tx, results){
						guardarSiento(tx, results, fechaFormato, attr, magnitud);
					}, errorCargarSiento);
		}
		,errorCargarSiento, successGuardarSiento
	);
}

function guardarSiento(tx, results, fecha, attr, magnitud){
	if(results.rows.length == 0){
		tx.executeSql("INSERT INTO sentimientos (fecha, atributo, magnitud) VALUES('" + fecha + "', '" + attr + "', '" + magnitud + "')", [], function(tx, res){
			var datosBase = [];
			datosBase.push({"fecha": fecha, "atributo": attr, "magnitud": magnitud, "idSiento": res.insertId});
			queryRespaldo("insert", "sentimientos", datosBase);
		}, function(tx, err){});
	}else{
		tx.executeSql("UPDATE sentimientos SET magnitud='" + magnitud + "' WHERE fecha='" + fecha + "' AND atributo = '" + attr + "'", [], function(tx, res){
			var datosBase = [];
			datosBase.push({"magnitud": magnitud});
			datosBase.push({"fecha": fecha, "atributo": attr});
			queryRespaldo("update", "sentimientos", datosBase);
		}, function(tx, err){});
	}
}

function errorCargarSiento(err){
	alert("ERRORX-" + err.code + ": " + err.message);
}

function successGuardarSiento(){
	console.log("DATABASE REQUEST COMPLETE");
}

function leerDatosGrafica(mes, anio, attr){//Mes del 0 al 11

	$("#barra-fechas-graph .mes").html(MESES[mes]);
	$("#barra-fechas-graph .anio").html(anio);
	$("#mes-grafica-actual").val(mes);
	$("#anio-grafica-actual").val(anio);
	var mesForm = parseInt(mes) + 1;
	db.transaction(function(tx){
		sql = 'SELECT * FROM sentimientos WHERE fecha >= "' + anio + '-' + mesForm + '-01" AND fecha <= "' + anio + '-' + mesForm + '-31" AND atributo = "' + attr + '" ORDER BY fecha ASC';
		tx.executeSql(sql, [],function(tx, results){
						desplegarGrafica(tx, results, mesForm, anio);
					}, errorCargarSiento);
	},errorCargarSiento);
}

function desplegarGrafica(tx, results, mes, anio){
	var hoy = new Date();
	var div = document.createElement('div');
	var contenedor = document.getElementById("contenedor-grafica");
	div.setAttribute("id", "contenedor-grafica-siento");
	div.setAttribute("class", "contenedor-grafica-siento");
	for(var ii = 1; ii< 32; ii ++){
		var mesJS = parseInt(mes) - 1;
		var fechaTemp = new Date(anio, mesJS, ii);
		var span = document.createElement('span');
		if(fechaTemp.getMonth() !== mesJS){
			break;
		}
		var mag = 1;
		for(var jj = 0; jj < results.rows.length; jj++){
			if(fechaTemp.toString() == fechaDBaJS(results.rows.item(jj).fecha).toString()){
				mag = results.rows.item(jj).magnitud;
			}
		}
		if(fechaTemp > hoy){
			span.setAttribute("data-magnitud", 0);
			span.className = 'futuro';
			span.innerHTML = '
' + ii + '
';
		}else{
			span.setAttribute("data-magnitud", mag);
			span.innerHTML = '
' + ii + '
';
		}
		div.appendChild(span);
	}
	contenedor.innerHTML = '';
	contenedor.appendChild(div);
	var medida = parseInt($("#contenedor-grafica-siento").width())/ii;
	$("#contenedor-grafica-siento span").width(medida);
}

function fechaDBaJS(string){
	var arr = string.split('-');
	var anio = arr[0];
	var mes = parseInt(arr[1]) - 1;
	var dia = arr[2];
	return new Date(anio, mes, dia);
}

function fechaJSaDB(fecha){
	console.log(fecha);
	var fechaFormato = '';
	fechaFormato += fecha.getFullYear() + '-';
	if(parseInt(fecha.getMonth()) + 1 < 10){
		fechaFormato += '0' + parseInt(fecha.getMonth()) + 1;
	}else{
		fechaFormato += parseInt(fecha.getMonth()) + 1;
	}
	fechaFormato += '-';
	if(parseInt(fecha.getDate()) < 10){
		fechaFormato += "0" + parseInt(fecha.getDate());
	}else{
		fechaFormato += parseInt(fecha.getDate());
	}
	return fechaFormato;
}

function guardarComentarioSiento(){
	var fecha = new Date($("#fecha-siento-actual").val());
	var attr = $("#attr-siento-actual").val();
	var comentario = $("#campo-texto-siento").val();

	fechaFormato = fechaJSaDB(fecha);
	console.log(comentario);
	db.transaction(function(tx){
			tx.executeSql('SELECT * FROM sentimientos WHERE fecha = "' + fechaFormato + '" AND atributo = "' + attr + '"', [],
					function(tx, results){
						guardarComentario(tx, results, fechaFormato, attr, comentario);
					}, errorCargarSiento);
		}
		,errorCargarSiento, successGuardarSiento
	);
}

function cargarComentarioSiento(comentario){
	$("#campo-texto-siento").val(comentario);
}

function guardarComentario(tx, results, fecha, attr, comentario){

	tx.executeSql("UPDATE sentimientos SET comentarios='" + comentario + "' WHERE fecha='" + fecha + "' AND atributo = '" + attr + "'", [], function(tx, res){
		var datosBase = [];
		datosBase.push({"comentarios": comentario});
		datosBase.push({"fecha": fecha, "atributo": attr});
		queryRespaldo("update", "sentimientos", datosBase);
	}, function(tx, err){});
}


text:
use crate::blob::generate_blob_uri;
use azure_sdk_core::{
    BlobNameRequired, BlobNameSupport, ContainerNameRequired, ContainerNameSupport, No, ToAssign,
    Yes,
};
use azure_sdk_storage_core::prelude::*;
use azure_sdk_storage_core::{
    shared_access_signature::SharedAccessSignature, SharedAccessSignatureRequired,
    SharedAccessSignatureSupport,
};
use std::marker::PhantomData;

#[derive(Debug, Clone)]
pub struct SignedUrlBuilder<'a, C, ContainerNameSet, BlobNameSet, SignatureSet>
where
    C: Client,
    ContainerNameSet: ToAssign,
    BlobNameSet: ToAssign,
{
    client: &'a C,
    p_container_name: PhantomData<ContainerNameSet>,
    p_blob_name: PhantomData<BlobNameSet>,
    p_signature: PhantomData<SignatureSet>,
    container_name: Option<&'a str>,
    blob_name: Option<&'a str>,
    signature: Option<&'a SharedAccessSignature>,
}

impl<'a, C> SignedUrlBuilder<'a, C, No, No, No>
where
    C: Client,
{
    pub fn new(client: &'a C) -> Self {
        Self {
            client,
            p_container_name: PhantomData {},
            container_name: None,
            p_blob_name: PhantomData {},
            blob_name: None,
            p_signature: PhantomData {},
            signature: None,
        }
    }
}

impl<'a, C, ContainerNameSet, BlobNameSet, SignatureSet> ClientRequired<'a, C>
    for SignedUrlBuilder<'a, C, ContainerNameSet, BlobNameSet, SignatureSet>
where
    C: Client,
    ContainerNameSet: ToAssign,
    BlobNameSet: ToAssign,
    SignatureSet: ToAssign,
{
    #[inline]
    fn client(&self) -> &'a C {
        &self.client
    }
}

impl<'a, C, BlobNameSet, SignatureSet> ContainerNameRequired<'a>
    for SignedUrlBuilder<'a, C, Yes, BlobNameSet, SignatureSet>
where
    C: Client,
    BlobNameSet: ToAssign,
    SignatureSet: ToAssign,
{
    #[inline]
    fn container_name(&self) -> &'a str {
        self.container_name.unwrap()
    }
}

impl<'a, C, ContainerNameSet, SignatureSet> BlobNameRequired<'a>
    for SignedUrlBuilder<'a, C, ContainerNameSet, Yes, SignatureSet>
where
    C: Client,
    ContainerNameSet: ToAssign,
    SignatureSet: ToAssign,
{
    #[inline]
    fn blob_name(&self) -> &'a str {
        self.blob_name.unwrap()
    }
}

impl<'a, C, ContainerNameSet, BlobNameSet> SharedAccessSignatureRequired<'a>
    for SignedUrlBuilder<'a, C, ContainerNameSet, BlobNameSet, Yes>
where
    C: Client,
    ContainerNameSet: ToAssign,
    BlobNameSet: ToAssign,
{
    #[inline]
    fn shared_access_signature(&self) -> &'a SharedAccessSignature {
        self.signature.unwrap()
    }
}

impl<'a, C, ContainerNameSet, BlobNameSet, SignatureSet> ContainerNameSupport<'a>
    for SignedUrlBuilder<'a, C, ContainerNameSet, BlobNameSet, SignatureSet>
where
    C: Client,
    ContainerNameSet: ToAssign,
    BlobNameSet: ToAssign,
    SignatureSet: ToAssign,
{
    type O = SignedUrlBuilder<'a, C, Yes, BlobNameSet, SignatureSet>;

    #[inline]
    fn with_container_name(self, container_name: &'a str) -> Self::O {
        SignedUrlBuilder {
            client: self.client,
            p_container_name: PhantomData {},
            p_blob_name: PhantomData {},
            p_signature: PhantomData {},
            container_name: Some(container_name),
            blob_name: self.blob_name,
            signature: self.signature,
        }
    }
}

impl<'a, C, ContainerNameSet, BlobNameSet, SignatureSet> BlobNameSupport<'a>
    for SignedUrlBuilder<'a, C, ContainerNameSet, BlobNameSet, SignatureSet>
where
    C: Client,
    ContainerNameSet: ToAssign,
    BlobNameSet: ToAssign,
    SignatureSet: ToAssign,
{
    type O = SignedUrlBuilder<'a, C, ContainerNameSet, Yes, SignatureSet>;

    #[inline]
    fn with_blob_name(self, blob_name: &'a str) -> Self::O {
        SignedUrlBuilder {
            client: self.client,
            p_container_name: PhantomData {},
            p_blob_name: PhantomData {},
            p_signature: PhantomData {},
            container_name: self.container_name,
            blob_name: Some(blob_name),
            signature: self.signature,
        }
    }
}

impl<'a, C, ContainerNameSet, BlobNameSet, SignatureSet> SharedAccessSignatureSupport<'a>
    for SignedUrlBuilder<'a, C, ContainerNameSet, BlobNameSet, SignatureSet>
where
    C: Client,
    ContainerNameSet: ToAssign,
    BlobNameSet: ToAssign,
    SignatureSet: ToAssign,
{
    type O = SignedUrlBuilder<'a, C, ContainerNameSet, BlobNameSet, Yes>;

    #[inline]
    fn with_shared_access_signature(self, signature: &'a SharedAccessSignature) -> Self::O {
        SignedUrlBuilder {
            client: self.client,
            p_container_name: PhantomData {},
            p_blob_name: PhantomData {},
            p_signature: PhantomData {},
            container_name: self.container_name,
            blob_name: self.blob_name,
            signature: Some(signature),
        }
    }
}

impl<'a, C> SignedUrlBuilder<'a, C, Yes, Yes, Yes>
where
    C: Client,
{
    #[inline]
    pub fn finalize(self) -> String {
        generate_blob_uri(
            self.client(),
            self.container_name(),
            self.blob_name(),
            Some(&self.signature.unwrap().token()),
        )
    }
}


text:
namespace Soloco.Composition.Container.IntegrationTests
{
    public class TestEntity
    {
    }
}


text:
require 'spec_helper'

shared_examples 'clusterable policies' do
  describe '#add_cluster?' do
    let(:current_user) { create(:user) }

    subject { described_class.new(current_user, clusterable) }

    context 'with a developer' do
      before do
        clusterable.add_developer(current_user)
      end

      it { expect_disallowed(:read_cluster) }
      it { expect_disallowed(:add_cluster) }
      it { expect_disallowed(:create_cluster) }
      it { expect_disallowed(:update_cluster) }
      it { expect_disallowed(:admin_cluster) }
    end

    context 'with a maintainer' do
      before do
        clusterable.add_maintainer(current_user)
      end

      context 'with no clusters' do
        it { expect_allowed(:read_cluster) }
        it { expect_allowed(:add_cluster) }
        it { expect_allowed(:create_cluster) }
        it { expect_allowed(:update_cluster) }
        it { expect_allowed(:admin_cluster) }
      end
    end
  end
end


text:
package net.resonious.sburb.game

import scala.collection.mutable.ArrayBuffer
import SburbProperties._
import cpw.mods.fml.common.network.ByteBufUtils
import cpw.mods.fml.relauncher.SideOnly
import io.netty.buffer.ByteBuf
import net.minecraft.entity.Entity
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.entity.player.EntityPlayerMP
import net.minecraft.util.ChunkCoordinates
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.server.MinecraftServer
import net.minecraft.world.World
import net.minecraftforge.common.IExtendedEntityProperties
import net.resonious.sburb.Sburb
import net.resonious.sburb.abstracts._
import net.minecraft.item.ItemStack
import net.resonious.sburb.abstracts.PacketPipeline
import net.resonious.sburb.commands.SburbCommand._
import net.resonious.sburb.game.grist._
import net.resonious.sburb.packets.ActivePacket
import net.resonious.sburb.items.SburbDisc
import cpw.mods.fml.relauncher.Side
import cpw.mods.fml.relauncher.SideOnly
import scala.collection.mutable.HashMap

/*
 * ======= OBJECT ========
 */
object SburbProperties {
  val PROPERTIES_NAME = "sburbprops"
  var ofDeadPlayers = new HashMap[String, NBTTagCompound]

  // IN ENTITY:
  // protected HashMap<String, IExtendedEntityProperties> extendedProperties;
  val extendedProperties = classOf[Entity].getDeclaredField("extendedProperties")
  extendedProperties.setAccessible(true)

  def register(player: EntityPlayer) = {
    // When constructing the player entity, it has no game profile, but still
    // needs this shit registered.
    val uuid: String = try {
      player.getGameProfile.getId.toString
    } catch {
      case _: NullPointerException => null
    }

    if (uuid == null)
      Sburb log "NULL NAME BEING REGISTERED"
    else
      Sburb log "Registering player: " + uuid

    if (uuid != null && ofDeadPlayers.contains(uuid)) {
      val props = of(player)
      if (props != null) {
        props.loadNBTData(ofDeadPlayers(uuid))
        ofDeadPlayers -= uuid
      }
    }
    else if (player.getExtendedProperties(PROPERTIES_NAME) == null)
      player.registerExtendedProperties(PROPERTIES_NAME, new SburbProperties(player))

    val props = of(player)
    props
  }

  def of(player: EntityPlayer) = player.getExtendedProperties(PROPERTIES_NAME).asInstanceOf[SburbProperties]

  // Sets client name, server name, and game id for the client
  class GameInfoPacket(var props: SburbProperties) extends ActivePacket {
    def this() = this(null)
    @SideOnly(Side.SERVER)
    def send() = {
      PacketPipeline.sendTo(this, props.mpPlayer)
    }

    var clientName = ""
    var serverName = ""
    var gameId = ""

    override def write(buf: ByteBuf) = {
      buf writeBoolean props.hasGame
      if (props.hasGame) {
        ByteBufUtils.writeUTF8String(buf, props.gameId)
        ByteBufUtils.writeUTF8String(buf, props.gameEntry.client)
        ByteBufUtils.writeUTF8String(buf, props.gameEntry.server)
      }
    }
    override def read(buf: ByteBuf) = {
      if (buf.readBoolean) {
        gameId = ByteBufUtils.readUTF8String(buf)
        clientName = ByteBufUtils.readUTF8String(buf)
        serverName = ByteBufUtils.readUTF8String(buf)
      } else {
        gameId = ""
        clientName = "???"
        serverName = "???"
      }
    }
    override def onClient(player: EntityPlayer) = {
      props = SburbProperties of player
      props.gameId = gameId
      props.clientPlayerName = clientName
      props.serverPlayerName = serverName
    }
  }

  // Sync grist by type
  class GristPacket(props: SburbProperties) extends ActivePacket {
    def this() = this(null)
    var grist: ArrayBuffer[(Grist.Value, Long)] = null

    @SideOnly(Side.SERVER)
    def sync(gtypes: Grist.Value*) = {
      grist = new ArrayBuffer[(Grist.Value, Long)]
      val entry = props.gameEntry
      gtypes foreach { gtype =>
        grist += gtype -> entry.grist(gtype)
      }
      PacketPipeline.sendTo(this, props.mpPlayer)
    }

    override def write(buf: ByteBuf) = {
      buf writeInt grist.length
      grist foreach { kv =>
        buf writeInt kv._1.id
        buf writeLong kv._2
      }
    }
    override def read(buf: ByteBuf) = {
      grist = new ArrayBuffer[(Grist.Value, Long)]
      val length = buf.readInt
      for (i <- 0 until length) {
        val gtype = Grist(buf.readInt)
        val amnt = buf.readLong
        grist += gtype -> amnt
      }
    }

    override def onClient(player: EntityPlayer) = {
      val props = SburbProperties of player
      val sm = props.serverMode
      grist foreach { kv => sm.grist(kv._1) = kv._2 }
    }
  }
}

/*
 * ======= CLASS ========
 */
class SburbProperties(_player: EntityPlayer) extends IExtendedEntityProperties {
  Sburb log "Registered some sburb propz"
  // After(5, 'seconds) execute { _=> Sburb log "It was for "+player.getDisplayName }

  // This is used in Events#onPlayerInteractEvent to make it so people
  // don't accidentally spend 500 grist on breaking all blocks in front of
  // them.
  var disallowBlockGrab = false

  val gameInfoPacket: GameInfoPacket =
    if(Sburb.isServer)
      new GameInfoPacket(this)
    else
      null
  val gristPacket = new GristPacket(this)

  // Accessors for the associated player
  def player = _player
  def playerName = _player.getGameProfile.getName
  lazy val mpPlayer = Sburb.playerOfName(player.getGameProfile.getName)

  // For the MC client (I hate 'client' and 'server' being common to SBURB and Minecraft)
  var clientPlayerName = "???"
  var serverPlayerName = "???"

  // Game ID of the player
  private var _gameId = ""
  def gameId = if(_gameId.isEmpty) "---" else  _gameId
  // Only set it if it's client!
  def gameId_=(id:String) =
    if (Sburb.isServer)
      throw new SburbException("Game ID should not be directly set on the server!")
    else
      _gameId = id

  // Sburb game that this player belongs to (SERVER ONLY)
  private var _game: SburbGame = null
  def game = {
    if (_game == null)
      _game = if (Sburb.isClient) throw new SburbException("Client cannot access game info")
              else if (_gameId.isEmpty) null
              else if (!Sburb.games.contains(_gameId))
                throw new SburbException("Couldn't find game ID "+_gameId)
              else
                Sburb.games(gameId)
    _game
  }
  def game_=(g: SburbGame): Unit = {
    if (Sburb.isClient) throw new SburbException("No way can the client assign the Sburb game!")
    // Setting the game to null will clear all game data (hopefully)
    if (g == null) {
      try {
        serverMode.activated = false
      } catch {
        case e: Exception => e.printStackTrace()
      }

      if (gameId == null || gameId.isEmpty)
        return

      val entry = _gameEntry
      if (entry != null)
        entry.beforeClear()
      _game = null
      _gameId = ""
      _serverMode = new SburbServerMode(this)

      Sburb log playerName + "'s Sburb game was cleared!"
    }
    // Otherwise just sets it of course
    else {
      _gameId = g.gameId
      _game = g
      Sburb log playerName + " was assigned to game " + _gameId
    }
    gameInfoPacket.send()
  }

  // Whether or not this player is in an Sburb game
  def hasGame = !_gameId.isEmpty && (Sburb.isClient || game != null)

  def gameEntry = game entryOf player
  // Underscore version to combat bad recursion in game clearing.
  def _gameEntry = {
    try {
      Sburb.games(_gameId) entryOf player
    } catch {
      case e: NoSuchElementException => null
    }
  }

  // Called from events
  def onJoin(): Unit = {
    if (hasGame) {
      serverMode.onJoin()
      if (Sburb.isServer) {
        if (gameEntry.spawnPointDirty) {
          val housePos = gameEntry.house.spawn
          val coords = new ChunkCoordinates(housePos.x, housePos.y, housePos.z)
          player.setSpawnChunk(coords, true, gameEntry.mediumId)
          // So yeah, if someone immediately logs out after logging in, they'll get fucked.
          After(2, 'seconds) execute {
            Sburb.warpPlayer(player, gameEntry.mediumId, housePos)
          }
          gameEntry.spawnPointDirty = false
        }
        else {
          if (player.worldObj.provider.dimensionId == 0) {
            if (gameEntry.mediumId != 0) {
              Sburb log "Recovering"+player.getCommandSenderName+" from broken medium"
              gameEntry.mediumId = 0
              gameEntry.mediumColor = null
            }
            gameEntry.houseCurrentlyBeingMoved = false
          }
        }

        if (gameEntry.needsSburbDisc) {
          player.inventory.addItemStackToInventory(new ItemStack(SburbDisc, 1))
          gameEntry.needsSburbDisc = false
        }

        After(3, 'seconds) execute {
          // Why in the devil I have to send this packet twice I do not know.
          gameInfoPacket.send()
          After(5, 'ticks) execute gameInfoPacket.send
        }
      }
    }
  }

  // Assign server player, oh shit
  def assignServer(server: EntityPlayer) = {
    val serverProps = SburbProperties of server
    val sgame =
      if (hasGame) game
      else if(serverProps.hasGame) serverProps.game
      else Sburb.newGame

    sgame.assign(player, server, false)
    gameInfoPacket.send()
  }

  // Server mode module of the player
  private var _serverMode = new SburbServerMode(this)
  def serverMode = _serverMode

  // Overrides
  override def saveNBTData(comp: NBTTagCompound):Unit = {
    comp.setString("gameId", _gameId)
    // Sburb log "SAVED GAME ID OF " + _gameId
    serverMode save comp
  }

  override def loadNBTData(comp: NBTTagCompound):Unit = {
    _gameId = comp.getString("gameId")
    Sburb log "LOADED GAME ID OF " + _gameId
    serverMode load comp
  }

  override def init(entity: Entity, world: World) = {}
}


text:
package org.dominokit.domino.api.server.fileuploads;

public interface FileUpload {

  String name();

  String uploadedFileName();

  String fileName();

  long size();

  String contentType();

  String contentTransferEncoding();

  String charSet();
}


text:
package com.josonprog.common.expression.util;

import java.util.ArrayList;
import java.util.Iterator;

public class ComparableArrayList<E extends Comparable<E>> extends ArrayList<E>
		implements Comparable<ComparableArrayList<E>> {

	/**
	 *
	 */
	private static final long serialVersionUID = 7239738545779109991L;

	@Override
	public int compareTo(ComparableArrayList<E> o) {
		int res = 0;

		Iterator<E> curIter = this.iterator();
		Iterator<E> toIter = o.iterator();

		E curElem, toElem;
		while (curIter.hasNext() && toIter.hasNext()) {
			curElem = curIter.next();
			toElem = toIter.next();

			res = curElem.compareTo(toElem);

			if (res != 0) {
				break;
			}
		}

		if (res == 0) {
			// if one is longer than other.
			if (curIter.hasNext())
				res = 1;
			else if (toIter.hasNext())
				res = -1;
		}

		return res;
	}
}


text:
package com.example.soundararajan.testopengl;

import android.app.Activity;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;

import java.util.HashMap;

public class MainActivity extends Activity {

    PlusListener plusListener;
    MinusListener minusListener;
    public MainActivity()
    {
        plusListener = new PlusListener();
        minusListener = new MinusListener();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Display display = ((WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int screenRotation = display.getRotation();

        GLSurfaceView shotView = (GLSurfaceView) findViewById(R.id.shotView);
        MyRenderer renderer = new MyRenderer(this,screenRotation);
        shotView.setRenderer(renderer);

        RegisterMenuItemClickListener(R.id.xplus, true);
        RegisterMenuItemClickListener(R.id.xminus, false);

        RegisterMenuItemClickListener(R.id.yplus, true);
        RegisterMenuItemClickListener(R.id.yplus, false);

        RegisterMenuItemClickListener(R.id.zplus, true);
        RegisterMenuItemClickListener(R.id.zminus, false);

        RegisterMenuItemClickListener(R.id.rollplus, true);
        RegisterMenuItemClickListener(R.id.rollminus, false);

        RegisterMenuItemClickListener(R.id.yawplus, true);
        RegisterMenuItemClickListener(R.id.yawminus, false);

        RegisterMenuItemClickListener(R.id.pitchplus, true);
        RegisterMenuItemClickListener(R.id.pitchminus, false);

    }

    HashMap hm = new HashMap();

    void RegisterMenuItemClickListener(int id, boolean plus)
    {
        if(plus)
            findViewById(id).setOnClickListener(plusListener);
        else
            findViewById(id).setOnClickListener(minusListener);
        hm.put(id, 0.0f);
    }

    private class PlusListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            int id = v.getId();
            float val = (float)hm.get(id);
            val +=1.0f;
            hm.put(id, val);
        }
    }

    private class MinusListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            int id = v.getId();
            float val = (float)hm.get(id);
            val -=0.1f;
            hm.put(id, val);

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}


text:
require_relative 'spec_helper'

describe 'Cli#version' do
  it 'shows correct persie version' do
    shows = persie_command 'version'
    expect(shows).to eq("persie #{::Persie::VERSION}")
  end
end